diff --git a/Automated/Automated.cpp b/Automated/Automated.cpp deleted file mode 100644 index dac5abd..0000000 --- a/Automated/Automated.cpp +++ /dev/null @@ -1,548 +0,0 @@ -// Automated.cpp : Defines the entry point for the console application. -// - -#include "stdafx.h" -#include "automater.h" - -/* -START screen is Herausgebeauftrag -screen title "HTML5 Browser" -button: ulds_scannen = 230,210 -input: 1st input box = 230,180 (double click + backspace to mark and delete all existing text?) -type: barcode_text = AKE00006LH -button: uebernehmen = 240, 350 -button: abbrechen = 240, 440 -delete: uld_delete1 = 436, 242 -delete2: uld_delete2 = 404, 242 -button: abbrechen ---back at START -*/ -TCHAR* sz_winTitle = L"HTML5 Browser"; -//TCHAR* sz_winTitle = L"IntermecBrowser"; -TCHAR* sz_winClass = NULL; -bool activateWindow(TCHAR* sz_Class, TCHAR* sz_Title); -DWORD backgroundThreadID; -HANDLE backgroundThreadH; - -TCHAR* sz_ScanData = L"AKE00006LH"; - -int x=430; -int y=590; - -int dx = (int)((65535 / 480) * x); //Screen.PrimaryScreen.Bounds.Width -int dy = (int)((65535 / 640) * y); //Screen.PrimaryScreen.Bounds.Height - -/* -class clickPoint{ -public: - int x; - int y; - TCHAR* name; - clickPoint(int i1, int i2){ - x=i1; - y=i2; - } - clickPoint(int i1, int i2, TCHAR* n){ - x=i1; - y=i2; - name=(TCHAR*) malloc((32+1)+sizeof(TCHAR)); - wcsncpy(name, n, 32); - } - ~clickPoint(void){ - free(name); - } -}; -*/ - -void DoClickAt(int x, int y){ - BOOL bUseTouch=false; - int dx = (int)((65535 / 480) * x); //Screen.PrimaryScreen.Bounds.Width - int dy = (int)((65535 / 640) * y); //Screen.PrimaryScreen.Bounds.Height - - if (bUseTouch){ - mouse_event(MOUSEEVENTF_TOUCH, dx, dy, 0, 0); - Sleep(1); - }else{ - mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_ABSOLUTE , dx, dy, 0, 0); - Sleep(10); - mouse_event(MOUSEEVENTF_LEFTUP , 0, 0, 0, 0); - Sleep(5); - } -} - -int screenW, screenH; - -void GetMetrics(int* width, int* height){ - int screenX = GetSystemMetrics(SM_CXFULLSCREEN); - int screenY = GetSystemMetrics(SM_CYFULLSCREEN); - *width=screenX; - *height=screenY; -} - -BOOL DoClickAt(clickPoint* cp){ - TCHAR szTxt[64]; - if(!activateWindow(sz_winClass, sz_winTitle)){ - return FALSE; - } - HWND hwndMsg=FindWindow(myclass, NULL); - - int dx = (int)((65535 / screenW) * cp->x); //Screen.PrimaryScreen.Bounds.Width - int dy = (int)((65535 / screenH) * cp->y); //Screen.PrimaryScreen.Bounds.Height - - wsprintf(szTxt,L"Action: %s at %i/%i\n", cp->name, cp->x, cp->y); - DEBUGMSG(1, (szTxt)); - if(hwndMsg!=NULL){ - MYREC mRec; - wcsncpy(mRec.s1, szTxt, 80); - MyCDS.cbData=sizeof(MYREC); - MyCDS.lpData=&mRec; - MyCDS.dwData=1; - - SendMessage(hwndMsg, WM_COPYDATA, 0, (LPARAM) (LPVOID) &MyCDS); - } - - mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_ABSOLUTE , dx, dy, 0, 0); - Sleep(5); - mouse_event(MOUSEEVENTF_LEFTUP | MOUSEEVENTF_ABSOLUTE , dx, dy, 0, 0); - return TRUE; -} - -BOOL DoEnterText(TCHAR* text){ - if(!activateWindow(sz_winClass, sz_winTitle)){ - return FALSE; - } - char* textA; - textA = (char*)malloc((wcslen(text)+1)*sizeof(TCHAR)); - int num = wcstombs(textA, text, wcslen(text)+1); - byte* pByte=(byte*) textA; //set pointer to first char - int cnt=0; - //while (pByte!=NULL && pByte!=0){ - while(cntname)); - //if(!DoClickAt(clickPoints[2])) //click zur bersicht - // return -3; - - //if(!DoClickAt(clickPoints[3])) //click Delete symbol - // return -3; - //DoSendSpace(); //to ensure bernehmen is clicked - //visualDelay(4); - //if(!DoClickAt(clickPoints[4])) //click confirm delete icon - // return -3; - visualDelay(3); - //Back at START - }else{ - //START, we are on Herausgabeauftrag - //execute [ULDs scannen] by pressing RETURN two times!! - DEBUGMSG(1, (L"Action: [ULDs scannen]\n")); - DoSendEnter(); DoSendEnter(); - visualDelay(4); - - DEBUGMSG(1, (L"Action: enter data %s\n", sz_ScanData)); - DoEnterText(sz_ScanData); //enter data in edit box - visualDelay(1); - DEBUGMSG(1, (L"Action: ->[bernehmen] (1)\n")); - - //now data entered and second empty row - DoSendTab(); //to move onto [bernehmen] - visualDelay(1); - DEBUGMSG(1, (L"Action: ->[bernehmen] (2)\n")); - DoSendSpace(); //execute [bernehmen] - visualDelay(2); //focus on delete symbol - - DEBUGMSG(1, (L"Action: [Delete]\n")); - DoSendSpace(); //focus on DELETE - visualDelay(1); //exec delete - DEBUGMSG(1, (L"Action: [Confirm] (1)\n")); - DoSendTab(); //focus on rect around confirm symbol - DEBUGMSG(1, (L"Action: [Confirm] (2)\n")); - DoSendTab(); //focus on confirm - DEBUGMSG(1, (L"Action: [Confirm] (3)\n")); - DoSendSpace(); //exec confirm - //back at Herausgabeauftrag - visualDelay(6); - }//if else - }//for - return 0; -} - - - -int _tmain(int argc, _TCHAR* argv[]) -{ - GetMetrics(&screenW, &screenH); - - //goto TEST; - - HWND hWnd = FindWindow(NULL, sz_winTitle); - hWnd = FindWindow(sz_winTitle, NULL); //Intermec Browser CLASS - if (hWnd==NULL){ - DEBUGMSG(1, (L"'%s' running?\n", sz_winTitle)); - return -1; - } - -TEST: - //########################## - //RECT rect; - //GetWindowRect(GetDesktopWindow(), &rect); - //rect.bottom=rect.top; - //rect.top=0; - //startWin(&rect); - //CreateThread(0, 0, test2, NULL, 0, &backgroundThreadID); - DWORD dwWait; - //########################## - - automater _automater=automater(hWnd);// (NULL, sz_winTitle);// (hWnd); //start automater class with hwnd of window to control - _automater.DoClickAt(clickPoints[0]); - Sleep(3000); - _automater.DoSendTextMsg(sz_ScanData); - Sleep(3000); - - do{ - dwWait=WaitForSingleObject(stopHandle, 1000); - switch(dwWait){ - case WAIT_OBJECT_0: - stopApp=TRUE; - break; - case WAIT_TIMEOUT: - PostMessage(hWndMain, WM_UPDATEWIN, (WPARAM)L'#', 0); - DEBUGMSG(1, (L"+")); - break; - default: - break; - } - }while(!stopApp); - - - return 22; - //########################## - - //START - SetForegroundWindow(hWnd); - int iRes = test2(NULL); - return iRes; - -} - diff --git a/Automated/Automated.sln b/Automated/Automated.sln deleted file mode 100644 index 76192d0..0000000 --- a/Automated/Automated.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Automated", "Automated.vcproj", "{B15B5A38-6522-4C5E-BDEC-7918B028464D}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B15B5A38-6522-4C5E-BDEC-7918B028464D}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {B15B5A38-6522-4C5E-BDEC-7918B028464D}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {B15B5A38-6522-4C5E-BDEC-7918B028464D}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {B15B5A38-6522-4C5E-BDEC-7918B028464D}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {B15B5A38-6522-4C5E-BDEC-7918B028464D}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {B15B5A38-6522-4C5E-BDEC-7918B028464D}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Automated/Automated.vcproj b/Automated/Automated.vcproj deleted file mode 100644 index 243099e..0000000 --- a/Automated/Automated.vcproj +++ /dev/null @@ -1,268 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Automated/ReadMe.txt b/Automated/ReadMe.txt deleted file mode 100644 index 6abbee4..0000000 --- a/Automated/ReadMe.txt +++ /dev/null @@ -1,33 +0,0 @@ -======================================================================== - CONSOLE APPLICATION : Automated Project Overview -======================================================================== - -AppWizard has created this Automated application for you. - -This file contains a summary of what you will find in each of the files that -make up your Automated application. - - -Automated.vcproj - This is the main project file for VC++ projects generated using an Application Wizard. - It contains information about the version of Visual C++ that generated the file, and - information about the platforms, configurations, and project features selected with the - Application Wizard. - -Automated.cpp - This is the main application source file. - -///////////////////////////////////////////////////////////////////////////// -Other standard files: - -StdAfx.h, StdAfx.cpp - These files are used to build a precompiled header (PCH) file - named Automated.pch and a precompiled types file named StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Other notes: - -AppWizard uses "TODO:" comments to indicate parts of the source code you -should add to or customize. - -/////////////////////////////////////////////////////////////////////////////s \ No newline at end of file diff --git a/Automated/Windows Mobile 5.0 Pocket PC SDK (ARMV4I)/Debug/Automated.exe b/Automated/Windows Mobile 5.0 Pocket PC SDK (ARMV4I)/Debug/Automated.exe deleted file mode 100644 index 76f7f17..0000000 Binary files a/Automated/Windows Mobile 5.0 Pocket PC SDK (ARMV4I)/Debug/Automated.exe and /dev/null differ diff --git a/Automated/automater.cpp b/Automated/automater.cpp deleted file mode 100644 index 3573b17..0000000 --- a/Automated/automater.cpp +++ /dev/null @@ -1,272 +0,0 @@ -//autometer.cpp -#include "stdafx.h" -#include "automater.h" -#include "minwin.h" - -HWND hWndMsgWin=NULL; - - -void automater::initMsgWin(){ - RECT rect; - GetWindowRect(GetDesktopWindow(), &rect); - rect.bottom=rect.top; - rect.top=0; - startWin(&rect); - Sleep(1000); - hWndMsgWin=FindWindow(myclass,NULL); - if(hWndMsgWin) - PostMessage(hWndMsgWin, WM_UPDATEWIN, (WPARAM)L'*', 0); -} - -automater::automater(){ - wsprintf(mszTitle,L""); - wsprintf(mszClass, L""); - getMetrics(&mScreenW, &mScreenH); -} - -automater::automater(HWND hWnd){ - mhWnd=hWnd; - TCHAR szTxt[MAX_PATH]; - wsprintf(szTxt, L"hallo"); - int len=0; - len = GetWindowText(mhWnd, mszTitle, MAX_PATH); - len = GetClassName(mhWnd, mszClass, MAX_PATH); - - getMetrics(&mScreenW, &mScreenH); - initMsgWin(); -} - -automater::automater(TCHAR *szClass, TCHAR *szTitle){ - wsprintf(mszClass, L"%s", szClass); - wsprintf(mszTitle, L"%s", szTitle); - - mhWnd=FindWindow(mszClass,mszTitle); - getMetrics(&mScreenW, &mScreenH); - initMsgWin(); -} - -automater::~automater(){ - stopApp=TRUE; - SetEvent(stopHandle); -} - -BOOL automater::testWindow(){ - if(FindWindow(mszClass,mszTitle)==NULL) - return FALSE; - else - return TRUE; -} - -void automater::visualDelay(int delay){ - DEBUGMSG(1, (L"\nDELAY: ")); - for (int i=1; i<=delay; i++){ - DEBUGMSG(1, (L".")); - Sleep(i*1000); - } -} - -void automater::getMetrics(int* width, int* height){ - int screenX = GetSystemMetrics(SM_CXFULLSCREEN); - int screenY = GetSystemMetrics(SM_CYFULLSCREEN); - *width=screenX; - *height=screenY; -} - -void automater::updateMessage(TCHAR* szTxt){ - HWND hwndMsg=FindWindow(myclass, NULL); - if(hwndMsg!=NULL){ - MYREC mRec; - wcsncpy(mRec.s1, szTxt, 80); - MyCDS.cbData=sizeof(MYREC); - MyCDS.lpData=&mRec; - MyCDS.dwData=1; - - SendMessage(hwndMsg, WM_COPYDATA, 0, (LPARAM) (LPVOID) &MyCDS); - } -} - -BOOL automater::DoClickAt(clickPoint* cp){ - if(!testWindow()){ - return FALSE; - } - - TCHAR* szTxt=(TCHAR*)malloc(sizeof(TCHAR)*80); - memset(szTxt,0,sizeof(TCHAR)*80); - - int dx = (int)((65535 / mScreenW) * cp->x); //Screen.PrimaryScreen.Bounds.Width - int dy = (int)((65535 / mScreenH) * cp->y); //Screen.PrimaryScreen.Bounds.Height - - wsprintf(szTxt,L"Action: %s at %i/%i\n", cp->name, cp->x, cp->y); - DEBUGMSG(1, (szTxt)); - updateMessage(szTxt); - /* - HWND hwndMsg=FindWindow(myclass, NULL); - if(hwndMsg!=NULL){ - MYREC mRec; - wcsncpy(mRec.s1, szTxt, 80); - MyCDS.cbData=sizeof(MYREC); - MyCDS.lpData=&mRec; - MyCDS.dwData=1; - - SendMessage(hwndMsg, WM_COPYDATA, 0, (LPARAM) (LPVOID) &MyCDS); - } - */ - mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_ABSOLUTE , dx, dy, 0, 0); - Sleep(5); - mouse_event(MOUSEEVENTF_LEFTUP | MOUSEEVENTF_ABSOLUTE , dx, dy, 0, 0); - - free(szTxt); - return TRUE; -} - -BOOL automater::DoEnterText(TCHAR* text){ - if(!testWindow()){ - return FALSE; - } - TCHAR sMsg[128]; - wsprintf(sMsg, L"entering data: %s", text); - updateMessage(sMsg); - - char* textA; - textA = (char*)malloc((wcslen(text)+1)*sizeof(TCHAR)); - int num = wcstombs(textA, text, wcslen(text)+1); - byte* pByte=(byte*) textA; //set pointer to first char - int cnt=0; - //while (pByte!=NULL && pByte!=0){ - while(cntlpData))->s1); - InvalidateRect(window,NULL, false); - break; - case WM_PAINT: - SetForegroundWindow(window); - hDC=BeginPaint(window, &pps); - //original=SelectObject(hDC,GetStockObject(DC_BRUSH)); - SetBkColor(hDC,RGB(0xef,0x00,0x00)); - - GetClientRect(window, &rect); - if(wcslen(szTxt)>0) - DrawText(hDC, szTxt, -1, &rect, DT_LEFT); - else - DrawText(hDC, tch1, -1, &rect, DT_LEFT); - - //Restore original object. - //SelectObject(hDC,original); - EndPaint(window, &pps); - break; - default: - DEBUGMSG(1, (L".")) ; - return DefWindowProc( window, msg, wp, lp ) ; - } - return TRUE; -} - -DWORD myWndProcThread(LPVOID lpParam){ - RECT rectWin; - memcpy(&rectWin, lpParam, sizeof(RECT));// (RECT)lpParam; - - HBRUSH redBrush = CreateSolidBrush(RGB(0xef,0x00,0x70)); - WNDCLASS wndclass = { - CS_DBLCLKS, - WindowProcedure, - 0, //clsExtra - 0, //winExtra - GetModuleHandle(0), //instance - NULL, //LoadIcon(0,IDI_APPLICATION), //icon - NULL, //LoadCursor(0,IDC_ARROW), //cursor - HBRUSH(redBrush),//COLOR_WINDOW+1), //background - 0, //menu name - myclass //class name - } ; - int captH = GetSystemMetrics(SM_CYCAPTION); - if( RegisterClass(&wndclass) ) - { - HWND window = CreateWindowEx( 0, myclass, L"title", - WS_OVERLAPPED | //WS_OVERLAPPED makes a floating window, - WS_EX_CAPTIONOKBTN | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | - WS_SYSMENU, // WS_SYSMENU shows the closing X in caption - rectWin.left, rectWin.top, //CW_USEDEFAULT, CW_USEDEFAULT, - rectWin.right, captH*2, //rectWin.bottom*2,// 200, 200, // CW_USEDEFAULT, CW_USEDEFAULT, - 0, 0, GetModuleHandle(0), 0 ) ; - if(window) - { - hWndMain=window; - ShowWindow( window, SW_SHOWNORMAL ) ; - UpdateWindow(window); - SetWindowTop(window, TRUE); - MSG msg ; - while( GetMessage( &msg, 0, 0, 0 ) ) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - else{ - SetEvent(stopHandle); - return -2; - } - } - else { - SetEvent(stopHandle); - return -3; - } - stopApp=TRUE; - SetEvent(stopHandle); - return 0; -} - -int startWin(RECT* rect){ - stopHandle=CreateEvent(0, FALSE, FALSE, stopEventName); - if(stopHandle==NULL) - return -1; //failed to create stopHandle - - _threadWndProcH = CreateThread(0,0,myWndProcThread, (LPVOID)rect, 0, &_threadWndProcID); - if(_threadWndProcH==NULL) - return -4; //failed to create thread - else - return -2; //failed to RegisterClass - return 0; -} \ No newline at end of file diff --git a/Automated/minwin.h b/Automated/minwin.h deleted file mode 100644 index 4ae4fa0..0000000 --- a/Automated/minwin.h +++ /dev/null @@ -1,24 +0,0 @@ -//minwin.h - -#ifndef _MIN_WIN_H_ -#define _MIN_WIN_H_ - -#include "stdafx.h" - -int startWin(RECT* rect); -extern BOOL stopApp; -extern HANDLE stopHandle; -extern HWND hWndMain; -extern const TCHAR* const myclass; -#define WM_UPDATEWIN WM_USER + 47 -#define WM_NEWTEXT WM_USER + 48 - -typedef struct tagMYREC -{ - TCHAR s1[80]; - DWORD n; -} MYREC; - -extern COPYDATASTRUCT MyCDS; - -#endif //_MIN_WIN_H_ \ No newline at end of file diff --git a/Automated/stdafx.cpp b/Automated/stdafx.cpp deleted file mode 100644 index 7d0cf57..0000000 --- a/Automated/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// Automated.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/Automated/stdafx.h b/Automated/stdafx.h deleted file mode 100644 index 6321d00..0000000 --- a/Automated/stdafx.h +++ /dev/null @@ -1,58 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include - -#include -#pragma comment(lib, "aygshell.lib") - - - -#include -#include - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here -#include -#include "minwin.h" \ No newline at end of file diff --git a/BTchatVB/32feet.ico b/BTchatVB/32feet.ico deleted file mode 100644 index 4c8e74c..0000000 Binary files a/BTchatVB/32feet.ico and /dev/null differ diff --git a/BTchatVB/AssemblyInfo.vb b/BTchatVB/AssemblyInfo.vb deleted file mode 100644 index 54017a3..0000000 --- a/BTchatVB/AssemblyInfo.vb +++ /dev/null @@ -1,28 +0,0 @@ -Imports System.Reflection -Imports System.Runtime.InteropServices - -' General Information about an assembly is controlled through the following -' set of attributes. Change these attribute values to modify the information -' associated with an assembly. - -' Review the values of the assembly attributes - - - - - - - - - -' Version information for an assembly consists of the following four values: -' -' Major Version -' Minor Version -' Build Number -' Revision -' -' You can specify all the values or you can default the Build and Revision Numbers -' by using the '*' as shown below: - - diff --git a/BTchatVB/BluetoothChatPPC.vbproj b/BTchatVB/BluetoothChatPPC.vbproj deleted file mode 100644 index 838abaa..0000000 --- a/BTchatVB/BluetoothChatPPC.vbproj +++ /dev/null @@ -1,147 +0,0 @@ - - - Local - 9.0.30729 - 2.0 - {6D424B0E-ACBF-4832-BB59-7C6D674F971B} - Debug - AnyCPU - {68B1623D-7FB9-47D8-8664-7ECEA3297D4F};{F184B08F-C81C-45F6-A57F-5ABD9991F28F} - ..\..\Common\32feet.ico - - - BluetoothChat - - - None - false - WinExe - Binary - On - Off - \Program Files\BluetoothChat - ThirtyTwoFeet - ThirtyTwoFeet.ChatForm - - - Empty - - - - - SAK - SAK - SAK - SAK - 2.0 - Pocket PC 2003 - - - 3C41C503-53EF-4c2a-8DD4-A8217CAD115E - PocketPC - $(AssemblyName) - v2.0 - - - bin\Debug\ - 0 - - - - - true - true - true - false - false - false - false - 1 - full - true - true - off - - - bin\Release\ - 0 - - - - - false - true - false - false - false - false - false - 1 - none - true - true - off - - - - False - - - System - False - - - System.Drawing - False - - - System.Windows.Forms - False - - - - - - - - - - - - - - Code - - - Form - - - ChatForm.vb - Designer - - - - - 32feet.ico - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/BTchatVB/BluetoothChatPPC.vbproj.vspscc b/BTchatVB/BluetoothChatPPC.vbproj.vspscc deleted file mode 100644 index feffdec..0000000 --- a/BTchatVB/BluetoothChatPPC.vbproj.vspscc +++ /dev/null @@ -1,10 +0,0 @@ -"" -{ -"FILE_VERSION" = "9237" -"ENLISTMENT_CHOICE" = "NEVER" -"PROJECT_FILE_RELATIVE_PATH" = "" -"NUMBER_OF_EXCLUDED_FILES" = "0" -"ORIGINAL_PROJECT_FILE_PATH" = "" -"NUMBER_OF_NESTED_PROJECTS" = "0" -"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" -} diff --git a/BTchatVB/ChatForm.cs b/BTchatVB/ChatForm.cs deleted file mode 100644 index 91e99df..0000000 --- a/BTchatVB/ChatForm.cs +++ /dev/null @@ -1,238 +0,0 @@ -using System.Net; -using System.IO; -using System.Net.Sockets; -using InTheHand.Net.Sockets; -using InTheHand.Net.Bluetooth; -using InTheHand.Net; -public class ChatForm : System.Windows.Forms.Form { - - internal System.Windows.Forms.MainMenu MainMenu1; - - const int MAX_MESSAGE_SIZE = 128; - - const int MAX_TRIES = 3; - - private Guid ServiceName = new Guid("{E075D486-E23D-4887-8AF5-DAA1F6A5B172}"); - - private BluetoothClient btClient = new BluetoothClient(); - - private BluetoothListener btListener; - - private bool listening = true; - - private string str; - - // NOTE: The following procedure is required by the Windows Form Designer - // It can be modified using the Windows Form Designer. - // Do not modify it using the code editor. - internal System.Windows.Forms.TextBox txtMessagesArchive; - - internal System.Windows.Forms.TextBox txtMessage; - - internal System.Windows.Forms.MenuItem mnuSend; - - internal System.Windows.Forms.MenuItem mnuMenu; - - internal System.Windows.Forms.MenuItem mnuSearch; - - internal System.Windows.Forms.MenuItem mnuExit; - - internal System.Windows.Forms.ComboBox cboDevices; - - internal System.Windows.Forms.Button btnSend; - - public ChatForm() { - // This call is required by the Windows Form Designer. - InitializeComponent(); - // Add any initialization after the InitializeComponent() call - } - - // Form overrides dispose to clean up the component list. - protected override void Dispose(bool disposing) { - base.Dispose(disposing); - } - - private void InitializeComponent() { - this.MainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuSend = new System.Windows.Forms.MenuItem(); - this.mnuMenu = new System.Windows.Forms.MenuItem(); - this.mnuSearch = new System.Windows.Forms.MenuItem(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.txtMessagesArchive = new System.Windows.Forms.TextBox(); - this.txtMessage = new System.Windows.Forms.TextBox(); - this.cboDevices = new System.Windows.Forms.ComboBox(); - this.btnSend = new System.Windows.Forms.Button(); - // - // MainMenu1 - // - this.MainMenu1.MenuItems.Add(this.mnuSend); - this.MainMenu1.MenuItems.Add(this.mnuMenu); - // - // mnuSend - // - this.mnuSend.Text = "Send"; - this.mnuMenu.MenuItems.Add(this.mnuSearch); - this.mnuMenu.MenuItems.Add(this.mnuExit); - this.mnuMenu.Text = "Menu"; - this.mnuSearch.Text = "Search Again"; - this.mnuExit.Text = "Exit"; - this.txtMessagesArchive.Location = new System.Drawing.Point(8, 72); - this.txtMessagesArchive.Multiline = true; - this.txtMessagesArchive.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.txtMessagesArchive.Size = new System.Drawing.Size(224, 184); - this.txtMessagesArchive.Text = ""; - this.txtMessage.Location = new System.Drawing.Point(8, 8); - this.txtMessage.Size = new System.Drawing.Size(176, 20); - this.txtMessage.Text = ""; - this.cboDevices.Location = new System.Drawing.Point(8, 40); - this.cboDevices.Size = new System.Drawing.Size(224, 21); - // - // btnSend - // - this.btnSend.Location = new System.Drawing.Point(184, 8); - this.btnSend.Size = new System.Drawing.Size(48, 24); - this.btnSend.Text = "Send"; - this.Controls.Add(this.btnSend); - this.Controls.Add(this.cboDevices); - this.Controls.Add(this.txtMessage); - this.Controls.Add(this.txtMessagesArchive); - this.Menu = this.MainMenu1; - this.MinimizeBox = false; - this.Text = "Bluetooth Chat"; - } - - private void sendMessage(int NumRetries, byte[] Buffer, int BufferLen) { - BluetoothClient client = null; - int CurrentTries = 0; - for ( - ; ((client == null) - && (CurrentTries < NumRetries)); - ) { - try { - client = new BluetoothClient(); - client.Connect(new BluetoothEndPoint(((BluetoothDeviceInfo)(cboDevices.SelectedItem)).DeviceAddress, ServiceName)); - } - catch (SocketException se) { - if ((CurrentTries >= NumRetries)) { - throw se; - } - client = null; - } - CurrentTries = (CurrentTries + 1); - } - if ((client == null)) { - // timeout occurred - MsgBox("Error establishing contact"); - return; - } - System.IO.Stream stream = null; - try { - stream = client.GetStream(); - stream.Write(Buffer, 0, BufferLen); - } - catch (Exception e) { - MsgBox("Error sending"); - } - finally { - if (!(stream == null)) { - stream.Close(); - } - if (!(client == null)) { - client.Close(); - } - } - } - - private string receiveMessage(int BufferLen) { - int bytesRead = 0; - BluetoothClient client = null; - System.IO.Stream stream = null; - byte[,] Buffer; - try { - client = btListener.AcceptBluetoothClient(); - // blocking call - stream = client.GetStream(); - bytesRead = stream.Read(Buffer, 0, BufferLen); - str = (client.RemoteMachineName + ("->" - + (System.Text.Encoding.Unicode.GetString(Buffer, 0, bytesRead) + "\r\n"))); - } - catch (Exception e) { - // dont display error if we are ending the listener - if (listening) { - MsgBox("Error listening to incoming message"); - } - } - finally { - if (!(stream == null)) { - stream.Close(); - } - if (!(client == null)) { - client.Close(); - } - } - return str; - } - - private void Form1_Load(object sender, System.EventArgs e) { - // Dim s As New InTheHand.Windows.Forms.SelectBluetoothDeviceDialog() - // s.ForceAuthentication = True - // s.ShowAuthenticated = True - // s.ShowRemembered = True - // s.ShowUnknown = True - // s.ShowDialog() - System.Threading.Thread t1; - t1 = new Threading.Thread(new System.EventHandler(this.receiveLoop)); - t1.Start(); - btClient = new BluetoothClient(); - BluetoothDeviceInfo[] bdi = btClient.DiscoverDevices(); - cboDevices.DataSource = bdi; - cboDevices.DisplayMember = "DeviceName"; - } - - public void receiveLoop() { - string strReceived; - btListener = new BluetoothListener(ServiceName); - btListener.Start(); - strReceived = receiveMessage(MAX_MESSAGE_SIZE); - while (listening) { - // ---keep on listening for new message - if ((strReceived != "")) { - this.Invoke(new EventHandler(// TODO: Warning!!!! NULL EXPRESSION DETECTED... - .)); - strReceived = receiveMessage(MAX_MESSAGE_SIZE); - } - } - } - - private void UpdateTextBox(object sender, EventArgs e) { - // ---delegate to update the textbox control - txtMessagesArchive.Text = (txtMessagesArchive.Text + str); - } - - private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { - // stop receive loop - listening = false; - btListener.Stop(); - Application.Exit(); - } - - private void mnuSend_Click(object sender, System.EventArgs e) { - sendMessage(MAX_TRIES, System.Text.Encoding.Unicode.GetBytes(txtMessage.Text), (txtMessage.Text.Length * 2)); - } - - private void mnuExit_Click(object sender, System.EventArgs e) { - this.Close(); - } - - private void mnuSearch_Click(object sender, System.EventArgs e) { - Cursor.Current = Cursors.WaitCursor; - BluetoothDeviceInfo[] bdi = btClient.DiscoverDevices(); - cboDevices.DataSource = bdi; - Cursor.Current = Cursors.Default; - } - - private void btnSend_Click(object sender, System.EventArgs e) { - mnuSend_Click(sender, e); - } -} - diff --git a/BTchatVB/ChatForm.resx b/BTchatVB/ChatForm.resx deleted file mode 100644 index d84ab19..0000000 --- a/BTchatVB/ChatForm.resx +++ /dev/null @@ -1,130 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 17, 17 - - - False - - - False - - - False - - - False - - - False - - - (Default) - - - False - - - False - - - 8, 8 - - - True - - - 80 - - - ChatForm - - - True - - text/microsoft-resx2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 diff --git a/BTchatVB/ChatForm.vb b/BTchatVB/ChatForm.vb deleted file mode 100644 index caa86f4..0000000 --- a/BTchatVB/ChatForm.vb +++ /dev/null @@ -1,301 +0,0 @@ -Imports System.Net -Imports System.IO -Imports System.Net.Sockets -Imports InTheHand.Net.Sockets -Imports InTheHand.Net.Bluetooth -Imports InTheHand.Net - - - -Public Class ChatForm - Inherits System.Windows.Forms.Form - Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu - - Const MAX_MESSAGE_SIZE As Integer = 128 - Const MAX_TRIES As Integer = 3 - - Private ServiceName As New Guid("{E075D486-E23D-4887-8AF5-DAA1F6A5B172}") - - Dim btClient As New BluetoothClient - Dim btListener As BluetoothListener - - Private listening As Boolean = True - - 'holds the incoming message - Dim str As String - - - -#Region " Windows Form Designer generated code " - - Public Sub New() - MyBase.New() - - 'This call is required by the Windows Form Designer. - InitializeComponent() - - 'Add any initialization after the InitializeComponent() call - - - - End Sub - - 'Form overrides dispose to clean up the component list. - Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) - MyBase.Dispose(disposing) - End Sub - - 'NOTE: The following procedure is required by the Windows Form Designer - 'It can be modified using the Windows Form Designer. - 'Do not modify it using the code editor. - Friend WithEvents txtMessagesArchive As System.Windows.Forms.TextBox - Friend WithEvents txtMessage As System.Windows.Forms.TextBox - Friend WithEvents mnuSend As System.Windows.Forms.MenuItem - Friend WithEvents mnuMenu As System.Windows.Forms.MenuItem - Friend WithEvents mnuSearch As System.Windows.Forms.MenuItem - Friend WithEvents mnuExit As System.Windows.Forms.MenuItem - Friend WithEvents cboDevices As System.Windows.Forms.ComboBox - Friend WithEvents btnSend As System.Windows.Forms.Button - Private Sub InitializeComponent() - Me.MainMenu1 = New System.Windows.Forms.MainMenu - Me.mnuSend = New System.Windows.Forms.MenuItem - Me.mnuMenu = New System.Windows.Forms.MenuItem - Me.mnuSearch = New System.Windows.Forms.MenuItem - Me.mnuExit = New System.Windows.Forms.MenuItem - Me.txtMessagesArchive = New System.Windows.Forms.TextBox - Me.txtMessage = New System.Windows.Forms.TextBox - Me.cboDevices = New System.Windows.Forms.ComboBox - Me.btnSend = New System.Windows.Forms.Button - ' - 'MainMenu1 - ' - Me.MainMenu1.MenuItems.Add(Me.mnuSend) - Me.MainMenu1.MenuItems.Add(Me.mnuMenu) - ' - 'mnuSend - ' - Me.mnuSend.Text = "Send" - ' - 'mnuMenu - ' - Me.mnuMenu.MenuItems.Add(Me.mnuSearch) - Me.mnuMenu.MenuItems.Add(Me.mnuExit) - Me.mnuMenu.Text = "Menu" - ' - 'mnuSearch - ' - Me.mnuSearch.Text = "Search Again" - ' - 'mnuExit - ' - Me.mnuExit.Text = "Exit" - ' - 'txtMessagesArchive - ' - Me.txtMessagesArchive.Location = New System.Drawing.Point(8, 72) - Me.txtMessagesArchive.Multiline = True - Me.txtMessagesArchive.ScrollBars = System.Windows.Forms.ScrollBars.Vertical - Me.txtMessagesArchive.Size = New System.Drawing.Size(224, 184) - Me.txtMessagesArchive.Text = "" - ' - 'txtMessage - ' - Me.txtMessage.Location = New System.Drawing.Point(8, 8) - Me.txtMessage.Size = New System.Drawing.Size(176, 20) - Me.txtMessage.Text = "" - ' - 'cboDevices - ' - Me.cboDevices.Location = New System.Drawing.Point(8, 40) - Me.cboDevices.Size = New System.Drawing.Size(224, 21) - ' - 'btnSend - ' - Me.btnSend.Location = New System.Drawing.Point(184, 8) - Me.btnSend.Size = New System.Drawing.Size(48, 24) - Me.btnSend.Text = "Send" - ' - 'ChatForm - ' - Me.Controls.Add(Me.btnSend) - Me.Controls.Add(Me.cboDevices) - Me.Controls.Add(Me.txtMessage) - Me.Controls.Add(Me.txtMessagesArchive) - Me.Menu = Me.MainMenu1 - Me.MinimizeBox = False - Me.Text = "Bluetooth Chat" - - End Sub - -#End Region - - - Private Sub sendMessage(ByVal NumRetries As Integer, _ - ByVal Buffer() As Byte, _ - ByVal BufferLen As Integer) - - - Dim client As BluetoothClient = Nothing - Dim CurrentTries As Integer = 0 - Do - Try - client = New BluetoothClient - client.Connect(New BluetoothEndPoint(CType(cboDevices.SelectedItem, BluetoothDeviceInfo).DeviceAddress, ServiceName)) - - - Catch se As SocketException - If (CurrentTries >= NumRetries) Then - Throw se - End If - client = Nothing - End Try - CurrentTries = CurrentTries + 1 - - Loop While client Is Nothing And _ - CurrentTries < NumRetries - - If (client Is Nothing) Then - 'timeout occurred - MsgBox("Error establishing contact") - Return - End If - - Dim stream As System.IO.Stream = Nothing - Try - stream = client.GetStream() - stream.Write(Buffer, 0, BufferLen) - Catch e As Exception - MsgBox("Error sending") - Finally - If (Not stream Is Nothing) Then - stream.Close() - End If - If (Not client Is Nothing) Then - client.Close() - End If - End Try - End Sub - - Private Function receiveMessage(ByVal BufferLen As Integer) _ - As String - Dim bytesRead As Integer = 0 - Dim client As BluetoothClient = Nothing - Dim stream As System.IO.Stream = Nothing - Dim Buffer(MAX_MESSAGE_SIZE) As Byte - - Try - - client = btListener.AcceptBluetoothClient() ' blocking call - stream = client.GetStream() - bytesRead = stream.Read(Buffer, 0, BufferLen) - - str = client.RemoteMachineName + "->" + _ - System.Text.Encoding.Unicode.GetString(Buffer, 0, bytesRead) + vbCrLf - - Catch e As Exception - 'dont display error if we are ending the listener - If listening Then - MsgBox("Error listening to incoming message") - End If - - Finally - If (Not stream Is Nothing) Then - stream.Close() - End If - If (Not client Is Nothing) Then - client.Close() - End If - - End Try - Return str - End Function - - Private Sub Form1_Load(ByVal sender As System.Object, _ - ByVal e As System.EventArgs) _ - Handles MyBase.Load - - 'Dim s As New InTheHand.Windows.Forms.SelectBluetoothDeviceDialog() - 's.ForceAuthentication = True - 's.ShowAuthenticated = True - 's.ShowRemembered = True - 's.ShowUnknown = True - 's.ShowDialog() - - - Dim t1 As System.Threading.Thread - t1 = New Threading.Thread(AddressOf receiveLoop) - t1.Start() - - btClient = New BluetoothClient - - - Dim bdi As BluetoothDeviceInfo() = btClient.DiscoverDevices() - - - cboDevices.DataSource = bdi - cboDevices.DisplayMember = "DeviceName" - - - End Sub - - Public Sub receiveLoop() - Dim strReceived As String - btListener = New BluetoothListener(ServiceName) - btListener.Start() - - strReceived = receiveMessage(MAX_MESSAGE_SIZE) - While listening '---keep on listening for new message - If strReceived <> "" Then - Me.Invoke(New EventHandler(AddressOf UpdateTextBox)) - - strReceived = receiveMessage(MAX_MESSAGE_SIZE) - End If - End While - - End Sub - - - Private Sub UpdateTextBox(ByVal sender As Object, ByVal e As EventArgs) - '---delegate to update the textbox control - txtMessagesArchive.Text += str - End Sub - - Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing - - 'stop receive loop - listening = False - 'stop listening service - btListener.Stop() - - Application.Exit() - - - End Sub - - Private Sub mnuSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSend.Click - - sendMessage(MAX_TRIES, _ - System.Text.Encoding.Unicode.GetBytes(txtMessage.Text), _ - txtMessage.Text.Length * 2) - - End Sub - - Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click - Me.Close() - End Sub - - Private Sub mnuSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSearch.Click - - Cursor.Current = Cursors.WaitCursor - - Dim bdi As BluetoothDeviceInfo() = btClient.DiscoverDevices() - cboDevices.DataSource = bdi - - Cursor.Current = Cursors.Default - - End Sub - - Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click - mnuSend_Click(sender, e) - End Sub -End Class diff --git a/BitImageTest/BitImageTest.sln b/BitImageTest/BitImageTest.sln deleted file mode 100644 index 1f22449..0000000 --- a/BitImageTest/BitImageTest.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BitImageTest", "BitImageTest\BitImageTest.csproj", "{0D314DB1-B142-49C4-A37F-F74D9087FA64}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BitImageTestCF", "BitImageTestCF\BitImageTestCF.csproj", "{94B436A4-89D4-452E-8622-F24EF33FA12F}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {0D314DB1-B142-49C4-A37F-F74D9087FA64}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0D314DB1-B142-49C4-A37F-F74D9087FA64}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0D314DB1-B142-49C4-A37F-F74D9087FA64}.Release|Any CPU.Build.0 = Release|Any CPU - {94B436A4-89D4-452E-8622-F24EF33FA12F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {94B436A4-89D4-452E-8622-F24EF33FA12F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {94B436A4-89D4-452E-8622-F24EF33FA12F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {94B436A4-89D4-452E-8622-F24EF33FA12F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {94B436A4-89D4-452E-8622-F24EF33FA12F}.Release|Any CPU.Build.0 = Release|Any CPU - {94B436A4-89D4-452E-8622-F24EF33FA12F}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/BitImageTest/BitImageTest.suo b/BitImageTest/BitImageTest.suo deleted file mode 100644 index 5708a48..0000000 Binary files a/BitImageTest/BitImageTest.suo and /dev/null differ diff --git a/BitImageTest/BitImageTest.userprefs b/BitImageTest/BitImageTest.userprefs deleted file mode 100644 index e3b3caf..0000000 --- a/BitImageTest/BitImageTest.userprefs +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/BitImageTest/BitImageTest/AsciiControlChars.cs b/BitImageTest/BitImageTest/AsciiControlChars.cs deleted file mode 100644 index 701d9d2..0000000 --- a/BitImageTest/BitImageTest/AsciiControlChars.cs +++ /dev/null @@ -1,67 +0,0 @@ -namespace BitImageTest -{ - /// - /// A listing of ASCII control characters for readability. - /// - public static class AsciiControlChars - { - /// - /// Usually indicates the end of a string. - /// - public const char Nul = (char)0x00; - - /// - /// Meant to be used for printers. When receiving this code the - /// printer moves to the next sheet of paper. - /// - public const char FormFeed = (char)0x0C; - - /// - /// Starts an extended sequence of control codes. - /// - public const char Escape = (char)0x1B; - - /// - /// Advances to the next line. - /// - public const char Newline = (char)0x0A; - - /// - /// Defined to separate tables or different sets of data in a serial - /// data storage system. - /// - public const char GroupSeparator = (char)0x1D; - - /// - /// A horizontal tab. - /// - public const char HorizontalTab = (char)0x09; - - /// - /// Returns the carriage to the start of the line. - /// - public const char CarriageReturn = (char)0x0D; - - /// - /// Cancels the operation. - /// - public const char Cancel = (char)0x18; - - /// - /// Indicates that control characters present in the stream should - /// be passed through as transmitted and not interpreted as control - /// characters. - /// - public const char DataLinkEscape = (char)0x10; - - /// - /// Signals the end of a transmission. - /// - public const char EndOfTransmission = (char)0x04; - - /// - /// In serial storage, signals the separation of two files. - /// - public const char FileSeparator = (char)0x1C; - } -} \ No newline at end of file diff --git a/BitImageTest/BitImageTest/BitImageTest.csproj b/BitImageTest/BitImageTest/BitImageTest.csproj deleted file mode 100644 index 29a22bb..0000000 --- a/BitImageTest/BitImageTest/BitImageTest.csproj +++ /dev/null @@ -1,69 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {0D314DB1-B142-49C4-A37F-F74D9087FA64} - Exe - Properties - BitImageTest - BitImageTest - v3.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE;MONODEV - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - 3.5 - - - - 3.5 - - - 3.5 - - - - - - - - - - - - - - PreserveNewest - - - - - - \ No newline at end of file diff --git a/BitImageTest/BitImageTest/NativeMethods.cs b/BitImageTest/BitImageTest/NativeMethods.cs deleted file mode 100644 index 1ddd5b5..0000000 --- a/BitImageTest/BitImageTest/NativeMethods.cs +++ /dev/null @@ -1,474 +0,0 @@ -// -// Copyright (c) 2009 by Skiviez, Inc. All rights reserved. -// - -namespace BitImageTest -{ - using System; - using System.Runtime.InteropServices; - - /// - /// Contains native methods invoked via P/Invoke to the underlying Windows - /// operating system. Only supported on NT platforms. - /// - internal static class NativeMethods - { - /// - /// An enumeration of GetDeviceCaps parameters. - /// - internal enum DeviceCap : int - { - /// - /// Device driver version - /// - DRIVERVERSION = 0, - - /// - /// Device classification - /// - TECHNOLOGY = 2, - - /// - /// Horizontal size in millimeters - /// - HORZSIZE = 4, - - /// - /// Vertical size in millimeters - /// - VERTSIZE = 6, - - /// - /// Horizontal width in pixels - /// - HORZRES = 8, - - /// - /// Vertical height in pixels - /// - VERTRES = 10, - - /// - /// Number of bits per pixel - /// - BITSPIXEL = 12, - - /// - /// Number of planes - /// - PLANES = 14, - - /// - /// Number of brushes the device has - /// - NUMBRUSHES = 16, - - /// - /// Number of pens the device has - /// - NUMPENS = 18, - - /// - /// Number of markers the device has - /// - NUMMARKERS = 20, - - /// - /// Number of fonts the device has - /// - NUMFONTS = 22, - - /// - /// Number of colors the device supports - /// - NUMCOLORS = 24, - - /// - /// Size required for device descriptor - /// - PDEVICESIZE = 26, - - /// - /// Curve capabilities - /// - CURVECAPS = 28, - - /// - /// Line capabilities - /// - LINECAPS = 30, - - /// - /// Polygonal capabilities - /// - POLYGONALCAPS = 32, - - /// - /// Text capabilities - /// - TEXTCAPS = 34, - - /// - /// Clipping capabilities - /// - CLIPCAPS = 36, - - /// - /// Bitblt capabilities - /// - RASTERCAPS = 38, - - /// - /// Length of the X leg - /// - ASPECTX = 40, - - /// - /// Length of the Y leg - /// - ASPECTY = 42, - - /// - /// Length of the hypotenuse - /// - ASPECTXY = 44, - - /// - /// Shading and Blending caps - /// - SHADEBLENDCAPS = 45, - - /// - /// Logical pixels inch in X - /// - LOGPIXELSX = 88, - - /// - /// Logical pixels inch in Y - /// - LOGPIXELSY = 90, - - /// - /// Number of entries in physical palette - /// - SIZEPALETTE = 104, - - /// - /// Number of reserved entries in palette - /// - NUMRESERVED = 106, - - /// - /// Actual color resolution - /// - COLORRES = 108, - - /// - /// Physical Width in device units - /// - PHYSICALWIDTH = 110, - - /// - /// Physical Height in device units - /// - PHYSICALHEIGHT = 111, - - /// - /// Physical Printable Area x margin - /// - PHYSICALOFFSETX = 112, - - /// - /// Physical Printable Area y margin - /// - PHYSICALOFFSETY = 113, - - /// - /// Scaling factor x - /// - SCALINGFACTORX = 114, - - /// - /// Scaling factor y - /// - SCALINGFACTORY = 115, - - /// - /// Current vertical refresh rate of the display device (for displays only) in Hz - /// - VREFRESH = 116, - - /// - /// Horizontal width of entire desktop in pixels - /// - DESKTOPVERTRES = 117, - - /// - /// Vertical height of entire desktop in pixels - /// - DESKTOPHORZRES = 118, - - /// - /// Preferred blt alignment - /// - BLTALIGNMENT = 119 - } - - /// - /// The CreateDC function creates a device context (DC) for a device - /// using the specified name. - /// - /// Pointer to a null-terminated character - /// string that specifies either DISPLAY or the name of a specific - /// display device or the name of a print provider, which is usually WINSPOOL. - /// Pointer to a null-terminated character string - /// that specifies the name of the specific output device being used, - /// as shown by the Print Manager (for example, Epson FX-80). It is not - /// the printer model name. The lpszDevice parameter must be used. - /// This parameter is ignored and should be set - /// to NULL. It is provided only for compatibility with 16-bit Windows. - /// Pointer to a DEVMODE structure containing - /// device-specific initialization data for the device driver. The - /// DocumentProperties function retrieves this structure filled in for - /// a specified device. The lpInitData parameter must be NULL if the - /// device driver is to use the default initialization (if any) specified - /// by the user. - /// If the function succeeds, the return value is the handle - /// to a DC for the specified device. If the function fails, the - /// return value is NULL. The function will return NULL for a DEVMODE - /// structure other than the current DEVMODE. - [DllImport("gdi32.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CreateDC( - string lpszDriver, - string lpszDevice, - string lpszOutput, - IntPtr lpInitData); - - /// - /// The DeleteDC function deletes the specified device context (DC). - /// - /// Handle to the device context. - /// If the function succeeds, the return value is nonzero. - /// If the function fails, the return value is zero. - [DllImport("gdi32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool DeleteDC(IntPtr hdc); - - [DllImport( - "winspool.drv", - EntryPoint = "OpenPrinterW", - SetLastError = true, - CharSet = CharSet.Unicode, - ExactSpelling = true, - CallingConvention = CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool OpenPrinter( - [MarshalAs(UnmanagedType.LPWStr)] string szPrinter, - out IntPtr hPrinter, - IntPtr pd); - - /// - /// Closes the specified printer object. - /// - /// Handle to the printer object to be closed. - /// This handle is returned by the OpenPrinter or AddPrinter function. - /// If the function succeeds, the return value is a nonzero value. - /// If the function fails, the return value is zero - [DllImport( - "winspool.drv", - EntryPoint = "ClosePrinter", - SetLastError = true, - ExactSpelling = true, - CallingConvention = CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool ClosePrinter(IntPtr hPrinter); - - /// - /// The StartDoc function starts a print job. - /// - /// Handle to the device context for the print job. - /// Pointer to a DOCINFO structure containing the name - /// of the document file and the name of the output file. - /// If the function succeeds, the return value is greater than - /// zero. This value is the print job identifier for the document. - [DllImport("gdi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern int StartDoc(IntPtr hdc, DOCINFO lpdi); - - /// - /// The EndDoc function ends a print job. - /// - /// Handle to the device context for the print job. - /// If the function succeeds, the return value is greater than zero. - /// If the function fails, the return value is less than or equal - /// to zero. - [DllImport("gdi32.dll")] - internal static extern int EndDoc(IntPtr hdc); - - /// - /// The GetDeviceCaps function retrieves device-specific information - /// for the specified device. - /// - /// Handle to the DC. - /// Specifies the item to return. - /// The return value specifies the value of the desired item. - [DllImport("gdi32.dll")] - internal static extern int GetDeviceCaps(IntPtr hdc, DeviceCap capindex); - - /// - /// The StartPage function prepares the printer driver to accept data. - /// - /// Handle to the device context for the print job. - /// If the function succeeds, the return value is greater than zero. - /// If the function fails, the return value is less than or equal to zero. - [DllImport("gdi32.dll")] - internal static extern int StartPage(IntPtr hdc); - - /// - /// The EndPage function notifies the device that the application has - /// finished writing to a page. This function is typically used to - /// direct the device driver to advance to a new page. - /// - /// Handle to the device context for the print job. - /// If the function succeeds, the return value is greater than zero. - /// If the function fails, the return value is less than or equal to zero. - [DllImport("gdi32.dll")] - internal static extern int EndPage(IntPtr hdc); - - /// - /// The StartDocPrinter function notifies the print spooler - /// that a document is to be spooled for printing. - /// - /// Handle to the printer. Use the OpenPrinter or - /// AddPrinter function to retrieve a printer handle. - /// Specifies the version of the structure to - /// which pDocInfo points. On WIndows NT/2000/XP, the value must be 1. - /// Pointer to a structure that describes the document to print. - /// If the function succeeds, the return value identifies the print job. - /// If the function fails, the return value is zero. - [DllImport( - "winspool.drv", - EntryPoint = "StartDocPrinterW", - SetLastError = true, - CharSet = CharSet.Unicode, - ExactSpelling = true, - CallingConvention = CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool StartDocPrinter( - IntPtr hPrinter, - int level, - [In, MarshalAs(UnmanagedType.LPStruct)] DOC_INFO_1 di); - - [DllImport( - "winspool.drv", - EntryPoint = "EndDocPrinter", - SetLastError = true, - ExactSpelling = true, - CallingConvention = CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool EndDocPrinter(IntPtr hPrinter); - - [DllImport( - "winspool.drv", - EntryPoint = "StartPagePrinter", - SetLastError = true, - ExactSpelling = true, - CallingConvention = CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool StartPagePrinter(IntPtr hPrinter); - - [DllImport( - "winspool.drv", - EntryPoint = "EndPagePrinter", - SetLastError = true, - ExactSpelling = true, - CallingConvention = CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool EndPagePrinter(IntPtr hPrinter); - - [DllImport( - "winspool.drv", - EntryPoint = "WritePrinter", - SetLastError = true, - ExactSpelling = true, - CallingConvention = CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool WritePrinter( - IntPtr hPrinter, - IntPtr pBytes, - int dwCount, - out int dwWritten); - - /// - /// The DOCINFO structure contains the input and output file names and - /// other information used by the StartDoc function. - /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal class DOCINFO - { - /// - /// The size, in bytes, of the structure. - /// - public int cbSize = 20; - - /// - /// Pointer to a null-terminated string that specifies the name - /// of the document. - /// - [MarshalAs(UnmanagedType.LPWStr)] - public string lpszDocName; - - /// - /// Pointer to a null-terminated string that specifies the name of - /// an output file. If this pointer is NULL, the output will be - /// sent to the device identified by the device context handle that - /// was passed to the StartDoc function. - /// - [MarshalAs(UnmanagedType.LPWStr)] - public string lpszOutput; - - /// - /// Pointer to a null-terminated string that specifies the type of - /// data used to record the print job. The legal values for this - /// member can be found by calling EnumPrintProcessorDatatypes and - /// can include such values as raw, emf, or XPS_PASS. This member - /// can be NULL. Note that the requested data type might be ignored. - /// - [MarshalAs(UnmanagedType.LPWStr)] - public string lpszDatatype; - - /// - /// Specifies additional information about the print job. This - /// member must be zero or one of the following values. - /// - public int fwType; - } - - /// - /// The DOC_INFO_1 structure describes a document that will be printed. - /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal class DOC_INFO_1 - { - /// - /// Pointer to a null-terminated string that specifies the name of - /// the document. - /// - [MarshalAs(UnmanagedType.LPWStr)] - public string pDocName; - - /// - /// Pointer to a null-terminated string that specifies the name of - /// an output file. To print to a printer, set this to NULL. - /// - [MarshalAs(UnmanagedType.LPWStr)] - public string pOutputFile; - - /// - /// Pointer to a null-terminated string that identifies the type - /// of data used to record the document. - /// - [MarshalAs(UnmanagedType.LPWStr)] - public string pDataType; - } - } -} diff --git a/BitImageTest/BitImageTest/Program.cs b/BitImageTest/BitImageTest/Program.cs deleted file mode 100644 index c719c0c..0000000 --- a/BitImageTest/BitImageTest/Program.cs +++ /dev/null @@ -1,279 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Runtime.InteropServices; -using System.ComponentModel; -using System.Collections; -using System.Drawing; -using System.IO; - -namespace BitImageTest -{ - public class Program - { - private const string PrinterName = @"\\ASHWHWS004\EPSON TM-T88III Receipt"; - - private class BitmapData - { - public BitArray Dots - { - get; - set; - } - - public int Height - { - get; - set; - } - - public int Width - { - get; - set; - } - } - - public static void Main(string[] args) - { - Print(PrinterName, GetDocument()); - } - - private static BitmapData GetBitmapData(string bmpFileName) - { - using (var bitmap = (Bitmap)Bitmap.FromFile(bmpFileName)) - { - var threshold = 127; - var index = 0; - var dimensions = bitmap.Width * bitmap.Height; - var dots = new BitArray(dimensions); - - for (var y = 0; y < bitmap.Height; y++) - { - for (var x = 0; x < bitmap.Width; x++) - { - var color = bitmap.GetPixel(x, y); - var luminance = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11); - dots[index] = (luminance < threshold); - index++; - } - } - - return new BitmapData() - { - Dots = dots, - Height = bitmap.Height, - Width = bitmap.Width - }; - } - } - - private static byte[] GetDocument() - { - using (var ms = new MemoryStream()) - using (var bw = new BinaryWriter(ms)) - { - // Reset the printer bws (NV images are not cleared) - bw.Write(AsciiControlChars.Escape); - bw.Write('@'); - - // Render the logo - RenderLogo(bw); - - // Feed 3 vertical motion units and cut the paper with a 1 point cut - bw.Write(AsciiControlChars.GroupSeparator); - bw.Write('V'); - bw.Write((byte)66); - bw.Write((byte)3); - - bw.Flush(); - - return ms.ToArray(); - } - } - - private static void RenderLogo(BinaryWriter bw) - { - var data = GetBitmapData("RM-Logo.bmp"); - var dots = data.Dots; - var width = BitConverter.GetBytes(data.Width); - - bw.Write(AsciiControlChars.Newline); - bw.Write("CASE 1"); - bw.Write(AsciiControlChars.Newline); - - bw.Write(AsciiControlChars.Escape); - bw.Write('*'); // bit-image mode - bw.Write((byte)0); // 8-dot single-density - bw.Write((byte)5); // width low byte - bw.Write((byte)0); // width high byte - bw.Write((byte)128); - bw.Write((byte)64); - bw.Write((byte)32); - bw.Write((byte)16); - bw.Write((byte)8); - - bw.Write(AsciiControlChars.Newline); - bw.Write("CASE 2"); - bw.Write(AsciiControlChars.Newline); - - bw.Write(AsciiControlChars.Escape); - bw.Write('*'); // bit-image mode - bw.Write((byte)0); // 8-dot single-density - bw.Write((byte)5); // width low byte - bw.Write((byte)0); // width high byte - bw.Write((byte)1); - bw.Write((byte)2); - bw.Write((byte)4); - bw.Write((byte)8); - bw.Write((byte)16); - - bw.Write(AsciiControlChars.Newline); - - - bw.Write(AsciiControlChars.Newline); - bw.Write("CASE 3"); - bw.Write(AsciiControlChars.Newline); - - // So we have our bitmap data sitting in a bit array called "dots." - // This is one long array of 1s (black) and 0s (white) pixels arranged - // as if we had scanned the bitmap from top to bottom, left to right. - // The printer wants to see these arranged in bytes stacked three high. - // So, essentially, we need to read 24 bits for x = 0, generate those - // bytes, and send them to the printer, then keep increasing x. If our - // image is more than 24 dots high, we have to send a second bit image - // command. - - // Set the line spacing to 24 dots, the height of each "stripe" of the - // image that we're drawing. - bw.Write(AsciiControlChars.Escape); - bw.Write('3'); - bw.Write((byte)24); - - // OK. So, starting from x = 0, read 24 bits down and send that data - // to the printer. - int offset = 0; - - while (offset < data.Height) - { - bw.Write(AsciiControlChars.Escape); - bw.Write('*'); // bit-image mode - bw.Write((byte)33); // 24-dot double-density - bw.Write(width[0]); // width low byte - bw.Write(width[1]); // width high byte - - for (int x = 0; x < data.Width; ++x) - { - for (int k = 0; k < 3; ++k) - { - byte slice = 0; - -/* -We have our working copy of a byte that we’re munging with in a variable - called ‘slice’. I have a Boolean named ‘v’ that tells me if I want to - shove a 1 or a zero into this byte. So if v is true, I take the - integer 1 and shift it (7 – b) units to the left. (I think in Delphi this - is ‘Shl’?) If it’s a zero, well, I don’t have to do anything actually - but there is not harm in “shifting zero” in a one-liner. Then I - bitwise OR my shifted integer with the ‘slice’. - -So if ‘slice’ looked like ’01000000′ and I’m working on b = 3, -then I take ’00000001′, shift it to the left (7 – 3) == 4 places -to get ’00010000′, and then I OR that number (’00010000′) with -the slice (’01000000′) to get ’01010000′. And then I keep on -trucking. (If it was zero, I would have shifted zero and then OR it -with the slice, effectively doing nothing.) -*/ - for (int b = 0; b < 8; ++b) - { - int y = (((offset / 8) + k) * 8) + b; - - // Calculate the location of the pixel we want in the bit array. - // It'll be at (y * width) + x. - int i = (y * data.Width) + x; - - // If the image is shorter than 24 dots, pad with zero. - bool v = false; - if (i < dots.Length) - { - v = dots[i]; - } - - slice |= (byte)((v ? 1 : 0) << (7 - b)); - } - - bw.Write(slice); - } - } - - offset += 24; - bw.Write(AsciiControlChars.Newline); - } - - // Restore the line spacing to the default of 30 dots. - bw.Write(AsciiControlChars.Escape); - bw.Write('3'); - bw.Write((byte)30); - } - - private static void Print(string printerName, byte[] document) - { -#if !MONODEV - NativeMethods.DOC_INFO_1 documentInfo; - IntPtr printerHandle; - - documentInfo = new NativeMethods.DOC_INFO_1(); - documentInfo.pDataType = "RAW"; - documentInfo.pDocName = "Bit Image Test"; - - printerHandle = new IntPtr(0); - - if (NativeMethods.OpenPrinter(printerName.Normalize(), out printerHandle, IntPtr.Zero)) - { - if (NativeMethods.StartDocPrinter(printerHandle, 1, documentInfo)) - { - int bytesWritten; - byte[] managedData; - IntPtr unmanagedData; - - managedData = document; - unmanagedData = Marshal.AllocCoTaskMem(managedData.Length); - Marshal.Copy(managedData, 0, unmanagedData, managedData.Length); - - if (NativeMethods.StartPagePrinter(printerHandle)) - { - NativeMethods.WritePrinter( - printerHandle, - unmanagedData, - managedData.Length, - out bytesWritten); - NativeMethods.EndPagePrinter(printerHandle); - } - else - { - throw new Win32Exception(); - } - - Marshal.FreeCoTaskMem(unmanagedData); - - NativeMethods.EndDocPrinter(printerHandle); - } - else - { - throw new Win32Exception(); - } - - NativeMethods.ClosePrinter(printerHandle); - } - else - { - throw new Win32Exception(); - } -#else - Console.WriteLine(tools.tools.ByteAr2HexStr(document)); - Console.WriteLine(tools.tools.ByteAr2BinStr(document)); -#endif - } - } -} diff --git a/BitImageTest/BitImageTest/Properties/AssemblyInfo.cs b/BitImageTest/BitImageTest/Properties/AssemblyInfo.cs deleted file mode 100644 index 4356a52..0000000 --- a/BitImageTest/BitImageTest/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("BitImageTest")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("BitImageTest")] -[assembly: AssemblyCopyright("Copyright © 2009")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("e788b4e6-b9b7-4c4e-8ebc-8da7da37340e")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/BitImageTest/BitImageTest/RM-Logo.bmp b/BitImageTest/BitImageTest/RM-Logo.bmp deleted file mode 100644 index 17863a3..0000000 Binary files a/BitImageTest/BitImageTest/RM-Logo.bmp and /dev/null differ diff --git a/BitImageTest/BitImageTest/tools.cs b/BitImageTest/BitImageTest/tools.cs deleted file mode 100644 index 85f3c56..0000000 --- a/BitImageTest/BitImageTest/tools.cs +++ /dev/null @@ -1,350 +0,0 @@ -using System; -using System.IO; -using System.Collections; -using System.Collections.Generic; -//using System.Windows.Forms; - -namespace tools -{ - public class tools - { - public static string ByteAr2HexStr(byte[] b){ - string s=""; - foreach (byte b1 in b){ - s+=b1.ToString("x"); - } - return s; - } - static int iByteGroup=3; - static int iByteCount=1; - public static string ByteAr2BinStr(byte[] b){ - string s=""; - - foreach(byte b1 in b){ - iByteCount++; - s += Byte2DotStr(b1); - //s += Byte2BinStr(b1); - if(iByteCount>iByteGroup){ - s += "\r\n"; - iByteCount=1; - } - } - - return s; - } - public static string Byte2BinStr(byte b) - { - int maxbits = 8; - byte b8 = b; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (b8 >= Math.Pow(2, i-1)) - { - s = "1" + s; - b8 -= (byte)Math.Pow(2, i-1); - } - else - s = "0" + s; - } - s.PadRight(8, '0'); - return s; - } - public static string Byte2DotStr(byte b) - { - int maxbits = 8; - byte b8 = b; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (b8 >= Math.Pow(2, i-1)) - { - s = "." + s; - b8 -= (byte)Math.Pow(2, i-1); - } - else - s = " " + s; - } - s.PadRight(8, ' '); - return s; - } - public static string ReverseString(string s) - { - int i = 0; - string str=""; - for (i = s.Length-1; i >= 0; i--) - { - str = str + s.Substring(i, 1); - } - return str; - } - - /// - /// Copy a string until a \r appears - /// - /// input string - /// string cutdown to \r - public static string CopyToR(string s) - { - int i = 0; - string t = ""; - while (s.Substring(i, 1) != "\r") - { - t += s.Substring(i, 1); - i++; - } - return t; - } - /// - /// C# to convert a string to a byte array. - /// - /// - /// sbyte[] - public static sbyte[] StrToSByteArray(string str) - { - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - byte[] src = new byte[str.Length]; - sbyte[] dest = new sbyte[src.Length]; - src = encoding.GetBytes(str); - System.Buffer.BlockCopy(src, 0, dest, 0, src.Length); - return dest; - } - - -#region NewStuff - //=============================================================================================== - // New stuff - //=============================================================================================== - - /// - /// takes a string of 0s and 1s and returns a uint - /// - /// a 'binary' string of 0s and 1s - /// - public static UInt32 BinStr2Uint(string s) - { - int maxbits = s.Length; - int i; - UInt32 u=0; - //s[s.lenghth] = Bit[0] - //start at end of string, highest bit - for (i = 0; i < maxbits ; i++) - { - if (s.Substring( i, 1).Equals("1")) - { - u += (uint)Math.Pow(2, i); - } - } - return u; - } - - /// - /// convert an uint to a BinStr - /// - /// - /// a BinStr of 0s and 1s, lowest bit left - public static string Uint2BinStr(UInt32 u) - { - int maxbits = 32; - UInt32 u32 = u; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (u32 >= Math.Pow(2, i-1)) - { - s = "1" + s; - u32 -= (UInt32)Math.Pow(2, i-1); - } - else - s = "0" + s; - } - s.PadRight(32, '0'); - return s; - } - - /// - /// get binary string in reverse order - /// - /// - /// - /// - public static string Uint2BinStr(UInt32 u, int bitcount) - { - //49977473 -> //10111110101001100010000001 - //123456789 -> 00000111010110111100110100010101 - // "00000111 01011011 11001101 00010101 - // " - string s = Uint2BinStr(u); - if (s.Length > bitcount) - { - s = s.Substring(0, bitcount); - } - else if (s.Length < bitcount) - s = s.PadRight(bitcount, '0'); - return s; - } - - /// - /// Convert a BinStr ie '01010011' to a hex string '53'hex - /// - /// - /// a hex str - public static string BinStr2HexStr(string BinStr) - { - //convert byte by byte - string sHex2=""; - string sBin8=""; - string sHex=""; - string sBin = BinStr; - byte b = 0; - //ensure a binstr dividable by 8 - if (sBin.Length % 8 > 0) //is there any rest? - { - int l = sBin.Length; - int c = l / 8; - c++; - c = c * 8; - l = c - l; - for (int i = 0; i < l; i++) - sBin = sBin + "0"; - } - //start at lowest bit - while (sBin.Length > 0) - { - sBin8 = sBin.Substring(0, 8); //01010011 - b = (byte)BinStr2Uint(sBin); - sHex2 = Convert.ToString(b, 16); //0x53 - sHex = sHex2.PadLeft(2,'0') + sHex ; - sBin = sBin.Substring(8); - } - return sHex; - } - /// - /// convert a BinStr to a Hex string - /// - /// - /// the Byte width, ie 12 means you get a string with 24 letters - /// each byte is translated to a two-letter hex str - /// - public static string BinStr2HexStr(string BinStr, int ByteWidth) - { - string HexStr = BinStr2HexStr(BinStr); - if (HexStr.Length < ByteWidth) //pad left with '0' - HexStr = HexStr.PadLeft(ByteWidth*2, '0'); - else if (HexStr.Length > ByteWidth) //return right part, cut left - HexStr = HexStr.Substring(HexStr.Length - (ByteWidth * 2), ByteWidth * 2); - return HexStr; - } - - public static char[] HexStr2CharAr(string sHex) - { - char[] c; - string sBin = ""; - sBin = HexStr2BinStr(sHex); - c=BinStr2CharAr(sBin); - return c; - } - - public static string CharAr2HexStr(char[] c) - { - string s = ""; - string sBin = ""; - sBin = CharAr2BinStr(c); - s = BinStr2HexStr(sBin); - return s; - } - - public static string HexStr2BinStr(string hex) - { - byte b; - string BinStr = ""; - string sBin8 = ""; - string hex2 = ""; - if (hex.Length == 24) - { - //from left to right //34 ....... - for (int i = 0; i < 12; i++) - { //0-1-2-3-4- 5- 6- 7- 8- 9-10-11 - hex2 = hex.Substring(i*2, 2);//start at right, 0-2-4-6-8-10-12-14-16-18-20-22 - b = Convert.ToByte(hex2, 16); - sBin8 = Uint2BinStr(b).Substring(0,8); - BinStr = sBin8 + BinStr ; - } - } - else{ - //is this a even number of chars? - if(hex.Length % 2 > 0) - hex="0"+hex; //add a zero in front - //from left to right //34 ....... - for (int i = 0; i < hex.Length/2; i++) - { //0-1-2-3-4- 5- 6- 7- 8- 9-10-11 - hex2 = hex.Substring(i*2, 2);//start at right, 0-2-4-6-8-10-12-14-16-18-20-22 - b = Convert.ToByte(hex2, 16); - sBin8 = Uint2BinStr(b).Substring(0,8); - BinStr = sBin8 + BinStr ; - } - - } - if (!BinStr2HexStr(BinStr).Equals(hex.ToLower())) - System.Diagnostics.Debugger.Break(); - return BinStr; - } - - /// - /// convert a BinStr to a char[] array - /// - /// - /// - public static char[] BinStr2CharAr(string BinStr) - { - int bitcount = BinStr.Length; - if (BinStr.Length > 96) - BinStr = BinStr.Substring(0,96);//limit bitcount to 96 - else if (BinStr.Length < 96) - BinStr = BinStr.PadRight(96, '0'); - - char[] c = new char[96]; - for (int i = 0; i < 96; i++) - { - if (BinStr.Substring(i, 1).Equals("1")) - c[i] = '1'; - else - c[i] = '0'; - } - return c; - } - /// - /// convert a char[] to BinStr (substr(0,1)=char[0] - /// BinStr highest Bit at RIGHT! - /// - /// - /// - public static string CharAr2BinStr(char[] c) - { - int bitcount = c.Length; - string s = ""; - for (int i = 0; i < bitcount; i++) - { - if (c[i] == '1') - s = s + "1"; - else - s = s + "0"; - } - if (s.Length < 96) - s.PadRight(96, '0'); - else if (s.Length > 96) - s = s.Substring(0, 96); - return s; - } -#endregion - } -} \ No newline at end of file diff --git a/BitImageTest/BitImageTestCF/AsciiControlChars.cs b/BitImageTest/BitImageTestCF/AsciiControlChars.cs deleted file mode 100644 index ce9d871..0000000 --- a/BitImageTest/BitImageTestCF/AsciiControlChars.cs +++ /dev/null @@ -1,67 +0,0 @@ -namespace ASCIIhelper -{ - /// - /// A listing of ASCII control characters for readability. - /// - public static class AsciiControlChars - { - /// - /// Usually indicates the end of a string. - /// - public const char Nul = (char)0x00; - - /// - /// Meant to be used for printers. When receiving this code the - /// printer moves to the next sheet of paper. - /// - public const char FormFeed = (char)0x0C; - - /// - /// Starts an extended sequence of control codes. - /// - public const char Escape = (char)0x1B; - - /// - /// Advances to the next line. - /// - public const char Newline = (char)0x0A; - - /// - /// Defined to separate tables or different sets of data in a serial - /// data storage system. - /// - public const char GroupSeparator = (char)0x1D; - - /// - /// A horizontal tab. - /// - public const char HorizontalTab = (char)0x09; - - /// - /// Returns the carriage to the start of the line. - /// - public const char CarriageReturn = (char)0x0D; - - /// - /// Cancels the operation. - /// - public const char Cancel = (char)0x18; - - /// - /// Indicates that control characters present in the stream should - /// be passed through as transmitted and not interpreted as control - /// characters. - /// - public const char DataLinkEscape = (char)0x10; - - /// - /// Signals the end of a transmission. - /// - public const char EndOfTransmission = (char)0x04; - - /// - /// In serial storage, signals the separation of two files. - /// - public const char FileSeparator = (char)0x1C; - } -} \ No newline at end of file diff --git a/BitImageTest/BitImageTestCF/BitImageTestCF.csproj b/BitImageTest/BitImageTestCF/BitImageTestCF.csproj deleted file mode 100644 index e8b7d21..0000000 --- a/BitImageTest/BitImageTestCF/BitImageTestCF.csproj +++ /dev/null @@ -1,103 +0,0 @@ - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {94B436A4-89D4-452E-8622-F24EF33FA12F} - WinExe - Properties - BitImageTestCF - BitImageTestCF - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.1 - BitImageTestCF - v2.0 - Windows Mobile 5.0 Pocket PC SDK - - - Svn - Svn - Svn - SubversionScc - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - Form - - - Form1.cs - - - - - Form1.cs - Designer - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/BitImageTest/BitImageTestCF/BitimageClass.cs b/BitImageTest/BitImageTestCF/BitimageClass.cs deleted file mode 100644 index 0fdaa4c..0000000 --- a/BitImageTest/BitImageTestCF/BitimageClass.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -using System.Collections; -using System.IO; -using System.Drawing; -/* -USAGE: - if(System.IO.File.Exists("RM-Logo.bmp")){ - BitImage.BitimageClass.dumpBands("RM-Logo.bmp"); - bitmap = BitImage.BitimageClass.getRawBitmap("RM-Logo.bmp"); - } - else - MessageBox.Show("Missing file: " + "RM-Logo.bmp"); -... - private System.Drawing.Bitmap bitmap = null; - private void Form1_Paint(object sender, PaintEventArgs e){ - //e.Graphics.Dr - if(bitmap!=null){ - e.Graphics.DrawImage(bitmap,new System.Drawing.Point(0,100)); - } - } -*/ -namespace BitImage -{ - public class BitmapDotData - { - public BitArray Dots - { - get; - set; - } - - public int Height - { - get; - set; - } - - public int Width - { - get; - set; - } - } - - class BitimageClass - { - /// - /// get the B&W 1BPP bitmap for a bmp file - /// - /// - /// - /// - /// - private static BitmapDotData GetBitmapData(string bmpFileName) - { - Image img = new Bitmap(bmpFileName); - using (var bitmap = new Bitmap(img))// (Bitmap)Bitmap.FromFile(bmpFileName)) - { - var threshold = 127; - var index = 0; - var dimensions = bitmap.Width * bitmap.Height; - var dots = new BitArray(dimensions); - - for (var y = 0; y < bitmap.Height; y++) - { - for (var x = 0; x < bitmap.Width; x++) - { - var color = bitmap.GetPixel(x, y); - var luminance = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11); - dots[index] = (luminance < threshold); - index++; - } - } - - return new BitmapDotData() - { - Dots = dots, - Height = bitmap.Height, - Width = bitmap.Width - }; - } - } - public static byte[] GetDocument(string sBitmapFile) - { - using (var ms = new MemoryStream()) - using (var bw = new BinaryWriter(ms)) - { - // Reset the printer bws (NV images are not cleared) -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('@'); -*/ - // Render the logo - RenderBands(sBitmapFile, bw); - - // Feed 3 vertical motion units and cut the paper with a 1 point cut -/* bw.Write(ASCIIhelper.AsciiControlChars.GroupSeparator); - bw.Write('V'); - bw.Write((byte)66); - bw.Write((byte)3); -*/ - bw.Flush(); - - return ms.ToArray(); - } - } - - private static void RenderBands(string bitmapFile, BinaryWriter bw) - { - var data = GetBitmapData(bitmapFile); - //var data = GetBitmapData("RM-Logo.bmp"); - var dots = data.Dots; - var width = BitConverter.GetBytes(data.Width); - - //write header -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('*'); // bit-image mode - bw.Write((byte)0); // 8-dot single-density - bw.Write((byte)5); // width low byte - bw.Write((byte)0); // width high byte - bw.Write((byte)1); - bw.Write((byte)2); - bw.Write((byte)4); - bw.Write((byte)8); - bw.Write((byte)16); -*/ - // So we have our bitmap data sitting in a bit array called "dots." - // This is one long array of 1s (black) and 0s (white) pixels arranged - // as if we had scanned the bitmap from top to bottom, left to right. - // The printer wants to see these arranged in bytes stacked three high. - // So, essentially, we need to read 24 bits for x = 0, generate those - // bytes, and send them to the printer, then keep increasing x. If our - // image is more than 24 dots high, we have to send a second bit image - // command. - - // Set the line spacing to 24 dots, the height of each "stripe" of the - // image that we're drawing. -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('3'); - bw.Write((byte)24); -*/ - // OK. So, starting from x = 0, read 24 bits down and send that data - // to the printer. - int offset = 0; - - while (offset < data.Height) - { -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('*'); // bit-image mode - bw.Write((byte)33); // 24-dot double-density - bw.Write(width[0]); // width low byte - bw.Write(width[1]); // width high byte -*/ - for (int x = 0; x < data.Width; ++x) - { - for (int k = 0; k < 3; ++k) - { - byte slice = 0; - - /* - We have our working copy of a byte that we’re munging with in a variable - called ‘slice’. I have a Boolean named ‘v’ that tells me if I want to - shove a 1 or a zero into this byte. So if v is true, I take the - integer 1 and shift it (7 – b) units to the left. (I think in Delphi this - is ‘Shl’?) If it’s a zero, well, I don’t have to do anything actually - but there is not harm in “shifting zero” in a one-liner. Then I - bitwise OR my shifted integer with the ‘slice’. - - So if ‘slice’ looked like ’01000000′ and I’m working on b = 3, - then I take ’00000001′, shift it to the left (7 – 3) == 4 places - to get ’00010000′, and then I OR that number (’00010000′) with - the slice (’01000000′) to get ’01010000′. And then I keep on - trucking. (If it was zero, I would have shifted zero and then OR it - with the slice, effectively doing nothing.) - */ - for (int b = 0; b < 8; ++b) - { - int y = (((offset / 8) + k) * 8) + b; - - // Calculate the location of the pixel we want in the bit array. - // It'll be at (y * width) + x. - int i = (y * data.Width) + x; - - // If the image is shorter than 24 dots, pad with zero. - bool v = false; - if (i < dots.Length) - { - v = dots[i]; - } - - slice |= (byte)((v ? 1 : 0) << (7 - b)); - } - - bw.Write(slice); - } - } - - offset += 24; -/* bw.Write(ASCIIhelper.AsciiControlChars.Newline); -*/ } - - // Restore the line spacing to the default of 30 dots. -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('3'); - bw.Write((byte)30); -*/ } - public static void dumpBands(string sBitmapFile, byte[] bytes) - { - byte[] bs = GetDocument("RM-Logo.bmp"); - Console.WriteLine(tools.tools.ByteAr2HexStr(bs)); - Console.WriteLine(tools.tools.ByteAr2BinStr(bs)); - } - public static void dumpBands(string sBitmapFile) - { - byte[] bs = GetDocument(sBitmapFile);//"RM-Logo.bmp"); -// Console.WriteLine(tools.tools.ByteAr2HexStr(bs)); - Console.WriteLine(tools.tools.ByteAr2BinStr(bs)); - } - public static Bitmap getRawBitmap(string sBitmapFile){ - //byte[] bs = GetDocument(sBitmapFile);//"RM-Logo.bmp"); - BitmapDotData data = GetBitmapData(sBitmapFile); - Bitmap bmp = new Bitmap(data.Width,data.Height,System.Drawing.Imaging.PixelFormat.Format1bppIndexed); - int width = bmp.Width; - int height = bmp.Height; - System.Drawing.Imaging.BitmapData bits = - bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), - System.Drawing.Imaging.ImageLockMode.ReadWrite, - System.Drawing.Imaging.PixelFormat.Format1bppIndexed); - - unsafe - { -/* - http://www.bobpowell.net/lockingbits.htm - Format1BppIndexed Given the X and Y coordinates, the byte containing the pixel is calculated - by Scan0+(y*Stride)+(x/8). The byte contains 8 bits, each bit is one pixel with the leftmost - pixel in bit 8 and the rightmost pixel in bit 0. The bits select from the two entry colour - palette. -*/ - for (int y = 0; y < height; y++) - { - //int* row = (int*)((byte*)bits.Scan0 + (y * bits.Stride)); - for (int x = 0; x < width; x++) - { - //int* row = (int*)((byte*)bits.Scan0 + (y * bits.Stride)+(x/8)); - byte* p=(byte*)bits.Scan0.ToPointer(); - int index=y*bits.Stride+(x>>3); - byte mask=(byte)(0x80>>(x&0x7)); - bool pixel = !(data.Dots[y * width + x]); - if(pixel) - p[index]|=mask; - else - p[index]&=(byte)(mask^0xff); - - //row[x] = data.Dots[y * width + x]; - } - } - } - bmp.UnlockBits(bits); - return bmp; - } - } -} diff --git a/BitImageTest/BitImageTestCF/Form1.Designer.cs b/BitImageTest/BitImageTestCF/Form1.Designer.cs deleted file mode 100644 index 46b1b1d..0000000 --- a/BitImageTest/BitImageTestCF/Form1.Designer.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace BitImageTestCF -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuExit); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "Form1"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuExit; - } -} - diff --git a/BitImageTest/BitImageTestCF/Form1.cs b/BitImageTest/BitImageTestCF/Form1.cs deleted file mode 100644 index 930aa91..0000000 --- a/BitImageTest/BitImageTestCF/Form1.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace BitImageTestCF -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - - private void mnuExit_Click(object sender, EventArgs e) - { - this.Close(); - } - } -} \ No newline at end of file diff --git a/BitImageTest/BitImageTestCF/Form1.resx b/BitImageTest/BitImageTestCF/Form1.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/BitImageTest/BitImageTestCF/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/BitImageTest/BitImageTestCF/Program.cs b/BitImageTest/BitImageTestCF/Program.cs deleted file mode 100644 index 07e66a0..0000000 --- a/BitImageTest/BitImageTestCF/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace BitImageTestCF -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/BitImageTest/BitImageTestCF/Properties/AssemblyInfo.cs b/BitImageTest/BitImageTestCF/Properties/AssemblyInfo.cs deleted file mode 100644 index a1f555c..0000000 --- a/BitImageTest/BitImageTestCF/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("BitImageTestCF")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("BitImageTestCF")] -[assembly: AssemblyCopyright("Copyright © 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("442c136a-f8c0-4d0b-983f-f011940d9775")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/BitImageTest/BitImageTestCF/Properties/Resources.Designer.cs b/BitImageTest/BitImageTestCF/Properties/Resources.Designer.cs deleted file mode 100644 index d229b79..0000000 --- a/BitImageTest/BitImageTestCF/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.3053 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace BitImageTestCF.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("BitImageTestCF.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/BitImageTest/BitImageTestCF/Properties/Resources.resx b/BitImageTest/BitImageTestCF/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/BitImageTest/BitImageTestCF/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/BitImageTest/BitImageTestCF/RM-Logo.bmp b/BitImageTest/BitImageTestCF/RM-Logo.bmp deleted file mode 100644 index 17863a3..0000000 Binary files a/BitImageTest/BitImageTestCF/RM-Logo.bmp and /dev/null differ diff --git a/BitImageTest/BitImageTestCF/tools.cs b/BitImageTest/BitImageTestCF/tools.cs deleted file mode 100644 index 85f3c56..0000000 --- a/BitImageTest/BitImageTestCF/tools.cs +++ /dev/null @@ -1,350 +0,0 @@ -using System; -using System.IO; -using System.Collections; -using System.Collections.Generic; -//using System.Windows.Forms; - -namespace tools -{ - public class tools - { - public static string ByteAr2HexStr(byte[] b){ - string s=""; - foreach (byte b1 in b){ - s+=b1.ToString("x"); - } - return s; - } - static int iByteGroup=3; - static int iByteCount=1; - public static string ByteAr2BinStr(byte[] b){ - string s=""; - - foreach(byte b1 in b){ - iByteCount++; - s += Byte2DotStr(b1); - //s += Byte2BinStr(b1); - if(iByteCount>iByteGroup){ - s += "\r\n"; - iByteCount=1; - } - } - - return s; - } - public static string Byte2BinStr(byte b) - { - int maxbits = 8; - byte b8 = b; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (b8 >= Math.Pow(2, i-1)) - { - s = "1" + s; - b8 -= (byte)Math.Pow(2, i-1); - } - else - s = "0" + s; - } - s.PadRight(8, '0'); - return s; - } - public static string Byte2DotStr(byte b) - { - int maxbits = 8; - byte b8 = b; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (b8 >= Math.Pow(2, i-1)) - { - s = "." + s; - b8 -= (byte)Math.Pow(2, i-1); - } - else - s = " " + s; - } - s.PadRight(8, ' '); - return s; - } - public static string ReverseString(string s) - { - int i = 0; - string str=""; - for (i = s.Length-1; i >= 0; i--) - { - str = str + s.Substring(i, 1); - } - return str; - } - - /// - /// Copy a string until a \r appears - /// - /// input string - /// string cutdown to \r - public static string CopyToR(string s) - { - int i = 0; - string t = ""; - while (s.Substring(i, 1) != "\r") - { - t += s.Substring(i, 1); - i++; - } - return t; - } - /// - /// C# to convert a string to a byte array. - /// - /// - /// sbyte[] - public static sbyte[] StrToSByteArray(string str) - { - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - byte[] src = new byte[str.Length]; - sbyte[] dest = new sbyte[src.Length]; - src = encoding.GetBytes(str); - System.Buffer.BlockCopy(src, 0, dest, 0, src.Length); - return dest; - } - - -#region NewStuff - //=============================================================================================== - // New stuff - //=============================================================================================== - - /// - /// takes a string of 0s and 1s and returns a uint - /// - /// a 'binary' string of 0s and 1s - /// - public static UInt32 BinStr2Uint(string s) - { - int maxbits = s.Length; - int i; - UInt32 u=0; - //s[s.lenghth] = Bit[0] - //start at end of string, highest bit - for (i = 0; i < maxbits ; i++) - { - if (s.Substring( i, 1).Equals("1")) - { - u += (uint)Math.Pow(2, i); - } - } - return u; - } - - /// - /// convert an uint to a BinStr - /// - /// - /// a BinStr of 0s and 1s, lowest bit left - public static string Uint2BinStr(UInt32 u) - { - int maxbits = 32; - UInt32 u32 = u; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (u32 >= Math.Pow(2, i-1)) - { - s = "1" + s; - u32 -= (UInt32)Math.Pow(2, i-1); - } - else - s = "0" + s; - } - s.PadRight(32, '0'); - return s; - } - - /// - /// get binary string in reverse order - /// - /// - /// - /// - public static string Uint2BinStr(UInt32 u, int bitcount) - { - //49977473 -> //10111110101001100010000001 - //123456789 -> 00000111010110111100110100010101 - // "00000111 01011011 11001101 00010101 - // " - string s = Uint2BinStr(u); - if (s.Length > bitcount) - { - s = s.Substring(0, bitcount); - } - else if (s.Length < bitcount) - s = s.PadRight(bitcount, '0'); - return s; - } - - /// - /// Convert a BinStr ie '01010011' to a hex string '53'hex - /// - /// - /// a hex str - public static string BinStr2HexStr(string BinStr) - { - //convert byte by byte - string sHex2=""; - string sBin8=""; - string sHex=""; - string sBin = BinStr; - byte b = 0; - //ensure a binstr dividable by 8 - if (sBin.Length % 8 > 0) //is there any rest? - { - int l = sBin.Length; - int c = l / 8; - c++; - c = c * 8; - l = c - l; - for (int i = 0; i < l; i++) - sBin = sBin + "0"; - } - //start at lowest bit - while (sBin.Length > 0) - { - sBin8 = sBin.Substring(0, 8); //01010011 - b = (byte)BinStr2Uint(sBin); - sHex2 = Convert.ToString(b, 16); //0x53 - sHex = sHex2.PadLeft(2,'0') + sHex ; - sBin = sBin.Substring(8); - } - return sHex; - } - /// - /// convert a BinStr to a Hex string - /// - /// - /// the Byte width, ie 12 means you get a string with 24 letters - /// each byte is translated to a two-letter hex str - /// - public static string BinStr2HexStr(string BinStr, int ByteWidth) - { - string HexStr = BinStr2HexStr(BinStr); - if (HexStr.Length < ByteWidth) //pad left with '0' - HexStr = HexStr.PadLeft(ByteWidth*2, '0'); - else if (HexStr.Length > ByteWidth) //return right part, cut left - HexStr = HexStr.Substring(HexStr.Length - (ByteWidth * 2), ByteWidth * 2); - return HexStr; - } - - public static char[] HexStr2CharAr(string sHex) - { - char[] c; - string sBin = ""; - sBin = HexStr2BinStr(sHex); - c=BinStr2CharAr(sBin); - return c; - } - - public static string CharAr2HexStr(char[] c) - { - string s = ""; - string sBin = ""; - sBin = CharAr2BinStr(c); - s = BinStr2HexStr(sBin); - return s; - } - - public static string HexStr2BinStr(string hex) - { - byte b; - string BinStr = ""; - string sBin8 = ""; - string hex2 = ""; - if (hex.Length == 24) - { - //from left to right //34 ....... - for (int i = 0; i < 12; i++) - { //0-1-2-3-4- 5- 6- 7- 8- 9-10-11 - hex2 = hex.Substring(i*2, 2);//start at right, 0-2-4-6-8-10-12-14-16-18-20-22 - b = Convert.ToByte(hex2, 16); - sBin8 = Uint2BinStr(b).Substring(0,8); - BinStr = sBin8 + BinStr ; - } - } - else{ - //is this a even number of chars? - if(hex.Length % 2 > 0) - hex="0"+hex; //add a zero in front - //from left to right //34 ....... - for (int i = 0; i < hex.Length/2; i++) - { //0-1-2-3-4- 5- 6- 7- 8- 9-10-11 - hex2 = hex.Substring(i*2, 2);//start at right, 0-2-4-6-8-10-12-14-16-18-20-22 - b = Convert.ToByte(hex2, 16); - sBin8 = Uint2BinStr(b).Substring(0,8); - BinStr = sBin8 + BinStr ; - } - - } - if (!BinStr2HexStr(BinStr).Equals(hex.ToLower())) - System.Diagnostics.Debugger.Break(); - return BinStr; - } - - /// - /// convert a BinStr to a char[] array - /// - /// - /// - public static char[] BinStr2CharAr(string BinStr) - { - int bitcount = BinStr.Length; - if (BinStr.Length > 96) - BinStr = BinStr.Substring(0,96);//limit bitcount to 96 - else if (BinStr.Length < 96) - BinStr = BinStr.PadRight(96, '0'); - - char[] c = new char[96]; - for (int i = 0; i < 96; i++) - { - if (BinStr.Substring(i, 1).Equals("1")) - c[i] = '1'; - else - c[i] = '0'; - } - return c; - } - /// - /// convert a char[] to BinStr (substr(0,1)=char[0] - /// BinStr highest Bit at RIGHT! - /// - /// - /// - public static string CharAr2BinStr(char[] c) - { - int bitcount = c.Length; - string s = ""; - for (int i = 0; i < bitcount; i++) - { - if (c[i] == '1') - s = s + "1"; - else - s = s + "0"; - } - if (s.Length < 96) - s.PadRight(96, '0'); - else if (s.Length > 96) - s = s.Substring(0, 96); - return s; - } -#endregion - } -} \ No newline at end of file diff --git a/BitimageRaw/BitimageRaw.sln b/BitimageRaw/BitimageRaw.sln deleted file mode 100644 index c955b16..0000000 --- a/BitimageRaw/BitimageRaw.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BitimageRaw", "BitimageRaw\BitimageRaw.csproj", "{66B0CA4A-4DB4-4D50-AB54-EA7911EC8F1B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|x86 = Debug|x86 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {66B0CA4A-4DB4-4D50-AB54-EA7911EC8F1B}.Debug|x86.ActiveCfg = Debug|x86 - {66B0CA4A-4DB4-4D50-AB54-EA7911EC8F1B}.Debug|x86.Build.0 = Debug|x86 - {66B0CA4A-4DB4-4D50-AB54-EA7911EC8F1B}.Release|x86.ActiveCfg = Release|x86 - {66B0CA4A-4DB4-4D50-AB54-EA7911EC8F1B}.Release|x86.Build.0 = Release|x86 - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = BitimageRaw\BitimageRaw.csproj - EndGlobalSection -EndGlobal diff --git a/BitimageRaw/BitimageRaw.userprefs b/BitimageRaw/BitimageRaw.userprefs deleted file mode 100644 index 247b8cc..0000000 --- a/BitimageRaw/BitimageRaw.userprefs +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/BitimageRaw/BitimageRaw/AsciiControlChars.cs b/BitimageRaw/BitimageRaw/AsciiControlChars.cs deleted file mode 100644 index ce9d871..0000000 --- a/BitimageRaw/BitimageRaw/AsciiControlChars.cs +++ /dev/null @@ -1,67 +0,0 @@ -namespace ASCIIhelper -{ - /// - /// A listing of ASCII control characters for readability. - /// - public static class AsciiControlChars - { - /// - /// Usually indicates the end of a string. - /// - public const char Nul = (char)0x00; - - /// - /// Meant to be used for printers. When receiving this code the - /// printer moves to the next sheet of paper. - /// - public const char FormFeed = (char)0x0C; - - /// - /// Starts an extended sequence of control codes. - /// - public const char Escape = (char)0x1B; - - /// - /// Advances to the next line. - /// - public const char Newline = (char)0x0A; - - /// - /// Defined to separate tables or different sets of data in a serial - /// data storage system. - /// - public const char GroupSeparator = (char)0x1D; - - /// - /// A horizontal tab. - /// - public const char HorizontalTab = (char)0x09; - - /// - /// Returns the carriage to the start of the line. - /// - public const char CarriageReturn = (char)0x0D; - - /// - /// Cancels the operation. - /// - public const char Cancel = (char)0x18; - - /// - /// Indicates that control characters present in the stream should - /// be passed through as transmitted and not interpreted as control - /// characters. - /// - public const char DataLinkEscape = (char)0x10; - - /// - /// Signals the end of a transmission. - /// - public const char EndOfTransmission = (char)0x04; - - /// - /// In serial storage, signals the separation of two files. - /// - public const char FileSeparator = (char)0x1C; - } -} \ No newline at end of file diff --git a/BitimageRaw/BitimageRaw/AssemblyInfo.cs b/BitimageRaw/BitimageRaw/AssemblyInfo.cs deleted file mode 100644 index f1aead5..0000000 --- a/BitimageRaw/BitimageRaw/AssemblyInfo.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("BitimageRaw")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". -// The form "{Major}.{Minor}.*" will automatically update the build and revision, -// and "{Major}.{Minor}.{Build}.*" will update just the revision. - -[assembly: AssemblyVersion("1.0.*")] - -// The following attributes are used to specify the signing key for the assembly, -// if desired. See the Mono documentation for more information about signing. - -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile("")] - diff --git a/BitimageRaw/BitimageRaw/BitimageClass.cs b/BitimageRaw/BitimageRaw/BitimageClass.cs deleted file mode 100644 index f39331b..0000000 --- a/BitimageRaw/BitimageRaw/BitimageClass.cs +++ /dev/null @@ -1,317 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -using System.Collections; -using System.IO; -using System.Drawing; -/* -USAGE: - if(System.IO.File.Exists("RM-Logo.bmp")){ - BitImage.BitimageClass.dumpBands("RM-Logo.bmp"); - bitmap = BitImage.BitimageClass.getRawBitmap("RM-Logo.bmp"); - } - else - MessageBox.Show("Missing file: " + "RM-Logo.bmp"); -... - private System.Drawing.Bitmap bitmap = null; - private void Form1_Paint(object sender, PaintEventArgs e){ - //e.Graphics.Dr - if(bitmap!=null){ - e.Graphics.DrawImage(bitmap,new System.Drawing.Point(0,100)); - } - } -*/ -/* Different bitimage graphics mode - * this is actually using 24 or 8 byte bands - * but some ESCP manuals say ESC V n1 n2 is for line image mode: - * PB50 pixelwidth=832pixels, 104 bytes. - * ESC V n1 n2 - number of lines with graphics is n1*256+n2 (just as it - * says in the ESC/P manual). - * - * so the code has to be reordered to provide line image mode - * where one line of pixels has to be printed after the other -*/ - - -namespace BitImage -{ - public class BitmapDotData - { - public BitArray Dots - { - get; - set; - } - - public int Height - { - get; - set; - } - - public int Width - { - get; - set; - } - } - - class BitimageClass - { - private static int bytesPerRow=3; - public static int _bytesPerRow{ - get{ return bytesPerRow;} - set{ bytesPerRow=value;} - } - private static int numPixelRows=0; - public static int _numPixelRows{ - get{ return numPixelRows;} - } - /// - /// get the B&W 1BPP bitmap for a bmp file - /// - /// - /// - /// - /// - private static BitmapDotData GetBitmapData(string bmpFileName) - { - Image img = new Bitmap(bmpFileName); - using (var bitmap = new Bitmap(img))// (Bitmap)Bitmap.FromFile(bmpFileName)) - { - var threshold = 127; - var index = 0; - var dimensions = bitmap.Width * bitmap.Height; - var dots = new BitArray(dimensions); - - for (var y = 0; y < bitmap.Height; y++) - { - for (var x = 0; x < bitmap.Width; x++) - { - var color = bitmap.GetPixel(x, y); - var luminance = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11); - dots[index] = (luminance < threshold); - index++; - } - } - - return new BitmapDotData() - { - Dots = dots, - Height = bitmap.Height, - Width = bitmap.Width - }; - } - } - public static byte[] GetDocument(string sBitmapFile) - { - using (var ms = new MemoryStream()) - using (var bw = new BinaryWriter(ms)) - { - // Reset the printer bws (NV images are not cleared) -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('@'); -*/ - // Render the logo - RenderBands(sBitmapFile, bw); - - // Feed 3 vertical motion units and cut the paper with a 1 point cut -/* bw.Write(ASCIIhelper.AsciiControlChars.GroupSeparator); - bw.Write('V'); - bw.Write((byte)66); - bw.Write((byte)3); -*/ - bw.Flush(); - - return ms.ToArray(); - } - } - - private static void RenderBands(string bitmapFile, BinaryWriter bw) - { - var data = GetBitmapData(bitmapFile); - //var data = GetBitmapData("RM-Logo.bmp"); - var dots = data.Dots; - var width = BitConverter.GetBytes(data.Width); - - //write header -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('*'); // bit-image mode - bw.Write((byte)0); // 8-dot single-density - bw.Write((byte)5); // width low byte - bw.Write((byte)0); // width high byte - bw.Write((byte)1); - bw.Write((byte)2); - bw.Write((byte)4); - bw.Write((byte)8); - bw.Write((byte)16); -*/ - // So we have our bitmap data sitting in a bit array called "dots." - // This is one long array of 1s (black) and 0s (white) pixels arranged - // as if we had scanned the bitmap from top to bottom, left to right. - // The printer wants to see these arranged in bytes stacked three high. - // So, essentially, we need to read 24 bits for x = 0, generate those - // bytes, and send them to the printer, then keep increasing x. If our - // image is more than 24 dots high, we have to send a second bit image - // command. - - // Set the line spacing to 24 dots, the height of each "stripe" of the - // image that we're drawing. -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('3'); - bw.Write((byte)24); -*/ - // OK. So, starting from x = 0, read 24 bits down and send that data - // to the printer. - int offset = 0; - - while (offset < data.Height) - { -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('*'); // bit-image mode - bw.Write((byte)33); // 24-dot double-density - bw.Write(width[0]); // width low byte - bw.Write(width[1]); // width high byte -*/ - for (int x = 0; x < data.Width; ++x) - { - for (int k = 0; k < bytesPerRow; ++k) - { - byte slice = 0; - - /* - We have our working copy of a byte that we’re munging with in a variable - called ‘slice’. I have a Boolean named ‘v’ that tells me if I want to - shove a 1 or a zero into this byte. So if v is true, I take the - integer 1 and shift it (7 – b) units to the left. (I think in Delphi this - is ‘Shl’?) If it’s a zero, well, I don’t have to do anything actually - but there is not harm in “shifting zero” in a one-liner. Then I - bitwise OR my shifted integer with the ‘slice’. - - So if ‘slice’ looked like ’01000000′ and I’m working on b = 3, - then I take ’00000001′, shift it to the left (7 – 3) == 4 places - to get ’00010000′, and then I OR that number (’00010000′) with - the slice (’01000000′) to get ’01010000′. And then I keep on - trucking. (If it was zero, I would have shifted zero and then OR it - with the slice, effectively doing nothing.) - */ - for (int b = 0; b < 8; ++b) - { - int y = (((offset / 8) + k) * 8) + b; - - // Calculate the location of the pixel we want in the bit array. - // It'll be at (y * width) + x. - int i = (y * data.Width) + x; - - // If the image is shorter than 24 dots, pad with zero. - bool v = false; - if (i < dots.Length) - { - v = dots[i]; - } - - slice |= (byte)((v ? 1 : 0) << (7 - b)); - } - - bw.Write(slice); - } - } - - offset += bytesPerRow * 8;// 24; -/* bw.Write(ASCIIhelper.AsciiControlChars.Newline); -*/ } - - // Restore the line spacing to the default of 30 dots. -/* bw.Write(ASCIIhelper.AsciiControlChars.Escape); - bw.Write('3'); - bw.Write((byte)30); -*/ } - public static Image resizeImage(Image imgToResize, Size size) - { - int sourceWidth = imgToResize.Width; - int sourceHeight = imgToResize.Height; - - float nPercent = 0; - float nPercentW = 0; - float nPercentH = 0; - - nPercentW = ((float)size.Width / (float)sourceWidth); - nPercentH = ((float)size.Height / (float)sourceHeight); - - if (nPercentH < nPercentW) - nPercent = nPercentH; - else - nPercent = nPercentW; - - int destWidth = (int)(sourceWidth * nPercent); - int destHeight = (int)(sourceHeight * nPercent); - - Bitmap b = new Bitmap(destWidth, destHeight); - Graphics g = Graphics.FromImage((Image)b); - g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; - //g.InterpolationMode = InterpolationMode.HighQualityBicubic; - - g.DrawImage(imgToResize, 0, 0, destWidth, destHeight); - g.Dispose(); - - return (Image)b; - } - public static void dumpBands(string sBitmapFile, byte[] bytes) - { - byte[] bs = GetDocument("RM-Logo.bmp"); - Console.WriteLine(tools.tools.ByteAr2HexStr(bs)); - Console.WriteLine(tools.tools.ByteAr2BinStr(bs)); - } - public static void dumpBands(string sBitmapFile) - { - byte[] bs = GetDocument(sBitmapFile);//"RM-Logo.bmp"); -// Console.WriteLine(tools.tools.ByteAr2HexStr(bs)); - Console.WriteLine(tools.tools.ByteAr2BinStr(bs)); - } - public static Bitmap getRawBitmap(string sBitmapFile){ - //byte[] bs = GetDocument(sBitmapFile);//"RM-Logo.bmp"); - BitmapDotData data = GetBitmapData(sBitmapFile); - Bitmap bmp = new Bitmap(data.Width,data.Height,System.Drawing.Imaging.PixelFormat.Format1bppIndexed); - int width = bmp.Width; - int height = bmp.Height; - System.Drawing.Imaging.BitmapData bits = - bmp.LockBits(new Rectangle(0,0,bmp.Width,bmp.Height), - System.Drawing.Imaging.ImageLockMode.ReadWrite, - System.Drawing.Imaging.PixelFormat.Format1bppIndexed); - numPixelRows=0; - - unsafe - { -/* - http://www.bobpowell.net/lockingbits.htm - Format1BppIndexed Given the X and Y coordinates, the byte containing the pixel is calculated - by Scan0+(y*Stride)+(x/8). The byte contains 8 bits, each bit is one pixel with the leftmost - pixel in bit 8 and the rightmost pixel in bit 0. The bits select from the two entry colour - palette. -*/ - for (int y = 0; y < height; y++) - { - numPixelRows++; - //int* row = (int*)((byte*)bits.Scan0 + (y * bits.Stride)); - for (int x = 0; x < width; x++) - { - //int* row = (int*)((byte*)bits.Scan0 + (y * bits.Stride)+(x/8)); - byte* p=(byte*)bits.Scan0.ToPointer(); - int index=y*bits.Stride+(x>>3); - byte mask=(byte)(0x80>>(x&0x7)); - bool pixel = !(data.Dots[y * width + x]); - if(pixel) - p[index]|=mask; - else - p[index]&=(byte)(mask^0xff); - - //row[x] = data.Dots[y * width + x]; - } - } - } - bmp.UnlockBits(bits); - return bmp; - } - } -} diff --git a/BitimageRaw/BitimageRaw/BitimageRaw.csproj b/BitimageRaw/BitimageRaw/BitimageRaw.csproj deleted file mode 100644 index b8187dc..0000000 --- a/BitimageRaw/BitimageRaw/BitimageRaw.csproj +++ /dev/null @@ -1,54 +0,0 @@ - - - - Debug - x86 - 9.0.21022 - 2.0 - {66B0CA4A-4DB4-4D50-AB54-EA7911EC8F1B} - Exe - BitimageRaw - BitimageRaw - v3.5 - - - true - full - false - bin\Debug - DEBUG - prompt - 4 - x86 - false - true - - - none - false - bin\Release - prompt - 4 - x86 - false - true - - - - - - - - - - - - - - - - - PreserveNewest - - - \ No newline at end of file diff --git a/BitimageRaw/BitimageRaw/Main.cs b/BitimageRaw/BitimageRaw/Main.cs deleted file mode 100644 index 912f7d0..0000000 --- a/BitimageRaw/BitimageRaw/Main.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Windows.Forms; - -namespace BitimageRaw -{ - class MainClass - { - public static void Main (string[] args) - { - WinForm form = new WinForm (); - Application.Run (form); - //Console.WriteLine("Hello World!"); - } - } - public class WinForm : Form - { - public WinForm () - { - InitializeComponent (); - } - - private void InitializeComponent () - { - this.Width = 400; - this.Height = 300; - this.Text = "My Dialog"; - - this.Paint+=new PaintEventHandler(Form1_Paint); - Button btnOK = new Button (); - btnOK.Text = "OK"; - btnOK.Location = new System.Drawing.Point (10, 10); - btnOK.Size = new System.Drawing.Size (80, 24); - this.Controls.Add (btnOK); - btnOK.Click += new EventHandler (btnOK_Click); - - if(System.IO.File.Exists("RM-Logo.bmp")){ - - BitImage.BitimageClass._bytesPerRow=1; - BitImage.BitimageClass.dumpBands("RM-Logo.bmp"); - bitmap = BitImage.BitimageClass.getRawBitmap("RM-Logo.bmp"); - - //resize for paint - //calc aspect ratio - decimal dRatio = bitmap.Width / bitmap.Height; - //new width is width of printhead, ie 203 - int iWidth = 203; //use thermal printer print width - int iHeight=(int) (iWidth * dRatio / bitmap.Height); - System.Drawing.Bitmap bitmap2 = - (System.Drawing.Bitmap) BitImage.BitimageClass.resizeImage(bitmap, - new System.Drawing.Size(iWidth, iHeight)); - bitmap = bitmap2; - - Console.WriteLine("bytesPerRow: " +BitImage.BitimageClass._bytesPerRow); - Console.WriteLine("numBands: " + - BitImage.BitimageClass._numPixelRows/BitImage.BitimageClass._bytesPerRow); - } - else - MessageBox.Show("Missing file: " + "RM-Logo.bmp"); - } - private System.Drawing.Bitmap bitmap = null; - private void Form1_Paint(object sender, PaintEventArgs e){ - //e.Graphics.Dr - if(bitmap!=null){ - e.Graphics.DrawImage(bitmap,new System.Drawing.Point(0,100)); - } - } - - private void btnOK_Click (object sender, System.EventArgs e) - { - this.DialogResult = DialogResult.OK; - this.Close (); - } - - } -} - diff --git a/BitimageRaw/BitimageRaw/RM-Logo.bmp b/BitimageRaw/BitimageRaw/RM-Logo.bmp deleted file mode 100644 index 17863a3..0000000 Binary files a/BitimageRaw/BitimageRaw/RM-Logo.bmp and /dev/null differ diff --git a/BitimageRaw/BitimageRaw/tools.cs b/BitimageRaw/BitimageRaw/tools.cs deleted file mode 100644 index e9cbdd0..0000000 --- a/BitimageRaw/BitimageRaw/tools.cs +++ /dev/null @@ -1,350 +0,0 @@ -using System; -using System.IO; -using System.Collections; -using System.Collections.Generic; -//using System.Windows.Forms; - -namespace tools -{ - public class tools - { - public static string ByteAr2HexStr(byte[] b){ - string s=""; - foreach (byte b1 in b){ - s+=b1.ToString("x"); - } - return s; - } - static int iByteGroup=3; - static int iByteCount=1; - public static string ByteAr2BinStr(byte[] b){ - string s=""; - - foreach(byte b1 in b){ - iByteCount++; - s += Byte2DotStr(b1); - //s += Byte2BinStr(b1); - if(iByteCount>iByteGroup){ - s += "\r\n"; - iByteCount=1; - } - } - - return s; - } - public static string Byte2BinStr(byte b) - { - int maxbits = 8; - byte b8 = b; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (b8 >= Math.Pow(2, i-1)) - { - s = "1" + s; - b8 -= (byte)Math.Pow(2, i-1); - } - else - s = "0" + s; - } - s.PadRight(8, '0'); - return s; - } - public static string Byte2DotStr(byte b) - { - int maxbits = 8; - byte b8 = b; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (b8 >= Math.Pow(2, i-1)) - { - s = "." + s; - b8 -= (byte)Math.Pow(2, i-1); - } - else - s = " " + s; - } - s.PadRight(8, ' '); - return s; - } - public static string ReverseString(string s) - { - int i = 0; - string str=""; - for (i = s.Length-1; i >= 0; i--) - { - str = str + s.Substring(i, 1); - } - return str; - } - - /// - /// Copy a string until a \r appears - /// - /// input string - /// string cutdown to \r - public static string CopyToR(string s) - { - int i = 0; - string t = ""; - while (s.Substring(i, 1) != "\r") - { - t += s.Substring(i, 1); - i++; - } - return t; - } - /// - /// C# to convert a string to a byte array. - /// - /// - /// sbyte[] - public static sbyte[] StrToSByteArray(string str) - { - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - byte[] src = new byte[str.Length]; - sbyte[] dest = new sbyte[src.Length]; - src = encoding.GetBytes(str); - System.Buffer.BlockCopy(src, 0, dest, 0, src.Length); - return dest; - } - - -#region NewStuff - //=============================================================================================== - // New stuff - //=============================================================================================== - - /// - /// takes a string of 0s and 1s and returns a uint - /// - /// a 'binary' string of 0s and 1s - /// - public static UInt32 BinStr2Uint(string s) - { - int maxbits = s.Length; - int i; - UInt32 u=0; - //s[s.lenghth] = Bit[0] - //start at end of string, highest bit - for (i = 0; i < maxbits ; i++) - { - if (s.Substring( i, 1).Equals("1")) - { - u += (uint)Math.Pow(2, i); - } - } - return u; - } - - /// - /// convert an uint to a BinStr - /// - /// - /// a BinStr of 0s and 1s, lowest bit left - public static string Uint2BinStr(UInt32 u) - { - int maxbits = 32; - UInt32 u32 = u; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (u32 >= Math.Pow(2, i-1)) - { - s = "1" + s; - u32 -= (UInt32)Math.Pow(2, i-1); - } - else - s = "0" + s; - } - s.PadRight(32, '0'); - return s; - } - - /// - /// get binary string in reverse order - /// - /// - /// - /// - public static string Uint2BinStr(UInt32 u, int bitcount) - { - //49977473 -> //10111110101001100010000001 - //123456789 -> 00000111010110111100110100010101 - // "00000111 01011011 11001101 00010101 - // " - string s = Uint2BinStr(u); - if (s.Length > bitcount) - { - s = s.Substring(0, bitcount); - } - else if (s.Length < bitcount) - s = s.PadRight(bitcount, '0'); - return s; - } - - /// - /// Convert a BinStr ie '01010011' to a hex string '53'hex - /// - /// - /// a hex str - public static string BinStr2HexStr(string BinStr) - { - //convert byte by byte - string sHex2=""; - string sBin8=""; - string sHex=""; - string sBin = BinStr; - byte b = 0; - //ensure a binstr dividable by 8 - if (sBin.Length % 8 > 0) //is there any rest? - { - int l = sBin.Length; - int c = l / 8; - c++; - c = c * 8; - l = c - l; - for (int i = 0; i < l; i++) - sBin = sBin + "0"; - } - //start at lowest bit - while (sBin.Length > 0) - { - sBin8 = sBin.Substring(0, 8); //01010011 - b = (byte)BinStr2Uint(sBin8);//sBin - sHex2 = Convert.ToString(b, 16); //0x53 - sHex = sHex2.PadLeft(2,'0') + sHex ; - sBin = sBin.Substring(8); - } - return sHex; - } - /// - /// convert a BinStr to a Hex string - /// - /// - /// the Byte width, ie 12 means you get a string with 24 letters - /// each byte is translated to a two-letter hex str - /// - public static string BinStr2HexStr(string BinStr, int ByteWidth) - { - string HexStr = BinStr2HexStr(BinStr); - if (HexStr.Length < ByteWidth) //pad left with '0' - HexStr = HexStr.PadLeft(ByteWidth*2, '0'); - else if (HexStr.Length > ByteWidth) //return right part, cut left - HexStr = HexStr.Substring(HexStr.Length - (ByteWidth * 2), ByteWidth * 2); - return HexStr; - } - - public static char[] HexStr2CharAr(string sHex) - { - char[] c; - string sBin = ""; - sBin = HexStr2BinStr(sHex); - c=BinStr2CharAr(sBin); - return c; - } - - public static string CharAr2HexStr(char[] c) - { - string s = ""; - string sBin = ""; - sBin = CharAr2BinStr(c); - s = BinStr2HexStr(sBin); - return s; - } - - public static string HexStr2BinStr(string hex) - { - byte b; - string BinStr = ""; - string sBin8 = ""; - string hex2 = ""; - if (hex.Length == 24) - { - //from left to right //34 ....... - for (int i = 0; i < 12; i++) - { //0-1-2-3-4- 5- 6- 7- 8- 9-10-11 - hex2 = hex.Substring(i*2, 2);//start at right, 0-2-4-6-8-10-12-14-16-18-20-22 - b = Convert.ToByte(hex2, 16); - sBin8 = Uint2BinStr(b).Substring(0,8); - BinStr = sBin8 + BinStr ; - } - } - else{ - //is this a even number of chars? - if(hex.Length % 2 > 0) - hex="0"+hex; //add a zero in front - //from left to right //34 ....... - for (int i = 0; i < hex.Length/2; i++) - { //0-1-2-3-4- 5- 6- 7- 8- 9-10-11 - hex2 = hex.Substring(i*2, 2);//start at right, 0-2-4-6-8-10-12-14-16-18-20-22 - b = Convert.ToByte(hex2, 16); - sBin8 = Uint2BinStr(b).Substring(0,8); - BinStr = sBin8 + BinStr ; - } - - } - if (!BinStr2HexStr(BinStr).Equals(hex.ToLower())) - System.Diagnostics.Debugger.Break(); - return BinStr; - } - - /// - /// convert a BinStr to a char[] array - /// - /// - /// - public static char[] BinStr2CharAr(string BinStr) - { - //int bitcount = BinStr.Length; - if (BinStr.Length > 96) - BinStr = BinStr.Substring(0,96);//limit bitcount to 96 - else if (BinStr.Length < 96) - BinStr = BinStr.PadRight(96, '0'); - - char[] c = new char[96]; - for (int i = 0; i < 96; i++) - { - if (BinStr.Substring(i, 1).Equals("1")) - c[i] = '1'; - else - c[i] = '0'; - } - return c; - } - /// - /// convert a char[] to BinStr (substr(0,1)=char[0] - /// BinStr highest Bit at RIGHT! - /// - /// - /// - public static string CharAr2BinStr(char[] c) - { - int bitcount = c.Length; - string s = ""; - for (int i = 0; i < bitcount; i++) - { - if (c[i] == '1') - s = s + "1"; - else - s = s + "0"; - } - if (s.Length < 96) - s.PadRight(96, '0'); - else if (s.Length > 96) - s = s.Substring(0, 96); - return s; - } -#endregion - } -} \ No newline at end of file diff --git a/CharMap/CharMap.sln b/CharMap/CharMap.sln deleted file mode 100644 index 1695cab..0000000 --- a/CharMap/CharMap.sln +++ /dev/null @@ -1,49 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CharMap", "CharMap\CharMap.csproj", "{05891CEC-1AA4-4654-A6FF-75DD87EA59C2}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CharMapCF", "CharMapCF\CharMapCF.csproj", "{89F3C913-82BF-4185-955A-786595C82B3F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Debug|Any CPU.ActiveCfg = Debug|x86 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Debug|x86.ActiveCfg = Debug|x86 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Debug|x86.Build.0 = Debug|x86 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Release|Any CPU.ActiveCfg = Release|x86 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Release|Mixed Platforms.Build.0 = Release|x86 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Release|x86.ActiveCfg = Release|x86 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2}.Release|x86.Build.0 = Release|x86 - {89F3C913-82BF-4185-955A-786595C82B3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Debug|Mixed Platforms.Deploy.0 = Debug|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Debug|x86.ActiveCfg = Debug|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Release|Any CPU.Build.0 = Release|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Release|Any CPU.Deploy.0 = Release|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Release|Mixed Platforms.Deploy.0 = Release|Any CPU - {89F3C913-82BF-4185-955A-786595C82B3F}.Release|x86.ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = CharMap\CharMap.csproj - EndGlobalSection -EndGlobal diff --git a/CharMap/CharMap.userprefs b/CharMap/CharMap.userprefs deleted file mode 100644 index 3dd9d36..0000000 --- a/CharMap/CharMap.userprefs +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/CharMap/CharMap/AssemblyInfo.cs b/CharMap/CharMap/AssemblyInfo.cs deleted file mode 100644 index dc9f9c6..0000000 --- a/CharMap/CharMap/AssemblyInfo.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("CharMap")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". -// The form "{Major}.{Minor}.*" will automatically update the build and revision, -// and "{Major}.{Minor}.{Build}.*" will update just the revision. - -[assembly: AssemblyVersion("1.0.*")] - -// The following attributes are used to specify the signing key for the assembly, -// if desired. See the Mono documentation for more information about signing. - -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile("")] - diff --git a/CharMap/CharMap/CharMap.csproj b/CharMap/CharMap/CharMap.csproj deleted file mode 100644 index 26d11fa..0000000 --- a/CharMap/CharMap/CharMap.csproj +++ /dev/null @@ -1,49 +0,0 @@ - - - - Debug - x86 - 9.0.30729 - 2.0 - {05891CEC-1AA4-4654-A6FF-75DD87EA59C2} - Exe - CharMap - CharMap - v3.5 - - - true - full - false - bin\Debug - DEBUG - prompt - 4 - x86 - false - - - none - false - bin\Release - prompt - 4 - x86 - false - - - - - - - - - Form - - - - Component - - - - \ No newline at end of file diff --git a/CharMap/CharMap/DrawUniMap.cs b/CharMap/CharMap/DrawUniMap.cs deleted file mode 100644 index 292b811..0000000 --- a/CharMap/CharMap/DrawUniMap.cs +++ /dev/null @@ -1,269 +0,0 @@ -#define PocketPC -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace CharMapTool -{ - public class DrawUniMap:Panel - { - public byte _bCurrCodepage{ - get{return bCurrCodepage;} - set{bCurrCodepage=value;} - } - private byte bCurrCodepage = 0x04; - - private int iOffsetTop = 4; - private int iOffsetLeft = 4; - - private int iWidth = 240; - public int _iWidth - { - get { return iWidth; } - set - { - iWidth = value; - //this.Refresh(); - } - } - private int iHeight = 320; - public int _iHeight - { - get { return iHeight; } - set - { - iHeight = value; - //this.Refresh(); - } - } - private int iXstep = 30, iYstep = 30; - private int uniFontSize=16; - private int uniFontSizeMap=32; - - private Font mapFont = new Font("Arial Unicode MS", 30, FontStyle.Regular); - public Font _mapFont{ - get {return mapFont;} - set {mapFont=value; - this.Refresh();} - } - - private void initDrawUni() - { - iWidth = this.Width-iOffsetLeft; - iHeight = this.Height - iOffsetTop; - - this.Paint += new PaintEventHandler(this.PaintMap); - this.Resize += new EventHandler(this.ResizeMap); - - //could assign click handler here, is done outside - this.MouseUp += new MouseEventHandler(_form_MouseUp); - - this.Refresh(); - } - - public DrawUniMap () - { - initDrawUni(); - } - - public class MessageEventArgs : EventArgs - { - private string _message; - public MessageEventArgs(string msg) - { - this._message = msg; - } - public string NewMessage - { - get - { - return _message; - } - } - } - public delegate void KlickedEventHandler(object sender, MessageEventArgs e); - public event KlickedEventHandler NewMessageHandler; - protected virtual void OnMessage(MessageEventArgs e) - { - System.Diagnostics.Debug.WriteLine("OnMessage"); - if (NewMessageHandler != null) - { - NewMessageHandler(this, e);//Raise the event - } - } - - public void _form_MouseUp(object sender, MouseEventArgs e) - { - System.Diagnostics.Debug.WriteLine("_form_MouseUp"); - if (e.Button == MouseButtons.Right) - return; - int x = e.X; - int y = e.Y; - if (x < iXstep) - return; - if (y < iYstep + iOffsetTop) - return; - int locX = (int)((x - iXstep) / iXstep); - int locY = (int)(((y - iYstep - iOffsetTop) / iYstep)) * 0x10; - int uCodePoint = locX + locY; - - //MessageBox.Show("You clicked: 0x" + locX.ToString("x02") + "/0x" + locY.ToString("x02") + " = " + uCodePoint.ToString("x02")); - - byte[] bytes = new byte[2]; - bytes[1] = bCurrCodepage; - bytes[0] = (byte)uCodePoint; - string s = Encoding.Unicode.GetString(bytes, 0, 2); - this.OnMessage(new MessageEventArgs(s)); - } - - public void ResizeMap(object sender, EventArgs e){ - System.Diagnostics.Debug.WriteLine("ResizeMap"); - iWidth = this.Width; - iHeight = this.Height; - //calculate cells, we want 16 columns and 16 rows - //plus one column for the indexing - //iXstep = _form.Width / 18; - //iYstep = iXstep; - - //iXstep - int iXCell = (iWidth - iOffsetLeft) / 18; - //iYstep - int iYCell = (iHeight - iOffsetTop) / 18; - iXstep = Math.Min(iXCell, iYCell); - iYstep = iXstep; - - //start with large font size - uniFontSizeMap=32; - uniFontSize=16; - - this.Refresh(); - } - //public delegate void PaintEventHandler(); - - public void PaintMap(object sender, PaintEventArgs e) - { - System.Diagnostics.Debug.WriteLine("PaintMap"); - int iX = 0, iY = 0; - byte bHigh = bCurrCodepage;// 0x04; - byte bLow = 0x00; - - - //calc maximum font cell size, for headers - uniFontSize = - this.getMaxFonzSize(e.Graphics, - new Font("Arial Unicode MS", 10, FontStyle.Regular), - iXstep, - 1); - - //calc maximum font size for map chars - uniFontSizeMap = this.getMaxFonzSize(e.Graphics, - _mapFont, - iXstep, - 1); - - - //headers font - Font drawFont = new Font("Arial Unicode MS", uniFontSize, FontStyle.Regular); - - SolidBrush drawBrush = new SolidBrush(Color.Black); - //draw header row - for (iX = 0; iX < 16; iX++) - { -#if PocketPC - e.Graphics.DrawString(iX.ToString("x2"), drawFont, drawBrush, - new RectangleF(iX * iXstep + iXstep + iOffsetLeft, - /*iYstep +*/ iOffsetTop, - iXstep, - iYstep)); -#else - e.Graphics.DrawString(iX.ToString("x2"), - drawFont, drawBrush, - new Point(iX * iXstep + iXstep, iYstep)); -#endif - } - for (iY = 0; iY < 16; iY++) - { - int xx = (iY * 0x10); - //draw header column -#if PocketPC - e.Graphics.DrawString(xx.ToString("x2"), - drawFont, drawBrush, - new RectangleF( - 0 + iOffsetLeft, //always left - iY * iYstep + iOffsetTop + iYstep, - iXstep, - iYstep)); -#else - e.Graphics.DrawString(xx.ToString("x2"), - drawFont, drawBrush, - new Point(0, iY * iYstep + iOffsetTop + iYstep)); -#endif - } - - for (iY = 0; iY < 16; iY++) - { - for (iX = 0; iX < 16; iX++) - { - Point p = new Point(iX * iXstep + iXstep + iOffsetLeft, - iY * iYstep + iOffsetTop + iYstep); - byte[] b = new byte[2]; - b[0] = bLow++; b[1] = bHigh; - - DrawUniChar(e, b, p); - } - } - } - - public void DrawUniChar(PaintEventArgs e, byte[] bUni, Point drawPoint) - { - byte[] bCode = bUni; - //bCode[1]=0x04; bCode[0]=0x16; - char[] uChr = Encoding.Unicode.GetChars(bCode); - String uStr = new string(uChr); - - //Font drawFont = new Font("Arial Unicode MS", uniFontSize, FontStyle.Regular); - mapFont = new Font(mapFont.Name, uniFontSizeMap, FontStyle.Regular); - - SolidBrush drawBrush = new SolidBrush(Color.Black); - - // Draw string to screen. -#if PocketPC - e.Graphics.DrawString(uStr, - mapFont, - drawBrush, - new RectangleF(drawPoint.X, drawPoint.Y, iXstep, iYstep)); -#else - - e.Graphics.DrawString(uStr, drawFont, drawBrush, drawPoint); -#endif - } - - private int getMaxFonzSize(Graphics g, Font font, int iCellWidth, int iNumChars){ - int iRet = 10; - Font testFont; // = font.Clone(); - - //start with a large font size - int iFSize = 72; // (int)font.Size; - testFont = new Font( font.Name, iFSize, FontStyle.Regular); - String sChars=""; - for(int x=0; xiCellWidth){ - iFSize--; - testFont = new Font( font.Name, iFSize, FontStyle.Regular); - } - //SizeF sizeF = g.MeasureString("00", font); - iRet = iFSize; - System.Diagnostics.Debug.WriteLine("Cell max="+iRet.ToString()); - return iRet; - } - } -} - diff --git a/CharMap/CharMap/Main.cs b/CharMap/CharMap/Main.cs deleted file mode 100644 index d3a2bb5..0000000 --- a/CharMap/CharMap/Main.cs +++ /dev/null @@ -1,260 +0,0 @@ -using System; -using System.Windows.Forms; - -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Text; - -using CharMapTool; - -namespace CharMap -{ - class MainClass - { - public static void Main (string[] args) - { - WinForm form = new WinForm (); - Application.Run (form); - //Console.WriteLine("Hello World!"); - } - } - public class WinForm : Form - { - DrawUniMap drawUniPanel; - public WinForm () - { - InitializeComponent (); - } - - ComboBox cboUnicodePlane; - - ComboBox lbFont; - Label lblFontName; - TextBox txtUniChar; - private System.Windows.Forms.MainMenu mainMenu1; - private System.Windows.Forms.MenuItem menuItem1; - private System.Windows.Forms.MenuItem mnuZoomIn; - private System.Windows.Forms.MenuItem mnuZoomOut; - private System.Windows.Forms.MenuItem mnuExit; - - byte bCurrCodepage=0x04; - int iOffsetTop = 30; - - private void InitializeComponent () - { - this.Width = 480; - this.Height = 640; - this.Text = "My Dialog"; - - - this.SuspendLayout(); - - drawUniPanel = new DrawUniMap(); - drawUniPanel.Location = new Point(0, 50); - drawUniPanel.Size = new Size(this.Width, this.Height - 50); - this.Controls.Add(drawUniPanel); - - Button btnOK = new Button (); - btnOK.Text = "OK"; - btnOK.Location = new System.Drawing.Point (4, 4); - btnOK.Size = new System.Drawing.Size (80, 24); - this.Controls.Add (btnOK); - btnOK.Click += new EventHandler (btnOK_Click); - - //combo to select 'codepage' - cboUnicodePlane = new ComboBox(); - cboUnicodePlane.DropDownStyle=ComboBoxStyle.DropDownList; - cboUnicodePlane.Items.Clear(); - for (int i=0; i<0xff; i++){ - cboUnicodePlane.Items.Insert(i, i.ToString("x02")); - } - cboUnicodePlane.SelectedIndex=0x04; - cboUnicodePlane.Location = new Point(100, 4); - cboUnicodePlane.Size = new System.Drawing.Size (80, 60); - cboUnicodePlane.SelectedIndexChanged+=new EventHandler(lb_SelectedIndexChanged); - this.Controls.Add(cboUnicodePlane); - - //combo to select font - lbFont = new ComboBox(); - lbFont.DropDownStyle=ComboBoxStyle.DropDownList; - lbFont.Items.Clear(); - lbFont.Items.Insert(0, "Arial"); - lbFont.Items.Insert(1, "Arial Unicode MS"); - lbFont.Items.Insert(2, "Times New Roman"); - lbFont.Items.Insert(3, "Fanatasie"); - lbFont.SelectedIndex=1; - lbFont.Location=new Point(190,4); - lbFont.Size=new Size(120,60); - lbFont.SelectedIndexChanged+=new EventHandler(lbFont_SelectedIndexChanged); - this.Controls.Add(lbFont); - - lblFontName = new Label(); - lblFontName.Text=lbFont.SelectedItem.ToString(); - lblFontName.Size = new Size(120, 24); - lblFontName.Location= new Point(330,4); - this.Controls.Add(lblFontName); - - txtUniChar = new System.Windows.Forms.TextBox(); - // - // txtUniChar - // - this.txtUniChar.Location = new System.Drawing.Point(240, 32); - this.txtUniChar.Name = "txtUniChar"; - this.txtUniChar.ReadOnly = true; - this.txtUniChar.Size = new System.Drawing.Size(23, 21); - this.Controls.Add(txtUniChar); - - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.menuItem1 = new System.Windows.Forms.MenuItem(); - this.mnuZoomIn = new System.Windows.Forms.MenuItem(); - this.mnuZoomOut = new System.Windows.Forms.MenuItem(); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // menuItem1 - // - this.menuItem1.MenuItems.Add(this.mnuZoomIn); - this.menuItem1.MenuItems.Add(this.mnuZoomOut); - this.menuItem1.Text = "Options"; - // - // mnuZoomIn - // - this.mnuZoomIn.Text = "Zoom In"; - this.mnuZoomIn.Click += new System.EventHandler(this.mnuZoomIn_Click); - // - // mnuZoomOut - // - this.mnuZoomOut.Text = "Zoom Out"; - this.mnuZoomOut.Click += new System.EventHandler(this.mnuZoomOut_Click); - this.Menu = this.mainMenu1; - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuExit); - this.mainMenu1.MenuItems.Add(this.menuItem1); - - this.Load += new System.EventHandler(this.Form1_Load); - - drawUniPanel._bCurrCodepage = (byte)cboUnicodePlane.SelectedIndex; - - this.FormBorderStyle = FormBorderStyle.Sizable; - drawUniPanel.NewMessageHandler += new DrawUniMap.KlickedEventHandler(drawUni_NewMessageHandler); - - this.ResumeLayout(); - } - - void drawUni_NewMessageHandler(object sender, DrawUniMap.MessageEventArgs e) - { - System.Diagnostics.Debug.WriteLine("Message: " + e.NewMessage); - txtUniChar.Text = e.NewMessage; - } - - private void lb_SelectedIndexChanged(object sender, EventArgs e){ - bCurrCodepage=(byte)cboUnicodePlane.SelectedIndex; - drawUniPanel._bCurrCodepage=bCurrCodepage; - this.Refresh(); - } - private void lbFont_SelectedIndexChanged(object sender, EventArgs e){ - drawUniPanel._mapFont=new Font(lbFont.SelectedItem.ToString(), 30, FontStyle.Regular); - lblFontName.Text=drawUniPanel._mapFont.Name; - } - private void Form_Paint (object sender, PaintEventArgs e) - { - /* - // Create string to draw. - // 0x0416 -> Ж - String drawString = "Sample Text: Ж / " +uStr ; - // Create font and brush. - Font drawFont = new Font("Arial Unicode MS", 16); - SolidBrush drawBrush = new SolidBrush(Color.Black); - - // Create point for upper-left corner of drawing. - PointF drawPoint = new PointF(150.0F, 150.0F); - - // Draw string to screen. - e.Graphics.DrawString(drawString, drawFont, drawBrush, drawPoint); - */ - int iX=0, iY=0; - int iXstep=30, iYstep=30; - byte bHigh=bCurrCodepage;// 0x04; - byte bLow=0x00; - - - Font drawFont = new Font("Arial Unicode MS", 10); - SolidBrush drawBrush = new SolidBrush(Color.Black); - for(iX=0; iX<16; iX++){ - e.Graphics.DrawString(iX.ToString("x2"), - drawFont, drawBrush, - new Point(iX*iXstep+iXstep, iYstep)); - } - for(iY=0; iY<16; iY++){ - int xx = (iY*0x10); - e.Graphics.DrawString(xx.ToString("x2"), - drawFont, drawBrush, - new Point(0, iY* iYstep + iOffsetTop+iYstep)); - } - - for(iY=0; iY<16; iY++){ - for (iX=0; iX<16; iX++){ - Point p = new Point(iX*iXstep+iXstep, iY*iYstep + iOffsetTop + iYstep); - byte[] b=new byte[2]; - b[0]=bLow++; b[1]=bHigh; - - DrawUniChar(e, b, p); - } - } - } - - public void DrawUniChar(PaintEventArgs e, byte[] bUni, Point drawPoint) - { - byte[] bCode = bUni; - //bCode[1]=0x04; bCode[0]=0x16; - char[] uChr = Encoding.Unicode.GetChars(bCode); - String uStr = new string(uChr); - - Font drawFont = new Font("Arial Unicode MS", 16); - SolidBrush drawBrush = new SolidBrush(Color.Black); - - // Draw string to screen. - e.Graphics.DrawString(uStr, drawFont, drawBrush, drawPoint); - } - - private void btnOK_Click (object sender, System.EventArgs e) - { - this.DialogResult = DialogResult.OK; - this.Close (); - } - private void mnuExit_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.OK; - this.Close(); - } - private void mnuZoomIn_Click(object sender, EventArgs e) - { - if (drawUniPanel.Width > 2 * Screen.PrimaryScreen.Bounds.Width) - return; - drawUniPanel.Width = (int)(drawUniPanel.Width * 1.2); - drawUniPanel.Height = (int)(drawUniPanel.Height * 1.2); - } - - private void Form1_Load(object sender, EventArgs e) - { - txtUniChar.Font = new Font("Arial Unicode MS", 9, FontStyle.Bold); - } - - private void mnuZoomOut_Click(object sender, EventArgs e) - { - if (drawUniPanel.Width < 120) - return; - drawUniPanel.Width = (int)(drawUniPanel.Width * 0.8); - drawUniPanel.Height = (int)(drawUniPanel.Height * 0.8); - - } - - } -} - diff --git a/CharMap/CharMapCF/CharMapCF.csproj b/CharMap/CharMapCF/CharMapCF.csproj deleted file mode 100644 index f5cf525..0000000 --- a/CharMap/CharMapCF/CharMapCF.csproj +++ /dev/null @@ -1,96 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {89F3C913-82BF-4185-955A-786595C82B3F} - WinExe - Properties - CharMapCF - CharMapCF - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.1 - CharMapCF - v2.0 - Windows Mobile 5.0 Pocket PC SDK - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - Component - - - - Form - - - Form1.cs - - - - - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - \ No newline at end of file diff --git a/CharMap/CharMapCF/DrawUniMap.cs b/CharMap/CharMapCF/DrawUniMap.cs deleted file mode 100644 index 9897ca5..0000000 --- a/CharMap/CharMapCF/DrawUniMap.cs +++ /dev/null @@ -1,391 +0,0 @@ -#define PocketPC -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -//Test with a copy of C:\Windows\Fonts\ARIALUNI.TTF on device! - -namespace CharMapTool -{ - /// - /// draw a panel with all 256 glyphs of a font using one of the unicode Basic Multilanguage Panel unicode codepages - /// - public class DrawUniMap:Panel - { - /// - /// a var for debug usage - /// - private static int msgCount=0; - /// - /// the 'codepage' used for display - /// - public byte _bCurrCodepage{ - get{return bCurrCodepage;} - set{ - bCurrCodepage=value; - this.Refresh(); - } - } - private byte bCurrCodepage = 0x04; - - /// - /// the top margin for drawing the table - /// - private int iOffsetTop = 4; - /// - /// the top margin for drawing the table - /// - private int iOffsetLeft = 4; - /// - /// the initial width of the table (panel) - /// ignored during init! - /// - private int iWidth = 240; - /// - /// the width of the panel (table) - /// - public int _iWidth - { - get { return iWidth; } - set - { - iWidth = value; - //this.Refresh(); - } - } - - /// - /// the initial height of the table (panel) - /// ignored during init! - /// - private int iHeight = 320; - /// - /// the height of the panel (table) - /// - public int _iHeight - { - get { return iHeight; } - set - { - iHeight = value; - //this.Refresh(); - } - } - - /// - /// the initial rectangle for each char - /// - private int iXstep = 30, iYstep = 30; - /// - /// initial fontsize of the font used for header row and column - /// - private int uniFontSize=16; - /// - /// initial fontsize of the font used for the unicode glyphs table - /// - private int uniFontSizeMap=32; - /// - /// initial font used for the glyphs table chars - /// - private Font mapFont = new Font("Arial Unicode MS", 30, FontStyle.Regular); - public Font _mapFont{ - get {return mapFont;} - set {mapFont=value; - this.Refresh();} - } - public FontStyle _fontStyle - { - get - { - return mapFont.Style; - } - set - { - mapFont = new Font(mapFont.Name, 30, value); - } - } - - /// - /// initialize the control - /// - private void initDrawUni() - { - iWidth = this.Width-iOffsetLeft; - iHeight = this.Height - iOffsetTop; - - this.Paint += new PaintEventHandler(this.PaintMap); - this.Resize += new EventHandler(this.ResizeMap); - - this.MouseUp += new MouseEventHandler(_panel_MouseUp); - - this.Refresh(); - } - /// - /// constructor for new unicode glyphs panel - /// - public DrawUniMap () - { - initDrawUni(); - } - #region MessageEventArgs - public class MessageEventArgs : EventArgs - { - private string _message; - private byte[] _bytes; - public MessageEventArgs(string msg) - { - this._message = msg; - _bytes = Encoding.Unicode.GetBytes(msg); - } - public string NewMessage - { - get - { - return _message; - } - } - public byte[] bytes - { - get { return _bytes; } - } - public string getBytesString - { - get - { - string sHex = ""; - for (int i = _bytes.Length-1; i >=0 ; i--) - { - sHex += _bytes[i].ToString("x02"); - } - sHex = "0x" + sHex; - return sHex; - } - } - } - #endregion - #region delegates_and_events - /// - /// this will inform the subscriber about the char clicked - /// - public delegate void KlickedEventHandler(object sender, MessageEventArgs e); - public event KlickedEventHandler NewMessageHandler; - protected virtual void OnMessage(MessageEventArgs e) - { - System.Diagnostics.Debug.WriteLine("OnMessage"); - if (NewMessageHandler != null) - { - NewMessageHandler(this, e);//Raise the event - } - } - #endregion - - /// - /// a click will fire the OnMessage event handlers and informs about the glyh clicked - /// - public void _panel_MouseUp(object sender, MouseEventArgs e) - { - System.Diagnostics.Debug.WriteLine(msgCount++.ToString() + " _form_MouseUp"); - if (e.Button == MouseButtons.Right) - return; - int x = e.X; - int y = e.Y; - if (x < iXstep) - return; - if (y < iYstep + iOffsetTop) - return; - int locX = (int)((x - iXstep) / iXstep); - int locY = (int)(((y - iYstep - iOffsetTop) / iYstep)) * 0x10; - int uCodePoint = locX + locY; - - //MessageBox.Show("You clicked: 0x" + locX.ToString("x02") + "/0x" + locY.ToString("x02") + " = " + uCodePoint.ToString("x02")); - - byte[] bytes = new byte[2]; - bytes[1] = bCurrCodepage; - bytes[0] = (byte)uCodePoint; - string s = Encoding.Unicode.GetString(bytes, 0, 2); - this.OnMessage(new MessageEventArgs(s)); - } - /// - /// the resize event handler will perform some updates for the drawing - /// - public void ResizeMap(object sender, EventArgs e){ - System.Diagnostics.Debug.WriteLine(msgCount++.ToString() + " ResizeMap"); - iWidth = this.Width; - iHeight = this.Height; - //calculate cells, we want 16 columns and 16 rows - //plus one column for the indexing - //iXstep = _form.Width / 18; - //iYstep = iXstep; - - //iXstep - int iXCell = (iWidth - iOffsetLeft) / 18; - //iYstep - int iYCell = (iHeight - iOffsetTop) / 18; - iXstep = Math.Min(iXCell, iYCell); - iYstep = iXstep; - - //start with large font size - uniFontSizeMap=32; - uniFontSize=16; - - this.Refresh(); - } - /// - /// this is the paint event handler which does all the drawing - /// - public void PaintMap(object sender, PaintEventArgs e) - { - System.Diagnostics.Debug.WriteLine(msgCount++.ToString() + " PaintMap"); - int iX = 0, iY = 0; - byte bHigh = bCurrCodepage;// 0x04; - byte bLow = 0x00; - - - //calc maximum font cell size, for headers - uniFontSize = - this.getMaxFonzSize(e.Graphics, - new Font("Arial Unicode MS", 10, FontStyle.Regular), - iXstep, - 1); - - //calc maximum font size for map chars - uniFontSizeMap = this.getMaxFonzSize(e.Graphics, - _mapFont, - iXstep, - 1); - - - //headers font - Font drawFont = new Font("Arial Unicode MS", uniFontSize, FontStyle.Regular); - - SolidBrush drawBrush = new SolidBrush(Color.Black); - //draw header row - for (iX = 0; iX < 16; iX++) - { - e.Graphics.DrawString(iX.ToString("x2"), drawFont, drawBrush, - new RectangleF(iX * iXstep + iXstep + iOffsetLeft, - /*iYstep +*/ iOffsetTop, - iXstep, - iYstep)); - } - for (iY = 0; iY < 16; iY++) - { - int xx = (iY * 0x10); - //draw header column - e.Graphics.DrawString(xx.ToString("x2"), - drawFont, drawBrush, - new RectangleF( - 0 + iOffsetLeft, //always left - iY * iYstep + iOffsetTop + iYstep, - iXstep, - iYstep)); - } - - //draw all glyphs at there rectangles - for (iY = 0; iY < 16; iY++) - { - for (iX = 0; iX < 16; iX++) - { - Point p = new Point(iX * iXstep + iXstep + iOffsetLeft, - iY * iYstep + iOffsetTop + iYstep); - byte[] b = new byte[2]; - b[0] = bLow++; b[1] = bHigh; - - DrawUniChar(e, b, p); - } - } - } - /// - /// draw one glyph - /// - /// - /// - /// - public void DrawUniChar(PaintEventArgs e, byte[] bUni, Point drawPoint) - { - byte[] bCode = bUni; - //bCode[1]=0x04; bCode[0]=0x16; - char[] uChr = Encoding.Unicode.GetChars(bCode); - String uStr = new string(uChr); - - //Font drawFont = new Font("Arial Unicode MS", uniFontSize, FontStyle.Regular); - mapFont = new Font(mapFont.Name, uniFontSizeMap, mapFont.Style);// FontStyle.Regular); - - SolidBrush drawBrush = new SolidBrush(Color.Black); - - // Draw string to screen. - e.Graphics.DrawString(uStr, - mapFont, - drawBrush, - new RectangleF(drawPoint.X, drawPoint.Y, iXstep, iYstep)); - } - /// - /// enlarge or shrink the panel size - /// no shrink lower than 120 and no enlarge to 2*parent.width - /// - /// the maginfication factor - /// magnification factor or 0 for error - public double zoomInOut(double fZoom) - { - CharMapCF.winhelper.enableRedraw(this, false); - if (fZoom < 1) - { - if ((this.Width * fZoom) < 120) - fZoom = 0; - else - { - this.Width = (int)(this.Width * 0.8); - this.Height = (int)(this.Height * 0.8); - } - } - else if (fZoom > 1) - { - if ((this.Width * fZoom) > 2 * Screen.PrimaryScreen.Bounds.Width) - fZoom = 0; - else - { - this.Width = (int)(this.Width * fZoom); - this.Height = (int)(this.Height * fZoom); - } - } - - CharMapCF.winhelper.enableRedraw(this, true); - return fZoom; - } - /// - /// return the max font size fitting in iWidth - /// - /// - /// font to use for measuring - /// width of the cell to fit - /// how many chars to measure, have to fit - /// - private int getMaxFonzSize(Graphics g, Font font, int iCellWidth, int iNumChars){ - int iRet = 10; - Font testFont; // = font.Clone(); - - //start with a large font size - int iFSize = 72; // (int)font.Size; - testFont = new Font( font.Name, iFSize, FontStyle.Regular); - String sChars=""; - for(int x=0; xiCellWidth){ - iFSize--; - testFont = new Font( font.Name, iFSize, FontStyle.Regular); - } - //SizeF sizeF = g.MeasureString("00", font); - iRet = iFSize; - System.Diagnostics.Debug.WriteLine("Cell max="+iRet.ToString()); - return iRet; - } - } -} - diff --git a/CharMap/CharMapCF/FontClass.cs b/CharMap/CharMapCF/FontClass.cs deleted file mode 100644 index 57a9e1e..0000000 --- a/CharMap/CharMapCF/FontClass.cs +++ /dev/null @@ -1,282 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; - -//disable unused warnings -#pragma warning disable 0169 - -namespace CharMapCF -{ - static class winhelper - { - //disable redraw - [DllImport("coredll")] - public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); - private const Int32 WM_SETREDRAW = 0x0B; - /* - SendMessage( .Handle, WM_SETREDRAW, IntPtr(CInt(False)), IntPtr.Zero) - */ - public static void enableRedraw(System.Windows.Forms.Control control, bool bEnable) - { - IntPtr hwnd = control.Handle; - SendMessage(hwnd, WM_SETREDRAW, Convert.ToInt32(bEnable), 0); - if (bEnable) - control.Refresh(); - } - - } - class FontClass - { - delegate int EnumFontDelegate(IntPtr lpelfe, IntPtr lpntme, EnumFontsType FontType, int lParam); - private List fontNames; - IntPtr fpEnumProc; - EnumFontDelegate enumFontDelegate; - - [DllImport("coredll.dll")] - private static extern int EnumFontFamilies(IntPtr hdc, string - fontFamily, IntPtr lpEnumFontFamExProc, IntPtr lParam); - - [DllImport("coredll.dll")] - private static extern IntPtr GetDesktopWindow(); - - [DllImport("coredll.dll")] - private static extern IntPtr GetDC(IntPtr hwnd); - - [DllImport("coredll.dll")] - private static extern IntPtr ReleaseDC(IntPtr hdc); - - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - class LOGFONT - { - public int lfHeight = 0; - public int lfWidth = 0; - public int lfEscapement = 0; - public int lfOrientation = 0; - public /*int*/ lfWeightType lfWeight = 0; - public byte lfItalic = 0; - public byte lfUnderline = 0; - public byte lfStrikeOut = 0; - public /*byte*/lfCharsetType lfCharSet = lfCharsetType.DEFAULT_CHARSET; // 1 = DEFAULT_CHARSET - public byte lfOutPrecision = 0; - public byte lfClipPrecision = 0; - public byte lfQuality = 0; - public byte lfPitchAndFamily = 0; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] - public string - lfFaceName = null; - - } - enum lfPitchAndFamilyType{ - DEFAULT_PITCH = 0, - FIXED_PITCH = 1, - VARIABLE_PITCH = 2 - }; - - enum lfCharsetType : byte{ - ANSI_CHARSET = 0, - DEFAULT_CHARSET = 1, - SYMBOL_CHARSET = 2, - SHIFTJIS_CHARSET = 128, - HANGEUL_CHARSET = 129, - HANGUL_CHARSET = 129, - GB2312_CHARSET = 134, - CHINESEBIG5_CHARSET = 136, - OEM_CHARSET = 255, - - JOHAB_CHARSET = 130, - HEBREW_CHARSET = 177, - ARABIC_CHARSET = 178, - GREEK_CHARSET = 161, - TURKISH_CHARSET = 162, - VIETNAMESE_CHARSET = 163, - THAI_CHARSET = 222, - EASTEUROPE_CHARSET = 238, - RUSSIAN_CHARSET = 204, - MAC_CHARSET = 77, - BALTIC_CHARSET = 186 - }; - - [Flags] - enum lfLangSetType:uint{ - FS_LATIN1 = 0x00000001, - FS_ATIN2 = 0x00000002, - FS_CYRIIC = 0x00000004, - FS_GREEK = 0x00000008, - FS_TURKISH = 0x00000010, - FS_HEBREW = 0x00000020, - FS_ARABIC = 0x00000040, - FS_BATIC = 0x00000080, - FS_VIETNAMESE = 0x00000100, - FS_THAI = 0x00010000, - FS_JISJAPAN = 0x00020000, - FS_CHINESESIMP = 0x00040000, - FS_WANSUNG = 0x00080000, - FS_CHINESETRAD = 0x00100000, - FS_JOHAB = 0x00200000, - FS_SYMBO = 0x80000000 - }; - - /// - /// Specifies whether the font is italic, underscored, outlined, bold, and so forth. - /// The following list shows the bits corresponding to each font type. - /// - [Flags] - enum ntmFlags{ - //Bit Font - Italic = 0, - Underscore = 0x02, - Negative = 0x04, - Outline = 0x08, - Strikeout = 0x10, - Bold = 0x20 - }; - class NEWTEXTMETRIC - { - UInt32 tmHeight; //LONG - UInt32 tmAscent; - UInt32 tmDescent; - UInt32 tmInternalLeading; - UInt32 tmExternalLeading; - UInt32 tmAveCharWidth; - UInt32 tmMaxCharWidth; - UInt32 tmWeight; - UInt32 tmOverhang; - UInt32 tmDigitizedAspectX; - UInt32 tmDigitizedAspectY; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] - string tmFirstChar; //BCHAR - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] - string tmLastChar; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] - string tmDefaultChar; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] - string tmBreakChar; - byte tmItalic; - byte tmUnderlined; - byte tmStruckOut; - byte tmPitchAndFamily; - byte tmCharSet; - short ntmFlags; //DWORD - uint ntmSizeEM; - uint ntmCellHeight; - uint ntmAvgWidth; - } ; - - enum EnumFontsType - { - DEVICE_FONTTYPE = 0x0000, //??? - RASTER_FONTTYPE = 0x0001, //wingdi.h - TRUETYPE_FONTTYPE = 0x0004 //wingdi.h - }; - /// - /// Specifies the weight of the font in the range 0 through 1000. For example, 400 is normal and 700 is bold. - /// If this value is zero, a default weight is used. - /// - public enum lfWeightType - { - //The following values are defined for convenience. - //Value Weight, - FW_DONTCARE = 0, - FW_THIN = 100, - FW_EXTRALIGHT = 200, - FW_ULTRALIGHT = 200, - FW_LIGHT = 300, - FW_NORMAL = 400, - FW_REGULAR = 400, - FW_MEDIUM = 500, - FW_SEMIBOLD = 600, - FW_DEMIBOLD = 600, - FW_BOLD = 700, - FW_EXTRABOLD = 800, - FW_ULTRABOLD = 800, - FW_HEAVY = 900, - FW_BLACK = 900 - }; - public FontClass() - { - fontNames = new List(); - buildList(); - } - /* - int CALLBACK EnumFontFamProc( - const LOGFONT FAR* lpelf, - const TEXTMETRIC FAR* lpntm, - DWORD FontType, - LPARAM lParam - ); - */ - /// - /// - /// - /// IntPtr LOGFONT structure that contains information about the logical attributes of the font - /// structure that contains information about the physical attributes of the font, if the font is a TrueType font. If the font is not a TrueType font, this parameter points to a TEXTMETRIC structure - /// [in] DWORD that specifies the type of the font: - /// DEVICE_FONTTYPE - /// RASTER_FONTTYPE - /// TRUETYPE_FONTTYPE - /// Pointer to the application-defined data passed by the EnumFontFamilies function - /// Nonzero continues enumeration. Zero stops enumeration - private int EnumFontFamiliesExProc(IntPtr lpelfe, IntPtr lpntme, EnumFontsType FontType, int lParam) - { - LOGFONT logFont = (LOGFONT)Marshal.PtrToStructure(lpelfe, typeof(LOGFONT)); - - if (logFont.lfWeight == lfWeightType.FW_REGULAR && logFont.lfItalic==0) - { - //we dont like duplicate names - if(!fontNames.Contains(logFont.lfFaceName)) - fontNames.Add(logFont.lfFaceName); - - System.Diagnostics.Debug.WriteLine(logFont.lfFaceName); - } - // Non-zero return continues enumerating - return 1; - } - private void buildList(){ - // Need an HDC to pass to EnumFontFamilies - IntPtr hwnd = GetDesktopWindow(); - IntPtr hdc = GetDC(hwnd); - - LOGFONT logFont = new LOGFONT(); - - enumFontDelegate = new EnumFontDelegate(EnumFontFamiliesExProc); - fpEnumProc = Marshal.GetFunctionPointerForDelegate(enumFontDelegate); - - EnumFontFamilies(hdc, null, fpEnumProc, IntPtr.Zero); - - // We got a list of the major families. Copy the list, - // then clear it so we can go back and grab all the individual fonts. - List fontFamilies = new List(); - fontFamilies.AddRange(fontNames); - fontNames.Clear(); - - foreach(string fontFamily in fontFamilies) - { - EnumFontFamilies(hdc, fontFamily, fpEnumProc, IntPtr.Zero); - } - - ReleaseDC(hdc); - - foreach(string s in fontNames) - { - //listBox1.Items.Add(s); - } - } - public string[] getFontList() - { - buildList(); - string[] sList = new string[fontNames.Count]; - int i = 0; - foreach(string s in fontNames) - { - sList[i] = s; - i++; - //listBox1.Items.Add(s); - } - return sList; - } - } -} diff --git a/CharMap/CharMapCF/Form1.Designer.cs b/CharMap/CharMapCF/Form1.Designer.cs deleted file mode 100644 index 0643cf7..0000000 --- a/CharMap/CharMapCF/Form1.Designer.cs +++ /dev/null @@ -1,163 +0,0 @@ -namespace CharMapCF -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.menuItem1 = new System.Windows.Forms.MenuItem(); - this.mnuZoomIn = new System.Windows.Forms.MenuItem(); - this.mnuZoomOut = new System.Windows.Forms.MenuItem(); - this.cboUnicodePlane = new System.Windows.Forms.ComboBox(); - this.cboFont = new System.Windows.Forms.ComboBox(); - this.lblFont = new System.Windows.Forms.Label(); - this.label1 = new System.Windows.Forms.Label(); - this.txtUniChar = new System.Windows.Forms.TextBox(); - this.btnCopy = new System.Windows.Forms.Button(); - this.mnuBold = new System.Windows.Forms.MenuItem(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuExit); - this.mainMenu1.MenuItems.Add(this.menuItem1); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // menuItem1 - // - this.menuItem1.MenuItems.Add(this.mnuZoomIn); - this.menuItem1.MenuItems.Add(this.mnuZoomOut); - this.menuItem1.MenuItems.Add(this.mnuBold); - this.menuItem1.Text = "Options"; - // - // mnuZoomIn - // - this.mnuZoomIn.Text = "Zoom In"; - this.mnuZoomIn.Click += new System.EventHandler(this.mnuZoomIn_Click); - // - // mnuZoomOut - // - this.mnuZoomOut.Text = "Zoom Out"; - this.mnuZoomOut.Click += new System.EventHandler(this.mnuZoomOut_Click); - // - // cboUnicodePlane - // - this.cboUnicodePlane.Location = new System.Drawing.Point(100, 3); - this.cboUnicodePlane.Name = "cboUnicodePlane"; - this.cboUnicodePlane.Size = new System.Drawing.Size(73, 22); - this.cboUnicodePlane.TabIndex = 0; - this.cboUnicodePlane.SelectedIndexChanged += new System.EventHandler(this.cboUnicodePlane_SelectedIndexChanged); - // - // cboFont - // - this.cboFont.Location = new System.Drawing.Point(3, 28); - this.cboFont.Name = "cboFont"; - this.cboFont.Size = new System.Drawing.Size(91, 22); - this.cboFont.TabIndex = 0; - this.cboFont.SelectedIndexChanged += new System.EventHandler(this.cboFont_SelectedIndexChanged); - // - // lblFont - // - this.lblFont.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); - this.lblFont.Location = new System.Drawing.Point(100, 28); - this.lblFont.Name = "lblFont"; - this.lblFont.Size = new System.Drawing.Size(102, 22); - // - // label1 - // - this.label1.Location = new System.Drawing.Point(3, 3); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(90, 22); - this.label1.Text = "Unicode Plane:"; - // - // txtUniChar - // - this.txtUniChar.Location = new System.Drawing.Point(179, 3); - this.txtUniChar.Name = "txtUniChar"; - this.txtUniChar.ReadOnly = true; - this.txtUniChar.Size = new System.Drawing.Size(23, 21); - this.txtUniChar.TabIndex = 2; - // - // btnCopy - // - this.btnCopy.Location = new System.Drawing.Point(208, 3); - this.btnCopy.Name = "btnCopy"; - this.btnCopy.Size = new System.Drawing.Size(22, 21); - this.btnCopy.TabIndex = 3; - this.btnCopy.Text = "C"; - this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click); - // - // mnuBold - // - this.mnuBold.Text = "Bold"; - this.mnuBold.Click += new System.EventHandler(this.mnuBold_Click); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.AutoScrollMargin = new System.Drawing.Size(10, 10); - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.btnCopy); - this.Controls.Add(this.txtUniChar); - this.Controls.Add(this.label1); - this.Controls.Add(this.lblFont); - this.Controls.Add(this.cboFont); - this.Controls.Add(this.cboUnicodePlane); - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "Form1"; - this.Text = "Form1"; - this.Load += new System.EventHandler(this.Form1_Load); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuExit; - private System.Windows.Forms.ComboBox cboUnicodePlane; - private System.Windows.Forms.ComboBox cboFont; - private System.Windows.Forms.Label lblFont; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.TextBox txtUniChar; - private System.Windows.Forms.Button btnCopy; - private System.Windows.Forms.MenuItem menuItem1; - private System.Windows.Forms.MenuItem mnuZoomIn; - private System.Windows.Forms.MenuItem mnuZoomOut; - private System.Windows.Forms.MenuItem mnuBold; - } -} - diff --git a/CharMap/CharMapCF/Form1.cs b/CharMap/CharMapCF/Form1.cs deleted file mode 100644 index 8420a37..0000000 --- a/CharMap/CharMapCF/Form1.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using CharMapTool; - -namespace CharMapCF -{ - public partial class Form1 : Form - { - DrawUniMap drawUniPanel; - byte bCurrCodepage = 0x04; - //int iOffsetTop = 30; - - public Form1() - { - - InitializeComponent(); - - drawUniPanel = new DrawUniMap(); - //is this a VGA screen? HI_RES_AWARE - if(Screen.PrimaryScreen.WorkingArea.Width>240) - drawUniPanel.Location = new Point(0, 100); - else - drawUniPanel.Location = new Point(0, 50); - drawUniPanel.Size = new Size(this.Width, this.Height - 50); - this.Controls.Add(drawUniPanel); - - //combo to select 'codepage' - cboUnicodePlane.Items.Clear(); - for (int i = 0; i < 0xff; i++) - { - cboUnicodePlane.Items.Insert(i, i.ToString("x02")); - } - cboUnicodePlane.SelectedIndex = 0x04; - - //combo to select font - cboFont.Items.Clear(); - //get a list of available fonts - FontClass fontClass = new FontClass(); - string[] sFonts = fontClass.getFontList(); - for (int iF = 0; iF < sFonts.Length; iF++) - { - cboFont.Items.Insert(0, sFonts[iF]); - } - - //add a fantasy font name to show what happens for non-existing fonts: - //windows replaces the font request with a 'matching' existing font - cboFont.Items.Insert(cboFont.Items.Count, "Fanatasie"); - - cboFont.SelectedIndex = 1; - - drawUniPanel._bCurrCodepage = (byte)cboUnicodePlane.SelectedIndex; - - this.FormBorderStyle = FormBorderStyle.Sizable; - drawUniPanel.NewMessageHandler += new DrawUniMap.KlickedEventHandler(drawUni_NewMessageHandler); - - this.ResumeLayout(); - } - - void drawUni_NewMessageHandler(object sender, DrawUniMap.MessageEventArgs e) - { - System.Diagnostics.Debug.WriteLine("Message: " + e.NewMessage); - txtUniChar.Text = e.NewMessage; - - this.Text = e.getBytesString; - } - - private void cboFont_SelectedIndexChanged(object sender, EventArgs e) - { - if (drawUniPanel == null) - return; - if(mnuBold.Checked) - drawUniPanel._mapFont = new Font(cboFont.SelectedItem.ToString(), 30, FontStyle.Bold); - else - drawUniPanel._mapFont = new Font(cboFont.SelectedItem.ToString(), 30, FontStyle.Regular); - - lblFont.Text = drawUniPanel._mapFont.Name; - } - - private void mnuExit_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.OK; - this.Close(); - } - - private void cboUnicodePlane_SelectedIndexChanged(object sender, EventArgs e) - { - if (drawUniPanel == null) - return; - bCurrCodepage = (byte)cboUnicodePlane.SelectedIndex; - drawUniPanel._bCurrCodepage = bCurrCodepage; - this.Refresh(); - - } - - private void btnCopy_Click(object sender, EventArgs e) - { - Clipboard.SetDataObject(txtUniChar.Text); - } - - private void mnuZoomIn_Click(object sender, EventArgs e) - { - drawUniPanel.zoomInOut(1.2); - } - - private void Form1_Load(object sender, EventArgs e) - { - txtUniChar.Font = new Font("Arial Unicode MS", 9, FontStyle.Bold); - } - - private void mnuZoomOut_Click(object sender, EventArgs e) - { - drawUniPanel.zoomInOut(0.8); - } - - private void mnuBold_Click(object sender, EventArgs e) - { - mnuBold.Checked = !mnuBold.Checked; - if (drawUniPanel == null) - return; - if(mnuBold.Checked) - drawUniPanel._mapFont = new Font(cboFont.SelectedItem.ToString(), 30, FontStyle.Bold); - else - drawUniPanel._mapFont = new Font(cboFont.SelectedItem.ToString(), 30, FontStyle.Regular); - - lblFont.Text = drawUniPanel._mapFont.Name; - } - - } -} \ No newline at end of file diff --git a/CharMap/CharMapCF/Form1.resx b/CharMap/CharMapCF/Form1.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/CharMap/CharMapCF/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/CharMap/CharMapCF/Program.cs b/CharMap/CharMapCF/Program.cs deleted file mode 100644 index 0e4fc99..0000000 --- a/CharMap/CharMapCF/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace CharMapCF -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/CharMap/CharMapCF/Properties/AssemblyInfo.cs b/CharMap/CharMapCF/Properties/AssemblyInfo.cs deleted file mode 100644 index fe1a6f6..0000000 --- a/CharMap/CharMapCF/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Resources; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("CharMapCF")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("CharMapCF")] -[assembly: AssemblyCopyright("Copyright © 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("e0745deb-4f6a-40d3-ba45-f8a9954d6c05")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] -[assembly: NeutralResourcesLanguageAttribute("ja-JP")] diff --git a/CharMap/CharMapCF/Properties/Resources.Designer.cs b/CharMap/CharMapCF/Properties/Resources.Designer.cs deleted file mode 100644 index 1f965c3..0000000 --- a/CharMap/CharMapCF/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.3053 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace CharMapCF.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("CharMapCF.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/CharMap/CharMapCF/Properties/Resources.resx b/CharMap/CharMapCF/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/CharMap/CharMapCF/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/CharMap/doc/Arial-Uni-0x04-zoomed.jpg b/CharMap/doc/Arial-Uni-0x04-zoomed.jpg deleted file mode 100644 index f83c05b..0000000 Binary files a/CharMap/doc/Arial-Uni-0x04-zoomed.jpg and /dev/null differ diff --git a/CharMap/doc/Arial-Uni-0x04.jpg b/CharMap/doc/Arial-Uni-0x04.jpg deleted file mode 100644 index 1f03006..0000000 Binary files a/CharMap/doc/Arial-Uni-0x04.jpg and /dev/null differ diff --git a/CharMap/doc/Dokument.1.txt b/CharMap/doc/Dokument.1.txt deleted file mode 100644 index 77307b4..0000000 --- a/CharMap/doc/Dokument.1.txt +++ /dev/null @@ -1,56 +0,0 @@ - /// <summary> - /// - /// </summary> - /// <param name="lpelfe">IntPtr LOGFONT structure that contains information about the logical attributes of the font</param> - /// <param name="lpntme">structure that contains information about the physical attributes of the font, if the font is a TrueType font. If the font is not a TrueType font, this parameter points to a TEXTMETRIC structure</param> - /// <param name="FontType">[in] DWORD that specifies the type of the font: - /// DEVICE_FONTTYPE - /// RASTER_FONTTYPE - /// TRUETYPE_FONTTYPE</param> - /// <param name="lParam">Pointer to the application-defined data passed by the EnumFontFamilies function</param> - /// <returns>Nonzero continues enumeration. Zero stops enumeration</returns> - private int EnumFontFamiliesExProc(IntPtr lpelfe, IntPtr lpntme, EnumFontsType FontType, int lParam) - { - LOGFONT logFont = (LOGFONT)Marshal.PtrToStructure(lpelfe, typeof(LOGFONT)); - - if (logFont.lfWeight == lfWeightType.FW_REGULAR && logFont.lfItalic==0) - { - //we dont like duplicate names - if(!fontNames.Contains(logFont.lfFaceName)) - fontNames.Add(logFont.lfFaceName); - - System.Diagnostics.Debug.WriteLine(logFont.lfFaceName); - } - // Non-zero return continues enumerating - return 1; - } - private void buildList(){ - // Need an HDC to pass to EnumFontFamilies - IntPtr hwnd = GetDesktopWindow(); - IntPtr hdc = GetDC(hwnd); - - LOGFONT logFont = new LOGFONT(); - - enumFontDelegate = new EnumFontDelegate(EnumFontFamiliesExProc); - fpEnumProc = Marshal.GetFunctionPointerForDelegate(enumFontDelegate); - - EnumFontFamilies(hdc, null, fpEnumProc, IntPtr.Zero); - - // We got a list of the major families. Copy the list, - // then clear it so we can go back and grab all the individual fonts. - List<string> fontFamilies = new List<string>(); - fontFamilies.AddRange(fontNames); - fontNames.Clear(); - - foreach(string fontFamily in fontFamilies) - { - EnumFontFamilies(hdc, fontFamily, fpEnumProc, IntPtr.Zero); - } - - ReleaseDC(hdc); - - foreach(string s in fontNames) - { - //listBox1.Items.Add(s); - } - } diff --git a/CharMap/doc/tahoma-0x00.jpg b/CharMap/doc/tahoma-0x00.jpg deleted file mode 100644 index 84f7638..0000000 Binary files a/CharMap/doc/tahoma-0x00.jpg and /dev/null differ diff --git a/CharMap/doc/tahoma-0x04.jpg b/CharMap/doc/tahoma-0x04.jpg deleted file mode 100644 index 42313f5..0000000 Binary files a/CharMap/doc/tahoma-0x04.jpg and /dev/null differ diff --git a/CharMap/doc/wingdings-0x00.jpg b/CharMap/doc/wingdings-0x00.jpg deleted file mode 100644 index 85c2acb..0000000 Binary files a/CharMap/doc/wingdings-0x00.jpg and /dev/null differ diff --git a/CharMapCF.md b/CharMapCF.md new file mode 100644 index 0000000..aad4eb5 --- /dev/null +++ b/CharMapCF.md @@ -0,0 +1,12 @@ +# An app to show unicode char table # + +Sometimes you may want to see which chars (better say glyphs) are supported by a font installed on your mobile device. Unfortunately there is no charmap application pre-installed on windows mobile OS and I did not find any current app for this need. + +So I started this small project to enable you to check the glyphs for installed fonts. You can switch the char set table index (for example 0x04 is for Cyrillic) and the font. + +CharMapCF uses UCS-2, UTF-16 encoding and is able to switch between all 256 char tables of the unicode Basic Multilanguage Plane (BMP). + +Using this small tool you may find many code points and charset table index with undefined glyphs. Dont worry, this is normal. The unicode consortium has not defined +all code points and char sets with glyphs, there i still room for additional glyphs. + +CharmapCF will show all glyphs of 256 code points of one char set index at once within a table. You can easily find the unicode UCS-2 code point for all displayed glyphs as there is a header row and column with the codepoint number as hex. \ No newline at end of file diff --git a/CommAppCF.md b/CommAppCF.md new file mode 100644 index 0000000..031ec90 --- /dev/null +++ b/CommAppCF.md @@ -0,0 +1,16 @@ +# CommAppCF # +## a simple serial port terminal application with file send option ## +This is only a simple project implementing serial port communication. It was designed to be able to send files to a virtual comm port attached to a bluetooth printer. + +CommAppCF is the under-contruction release + +CommAppCFSerial is a release using serial communication only, no Bluetooth code + +CommAppCFbtSearch is a release using serial communication but including a BT connect dialog with BT discovery option + + +--- + + * Needs CF2 (Compact Framework 2) or higher. + * Visual Studio 2008 C# sources, Windows Mobile 5 SDK + * BT ones need Intermec device with Bluetooth option \ No newline at end of file diff --git a/CommAppCF/BTPort.cs b/CommAppCF/BTPort.cs deleted file mode 100644 index 4d80097..0000000 --- a/CommAppCF/BTPort.cs +++ /dev/null @@ -1,282 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; -using System.Net; -using System.Net.Sockets; -using System.IO; -using System.Threading; - -using OpenNETCF.Net.Bluetooth; - -namespace Comm.BT -{ - public class BTPort - { - private byte[] _bda; - private BluetoothAddress _bta; - private myThread _thread; - private bool _bStopThread = false; - //private Socket _socket; - private BluetoothClient _bluetoothClient; - private NetworkStream _networkStream = null; - private StreamReader _streamReader; - private StreamWriter _streamWriter; - public BTPort() - { - } - - public BTPort(byte[] bdAddress) - { - this._bda = bdAddress; - } - - public bool IsOpen() - { - if (_networkStream == null) - return false; - else - return true; - } - - public void Open(byte[] byteAddress) - { - this._bda = byteAddress; - this.Open(); - } - public void Open() - { - this.Close(); - - if (_bda == null) - return; - try - { - //_socket = new System.Net.Sockets.Socket(); - _bluetoothClient = new BluetoothClient(); - _bta = new BluetoothAddress(_bda); - _bluetoothClient.Connect(new BluetoothEndPoint(_bta, BluetoothService.SerialPort)); - - _networkStream = _bluetoothClient.GetStream(); - if(_networkStream!=null) - _thread = new myThread(ref _networkStream); - } - catch (SocketException sx) - { - System.Diagnostics.Debug.WriteLine("SocketException in Open(): " + sx.Message); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in Open(): " +ex.Message); - } - - } - public void Write(string s) - { - if(_networkStream!=null){ - System.IO.StreamWriter sw = new System.IO.StreamWriter(_networkStream); - if (sw.BaseStream != null) - { - if (sw.BaseStream.CanWrite) - { - //byte[] buf = Encoding.ASCII.GetBytes(fp_text); - sw.Write(s); //ns.Write(buf, 0, buf.Length); - //ns.Flush(); - sw.Flush(); - } - sw.Close(); - } - } - } - //public string Read is handled by DataReceived event handler - - //private System.Net.Sockets.NetworkStream connectBT(byte[] ba) - //{ - // this._networkStream = null; - // try - // { - // BluetoothAddress bda = new BluetoothAddress(ba); - // //System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(); - // BluetoothClient btClient = new BluetoothClient(); - // btClient.Connect(new BluetoothEndPoint(bda, BluetoothService.SerialPort)); - // _networkStream = btClient.GetStream(); - // return _networkStream; - // // System.IO.StreamWriter sw = new System.IO.StreamWriter(ns); - // // if (sw.BaseStream != null) - // // { - // // if (sw.BaseStream.CanWrite) - // // { - // // //byte[] buf = Encoding.ASCII.GetBytes(fp_text); - // // sw.Write(fp_text); //ns.Write(buf, 0, buf.Length); - // // //ns.Flush(); - // // sw.Flush(); - // // } - // // sw.Close(); - // // } - // // ns.Close(); - // // btClient.CloseSocket(); - // // btClient.Close(); - // // Cursor.Current = Cursors.Default; - // //} - // } - // catch (Exception x) - // { - // Cursor.Current = Cursors.Default; - // MessageBox.Show("Exception :" + x.Message); - // return ns; - // } - //} - - public void Close() - { - if (_thread != null) - { - _networkStream.Close(); - - _thread.Dispose(); - _thread = null; - } - } - - private BTDataReceivedEventHandler onDataReceived; - - public delegate void BTDataReceivedEventHandler(object sender, DataEventArgs d); - - //public event BTDataReceivedEventHandler BTDataReceived; - public event BTDataReceivedEventHandler BTDataReceived - { - add - { - this.onDataReceived = ((BTDataReceivedEventHandler)Delegate.Combine(((Delegate)this.onDataReceived), ((Delegate)value))); - } - remove - { - this.onDataReceived = ((BTDataReceivedEventHandler)Delegate.Remove(((Delegate)this.onDataReceived), ((Delegate)value))); - } - - } - - private void onDataReceivedEvent(object sender, DataEventArgs d) - { - BTDataReceivedEventHandler dataReceived = this.onDataReceived; - - if (dataReceived == null) - return; - dataReceived(this, d); - } - - - #region THREAD - public class DataEventArgs : EventArgs - { - /* HACK: fields are typically private, but making this internal so it - * can be accessed from other classes. In practice should use properties. - */ - internal string _string; - public DataEventArgs() - { - } - public DataEventArgs(string str) - : base() - { - this._string = str; - } - } - - public class myThread : System.ComponentModel.Component, IDisposable - { - private Thread _thread; - private bool _bStopThread = false; - #region EVENTSTUFF - - private BTDataReceivedEventHandler onDataReceived; - - public delegate void BTDataReceivedEventHandler(object sender, DataEventArgs d); - - //public event BTDataReceivedEventHandler BTDataReceived; - public event BTDataReceivedEventHandler BTDataReceived - { - add - { - this.onDataReceived = ((BTDataReceivedEventHandler)Delegate.Combine(((Delegate)this.onDataReceived), ((Delegate)value))); - } - remove - { - this.onDataReceived = ((BTDataReceivedEventHandler)Delegate.Remove(((Delegate)this.onDataReceived), ((Delegate)value))); - } - - } - - private void onDataReceivedEvent(object sender, DataEventArgs d) - { - BTDataReceivedEventHandler dataReceived = this.onDataReceived; - - if (dataReceived == null) - return; - dataReceived(this, d); - } - - private StreamReader _sr; - - #endregion - public myThread(ref NetworkStream ns) - { - this.onDataReceived = (BTDataReceivedEventHandler)null; - _sr = new StreamReader(ns); - _bStopThread = false; - _thread = new Thread(theThread); - _thread.Start(); - } - private bool disposed = false; - protected override void Dispose(bool disposing) - { - if (disposing) - { - _thread.Abort(); - //_bStopThread = true; - } - else - { - _bStopThread = true; - Thread.Sleep(1000); - } - this.disposed = true; - base.Dispose(disposing); - } - private void theThread() - { - System.Diagnostics.Debug.WriteLine("theThread: started..."); - try - { - string s = ""; - char[] buf = new char[1]; - int iCount = 0; - DataEventArgs args = new DataEventArgs(); - while (!_bStopThread && _sr != null) - { - iCount = _sr.Read(buf, 0, 1); - if (iCount != 0) - { - s = buf.ToString(); - args._string = s; - onDataReceivedEvent(this, args); - } - Thread.Sleep(1000); - } - - } - catch (ThreadAbortException tax) - { - System.Diagnostics.Debug.WriteLine("theThread: ThreadAbortException=" + tax.Message); - _bStopThread = true; - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("theThread: Exception=" + ex.Message); - } - System.Diagnostics.Debug.WriteLine("theThread: ...ended"); - } - } - #endregion - } -} diff --git a/CommAppCF/BluetoothCode/BluetoothAddress.cs b/CommAppCF/BluetoothCode/BluetoothAddress.cs deleted file mode 100644 index db3a9f9..0000000 --- a/CommAppCF/BluetoothCode/BluetoothAddress.cs +++ /dev/null @@ -1,61 +0,0 @@ -#region Using - -using System; - -#endregion - -namespace OpenNETCF.Net.Bluetooth { - /// - /// BluetoothAddress - /// - public sealed class BluetoothAddress : IComparable { - - private byte[] data; - public const int Giac = 0x9e8b33; - internal const int IacFirst = 0x9e8b00; - internal const int IacLast = 0x9e8b3f; - public const int Liac = 0x9e8b00; - public static readonly BluetoothAddress None = new BluetoothAddress(); - - static BluetoothAddress() { - None = new BluetoothAddress(); - } - - internal BluetoothAddress() { - this.data = new byte[8]; - } - - public BluetoothAddress(byte[] address) : this() { - if (address.Length != 6) { - throw new ArgumentException("address"); - } - Buffer.BlockCopy(address, 0, this.data, 0, 6); - } - public BluetoothAddress(long address) : this() { - BitConverter.GetBytes(address).CopyTo(this.data, 0); - } - - #region IComparable - - int IComparable.CompareTo(object obj) { - BluetoothAddress address = obj as BluetoothAddress; - if (address != null) { - return this.ToInt64().CompareTo(address.ToInt64()); - } - return -1; - - } - #endregion - - public long ToInt64() { - return BitConverter.ToInt64(this.data, 0); - } - - public byte[] ToByteArray() { - return this.data; - } - - - - } -} diff --git a/CommAppCF/BluetoothCode/BluetoothClient.cs b/CommAppCF/BluetoothCode/BluetoothClient.cs deleted file mode 100644 index 8de7b45..0000000 --- a/CommAppCF/BluetoothCode/BluetoothClient.cs +++ /dev/null @@ -1,309 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.BluetoothClient -// Copyright (C) 2003-2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Collections; -using System.Data; -using System.Runtime.InteropServices; -using System.Windows.Forms; -using System.Net.Sockets; -using System.Net; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Contains functionality to control the state of the Bluetooth hardware on a Smart Device. - /// - /// This class currently only supports devices which use the Microsoft Bluetooth stack such as the Orange SPV E200, devices which use the WidComm stack will not work. - public class BluetoothClient { - /*add by qiuq*/ - private bool authenticate; - private bool encrypt; - private short queryLength; - private Socket socket; - - /// - /// Creates a new instance of BluetoothClient. - /// - public BluetoothClient() { - //want to initialise winsock 2.2 - short ver = 0x0202; - - byte[] data = new byte[512]; - int result = WSAStartup(ver, data); - - //MessageBox.Show(System.Text.Encoding.ASCII.GetString(data, 4, 257)); - - if (result != 0) { - throw new Exception(result.ToString()); - } - /*add by qiuq*/ - try { - this.socket = new BluetoothSocket(); - } - catch (SocketException) { - throw new PlatformNotSupportedException("Bluetooth.NET is not supported on this device."); - } - - } - /// - /// Creates a new instance of BluetoothClient.(add by qiuq) - /// - /// - internal BluetoothClient(Socket s) { - this.authenticate = false; - this.encrypt = false; - this.queryLength = 0x10; - this.socket = s; - } - - public void CloseSocket() { - if ((this.socket != null) && this.socket.Connected) { - this.socket.Close(); - } - } - - public void Connect(BluetoothEndPoint ep) { - this.CloseSocket(); - if (this.socket == null) { - this.socket = new BluetoothSocket(); - } - this.socket.Connect(ep); - } - - public NetworkStream GetStream() { - if (this.socket == null) { - throw new ObjectDisposedException("Client", "The BluetoothClient has been closed."); - } - return new NetworkStream(this.socket); - } - - - - /// - /// Gets or Sets the current mode of operation of the Bluetooth radio. - /// - /// This setting will be persisted when the device is reset. - /// An Icon will be displayed in the tray on the Home screen and the device will emit a blue LED when Bluetooth is enabled. - public static RadioMode RadioMode { - get { - RadioMode mode = 0; - //get the mode - int result = BthGetMode(ref mode); - - //if successful return retrieved value - if (result != 0) { - throw new ExternalException("Error getting Bluetooth mode"); - - } - - //return setting - return mode; - } - set { - //set the status - int result = BthSetMode(value); - - //check for error - if (result != 0) { - throw new ExternalException("Error setting Bluetooth mode"); - } - } - } - - /// - /// Discovers accessible Bluetooth devices and returns their names and addresses. - /// - /// An array of BluetoothDeviceInfo objects describing the devices discovered. - public BluetoothDeviceInfo[] DiscoverDevices() { - ArrayList al = new ArrayList(); - try { - int handle = 0; - byte[] queryset = new byte[1024]; - BitConverter.GetBytes((int)60).CopyTo(queryset, 0); - BitConverter.GetBytes((int)16).CopyTo(queryset, 20); - - int bufferlen = 1024; - - int lookupresult = 0; - - //start looking for Bluetooth devices - lookupresult = BthNsLookupServiceBegin(queryset, LookupFlags.Containers, ref handle); - - while (lookupresult != -1) { - - lookupresult = BthNsLookupServiceNext(handle, LookupFlags.ReturnAddr | LookupFlags.ReturnName, ref bufferlen, queryset); - if (lookupresult != -1) { - //pointer to outputbuffer - int bufferptr = BitConverter.ToInt32(queryset, 48); - //remote socket address - int sockaddrptr = Marshal.ReadInt32((IntPtr)bufferptr, 8); - //remote socket len - int sockaddrlen = Marshal.ReadInt32((IntPtr)bufferptr, 12); - - BluetoothSocketAddress btsa = new BluetoothSocketAddress(); - - Marshal.Copy((IntPtr)sockaddrptr, btsa.ToByteArray(), 0, BluetoothSocketAddress.Length); - - //new deviceinfo - BluetoothDeviceInfo newdevice = new BluetoothDeviceInfo(btsa.Address, Marshal.PtrToStringUni((IntPtr)BitConverter.ToInt32(queryset, 4))); - - //add to discovered list - al.Add(newdevice); - - } - } - - //stop looking - lookupresult = BthNsLookupServiceEnd(handle); - - //return results - - } - catch (Exception ex) { - System.Diagnostics.Debug.WriteLine("Exception in DiscoverDevices(): " + ex.Message); - } - return (BluetoothDeviceInfo[])al.ToArray(typeof(BluetoothDeviceInfo)); - } - - public void Close() { - int result = WSACleanup(); - - if (result != 0) { - throw new Exception(result.ToString()); - } - } - - public static int ConnectSerial(int portindex, PortEmuParams pep) { - return RegisterDevice("COM", portindex, "btd.dll", pep.ToByteArray()); - } - - [DllImport("coredll.dll", SetLastError = true)] - private static extern int RegisterDevice( - string lpszType, - int dwIndex, - string lpszLib, - byte[] dwInfo); - - [DllImport("coredll.dll")] - private static extern bool DeregisterDevice( - int handle); - - [DllImport("BthUtil.dll")] - private static extern int BthSetMode( - RadioMode dwMode); - - [DllImport("BthUtil.dll")] - private static extern int BthGetMode( - ref RadioMode dwMode); - - - [DllImport("ws2.dll")] - private static extern int WSAStartup( - short versionrequested, - byte[] wsadata); - [DllImport("ws2.dll")] - private static extern int WSACleanup(); - - - [DllImport("Btdrt.dll")] - private static extern int BthNsLookupServiceBegin( - byte[] pQuerySet, - LookupFlags dwFlags, - ref int lphLookup); - - [DllImport("Btdrt.dll")] - private static extern int BthNsLookupServiceNext( - int hLookup, - LookupFlags dwFlags, - ref int lpdwBufferLength, - byte[] pResults); - - [DllImport("Btdrt.dll")] - private static extern int BthNsLookupServiceEnd( - int hLookup); - - #region Hardware Status - /// - /// Returns the current status of the Bluetooth radio hardware. - /// - /// A member of the enumeration. - public static HardwareStatus HardwareStatus { - get { - HardwareStatus status = 0; - int result = BthGetHardwareStatus(ref status); - - if (result != 0) { - throw new ExternalException("Error retrieving Bluetooth hardware status"); - } - return status; - } - } - [DllImport("Btdrt.dll")] - private static extern int BthGetHardwareStatus(ref HardwareStatus pistatus); - - #endregion - - #region LocalAddress - /// - /// Returns the address of the local Bluetooth device. - /// - public static BluetoothSocketAddress LocalAddress { - get { - BluetoothSocketAddress bsa = new BluetoothSocketAddress(); - - int result = BthReadLocalAddr(bsa.ToByteArray()); - - if (result != 0) { - throw new ExternalException("Error retrieving local Bluetooth address"); - } - - return bsa; - } - } - [DllImport("Btdrt.dll")] - private static extern int BthReadLocalAddr(byte[] pba); - - #endregion - - [DllImport("Btdrt.dll")] - private static extern int BthReadLocalVersion( - ref ushort phci_version, - ref ushort phci_revision, - ref ushort plmp_version, - ref ushort plmp_subversion, - ref ushort pmanufacturer, - ref ushort plmp_features); - - } - - - - public enum LookupFlags : uint { - Containers = 0x0002, - ReturnName = 0x0010, - ReturnAddr = 0x0100, - ReturnBlob = 0x0200, - } - - -} diff --git a/CommAppCF/BluetoothCode/BluetoothDeviceInfo.cs b/CommAppCF/BluetoothCode/BluetoothDeviceInfo.cs deleted file mode 100644 index 7f643ca..0000000 --- a/CommAppCF/BluetoothCode/BluetoothDeviceInfo.cs +++ /dev/null @@ -1,58 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.BluetoothDeviceInfo -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== - -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Summary description for BluetoothDeviceInfo. - /// - public class BluetoothDeviceInfo { - private byte[] m_id; - private string m_name; - - internal BluetoothDeviceInfo(byte[] id, string name) { - m_id = id; - m_name = name; - } - - /// - /// Gets the device identifier. - /// - public byte[] DeviceID { - get { - return m_id; - } - } - - /// - /// Gets a name of a device. - /// - public string DeviceName { - get { - return m_name; - } - } - } -} diff --git a/CommAppCF/BluetoothCode/BluetoothEndPoint.cs b/CommAppCF/BluetoothCode/BluetoothEndPoint.cs deleted file mode 100644 index 096793b..0000000 --- a/CommAppCF/BluetoothCode/BluetoothEndPoint.cs +++ /dev/null @@ -1,138 +0,0 @@ -#region Using - -using System; -using System.Net; -using System.Net.Sockets; - -#endregion - -namespace OpenNETCF.Net.Bluetooth { - /// - /// BluetoothEndPoint - /// - public class BluetoothEndPoint : EndPoint{ - private static int m_addressoffset; - private static int m_defaultport; - private BluetoothAddress m_id; - private int m_port; - private static int m_portoffset; - private static int m_salength; - private Guid m_service; - private static int m_serviceoffset; - public const int MaxPort = 0xffff; - public const int MinPort = 1; - - public BluetoothAddress Address { - get { - return this.m_id; - } - set { - this.m_id = value; - } - } - - public override AddressFamily AddressFamily { - get { - return (AddressFamily)0x20; - } - } - - public int Port { - get { - return this.m_port; - } - set { - this.m_port = value; - } - } - - public Guid Service { - get { - return this.m_service; - } - set { - this.m_service = value; - } - } - - - static BluetoothEndPoint() { - m_addressoffset = 8; - m_serviceoffset = 0x10; - m_portoffset = 0x20; - m_salength = 40; - } - - - public BluetoothEndPoint(BluetoothAddress address, Guid service) - : this(address, service, m_defaultport) { - } - - public BluetoothEndPoint(BluetoothAddress address, Guid service, int port) { - this.m_id = address; - this.m_service = service; - this.m_port = port; - } - - public override EndPoint Create(SocketAddress socketAddress) { - int index; - if (socketAddress == null) { - throw new ArgumentNullException("socketAddress"); - } - if (socketAddress[0] != 0x20) { - return base.Create(socketAddress); - } - byte[] address = new byte[6]; - for (index = 0; index < 6; index++) { - address[index] = socketAddress[m_addressoffset + index]; - } - byte[] b = new byte[0x10]; - for (index = 0; index < 0x10; index++) { - b[index] = socketAddress[m_serviceoffset + index]; - } - byte[] buffer3 = new byte[4]; - for (index = 0; index < 4; index++) { - buffer3[index] = socketAddress[m_portoffset + index]; - } - return new BluetoothEndPoint(new BluetoothAddress(address), new Guid(b), BitConverter.ToInt32(buffer3, 0)); - } - - public override bool Equals(object obj) { - BluetoothEndPoint point = obj as BluetoothEndPoint; - if (point == null) { - return base.Equals(obj); - } - if (this.Address.Equals(point.Address)) { - return this.Service.Equals(point.Service); - } - return false; - } - - public override int GetHashCode() { - return this.Address.GetHashCode(); - } - - public override SocketAddress Serialize() { - SocketAddress address = new SocketAddress((AddressFamily)0x20, m_salength); - address[0] = 0x20; - if (this.m_id != null) { - byte[] buffer = this.m_id.ToByteArray(); - for (int i = 0; i < 6; i++) { - address[i + m_addressoffset] = buffer[i]; - } - } - if (this.m_service != Guid.Empty) { - byte[] buffer2 = this.m_service.ToByteArray(); - for (int j = 0; j < 0x10; j++) { - address[j + m_serviceoffset] = buffer2[j]; - } - } - byte[] bytes = BitConverter.GetBytes(this.m_port); - for (int k = 0; k < 4; k++) { - address[k + m_portoffset] = bytes[k]; - } - return address; - } - - } -} diff --git a/CommAppCF/BluetoothCode/BluetoothService.cs b/CommAppCF/BluetoothCode/BluetoothService.cs deleted file mode 100644 index a85c490..0000000 --- a/CommAppCF/BluetoothCode/BluetoothService.cs +++ /dev/null @@ -1,97 +0,0 @@ -#region Using - -using System; - -#endregion - -namespace OpenNETCF.Net.Bluetooth { - /// - /// BluetoothService - /// - public class BluetoothService { - public BluetoothService() { - // - // TODO: - // - } - - public static readonly Guid AdvancedAudioDistribution = new Guid(0x110d, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AudioSink = new Guid(0x110b, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AudioSource = new Guid(0x110a, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AudioVideo = new Guid(0x112c, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AVRemoteControl = new Guid(0x110e, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AVRemoteControlTarget = new Guid(0x110c, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid BasicPrinting = new Guid(0x1122, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid BluetoothBase = new Guid(0, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid BrowseGroupDescriptor = new Guid(0x1001, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid CommonIsdnAccess = new Guid(0x1128, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid CordlessTelephony = new Guid(0x1109, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid DialupNetworking = new Guid(0x1103, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid DirectPrinting = new Guid(0x1118, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid DirectPrintingReferenceObjects = new Guid(0x1120, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Empty = Guid.Empty; - public static readonly Guid Fax = new Guid(0x1111, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid FtpProtocol = new Guid(10, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GenericAudio = new Guid(0x1203, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GenericFileTransfer = new Guid(0x1202, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GenericNetworking = new Guid(0x1201, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GenericTelephony = new Guid(0x1204, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GN = new Guid(0x1117, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Handsfree = new Guid(0x111e, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HandsfreeAudioGateway = new Guid(0x111f, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HardcopyCableReplacement = new Guid(0x1125, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HardcopyCableReplacementPrint = new Guid(0x1126, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HardcopyCableReplacementScan = new Guid(0x1127, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Headset = new Guid(0x1108, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HeadsetAudioGateway = new Guid(0x1112, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HttpProtocol = new Guid(12, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HumanInterfaceDevice = new Guid(0x1124, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Imaging = new Guid(0x111a, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ImagingAutomaticArchive = new Guid(0x111c, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ImagingReferenceObjects = new Guid(0x111d, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ImagingResponder = new Guid(0x111b, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Intercom = new Guid(0x1110, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid IPProtocol = new Guid(9, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid IrMCSync = new Guid(0x1104, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid IrMCSyncCommand = new Guid(0x1107, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid L2CapProtocol = new Guid(0x100, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid LanAccessUsingPpp = new Guid(0x1102, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Nap = new Guid(0x1116, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ObexFileTransfer = new Guid(0x1106, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ObexObjectPush = new Guid(0x1105, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ObexProtocol = new Guid(8, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Panu = new Guid(0x1115, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PhonebookAccessPce = new Guid(0x112e, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PhonebookAccessPse = new Guid(0x112f, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PnPInformation = new Guid(0x1200, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PrintingStatus = new Guid(0x1123, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PublicBrowseGroup = new Guid(0x1002, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ReferencePrinting = new Guid(0x1119, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ReflectedUI = new Guid(0x1121, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid RFCommProtocol = new Guid(3, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid SdpProtocol = new Guid(1, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid SerialPort = new Guid(0x1101, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ServiceDiscoveryServer = new Guid(0x1000, 0, 0x1000, 0x80, 8, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid SimAccess = new Guid(0x112d, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid TcpProtocol = new Guid(4, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid TcsAtProtocol = new Guid(6, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid TcsBinProtocol = new Guid(5, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UdiMT = new Guid(0x112a, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UdiTA = new Guid(0x112b, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UdpProtocol = new Guid(2, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnp = new Guid(0x1205, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnpIP = new Guid(0x1206, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnpIPL2Cap = new Guid(0x1302, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnpIPLap = new Guid(0x1301, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnpIPPan = new Guid(0x1300, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoConferencing = new Guid(0x110f, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoConferencingGW = new Guid(0x1129, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoDistribution = new Guid(0x1305, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoSink = new Guid(0x1304, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoSource = new Guid(0x1303, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Wap = new Guid(0x1113, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid WapClient = new Guid(0x1114, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid WspProtocol = new Guid(14, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - - } -} diff --git a/CommAppCF/BluetoothCode/BluetoothSocket.cs b/CommAppCF/BluetoothCode/BluetoothSocket.cs deleted file mode 100644 index 4eb674c..0000000 --- a/CommAppCF/BluetoothCode/BluetoothSocket.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region Using - -using System; -using System.Net.Sockets; - -#endregion - -namespace OpenNETCF.Net.Bluetooth { - /// - /// BluetoothSocket - /// - public class BluetoothSocket : Socket{ - public BluetoothSocket() : base((AddressFamily)0x20, SocketType.Stream, ProtocolType.Ggp) { - } - } -} - - diff --git a/CommAppCF/BluetoothCode/BluetoothSocketAddress.cs b/CommAppCF/BluetoothCode/BluetoothSocketAddress.cs deleted file mode 100644 index 50848a7..0000000 --- a/CommAppCF/BluetoothCode/BluetoothSocketAddress.cs +++ /dev/null @@ -1,83 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.BluetoothSocketAddress -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== - -using System; -using System.Net; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Summary description for BluetoothSocketAddress. - /// - public class BluetoothSocketAddress { - //USHORT addressFamily; //2 - //bt_addr btAddr; //6 - //GUID serviceClassId; //16 - //ULONG port; //4 - - private byte[] m_data; - public const int Length = 40; - private const ushort AF_BTH = 32; - - public BluetoothSocketAddress() { - m_data = new byte[Length]; - BitConverter.GetBytes(AF_BTH).CopyTo(m_data, 0); - } - - public BluetoothSocketAddress(byte[] data) { - if (data.Length == Length) { - m_data = data; - } - else { - throw new ArgumentOutOfRangeException("Data length not expected"); - } - } - - public byte[] ToByteArray() { - return m_data; - } - - public override string ToString() { - string result = ""; - - result += m_data[13].ToString("X") + ":"; - result += m_data[12].ToString("X") + ":"; - result += m_data[11].ToString("X") + ":"; - result += m_data[10].ToString("X") + ":"; - result += m_data[9].ToString("X") + ":"; - result += m_data[8].ToString("X"); - - return result; - } - - - public byte[] Address { - get { - byte[] addr = new byte[6]; - Buffer.BlockCopy(m_data, 8, addr, 0, 6); - return addr; - //return BitConverter.ToInt64(m_data, 0); - } - } - } -} diff --git a/CommAppCF/BluetoothCode/ClassOfDevice.cs b/CommAppCF/BluetoothCode/ClassOfDevice.cs deleted file mode 100644 index ae513f0..0000000 --- a/CommAppCF/BluetoothCode/ClassOfDevice.cs +++ /dev/null @@ -1,76 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.ClassOfDevice -// Copyright (C) 2003-2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Collections; -using System.Data; -using System.Runtime.InteropServices; -using System.Windows.Forms; - -namespace OpenNETCF.Net.Bluetooth { - [Flags()] - public enum ClassOfDevice : int { - MAJOR_SERVICE_CLASS_INFORMATION = 0x800000, - MAJOR_SERVICE_CLASS_TELEPHONY = 0x400000, - MAJOR_SERVICE_CLASS_AUDIO = 0x200000, - MAJOR_SERVICE_CLASS_OBEX = 0x100000, - MAJOR_SERVICE_CLASS_CAPTURE = 0x080000, - MAJOR_SERVICE_CLASS_RENDERING = 0x040000, - MAJOR_SERVICE_CLASS_NETWORK = 0x020000, - MAJOR_SERVICE_CLASS_LIMITED_DISC = 0x002000, - - BTH_COD_MAJOR_DEVICE_CLASS_MISC = 0x000000, - BTH_COD_MAJOR_DEVICE_CLASS_COMPUTER = 0x000100, - BTH_COD_MAJOR_DEVICE_CLASS_PHONE = 0x000200, - BTH_COD_MAJOR_DEVICE_CLASS_LAP = 0x000300, - BTH_COD_MAJOR_DEVICE_CLASS_AUDIO = 0x000400, - BTH_COD_MAJOR_DEVICE_CLASS_PERIPHERAL = 0x000500, - BTH_COD_MAJOR_DEVICE_CLASS_UNCLASSIFIED = 0x001f00, - - BTH_COD_MINOR_COMPUTER_UNCLASSIFIED = 0x000000, - BTH_COD_MINOR_COMPUTER_DESKTOP = 0x000004, - BTH_COD_MINOR_COMPUTER_SERVER = 0x000008, - BTH_COD_MINOR_COMPUTER_LAPTOP = 0x00000c, - BTH_COD_MINOR_COMPUTER_HANDHELD = 0x000010, - BTH_COD_MINOR_COMPUTER_PDA = 0x000014, - - BTH_COD_MINOR_PHONE_UNCLASSIFIED = 0x000000, - BTH_COD_MINOR_PHONE_CELL = 0x000004, - BTH_COD_MINOR_PHONE_CORDLESS = 0x000008, - BTH_COD_MINOR_PHONE_SMART = 0x00000c, - BTH_COD_MINOR_PHONE_WIRED = 0x000010, - - BTH_COD_MINOR_LAP_AVAILABLE = 0x000000, - BTH_COD_MINOR_LAP_1_17 = 0x000004, - BTH_COD_MINOR_LAP_17_33 = 0x000008, - BTH_COD_MINOR_LAP_33_50 = 0x00000c, - BTH_COD_MINOR_LAP_50_67 = 0x000010, - BTH_COD_MINOR_LAP_67_83 = 0x000014, - BTH_COD_MINOR_LAP_83_99 = 0x000018, - BTH_COD_MINOR_LAP_NO_SERVICE = 0x00001c, - - BTH_COD_MINOR_AUDIO_UNCLASSIFIED = 0x000000, - BTH_COD_MINOR_AUDIO_HEADSET = 0x000004, - } -} - diff --git a/CommAppCF/BluetoothCode/HardwareStatus.cs b/CommAppCF/BluetoothCode/HardwareStatus.cs deleted file mode 100644 index 760469b..0000000 --- a/CommAppCF/BluetoothCode/HardwareStatus.cs +++ /dev/null @@ -1,56 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.HardwareStatus -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Specifies the current status of the Bluetooth hardware. - /// - public enum HardwareStatus : int { - /// - /// Status cannot be determined. - /// - Unknown = 0, - /// - /// Bluetooth radio not present. - /// - NotPresent = 1, - /// - /// Bluetooth radio is in the process of starting up. - /// - Initializing = 2, - /// - /// Bluetooth radio is active. - /// - Running = 3, - /// - /// Bluetooth radio is in the process of shutting down. - /// - Shutdown = 4, - /// - /// Bluetooth radio is in an error state. - /// - Error = 5, - } -} diff --git a/CommAppCF/BluetoothCode/PortEmuParams.cs b/CommAppCF/BluetoothCode/PortEmuParams.cs deleted file mode 100644 index c399de1..0000000 --- a/CommAppCF/BluetoothCode/PortEmuParams.cs +++ /dev/null @@ -1,83 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.PortEmuParams -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== - -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Summary description for PortEmuParams. - /// - public class PortEmuParams { - /*int channel; - int flocal; - //BD_ADDR device 48bits; - uint LAP; - //uint UAP; - ushort NAP; - - int imtu; - int iminmtu; - int imaxmtu; - int isendquota; - int irecvquota; - Guid uuidService; - uint uiportflags;*/ - - byte[] m_data; - - public PortEmuParams() { - m_data = new byte[50]; - - BitConverter.GetBytes((int)1).CopyTo(m_data, 46); - } - - public byte[] ToByteArray() { - return m_data; - } - - public bool Local { - get { - return Convert.ToBoolean(BitConverter.ToInt32(m_data, 4)); - } - set { - int val = 0; - if (value) { - val = -1; - } - BitConverter.GetBytes(val).CopyTo(m_data, 4); - } - } - - public byte[] Address { - get { - byte[] addrbytes = new byte[6]; - Buffer.BlockCopy(m_data, 8, addrbytes, 0, 6); - return addrbytes; - } - set { - Buffer.BlockCopy(value, 0, m_data, 8, 6); - } - } - } -} diff --git a/CommAppCF/BluetoothCode/RadioMode.cs b/CommAppCF/BluetoothCode/RadioMode.cs deleted file mode 100644 index e1e3d5e..0000000 --- a/CommAppCF/BluetoothCode/RadioMode.cs +++ /dev/null @@ -1,44 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.RadioMode -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Determine all the possible modes of operation of the Bluetooth radio. - /// - public enum RadioMode { - /// - /// Bluetooth is disabled on the device. - /// - PowerOff, - /// - /// Bluetooth is connectable but your device cannot be discovered by other devices. - /// - Connectable, - /// - /// Bluetooth is activated and fully discoverable. - /// - Discoverable, - } -} diff --git a/CommAppCF/BluetoothCode/SdpError.cs b/CommAppCF/BluetoothCode/SdpError.cs deleted file mode 100644 index 7ef4c16..0000000 --- a/CommAppCF/BluetoothCode/SdpError.cs +++ /dev/null @@ -1,41 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.Sdp.SdpError -// Copyright (C) 2003-2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Collections; -using System.Data; -using System.Runtime.InteropServices; -using System.Windows.Forms; - -namespace OpenNETCF.Net.Bluetooth { - - public enum SdpError : short { - INVALID_SDP_VERSION = 0x0001, - INVALID_RECORD_HANDLE = 0x0002, - INVALID_REQUEST_SYNTAX = 0x0003, - INVALID_PDU_SIZE = 0x0004, - INVALID_CONTINUATION_STATE = 0x0005, - INSUFFICIENT_RESOURCES = 0x0006, - } - -} diff --git a/CommAppCF/BluetoothCode/SdpQueryUuidUnion.cs b/CommAppCF/BluetoothCode/SdpQueryUuidUnion.cs deleted file mode 100644 index 43e5cb4..0000000 --- a/CommAppCF/BluetoothCode/SdpQueryUuidUnion.cs +++ /dev/null @@ -1,60 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.SdpQueryUuidUnion -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Summary description for SdpQueryUuidUnion. - /// - public class SdpQueryUuidUnion { - private byte[] m_data; - - public SdpQueryUuidUnion() { - m_data = new byte[18]; - } - - public Guid Uuid { - get { - byte[] guidbytes = new byte[16]; - - Buffer.BlockCopy(m_data, 0, guidbytes, 0, 16); - - return new Guid(guidbytes); - } - } - - /// - /// Uuid Type. - /// - public short UuidType { - get { - return BitConverter.ToInt16(m_data, 16); - } - /*set - { - BitConverter.GetBytes(value).CopyTo(m_data, 16); - }*/ - } - } -} diff --git a/CommAppCF/BluetoothConnect.Designer.cs b/CommAppCF/BluetoothConnect.Designer.cs deleted file mode 100644 index 920794c..0000000 --- a/CommAppCF/BluetoothConnect.Designer.cs +++ /dev/null @@ -1,136 +0,0 @@ -namespace CommAppCF -{ - partial class BluetoothConnect - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuCancel = new System.Windows.Forms.MenuItem(); - this.mnuOK = new System.Windows.Forms.MenuItem(); - this.label1 = new System.Windows.Forms.Label(); - this.txtBTAddress = new System.Windows.Forms.TextBox(); - this.label2 = new System.Windows.Forms.Label(); - this.btnSearch = new System.Windows.Forms.Button(); - this.comboBox1 = new System.Windows.Forms.ComboBox(); - this.radioSocketConnect = new System.Windows.Forms.CheckBox(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuCancel); - this.mainMenu1.MenuItems.Add(this.mnuOK); - // - // mnuCancel - // - this.mnuCancel.Text = "Cancel"; - this.mnuCancel.Click += new System.EventHandler(this.mnuCancel_Click); - // - // mnuOK - // - this.mnuOK.Text = "OK"; - this.mnuOK.Click += new System.EventHandler(this.mnuOK_Click); - // - // label1 - // - this.label1.Location = new System.Drawing.Point(11, 15); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(216, 21); - this.label1.Text = "Scan or type BT MAC address:"; - // - // txtBTAddress - // - this.txtBTAddress.Location = new System.Drawing.Point(12, 39); - this.txtBTAddress.Name = "txtBTAddress"; - this.txtBTAddress.Size = new System.Drawing.Size(215, 21); - this.txtBTAddress.TabIndex = 1; - // - // label2 - // - this.label2.Location = new System.Drawing.Point(11, 63); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(216, 21); - this.label2.Text = "Example: \"0006660309E8\""; - // - // btnSearch - // - this.btnSearch.Location = new System.Drawing.Point(12, 87); - this.btnSearch.Name = "btnSearch"; - this.btnSearch.Size = new System.Drawing.Size(38, 22); - this.btnSearch.TabIndex = 5; - this.btnSearch.Text = "..."; - this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click); - // - // comboBox1 - // - this.comboBox1.Location = new System.Drawing.Point(58, 87); - this.comboBox1.Name = "comboBox1"; - this.comboBox1.Size = new System.Drawing.Size(169, 22); - this.comboBox1.TabIndex = 6; - this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); - // - // radioSocketConnect - // - this.radioSocketConnect.Location = new System.Drawing.Point(11, 179); - this.radioSocketConnect.Name = "radioSocketConnect"; - this.radioSocketConnect.Size = new System.Drawing.Size(215, 19); - this.radioSocketConnect.TabIndex = 9; - this.radioSocketConnect.Text = "direct Socket"; - this.radioSocketConnect.CheckStateChanged += new System.EventHandler(this.radioSerialPort_CheckedChanged); - // - // BluetoothConnect - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.radioSocketConnect); - this.Controls.Add(this.comboBox1); - this.Controls.Add(this.btnSearch); - this.Controls.Add(this.txtBTAddress); - this.Controls.Add(this.label2); - this.Controls.Add(this.label1); - this.Menu = this.mainMenu1; - this.Name = "BluetoothConnect"; - this.Text = "BluetoothConnect"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuCancel; - private System.Windows.Forms.MenuItem mnuOK; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.TextBox txtBTAddress; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Button btnSearch; - private System.Windows.Forms.ComboBox comboBox1; - private System.Windows.Forms.CheckBox radioSocketConnect; - } -} \ No newline at end of file diff --git a/CommAppCF/BluetoothConnect.cs b/CommAppCF/BluetoothConnect.cs deleted file mode 100644 index 6110067..0000000 --- a/CommAppCF/BluetoothConnect.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Runtime.InteropServices; - -using OpenNETCF.Net.Bluetooth; - -namespace CommAppCF -{ - public partial class BluetoothConnect : Form - { - //using intermec bluetooth tool - [DllImport("ibt.dll", SetLastError = true)] - private static extern bool IBT_SetPrinter(StringBuilder AddrString, bool Register); - [DllImport("ibt.dll", SetLastError = true)] - private static extern UInt32 IBT_On (); - - //using SetBtPrinter.DLL, needs pswdm0c.cab (pswdm0cDll.dll) installed on intermec! - [DllImport("SetBtPrinter.dll", SetLastError = true)] - private static extern int registerPrinter(StringBuilder AddrString); - - public bool bUseSocket = false; - public byte[] bdAddress; - private Comm.BT.BTPort _btport; - - public BluetoothConnect(ref Comm.BT.BTPort btport) - { - _btport = btport; - InitializeComponent(); -#if DEBUG - txtBTAddress.Text = "0006660309E8"; -#endif - } - /* - */ - private bool serialPortConnect() - { - bool bSuccess = false; - int iRes = -1; - try - { - Cursor.Current = Cursors.WaitCursor; - StringBuilder sb = new StringBuilder(txtBTAddress.Text); - if (System.IO.File.Exists(@"\Windows\pswdm0cDLL.dll")) - { - iRes = registerPrinter(sb); //this may take a while... - if (iRes != 0) - { - System.Diagnostics.Debug.WriteLine("registerPrinter failed:" + Marshal.GetLastWin32Error().ToString("x")); - bSuccess = false; - } - else - bSuccess = true; - } - else if (System.IO.File.Exists(@"\Windows\ibt.dll")) - { - bSuccess = IBT_SetPrinter(sb, true); - if (!bSuccess) - System.Diagnostics.Debug.WriteLine("IBT_SetPrinter failed:" + Marshal.GetLastWin32Error().ToString("x")); - } - } - catch (Exception) - { - bSuccess = false; - } - finally - { - Cursor.Current = Cursors.Default; - } - - if (bSuccess) - { - MessageBox.Show("Connection success"); - this.DialogResult = DialogResult.OK; - } - else - { - MessageBox.Show("Connection failed"); - this.DialogResult = DialogResult.Abort; - } - return bSuccess; - } - private void mnuOK_Click(object sender, EventArgs e) - { - if (!bUseSocket) - serialPortConnect(); - else - { - string sBDA = txtBTAddress.Text; - int iDisc = 0; - byte[] bTemp = hexHelper.GetBytes(sBDA, out iDisc); - byte[] bRev = hexHelper.reverseBytes(bTemp); - _btport.Open(bRev); - } - this.Close(); - } - - private void mnuCancel_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.Cancel; - this.Close(); - } - - private void radioSerialPort_CheckedChanged(object sender, EventArgs e) - { - bUseSocket = radioSocketConnect.Checked; - } - - private void btnSearch_Click(object sender, EventArgs e) - { - this.Enabled = false; - Cursor.Current = Cursors.WaitCursor; - BluetoothDeviceInfo[] bdi; - BluetoothClient bc = new BluetoothClient(); - bdi = bc.DiscoverDevices(); - comboBox1.DisplayMember = "DeviceName"; - comboBox1.ValueMember = "DeviceID"; - comboBox1.DataSource = bdi; - if(comboBox1.Items.Count>0) - comboBox1.SelectedIndex = 0; - bc.Close(); - Cursor.Current = Cursors.Default; - this.Enabled = true; - } - - private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) - { - int x = comboBox1.SelectedIndex; - if (x == -1) - return; - - BluetoothDeviceInfo BDI = (BluetoothDeviceInfo)(comboBox1.Items[x]); - bdAddress = BDI.DeviceID; - byte[] bDisplay = hexHelper.reverseBytes(bdAddress); - txtBTAddress.Text = hexHelper.ToString(bDisplay); - } - } -} \ No newline at end of file diff --git a/CommAppCF/BluetoothConnect.resx b/CommAppCF/BluetoothConnect.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/CommAppCF/BluetoothConnect.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/CommAppCF/CommAppCF.csproj b/CommAppCF/CommAppCF.csproj deleted file mode 100644 index 2363ca3..0000000 --- a/CommAppCF/CommAppCF.csproj +++ /dev/null @@ -1,149 +0,0 @@ - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {151322CC-139B-455B-8B84-1A21D3D81834} - WinExe - Properties - CommAppCF - CommAppCF - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.01 - CommAppCF - v2.0 - - - - - - - 2.0 - Windows Mobile 5.0 Pocket PC SDK - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - - - - - - - - - - - - - Form - - - BluetoothConnect.cs - - - - Form - - - ConnectDlg.cs - - - Form - - - Form1.cs - - - - - Component - - - - - BluetoothConnect.cs - - - Designer - ConnectDlg.cs - - - Designer - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - - - - Always - - - Always - - - - - - - - - - - - - - \ No newline at end of file diff --git a/CommAppCF/CommAppCF.csproj.user b/CommAppCF/CommAppCF.csproj.user deleted file mode 100644 index 4943a79..0000000 --- a/CommAppCF/CommAppCF.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - 4118C335-430C-497f-BE48-11C3316B135Ed6518ffb-710f-11d3-99f2-00105a0df099 - false - - \ No newline at end of file diff --git a/CommAppCF/CommAppCF.sln b/CommAppCF/CommAppCF.sln deleted file mode 100644 index d3d32be..0000000 --- a/CommAppCF/CommAppCF.sln +++ /dev/null @@ -1,50 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommAppCF", "CommAppCF.csproj", "{151322CC-139B-455B-8B84-1A21D3D81834}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SetBTprinter", "SetBTprinter\SetBTprinter.vcproj", "{D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Any CPU.Build.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Mixed Platforms.Deploy.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Any CPU.ActiveCfg = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Any CPU.Build.0 = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Any CPU.Deploy.0 = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Mixed Platforms.Deploy.0 = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Any CPU - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/CommAppCF/CommAppCF.suo b/CommAppCF/CommAppCF.suo deleted file mode 100644 index 9f608d6..0000000 Binary files a/CommAppCF/CommAppCF.suo and /dev/null differ diff --git a/CommAppCF/ConnectDlg.Designer.cs b/CommAppCF/ConnectDlg.Designer.cs deleted file mode 100644 index b17f580..0000000 --- a/CommAppCF/ConnectDlg.Designer.cs +++ /dev/null @@ -1,230 +0,0 @@ -namespace CommAppCF -{ - partial class ConnectDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuCancel = new System.Windows.Forms.MenuItem(); - this.mnuConnect = new System.Windows.Forms.MenuItem(); - this.lblComPort = new System.Windows.Forms.Label(); - this.cmbPortName = new System.Windows.Forms.ComboBox(); - this.cmbBaudRate = new System.Windows.Forms.ComboBox(); - this.lblBaudRate = new System.Windows.Forms.Label(); - this.cmbParity = new System.Windows.Forms.ComboBox(); - this.label1 = new System.Windows.Forms.Label(); - this.lblStopBits = new System.Windows.Forms.Label(); - this.cmbStopBits = new System.Windows.Forms.ComboBox(); - this.lblDataBits = new System.Windows.Forms.Label(); - this.cmbDataBits = new System.Windows.Forms.ComboBox(); - this.cmbHandshake = new System.Windows.Forms.ComboBox(); - this.label2 = new System.Windows.Forms.Label(); - this.btnBTPrinter = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuCancel); - this.mainMenu1.MenuItems.Add(this.mnuConnect); - // - // mnuCancel - // - this.mnuCancel.Text = "Cancel"; - this.mnuCancel.Click += new System.EventHandler(this.mnuCancel_Click); - // - // mnuConnect - // - this.mnuConnect.Text = "Connect"; - this.mnuConnect.Click += new System.EventHandler(this.mnuConnect_Click); - // - // lblComPort - // - this.lblComPort.Location = new System.Drawing.Point(27, 11); - this.lblComPort.Name = "lblComPort"; - this.lblComPort.Size = new System.Drawing.Size(74, 13); - this.lblComPort.Text = "COM Port:"; - // - // cmbPortName - // - this.cmbPortName.Items.Add("COM0"); - this.cmbPortName.Items.Add("COM1"); - this.cmbPortName.Items.Add("COM2"); - this.cmbPortName.Items.Add("COM3"); - this.cmbPortName.Items.Add("COM4"); - this.cmbPortName.Location = new System.Drawing.Point(112, 3); - this.cmbPortName.Name = "cmbPortName"; - this.cmbPortName.Size = new System.Drawing.Size(68, 22); - this.cmbPortName.TabIndex = 18; - // - // cmbBaudRate - // - this.cmbBaudRate.Items.Add("1200"); - this.cmbBaudRate.Items.Add("2400"); - this.cmbBaudRate.Items.Add("4800"); - this.cmbBaudRate.Items.Add(""); - this.cmbBaudRate.Location = new System.Drawing.Point(112, 39); - this.cmbBaudRate.Name = "cmbBaudRate"; - this.cmbBaudRate.Size = new System.Drawing.Size(68, 22); - this.cmbBaudRate.TabIndex = 19; - // - // lblBaudRate - // - this.lblBaudRate.Location = new System.Drawing.Point(27, 47); - this.lblBaudRate.Name = "lblBaudRate"; - this.lblBaudRate.Size = new System.Drawing.Size(79, 13); - this.lblBaudRate.Text = "Baud Rate:"; - // - // cmbParity - // - this.cmbParity.Items.Add("None"); - this.cmbParity.Items.Add("1"); - this.cmbParity.Items.Add("2"); - this.cmbParity.Items.Add("3"); - this.cmbParity.Items.Add("4"); - this.cmbParity.Items.Add("5"); - this.cmbParity.Items.Add("6"); - this.cmbParity.Location = new System.Drawing.Point(112, 79); - this.cmbParity.Name = "cmbParity"; - this.cmbParity.Size = new System.Drawing.Size(68, 22); - this.cmbParity.TabIndex = 21; - // - // label1 - // - this.label1.Location = new System.Drawing.Point(27, 79); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(54, 13); - this.label1.Text = "Parity:"; - // - // lblStopBits - // - this.lblStopBits.Location = new System.Drawing.Point(27, 158); - this.lblStopBits.Name = "lblStopBits"; - this.lblStopBits.Size = new System.Drawing.Size(70, 13); - this.lblStopBits.Text = "Stop Bits:"; - // - // cmbStopBits - // - this.cmbStopBits.Items.Add("1"); - this.cmbStopBits.Items.Add("2"); - this.cmbStopBits.Items.Add("3"); - this.cmbStopBits.Location = new System.Drawing.Point(112, 155); - this.cmbStopBits.Name = "cmbStopBits"; - this.cmbStopBits.Size = new System.Drawing.Size(69, 22); - this.cmbStopBits.TabIndex = 26; - // - // lblDataBits - // - this.lblDataBits.Location = new System.Drawing.Point(27, 119); - this.lblDataBits.Name = "lblDataBits"; - this.lblDataBits.Size = new System.Drawing.Size(71, 13); - this.lblDataBits.Text = "Data Bits:"; - // - // cmbDataBits - // - this.cmbDataBits.Items.Add("5"); - this.cmbDataBits.Items.Add("6"); - this.cmbDataBits.Items.Add("7"); - this.cmbDataBits.Items.Add("8"); - this.cmbDataBits.Location = new System.Drawing.Point(112, 119); - this.cmbDataBits.Name = "cmbDataBits"; - this.cmbDataBits.Size = new System.Drawing.Size(68, 22); - this.cmbDataBits.TabIndex = 25; - // - // cmbHandshake - // - this.cmbHandshake.Items.Add("1"); - this.cmbHandshake.Items.Add("2"); - this.cmbHandshake.Items.Add("3"); - this.cmbHandshake.Location = new System.Drawing.Point(111, 192); - this.cmbHandshake.Name = "cmbHandshake"; - this.cmbHandshake.Size = new System.Drawing.Size(69, 22); - this.cmbHandshake.TabIndex = 26; - // - // label2 - // - this.label2.Location = new System.Drawing.Point(26, 195); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(70, 13); - this.label2.Text = "Handshake:"; - // - // btnBTPrinter - // - this.btnBTPrinter.Location = new System.Drawing.Point(27, 230); - this.btnBTPrinter.Name = "btnBTPrinter"; - this.btnBTPrinter.Size = new System.Drawing.Size(181, 22); - this.btnBTPrinter.TabIndex = 31; - this.btnBTPrinter.Text = "Bluetooth Printer"; - this.btnBTPrinter.Click += new System.EventHandler(this.btnBTPrinter_Click); - // - // ConnectDlg - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.btnBTPrinter); - this.Controls.Add(this.label2); - this.Controls.Add(this.lblStopBits); - this.Controls.Add(this.cmbHandshake); - this.Controls.Add(this.cmbStopBits); - this.Controls.Add(this.lblDataBits); - this.Controls.Add(this.cmbDataBits); - this.Controls.Add(this.lblComPort); - this.Controls.Add(this.cmbPortName); - this.Controls.Add(this.cmbBaudRate); - this.Controls.Add(this.lblBaudRate); - this.Controls.Add(this.cmbParity); - this.Controls.Add(this.label1); - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "ConnectDlg"; - this.Text = "ConnectDlg"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuCancel; - private System.Windows.Forms.MenuItem mnuConnect; - private System.Windows.Forms.Label lblComPort; - private System.Windows.Forms.ComboBox cmbPortName; - private System.Windows.Forms.ComboBox cmbBaudRate; - private System.Windows.Forms.Label lblBaudRate; - private System.Windows.Forms.ComboBox cmbParity; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label lblStopBits; - private System.Windows.Forms.ComboBox cmbStopBits; - private System.Windows.Forms.Label lblDataBits; - private System.Windows.Forms.ComboBox cmbDataBits; - private System.Windows.Forms.ComboBox cmbHandshake; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Button btnBTPrinter; - } -} \ No newline at end of file diff --git a/CommAppCF/ConnectDlg.cs b/CommAppCF/ConnectDlg.cs deleted file mode 100644 index ea35a9c..0000000 --- a/CommAppCF/ConnectDlg.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.IO.Ports; - -namespace CommAppCF -{ - public partial class ConnectDlg : Form - { - private SerialPort _serialPort; - private uint[] baudRates = { 1200, 2400, 4800, 9600, 19200, 38200, 57600, 115200, 230400, 460800, 921600 }; - - private serialSet _mySettings = new serialSet(); - - public ConnectDlg(ref SerialPort sp) - { - InitializeComponent(); - - if(System.IO.File.Exists("\\windows\\ibt.dll")) - btnBTPrinter.Enabled=true; - else - btnBTPrinter.Enabled=false; - - //port list - cmbPortName.Items.Clear(); - for (int i = 0; i < 10; i++) - { - cmbPortName.Items.Insert(i, "COM" + i.ToString()); - } - int ix = cmbPortName.Items.IndexOf(_mySettings.sPort); - if (ix != -1) - cmbPortName.SelectedIndex = ix; - else - cmbPortName.SelectedIndex = 0; - - //baud list - cmbBaudRate.Items.Clear(); - int j = 0; - foreach (uint u in _mySettings.baudRates) - { - cmbBaudRate.Items.Insert(j, u.ToString()); - j++; - } - ix = findInCombo(cmbBaudRate, _mySettings.baudRate.ToString()); - if (ix != -1) - cmbBaudRate.SelectedIndex = ix; - else - cmbBaudRate.SelectedIndex = 0; - - //databits - cmbDataBits.Items.Clear(); - for (int i = 6; i < 9; i++) - { - cmbDataBits.Items.Add(i.ToString()); - } - ix = findInCombo(cmbDataBits, _mySettings.databits.ToString()); - if (ix != -1) - cmbDataBits.SelectedIndex = ix; - else - cmbDataBits.SelectedIndex = 0; - - //parity - cmbParity.Items.Clear(); - for (int i = 0; i < myParity.parity.Length; i++) - { - cmbParity.Items.Insert(i, myParity.ToString(i)); - } - - cmbParity.SelectedIndex = (int)_mySettings.parity; - - //stopBits - cmbStopBits.Items.Clear(); - for (int i = 0; i < 3; i++) - { - cmbStopBits.Items.Insert(i, myStopBits.ToString(i)); - } - ix = findInCombo(cmbStopBits, _mySettings.stopBits.ToString()); - if (ix != -1) - cmbStopBits.SelectedIndex = ix; - else - cmbStopBits.SelectedIndex = 1; -// cmbStopBits.SelectedIndex = cmbStopBits.Items.IndexOf(_mySettings.stopBits); - - //handshake - cmbHandshake.Items.Clear(); - for (int i = 0; i < myHandshake.handshakes.Length; i++) - { - cmbHandshake.Items.Insert(i, myHandshake.ToString(i)); - } - cmbHandshake.SelectedIndex = (int)_mySettings.handshake; - - this._serialPort = sp; - - } - - private int findInCombo(ComboBox cbo, string s) - { - for (int j = 0; j < cbo.Items.Count; j++) - { - if (cbo.Items[j].ToString().Equals(s, StringComparison.OrdinalIgnoreCase)) - return j; - } - return -1; - } - private void mnuCancel_Click(object sender, EventArgs e) - { - this.Close(); - } - - private void mnuConnect_Click(object sender, EventArgs e) - { - if (_serialPort.IsOpen) - _serialPort.Close(); - else - { - // Set the port's settings - _serialPort.PortName = cmbPortName.Text; - _serialPort.BaudRate = int.Parse(cmbBaudRate.Text); - _serialPort.DataBits = int.Parse(cmbDataBits.Text); - - if(myStopBits.ToStopBits(cmbStopBits.Text) != StopBits.None) - _serialPort.StopBits = myStopBits.ToStopBits(cmbStopBits.Text); - - _serialPort.Parity = myParity.ToParity(cmbParity.Text); - _serialPort.Handshake = myHandshake.ToHandshake(cmbHandshake.Text); - _serialPort.ReadTimeout = 100; - - _mySettings.baudRate = (uint)_serialPort.BaudRate; - _mySettings.parity = (uint)_serialPort.Parity; - _mySettings.databits = (uint)_serialPort.DataBits; - _mySettings.stopBits = (uint)_serialPort.StopBits; - - _mySettings.sPort = _serialPort.PortName; - - _mySettings.saveSettings(); - - try - { - Cursor.Current = Cursors.WaitCursor; - _serialPort.Open(); - this.DialogResult = DialogResult.OK; - } - catch (Exception x) - { - System.Diagnostics.Debug.WriteLine("Exception in OpenPort: " + x.Message); - } - finally - { - Cursor.Current = Cursors.Default; - } - } - this.Close(); - } - - private void btnBTPrinter_Click(object sender, EventArgs e) - { - Comm.BT.BTPort btPort = new Comm.BT.BTPort(); - BluetoothConnect dlg = new BluetoothConnect(ref btPort); - dlg.ShowDialog(); - } - } -} \ No newline at end of file diff --git a/CommAppCF/ConnectDlg.resx b/CommAppCF/ConnectDlg.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/CommAppCF/ConnectDlg.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/CommAppCF/Form1.Designer.cs b/CommAppCF/Form1.Designer.cs deleted file mode 100644 index 617252c..0000000 --- a/CommAppCF/Form1.Designer.cs +++ /dev/null @@ -1,198 +0,0 @@ -namespace CommAppCF -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.mnuConnectMain = new System.Windows.Forms.MenuItem(); - this.mnuSerialConnect = new System.Windows.Forms.MenuItem(); - this.mnuSocketConnect = new System.Windows.Forms.MenuItem(); - this.txtSend = new System.Windows.Forms.TextBox(); - this.label1 = new System.Windows.Forms.Label(); - this.btnSend = new System.Windows.Forms.Button(); - this.txtReceive = new System.Windows.Forms.TextBox(); - this.btnSendFile = new System.Windows.Forms.Button(); - this.btnSendLine = new System.Windows.Forms.Button(); - this.btnClear = new System.Windows.Forms.Button(); - this.chkUseHexEncoder = new System.Windows.Forms.CheckBox(); - this.btnSendFileTXT = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuExit); - this.mainMenu1.MenuItems.Add(this.mnuConnectMain); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // mnuConnectMain - // - this.mnuConnectMain.MenuItems.Add(this.mnuSerialConnect); - this.mnuConnectMain.MenuItems.Add(this.mnuSocketConnect); - this.mnuConnectMain.Text = "Connect"; - // - // mnuSerialConnect - // - this.mnuSerialConnect.Text = "Serial"; - this.mnuSerialConnect.Click += new System.EventHandler(this.mnuSerialConnect_Click); - // - // mnuSocketConnect - // - this.mnuSocketConnect.Text = "BT Connect"; - this.mnuSocketConnect.Click += new System.EventHandler(this.mnuSocketConnect_Click); - // - // txtSend - // - this.txtSend.AcceptsReturn = true; - this.txtSend.AcceptsTab = true; - this.txtSend.Location = new System.Drawing.Point(3, 31); - this.txtSend.Multiline = true; - this.txtSend.Name = "txtSend"; - this.txtSend.Size = new System.Drawing.Size(234, 69); - this.txtSend.TabIndex = 0; - // - // label1 - // - this.label1.Location = new System.Drawing.Point(3, 10); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(72, 18); - this.label1.Text = "SEND:"; - // - // btnSend - // - this.btnSend.Location = new System.Drawing.Point(164, 135); - this.btnSend.Name = "btnSend"; - this.btnSend.Size = new System.Drawing.Size(62, 23); - this.btnSend.TabIndex = 2; - this.btnSend.Text = "Send"; - this.btnSend.Click += new System.EventHandler(this.btnSend_Click); - // - // txtReceive - // - this.txtReceive.AcceptsReturn = true; - this.txtReceive.AcceptsTab = true; - this.txtReceive.Location = new System.Drawing.Point(3, 191); - this.txtReceive.Multiline = true; - this.txtReceive.Name = "txtReceive"; - this.txtReceive.ReadOnly = true; - this.txtReceive.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtReceive.Size = new System.Drawing.Size(234, 74); - this.txtReceive.TabIndex = 0; - // - // btnSendFile - // - this.btnSendFile.Location = new System.Drawing.Point(3, 106); - this.btnSendFile.Name = "btnSendFile"; - this.btnSendFile.Size = new System.Drawing.Size(103, 23); - this.btnSendFile.TabIndex = 2; - this.btnSendFile.Text = "Send bin File"; - this.btnSendFile.Click += new System.EventHandler(this.btnSendFile_Click); - // - // btnSendLine - // - this.btnSendLine.Location = new System.Drawing.Point(164, 106); - this.btnSendLine.Name = "btnSendLine"; - this.btnSendLine.Size = new System.Drawing.Size(73, 23); - this.btnSendLine.TabIndex = 2; - this.btnSendLine.Text = "Send Line"; - this.btnSendLine.Click += new System.EventHandler(this.btnSendLine_Click); - // - // btnClear - // - this.btnClear.Location = new System.Drawing.Point(175, 5); - this.btnClear.Name = "btnClear"; - this.btnClear.Size = new System.Drawing.Size(62, 23); - this.btnClear.TabIndex = 2; - this.btnClear.Text = "Clear"; - this.btnClear.Click += new System.EventHandler(this.btnClear_Click); - // - // chkUseHexEncoder - // - this.chkUseHexEncoder.Location = new System.Drawing.Point(3, 166); - this.chkUseHexEncoder.Name = "chkUseHexEncoder"; - this.chkUseHexEncoder.Size = new System.Drawing.Size(234, 19); - this.chkUseHexEncoder.TabIndex = 4; - this.chkUseHexEncoder.Text = "use \\xAB en/decoding"; - this.chkUseHexEncoder.CheckStateChanged += new System.EventHandler(this.chkUseHexEncoder_CheckStateChanged); - // - // btnSendFileTXT - // - this.btnSendFileTXT.Location = new System.Drawing.Point(3, 135); - this.btnSendFileTXT.Name = "btnSendFileTXT"; - this.btnSendFileTXT.Size = new System.Drawing.Size(103, 23); - this.btnSendFileTXT.TabIndex = 2; - this.btnSendFileTXT.Text = "Send txt File"; - this.btnSendFileTXT.Click += new System.EventHandler(this.btnSendFileTXT_Click); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.chkUseHexEncoder); - this.Controls.Add(this.btnSendFileTXT); - this.Controls.Add(this.btnSendFile); - this.Controls.Add(this.btnSendLine); - this.Controls.Add(this.btnClear); - this.Controls.Add(this.btnSend); - this.Controls.Add(this.label1); - this.Controls.Add(this.txtReceive); - this.Controls.Add(this.txtSend); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "CommApp"; - this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuExit; - private System.Windows.Forms.MenuItem mnuConnectMain; - private System.Windows.Forms.TextBox txtSend; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Button btnSend; - private System.Windows.Forms.TextBox txtReceive; - private System.Windows.Forms.Button btnSendFile; - private System.Windows.Forms.Button btnSendLine; - private System.Windows.Forms.Button btnClear; - private System.Windows.Forms.CheckBox chkUseHexEncoder; - private System.Windows.Forms.MenuItem mnuSerialConnect; - private System.Windows.Forms.MenuItem mnuSocketConnect; - private System.Windows.Forms.Button btnSendFileTXT; - } -} - diff --git a/CommAppCF/Form1.cs b/CommAppCF/Form1.cs deleted file mode 100644 index c78cfda..0000000 --- a/CommAppCF/Form1.cs +++ /dev/null @@ -1,412 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.IO.Ports; - -//using OpenNETCF.Net.Bluetooth; -using Comm.BT; - -namespace CommAppCF -{ - public partial class Form1 : Form - { - private SerialPort comport = new SerialPort(); - private BTPort btport = new BTPort(); - private bool bUseHexDecode = false; - - public Form1() - { - InitializeComponent(); - comport.DataReceived += new SerialDataReceivedEventHandler(comport_DataReceived); - comport.ErrorReceived += new SerialErrorReceivedEventHandler(comport_ErrorReceived); - - btport.BTDataReceived += new BTPort.BTDataReceivedEventHandler(btport_BTDataReceived); - enableControls(false); - } - - void btport_BTDataReceived(object sender, BTPort.DataEventArgs d) - { - string data = d._string; - string s = ""; - // Display the text to the user in the terminal - if (bUseHexDecode) - s = Utility.HexEncoding.ToMixedString(data); - else - s = data; - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += "<" + s + "\r\n"; })); //added < to mark incoming data - } - - void comport_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) - { - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += e.ToString(); })); - } - - void comport_DataReceived(object sender, SerialDataReceivedEventArgs e) - { - // This method will be called when there is data waiting in the port's buffer - - // Determain which mode (string or binary) the user is in - // Read all the data waiting in the buffer - try - { - string data = ""; - data = comport.ReadLine();//.ReadExisting(); - string s = ""; - // Display the text to the user in the terminal - if (bUseHexDecode) - s = Utility.HexEncoding.ToMixedString(data); - else - s = data; - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += "<" + s + "\r\n"; })); //added < to mark incoming data - } - catch (Exception ex) - { - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += ex.Message + "\r\n"; })); - //MessageBox.Show(ex.Message); - } - //label2.Invoke(new EventHandler(delegate{label2.Text = data;})); - - //Log(LogMsgType.Incoming, data); - } - /// - /// enable controls based on active connection - /// - /// - private void enableControls(bool bEnable) - { - btnSend.Enabled = bEnable; - btnSendFile.Enabled = bEnable; - btnSendLine.Enabled = bEnable; - btnSendFileTXT.Enabled = bEnable; - } - delegate void SetTextCallback(string text); - private void updateTxtRcv(string text) - { - if (this.txtReceive.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(updateTxtRcv); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtReceive.Text.Length > 2000) - txtReceive.Text = ""; - txtReceive.Text += text + "\r\n"; - txtReceive.SelectionLength = text.Length; - txtReceive.SelectionStart = txtReceive.Text.Length - text.Length; - txtReceive.ScrollToCaret(); - } - - } - private void Form1_Closing(object sender, CancelEventArgs e) - { - try - { - //comport.DiscardOutBuffer(); - //comport.DiscardInBuffer(); - //comport.Dispose(); - if (comport.IsOpen) - { - comport.ReadExisting(); - comport.Close(); - } - } - catch (Exception ex) - { - MessageBox.Show(ex.Message); - } - - } - - private void mnuExit_Click(object sender, EventArgs e) - { - this.Close(); - } - - private void btnSend_Click(object sender, EventArgs e) - { - try - { - if (txtSend.Text.Length > 0) - { - string s = txtSend.Text; - if (chkUseHexEncoder.Checked) - { - byte[] b = Utility.HexEncoding.FromHexedString(s); - comport.Write(b, 0, b.Length); - } - else - comport.Write(s); - } - } - catch (Exception) - { - - } - } - - private void btnSendLine_Click(object sender, EventArgs e) - { - try - { - if (txtSend.Text.Length > 0) - { - string s = txtSend.Text; - if (chkUseHexEncoder.Checked) - { - byte[] b = Utility.HexEncoding.FromHexedString(s); - comport.Write(b, 0, b.Length); - comport.WriteLine(""); - } - else - comport.WriteLine(s); - } - } - catch (Exception) - { - - } - - } - - private void btnSendFile_Click(object sender, EventArgs e) - { - try - { - if (comport.IsOpen) - { - OpenFileDialog ofd = new OpenFileDialog(); - ofd.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; - ofd.FilterIndex = 0; - if (ofd.ShowDialog()==DialogResult.OK){ - string filename = ofd.FileName; - if (System.IO.File.Exists(filename)) - { - Cursor.Current = Cursors.WaitCursor; - sendFile(filename); - Cursor.Current = Cursors.Default; - } - } - } - - } - catch (Exception x) - { - updateTxtRcv(x.Message); - } - } - private void sendFileTXT(string filename) - { - try - { - updateTxtRcv("Starting sendFileTxt(" + filename + ")"); - - System.IO.StreamReader sr = new System.IO.StreamReader(filename); - byte[] bFile = Encoding.UTF8.GetBytes(sr.ReadToEnd()); - - int r; - int offset = 0; - int blockSize = 4096; - //how many blocks to send? - long lBlocks = (long)(bFile.Length / blockSize); - if (lBlocks == 0) - lBlocks = 1; - updateTxtRcv("Need to send " + lBlocks.ToString() + " blocks..."); - long lBlockNr = 1; - //any full blocks to send? - while (offset + blockSize < bFile.Length) - { - updateTxtRcv("Sending block " + lBlockNr.ToString() + " ..."); - comport.Write(bFile, offset, blockSize); - offset += blockSize; - } - - //send remaining - comport.Write(bFile, offset, bFile.Length - offset); - - sr.Close(); - updateTxtRcv("Finished sendFile(" + filename + ")"); - } - catch (Exception x) - { - updateTxtRcv("sendFile exception:" + x.Message); - System.Diagnostics.Debug.WriteLine(x.Message); - } - } - private void sendFile(string filename) - { - try - { - updateTxtRcv("Starting sendFile(" + filename + ")"); - - System.IO.StreamReader sr = new System.IO.StreamReader(filename); - int r; - int blockSize = 4096; - char[] buf = new char[blockSize]; - //how many blocks to send? - System.IO.FileInfo fi = new System.IO.FileInfo(filename); - long lBlocks = (long)(fi.Length / blockSize); - if (lBlocks == 0) - lBlocks = 1; - updateTxtRcv("Need to send " + lBlocks.ToString() + " blocks..."); - long lBlockNr = 1; - do - { - updateTxtRcv("Sending block " + lBlockNr.ToString() + " ..."); - r = sr.Read(buf, 0, blockSize); //r = number of bytes read - comport.Write(buf, 0, r); - } - while (r!=-1 && !sr.EndOfStream); - sr.Close(); - updateTxtRcv("Finished sendFile(" + filename + ")"); - } - catch (Exception x) - { - updateTxtRcv("sendFile exception:" + x.Message); - System.Diagnostics.Debug.WriteLine(x.Message); - } - } - - private void btnClear_Click(object sender, EventArgs e) - { - txtSend.Text = ""; - } - - private void chkUseHexEncoder_CheckStateChanged(object sender, EventArgs e) - { - bUseHexDecode = chkUseHexEncoder.Checked; - } - private bool bUseSocket; - private myThread _thread; - - private void mnuSocketConnect_Click(object sender, EventArgs e) - { - byte[] bdAddress = new byte[6]; - BluetoothConnect dlg = new BluetoothConnect(ref btport); - if (dlg.ShowDialog() == DialogResult.OK) - { - bUseSocket = true; - bdAddress=dlg.bdAddress; - } - dlg.Dispose(); - //if (bUseSocket) - //{ - // if (_thread == null) - // { - // System.Net.Sockets.NetworkStream ns = connectBT(bdAddress); - // if (ns != null) - // { - // _thread.BTDataReceived += new myThread.BTDataReceivedEventHandler(_thread_BTDataReceived); - // _thread = new myThread(ref ns); - // } - // } - //} - } - - void _thread_BTDataReceived(object sender, DataEventArgs d) - { - throw new NotImplementedException(); - } - private void OnDataReceived(object sender, DataEventArgs da){ - } - //private System.Net.Sockets.NetworkStream connectBT(byte[] ba) - //{ - // Cursor.Current = Cursors.WaitCursor; - // System.Net.Sockets.NetworkStream ns=null; - // try - // { - // BluetoothAddress bda = new BluetoothAddress(ba); - // //System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(); - // BluetoothClient btClient = new BluetoothClient(); - // btClient.Connect(new BluetoothEndPoint(bda, BluetoothService.SerialPort)); - // ns = btClient.GetStream(); - // return ns; - // // System.IO.StreamWriter sw = new System.IO.StreamWriter(ns); - // // if (sw.BaseStream != null) - // // { - // // if (sw.BaseStream.CanWrite) - // // { - // // //byte[] buf = Encoding.ASCII.GetBytes(fp_text); - // // sw.Write(fp_text); //ns.Write(buf, 0, buf.Length); - // // //ns.Flush(); - // // sw.Flush(); - // // } - // // sw.Close(); - // // } - // // ns.Close(); - // // btClient.CloseSocket(); - // // btClient.Close(); - // // Cursor.Current = Cursors.Default; - // //} - // } - // catch (Exception x) - // { - // Cursor.Current = Cursors.Default; - // MessageBox.Show("Exception :" + x.Message); - // return ns; - // } - //} - - private void mnuSerialConnect_Click(object sender, EventArgs e) - { - ConnectDlg dlg = new ConnectDlg(ref comport); - if(dlg.ShowDialog()==DialogResult.OK){ - if (comport.IsOpen) - { - bUseSocket = false; - mnuConnectMain.Text="Disconnect"; - enableControls(true); - } - } - - } - - private void btnSendFileTXT_Click(object sender, EventArgs e) - { - try - { - if (comport.IsOpen) - { - OpenFileDialog ofd = new OpenFileDialog(); - ofd.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; - ofd.FilterIndex = 0; - if (ofd.ShowDialog() == DialogResult.OK) - { - string filename = ofd.FileName; - if (System.IO.File.Exists(filename)) - { - Cursor.Current = Cursors.WaitCursor; - sendFileTXT(filename); - Cursor.Current = Cursors.Default; - } - } - } - - } - catch (Exception x) - { - updateTxtRcv(x.Message); - } - - } - //private void btSearch_Click(object sender, EventArgs e) - //{ - // this.Enabled = false; - // Cursor.Current = Cursors.WaitCursor; - // BluetoothDeviceInfo[] bdi; - // BluetoothClient bc = new BluetoothClient(); - // bdi = bc.DiscoverDevices(); - // comboBox1.DisplayMember = "DeviceName"; - // comboBox1.ValueMember = "DeviceID"; - // comboBox1.DataSource = bdi; - // Cursor.Current = Cursors.Default; - // this.Enabled = true; - //} - - - } -} \ No newline at end of file diff --git a/CommAppCF/Form1.resx b/CommAppCF/Form1.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/CommAppCF/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/CommAppCF/HexEncoding.cs b/CommAppCF/HexEncoding.cs deleted file mode 100644 index 41ff565..0000000 --- a/CommAppCF/HexEncoding.cs +++ /dev/null @@ -1,206 +0,0 @@ -using System; -using System.Text; -using System.Globalization; - -namespace Utility -{ - /// - /// Summary description for HexEncoding. - /// - public static class HexEncoding - { - //public HexEncoding() - //{ - //} - /// - /// helper to get count of hex chars in a string - /// - /// - /// only hex chars are counted - public static int GetByteCount(string hexString) - { - int numHexChars = 0; - char c; - // remove all none A-F, 0-9, characters - for (int i=0; i - /// Creates a byte array from the hexadecimal string. Each two characters are combined - /// to create one byte. First two hexadecimal characters become first byte in returned array. - /// Non-hexadecimal characters are ignored. - /// - /// string to convert to byte array - /// number of characters in string ignored - /// byte array, in the same left-to-right order as the hexString - public static byte[] GetBytes(string hexString, out int discarded) - { - discarded = 0; - string newString = ""; - char c; - // remove all none A-F, 0-9, characters - for (int i=0; i - /// convert a byte array to a sequence of hex chars - /// - /// - /// - public static string ToString(byte[] bytes) - { - string hexString = ""; - for (int i=0; i - /// convert a mixed string with \xAB encoded hex chars back to a byte array - /// - /// - /// - public static byte[] FromHexedString(string val){ - //replace \xHH with char of before using getbytes - int iPos = val.IndexOf("\\x"); - while(iPos>=0){ - string s = val.Substring(iPos, 4); - byte b = byte.Parse(val.Substring(iPos+2,2), NumberStyles.HexNumber); - //string c = Convert.ToString(b,16); - char ch = (char)b; - //test - //byte[] bTest = Encoding.ASCII.GetBytes(ch.ToString()); - //System.Diagnostics.Debug.WriteLine(string.Format("Encoded {0:x} as '{1}'", bTest,ch)); - string o = val.Substring(0, iPos) + ch + val.Substring(iPos + 4); - val = o; - iPos = val.IndexOf("\\x"); - } - byte[] valAsByteArray = Encoding.ASCII.GetBytes(val); - return valAsByteArray; - } - /// - /// convert a string with chars to a string that uses \xAB encoding for non-printable chars - /// - /// - /// - public static string ToMixedString(string s) - { - byte[] bytes = Encoding.ASCII.GetBytes(s); - string sReturn = ToMixedString(bytes); - return sReturn; - } - /// - /// convert a byte array to a string that uses \xAB encoding for non-printable chars - /// - /// - /// - public static string ToMixedString(byte[] bytes) - { - string hexString = ""; - for (int i = 0; i < bytes.Length; i++) - { - if (bytes[i] >= 0x20) - { - //hexString += bytes[i].ToString(); - hexString += ASCIIEncoding.ASCII.GetString(bytes, i, 1); - } - else - { - hexString += "\\x"; // "<" - hexString += bytes[i].ToString("X2"); - //if (i <= bytes.Length - 1) hexString += "-"; - //hexString += ">"; - } - } - return hexString; - } - - /// - /// Determines if given string is in proper hexadecimal string format - /// - /// - /// - public static bool InHexFormat(string hexString) - { - bool hexFormat = true; - - foreach (char digit in hexString) - { - if (!IsHexDigit(digit)) - { - hexFormat = false; - break; - } - } - return hexFormat; - } - - /// - /// Returns true is c is a hexadecimal digit (A-F, a-f, 0-9) - /// - /// Character to test - /// true if hex digit, false if not - public static bool IsHexDigit(Char c) - { - int numChar; - int numA = Convert.ToInt32('A'); - int num1 = Convert.ToInt32('0'); - c = Char.ToUpper(c); - numChar = Convert.ToInt32(c); - if (numChar >= numA && numChar < (numA + 6)) - return true; - if (numChar >= num1 && numChar < (num1 + 10)) - return true; - return false; - } - /// - /// Converts 1 or 2 character string into equivalant byte value - /// - /// 1 or 2 character string - /// byte - private static byte HexToByte(string hex) - { - if (hex.Length > 2 || hex.Length <= 0) - throw new ArgumentException("hex must be 1 or 2 characters in length"); - byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber); - return newByte; - } - } -} diff --git a/CommAppCF/Program.cs b/CommAppCF/Program.cs deleted file mode 100644 index fe09bd9..0000000 --- a/CommAppCF/Program.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; - -namespace CommAppCF -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/CommAppCF/Properties/AssemblyInfo.cs b/CommAppCF/Properties/AssemblyInfo.cs deleted file mode 100644 index 3f89d9c..0000000 --- a/CommAppCF/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("CommAppCF")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("CommAppCF")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("7c366247-0f89-4894-9690-a8ee15533cb7")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - diff --git a/CommAppCF/Properties/Resources.Designer.cs b/CommAppCF/Properties/Resources.Designer.cs deleted file mode 100644 index f87532b..0000000 --- a/CommAppCF/Properties/Resources.Designer.cs +++ /dev/null @@ -1,60 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.4952 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace CommAppCF.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CommAppCF.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/CommAppCF/Properties/Resources.resx b/CommAppCF/Properties/Resources.resx deleted file mode 100644 index 451318b..0000000 --- a/CommAppCF/Properties/Resources.resx +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 diff --git a/CommAppCF/SetBTprinter.dll b/CommAppCF/SetBTprinter.dll deleted file mode 100644 index 4aca93f..0000000 Binary files a/CommAppCF/SetBTprinter.dll and /dev/null differ diff --git a/CommAppCF/SetBTprinter/SetBTprinter.cpp b/CommAppCF/SetBTprinter/SetBTprinter.cpp deleted file mode 100644 index 562f69d..0000000 --- a/CommAppCF/SetBTprinter/SetBTprinter.cpp +++ /dev/null @@ -1,300 +0,0 @@ -// SetBTprinter.cpp : Defines the entry point for the DLL application. -// - -#include "stdafx.h" -#include -//#include - -// SetBTPrinter4dll.cpp : Defines the entry point for the DLL application. -// -/* - history - version - 1.1 replaced all DEBUGMSG by nclog - added nclog.h and nclog.cpp - changed log text for ITC_SetDefaultDevice() - addede iResult=-3 before while loop - added iResult=0 for found device below "if(wcsstr(uDeviceName, uBDA)!=NULL)" -*/ -#pragma comment (user, "SetBTprinter.DLL version 1.1") - -//#include "stdafx.h" -#include "SetBTprinter.h" - -#include "nclog.h" - -const TCHAR* szXmlFileName = L"\\Windows\\pswdm0c.xml"; -const LPTSTR szDeviceType = TEXT("Printer"); -const LPTSTR szDeviceSubtype = NULL; - -const TCHAR* csFP = L"NEW\r\n1 BARFONT ON\r\n2 BARFONT \"Swiss 721 BT\", 6\r\n10 PRPOS 10,10\r\n20 PRBOX 430,340,15\r\n50 PRPOS 75,27060 BARTYPE \"CODE39\"70 PRBAR \"ABC\"80 PRPOS 25,220\r\n90 FONT \"Swiss 721 BT\", 6\r\n100 PRTXT \"My FIRST label\"\r\n200 PRINTFEED\r\n300 END\r\nRUN\r\n"; - -const TCHAR* csESCP = L"Intermec Developer Conference 2005\n\n Multiblue Sample Order\n\nProduct Quantity Price\n______________________________\n Delicious Soda 123 $0.49\n\n\n\n\n\n"; - -//test func for pswdmc0 -// registerPrinter(TCHAR* szBDA) -// register and activate the BT device with BDA szBDA -// performs a device discovery and binds the device -// the registry has the BTPort entry as WPort not WPPort as in help doc -// returns -// 0 for success -// -1 for error in ITC_InitializeDeviceUtility -// -2 for failure with ITC_DiscoverDevices -// -3 for if unable to find device in range -// -4 ITC_SetActiveDevice failed -// -5 ITC_SetDefaultDevice failed -// -6 ITC_SaveDeviceUtilityChanges failed -// -7 ITC_CloseDeviceUtility failed -// -8 ITC_AddDevice failed -int registerPrinter(TCHAR* szBDA){ - int iResult = 0; //return code, assume no error - TCHAR uDeviceName[MAX_PATH]; //for upper case compare - TCHAR uBDA[MAX_PATH]; //for upper case compare - - wchar_t fillChar = '\0'; - TCHAR deviceName[MAX_PATH]; //var for ITC_GetDiscoveredDevice - TCHAR strSelectedDevice[MAX_PATH]; //var to be used for Registering - - nclog(L"registerPrinter: ITC_InitializeDeviceUtility()\r\n"); - int iRes = ITC_InitializeDeviceUtility(szXmlFileName); - if(iRes==0){ - ITC_DISCOVERPROC lpDiscoveryComplete=NULL; - DWORD lParam = 0; - nclog(L"registerPrinter: ITC_DiscoverDevices()...\r\n"); - iRes = ITC_DiscoverDevices(szDeviceType, szDeviceSubtype, lpDiscoveryComplete, lParam); - nclog(L"registerPrinter: ITC_DiscoverDevices() finished\r\n"); - if(iRes==0){ - iResult=-3; //assume device not found, v1.1 - BOOL bFirst = TRUE; - while(ITC_GetDiscoveredDevice(deviceName, MAX_PATH, bFirst)==ERROR_SUCCESS){ //find first device - //cDeviceName=deviceName; - nclog(L"registerPrinter: testing '%s'\r\n", deviceName); - //is the BDA in there? - wcscpy(uBDA, szBDA); _wcsupr(uBDA); //all upper case - wcscpy(uDeviceName, deviceName); _wcsupr(uDeviceName); //all upper case - //is this the searched printer - if(wcsstr(uDeviceName, uBDA)!=NULL){ - iResult=0; //found device, v1.1 - nclog(L"registerPrinter: found match '%s'\r\n", deviceName); - //found the printer in question, now set this as default - wsprintf(strSelectedDevice, L"%s", deviceName); - - // Determine if the computer needs to bond with the device. - nclog(L"registerPrinter: ITC_IsBondWithDeviceNeeded for %s...\r\n", strSelectedDevice); - if (ITC_IsBondWithDeviceNeeded(strSelectedDevice)) - { - // TODO: You should show a warning message suggesting - // that bonding should not be performed in a public - // place, because an attacker could eavesdrop and - // steal the Passkey. - - // TODO: If you do not want to use the default Passkey - // prompt for the Bluetooth stack, make sure a Passkey - // is set for the device. This sample just allows the - // default Passkey prompt so it does not use this code. - TCHAR strPasskey[MAX_PATH]; - iRes = ITC_GetDeviceProperty(strSelectedDevice, TEXT("Passkey"), strPasskey, MAX_PATH); - nclog(L"registerPrinter: ITC_GetDeviceProperty for passkey returned %i\r\n", iRes); - if (strPasskey==NULL || wcslen(strPasskey)==0) - { - // TODO: If all of your devices have a common - // Passkey, you could hardcode a value here. - // Otherwise, you could prompt the user for - // the Passkey. - wsprintf(strPasskey, L""); - // Store the Passkey. - iRes = ITC_SetDeviceProperty(strSelectedDevice, TEXT("Passkey"), strPasskey); - nclog(L"registerPrinter: ITC_SetDeviceProperty setting empty passkey returned %i\r\n", iRes); - } - - // Bond the computer and the device. - // TODO: Because radio connections can sometimes fail, - // you should build in retry logic when BondWithDevice - // fails. This sample just tries once. - iRes = ITC_BondWithDevice(strSelectedDevice); - if(iRes!=0) - nclog(L"registerPrinter: ITC_BondWithDevice failed with %i\r\n",iRes); - else - nclog(L"registerPrinter: ITC_BondWithDevice OK\r\n"); - - } - else{ - nclog(L"registerPrinter: ITC_IsBondWithDeviceNeeded not needed\r\n"); - } - - iRes = ITC_AddDevice(szDeviceType, /*szDeviceSubtype*/ NULL, strSelectedDevice); - if (iRes == ERROR_SUCCESS){ - nclog(L"registerPrinter: ITC_AddDevice for '%s' OK\r\n", strSelectedDevice); - } - else{ - nclog(L"registerPrinter: ITC_AddDevice for '%s' failed with error %i\r\n", strSelectedDevice, iRes); - iResult = -8; - } - - // Set up a port to use the selected device. Refer to the BtPort element in the XML file. - // Call ITC_SetActiveDevice to set up a port for accessing the device. Call ITC_SetActiveDevice before - // each attempt to access the device because the port is removed if the computer is rebooted. - - - iRes = ITC_SetActiveDevice(szDeviceType, /*szDeviceSubtype*/ NULL, strSelectedDevice); - if (iRes == ERROR_SUCCESS){ - nclog(L"registerPrinter: ITC_SetActiveDevice to '%s' OK\r\n", strSelectedDevice); - } - else{ - nclog(L"registerPrinter: ITC_SetActiveDevice to '%s' failed with error %i\r\n", strSelectedDevice, iRes); - iResult = -4; - } - // Set the selected device as the default. - iRes = ITC_SetDefaultDevice(szDeviceType, /*szDeviceSubtype*/ NULL, strSelectedDevice); - if (iRes == ERROR_SUCCESS) - nclog(L"registerPrinter: ITC_SetDefaultDevice to '%s' OK\r\n", strSelectedDevice); - else{ - nclog(L"registerPrinter: ITC_SetDefaultDevice to '%s' failed with error %i\r\n", strSelectedDevice, iRes); - iResult=-5; - } - nclog(L"...leaving registerPrinter\r\n"); - break; - }// if BDA found - bFirst=FALSE; - _wcsset(deviceName, fillChar); - }//while - nclog(L"registerPrinter: Leaving loop\r\n"); - }//ITC_DiscoverDevices - else{ - nclog(L"registerPrinter: ITC_DiscoverDevices() failed\r\n"); - iResult=-2; - } - - //save changes to utility - if(iRes = ITC_SaveDeviceUtilityChanges()==0) - nclog(L"registerPrinter: saved changes to '%s'\r\n", szXmlFileName); - else{ - nclog(L"registerPrinter: save to '%s' failed with error %i\r\n", szXmlFileName, iRes); - iResult=-6; - } - - //close device utility - if(iRes = ITC_CloseDeviceUtility()==0) - nclog(L"registerPrinter: ITC_CloseDeviceUtility() OK\r\n", szXmlFileName); - else{ - nclog(L"registerPrinter: ITC_CloseDeviceUtility() failed with error %i\r\n", iRes); - iResult=-7; - } - - nclog(L"registerPrinter: ITC_InitializeDeviceUtility() finished\r\n"); - } - else - { - nclog(L"registerPrinter: ITC_InitializeDeviceUtility() failed\r\n"); - return -1; - }//ITC_InitializeDeviceUtility - - return iResult; -} - -int doTestPrintESCP(TCHAR* szComPort) -{ - int iRet = 0; - nclog(_T("doTestPrint: printing...\r\n")); - - HANDLE hPort; - DWORD dwNumBytesWritten; -// TCHAR buf[1024+1]; // Printers expect regular chars but they'll throw away the nulls in the unicode - - hPort = CreateFile(szComPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - - if(hPort == INVALID_HANDLE_VALUE) - { - iRet=GetLastError(); - nclog(_T("doTestPrint: Unable to connect to printer at '%s', err=%i\r\n"), szComPort, iRet); - nclog(_T("doTestPrint: ...exit printing\r\n")); - //AfxMessageBox(_T("Unable to connect to printer."); - return iRet; - } - - nclog(_T("doTestPrint: connected...\r\n")); - - //TEST with FingerPrint - if (!WriteFile(hPort, csESCP, wcslen(csESCP) * sizeof(TCHAR), &dwNumBytesWritten, NULL)) { - iRet = GetLastError(); - nclog(_T("doTestPrint: Print error: %i\r\n"), iRet); - CloseHandle(hPort); - return iRet; - } - // AfxMessageBox(_T("Print error"); - - nclog(_T("doTestPrint: WriteFile did %i bytes\r\n"), dwNumBytesWritten); - - Sleep(2000); // Allow time to finish printing before closing the handle. Workaround for VM data flush issue - CloseHandle(hPort); - nclog(_T("doTestPrint: ...finished printing\r\n")); - - return 0; -} - -int doTestPrintFP(TCHAR* szComPort) -{ - nclog(L"doTestPrint: printing to '%s'...\r\n", szComPort); - int iRet=0; - - HANDLE hPort; - DWORD dwNumBytesWritten; -// TCHAR buf[1024+1]; // Printers expect regular chars but they'll throw away the nulls in the unicode - - hPort = CreateFile(szComPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - - if(hPort == INVALID_HANDLE_VALUE) - { - iRet=GetLastError(); - nclog(_T("doTestPrint: Unable to connect to printer at '%s', err=%i\r\n"), szComPort, iRet); - nclog(_T("doTestPrint: ...exit printing\r\n")); - return iRet; - } - - nclog(_T("doTestPrint: connected...\r\n")); - - //TEST with FingerPrint - if (!WriteFile(hPort, csFP, wcslen(csFP) * sizeof(TCHAR), &dwNumBytesWritten, NULL)) { - iRet = GetLastError(); - nclog(_T("doTestPrint: Print error: %i\r\n"), iRet); - CloseHandle(hPort); - return iRet; - // AfxMessageBox(_T("Print error"); - } - - nclog(_T("doTestPrint: WriteFile did %i bytes\r\n"), dwNumBytesWritten); - - Sleep(2000); // Allow time to finish printing before closing the handle. Workaround for VM data flush issue - CloseHandle(hPort); - nclog(_T("doTestPrint: ...finished printing\r\n")); - - return 0; -} - -BOOL APIENTRY DllMain( HANDLE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - switch (ul_reason_for_call){ - case DLL_PROCESS_ATTACH: - nclogEnable(FALSE); //enable or disable logging - nclog(L"SetBTPrinter DllMain: DLL_PROCESS_ATTACH\n"); - return TRUE; - case DLL_THREAD_ATTACH: - nclog(L"SetBTPrinter DllMain: DLL_THREAD_ATTACH\n"); - return TRUE; - case DLL_THREAD_DETACH: - nclog(L"SetBTPrinter DllMain: DLL_THREAD_DETACH\n"); - return TRUE; - case DLL_PROCESS_DETACH: - nclog(L"SetBTPrinter DllMain: DLL_PROCESS_DETACH\n"); - return TRUE; - default: - nclog(L"SetBTPrinter DllMain: default\n"); - return TRUE; - - } -} - - diff --git a/CommAppCF/SetBTprinter/SetBTprinter.def b/CommAppCF/SetBTprinter/SetBTprinter.def deleted file mode 100644 index 83d718a..0000000 --- a/CommAppCF/SetBTprinter/SetBTprinter.def +++ /dev/null @@ -1,9 +0,0 @@ -; SetBTprinter.def : Declares the module parameters for the DLL. - -LIBRARY "SetBTprinter" - -EXPORTS - ; Explicit exports can go here - registerPrinter - doTestPrintFP - doTestPrintESCP \ No newline at end of file diff --git a/CommAppCF/SetBTprinter/SetBTprinter.h b/CommAppCF/SetBTprinter/SetBTprinter.h deleted file mode 100644 index 7611e58..0000000 --- a/CommAppCF/SetBTprinter/SetBTprinter.h +++ /dev/null @@ -1,10 +0,0 @@ -//#include "C:/Programme/IBM/DeviceDeveloper/wsdd5.0/ive-2.2/runtimes/linux/x86/ppro10/bin/include/jni.h" -//#include "ijni.h" - -//the pswdm0c API -#include "include/pswdm0c.h" -#pragma comment (lib, "lib/pswdm0cDLL.lib") - -#ifndef _Included_SetBTprinterClass -#define _Included_SetBTprinterClass -#endif \ No newline at end of file diff --git a/CommAppCF/SetBTprinter/SetBTprinter.vcproj b/CommAppCF/SetBTprinter/SetBTprinter.vcproj deleted file mode 100644 index c989389..0000000 --- a/CommAppCF/SetBTprinter/SetBTprinter.vcproj +++ /dev/null @@ -1,250 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/CommAppCF/SetBTprinter/nclog.cpp b/CommAppCF/SetBTprinter/nclog.cpp deleted file mode 100644 index 728bfe9..0000000 --- a/CommAppCF/SetBTprinter/nclog.cpp +++ /dev/null @@ -1,241 +0,0 @@ -// --- nclog.cpp --- - -//#include "winsock.h" -#include "winsock2.h" -#pragma comment (lib, "ws2.lib") - -#include -#include - -static SOCKET wsa_socket=INVALID_SOCKET; -#pragma comment(lib , "winsock") - -static unsigned short theLogPort=9998; - -//file stuff -//global -static char logFileName[MAX_PATH]; -static TCHAR logFileNameW[MAX_PATH]; -static BOOL bFirstFileCall = true; -static int iUseLogging=0; - -//max log file size ~250KByte -#define MAX_LOG_SIZE 0x0002FFFF - -// enable disable logging globally -void nclogEnable(BOOL bEnable){ - if(bEnable) - iUseLogging=1; - else - iUseLogging=0; -} - -// bind the log socket to a specific port. -static bool wsa_bind(unsigned short port) -{ - SOCKADDR_IN addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = htonl(INADDR_ANY); - int r=bind(wsa_socket,(sockaddr*)&addr,sizeof(addr)); - if (r==0) - theLogPort=port; - return (r==0); -} - -// initialize everything, if the socket isn't open. -static bool wsa_init() -{ - //already loaded? - if (wsa_socket != INVALID_SOCKET) return true; - - int r; - WSADATA wd; - BOOL bc=true; - - if (0 != WSAStartup(0x101, &wd)) - goto error; - wsa_socket=socket(PF_INET, SOCK_DGRAM, 0); - if (wsa_socket == INVALID_SOCKET) - goto error; - r=setsockopt(wsa_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bc, sizeof(bc)); - if (r!=0) - goto error; - if (wsa_bind(theLogPort)) - return true; // bind to default port. - error: - if (wsa_socket != INVALID_SOCKET) - closesocket(wsa_socket); -#ifdef DEBUG - OutputDebugString(TEXT("nclog: TCP/IP Problem")); -#endif - return false; - -} - -// can be called externally to select a different port for operations -bool set_nclog_port(unsigned short x) { return wsa_bind(x); } - -static void wsa_send(const char *x) -{ - SOCKADDR_IN sa; - sa.sin_family = AF_INET; - sa.sin_port = htons(theLogPort); - sa.sin_addr.s_addr = htonl(INADDR_BROADCAST); - - if (SOCKET_ERROR == sendto(wsa_socket,x,strlen(x), 0, (sockaddr*) &sa, sizeof(sa))) - { -#ifdef DEBUG - //if (debug_mode) -// OutputDebugString(TEXT("nclog: Send Error")); -#endif - } - -} - -//========================== start of file stuff ============================= -static int initFileNames() -{ - // Get name of executable - TCHAR lpFileName[MAX_PATH+1]; - GetModuleFileName(NULL, lpFileName, MAX_PATH); //lpFileName will contain the exe name of this running app! - //add txt extension - TCHAR txtFileName[MAX_PATH+1]; - wsprintf(txtFileName, L"%s.log.txt", lpFileName); - //store the filename to use in char and tchar - TCHAR logFileNameW[MAX_PATH]; - wsprintf(logFileNameW, txtFileName); - wcstombs(logFileName, logFileNameW, sizeof(logFileNameW)*sizeof(logFileNameW[0])); - - FILE *fp; - fp = fopen(logFileName, "a+"); - //get the file size - if(fseek(fp, 0, SEEK_END)==0){ - long iEnd = ftell(fp); - if(iEnd > MAX_LOG_SIZE) - { - fclose(fp); - fp=fopen(logFileName, "w+"); //creates an empty file - } - } - - fclose(fp); - bFirstFileCall=false; - return 0; -} - -TCHAR* logDateTime(){ - static TCHAR str[64]; - TCHAR lpTimeStr[32]; - TCHAR lpDateStr[32]; - LONG res; - wsprintf(str,L""); - //Read the system time - res = GetTimeFormat(LOCALE_SYSTEM_DEFAULT, - TIME_FORCE24HOURFORMAT, - NULL, - L"hh:mm:ss", - lpTimeStr, - sizeof (lpTimeStr ) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpTimeStr, L"err"); - } - - //Read the system date - res = GetDateFormat( LOCALE_SYSTEM_DEFAULT, - NULL, - NULL, - L"dd.MM.yyyy", - lpDateStr, - sizeof (lpDateStr) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpDateStr, L"err"); - } - - //wsprintf(str, L"Date and Time: %s %s", lpDateStr, lpTimeStr); - wsprintf(str, L"%s %s", lpDateStr, lpTimeStr); - return str; -} - -static int writefile(TCHAR *filetext){ - /* File Write Function, written by professor chemicalX */ - FILE *fp; /* Declare FILE structure */ - TCHAR szTemp[255]; - char szTempA[255]; - - wsprintf(szTemp, L"%s", filetext); - wcstombs(szTempA, szTemp, sizeof(szTemp)/sizeof(TCHAR)); - - if (bFirstFileCall){ - // Get name of executable - initFileNames(); - } - - fp = fopen(logFileName, "a+"); - - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - /* First of we open the file supplied by the filename paremeter */ - - /* - * in the "a+" mode for appending, so if it doesnt exist its created. - * fp = fopen(filename,"w"); // Open using the "w" mode for writing. - */ - long fsize = strlen(szTempA); /* Declare the long fsize with the length of the filetext */ - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - /* paremeter witch stores the text or data to right to the file. */ - fwrite(szTempA, 1, fsize, fp); /* Write File */ - fclose(fp); /* Remember to close the file stream after calling file functions, */ - - /* otherwise the file wont be created. */ - return 0; -} -//========================== end of file stuff ============================= - -// format input, convert to 8-bit and send. -void nclog (const wchar_t *fmt, ...) -{ - if(iUseLogging==1){ - TCHAR StrW[1024]; - va_list vl; - va_start(vl,fmt); - wchar_t buf[1024]; // to bad CE hasn't got wvnsprintf - wvsprintf(buf,fmt,vl); - wsa_init(); - char bufOut[512]; - - //insert data/time - wsprintf(StrW, L"%s: %s", logDateTime(), buf); - wsprintf(buf, L"%s", StrW); - - WideCharToMultiByte(CP_ACP,0,buf,-1,bufOut,400, NULL, NULL); - - wsa_send(bufOut); - - writefile(buf); -#ifdef DEBUG - DEBUGMSG(1, (buf)); -#else - RETAILMSG(1, (buf)); -#endif - }//iUseLogging -} - -// finalize the socket on program termination. -struct _nclog_module -{ - ~_nclog_module() - { - if (wsa_socket!=INVALID_SOCKET) - { - nclog(L"nclog goes down\n"); - shutdown(wsa_socket,2); - closesocket(wsa_socket); - } - } - -}; - -static _nclog_module module; diff --git a/CommAppCF/SetBTprinter/nclog.h b/CommAppCF/SetBTprinter/nclog.h deleted file mode 100644 index 854c0bf..0000000 --- a/CommAppCF/SetBTprinter/nclog.h +++ /dev/null @@ -1,24 +0,0 @@ -//nclog.h - - -extern void nclog (const wchar_t *fmt, ...); -//extern bool set_nclog_port(unsigned short x) { return wsa_bind(x); } -extern TCHAR* logDateTime(); -extern void nclogEnable(BOOL bEnable); - -/* -usage: - nclog(L"The Window Handle is: %x\n",hwnd); - -On your desktop, you need netcat to capture the output from your -program, i.e. you open a console and type: - -netcat -lup 9998 - -This will instruct netcat to show you everything that comes to your UDP -socket 9998 (which is the default for netcat). Since nclog opens the -socket in broadcast mode, you don't have to give an target adress. (Be -sure to select a port which does not interfer with the network you are -living in) - -*/ \ No newline at end of file diff --git a/CommAppCF/SetBTprinter/stdafx.cpp b/CommAppCF/SetBTprinter/stdafx.cpp deleted file mode 100644 index b6d406b..0000000 --- a/CommAppCF/SetBTprinter/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// SetBTprinter.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/CommAppCF/SetBTprinter/stdafx.h b/CommAppCF/SetBTprinter/stdafx.h deleted file mode 100644 index 57ae26c..0000000 --- a/CommAppCF/SetBTprinter/stdafx.h +++ /dev/null @@ -1,54 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include -#pragma comment(lib, "aygshell.lib") - - -// Windows Header Files: -#include - - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here diff --git a/CommAppCF/bin/CommAppCF.exe b/CommAppCF/bin/CommAppCF.exe deleted file mode 100644 index b4a6e77..0000000 Binary files a/CommAppCF/bin/CommAppCF.exe and /dev/null differ diff --git a/CommAppCF/escp_test.txt b/CommAppCF/escp_test.txt deleted file mode 100644 index 4570d88..0000000 --- a/CommAppCF/escp_test.txt +++ /dev/null @@ -1,33 +0,0 @@ -w1G -w! -ROUTE# 227 11/08/01 08:35 - - Food City #3212 - 1500 E Lincoln Way - Hamilton OH - TAX ID# A32102 - - ITEM# DESCRIPTION NET - QTY PRICE DEPOS ALLOW - - SALES - - 1001 Reg Cola 6pk 12cn 63.50 - 5 11.50 1.20 0.00 - - 1002 Diet Cola 6pk 12cn 38.10 - 3 11.50 1.20 0.00 - - CREDITS SALES -PRODUCT 0.00 101.60 -SUBTOTAL 101.60 -5% State Tax 5.08 - ------------- -BALANCE DUE: CHARGE 106.68 - ============= - - Thank You For Your Business - - - - diff --git a/CommAppCF/fp_test.txt b/CommAppCF/fp_test.txt deleted file mode 100644 index 74a6a98..0000000 --- a/CommAppCF/fp_test.txt +++ /dev/null @@ -1,12 +0,0 @@ -NEW -1 BARFONT ON -2 BARFONT "Swiss 721 BT", 6 -10 PRPOS 10,10 -20 PRBOX 430,340,15 -50 PRPOS 75,27060 BARTYPE "CODE39"70 PRBAR "ABC"80 PRPOS 25,220 -90 FONT "Swiss 721 BT", 6 -100 PRTXT "My FIRST label" -200 PRINTFEED -300 END -RUN - diff --git a/CommAppCF/hexHelper.cs b/CommAppCF/hexHelper.cs deleted file mode 100644 index fdf121b..0000000 --- a/CommAppCF/hexHelper.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Runtime.InteropServices; - - -public static class hexHelper -{ - public static byte[] reverseBytes(byte[] inB) - { - byte[] bOut = new byte[inB.Length]; - int iLast = inB.Length - 1; - for (int i = 0; i < inB.Length; i++) - { - bOut[i] = inB[iLast - i]; - } - return bOut; - } - public static bool IsHexDigit(Char c) - { - int numChar; - int numA = Convert.ToInt32('A'); - int num1 = Convert.ToInt32('0'); - c = Char.ToUpper(c); - numChar = Convert.ToInt32(c); - if (numChar >= numA && numChar < (numA + 6)) - return true; - if (numChar >= num1 && numChar < (num1 + 10)) - return true; - return false; - } - public static byte[] GetBytes(string hexString, out int discarded) - { - discarded = 0; - string newString = ""; - char c; - // remove all none A-F, 0-9, characters - for (int i = 0; i < hexString.Length; i++) - { - c = hexString[i]; - if (IsHexDigit(c)) - newString += c; - else - discarded++; - } - // if odd number of characters, discard last character - if (newString.Length % 2 != 0) - { - discarded++; - newString = newString.Substring(0, newString.Length - 1); - } - - int byteLength = newString.Length / 2; - byte[] bytes = new byte[byteLength]; - string hex; - int j = 0; - for (int i = 0; i < bytes.Length; i++) - { - hex = new String(new Char[] { newString[j], newString[j + 1] }); - bytes[i] = HexToByte(hex); - j = j + 2; - } - return bytes; - } - private static byte HexToByte(string hex) - { - if (hex.Length > 2 || hex.Length <= 0) - throw new ArgumentException("hex must be 1 or 2 characters in length"); - byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber); - return newByte; - } - public static string ToString(byte[] bytes) - { - string hexString = ""; - for (int i = 0; i < bytes.Length; i++) - { - hexString += bytes[i].ToString("X2"); - //if (i <= bytes.Length - 1) - // hexString += "-"; - } - return hexString; - } - -} - diff --git a/CommAppCF/myThread.cs b/CommAppCF/myThread.cs deleted file mode 100644 index a6f8a92..0000000 --- a/CommAppCF/myThread.cs +++ /dev/null @@ -1,125 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using System.Threading; - -using System.Net; -using System.Net.Sockets; -using System.IO; -using System.Runtime.CompilerServices; - -namespace CommAppCF -{ - public class DataEventArgs : EventArgs - { - /* HACK: fields are typically private, but making this internal so it - * can be accessed from other classes. In practice should use properties. - */ - internal string _string; - public DataEventArgs() - { - } - public DataEventArgs(string str) - : base() - { - this._string = str; - } - } - - public class myThread:System.ComponentModel.Component,IDisposable - { - private Thread _thread; - private bool _bStopThread = false; - #region EVENTSTUFF - - private BTDataReceivedEventHandler onDataReceived; - - public delegate void BTDataReceivedEventHandler(object sender, DataEventArgs d); - - //public event BTDataReceivedEventHandler BTDataReceived; - public event BTDataReceivedEventHandler BTDataReceived - { - add - { - this.onDataReceived = ((BTDataReceivedEventHandler)Delegate.Combine(((Delegate)this.onDataReceived), ((Delegate)value))); - } - remove - { - this.onDataReceived = ((BTDataReceivedEventHandler)Delegate.Remove(((Delegate)this.onDataReceived), ((Delegate)value))); - } - - } - - private void onDataReceivedEvent(object sender, DataEventArgs d) - { - BTDataReceivedEventHandler dataReceived = this.onDataReceived; - - if (dataReceived == null) - return; - dataReceived(this, d); - } - - private StreamReader _sr; - - #endregion - public myThread(ref NetworkStream ns) - { - this.onDataReceived = (BTDataReceivedEventHandler)null; - _sr = new StreamReader(ns); - _bStopThread = false; - _thread = new Thread(theThread); - _thread.Start(); - } - private bool disposed = false; - protected override void Dispose(bool disposing) - { - if (disposing) - { - _thread.Abort(); - //_bStopThread = true; - } - else - { - _bStopThread = true; - Thread.Sleep(1000); - } - this.disposed = true; - base.Dispose(disposing); - } - private void theThread() - { - System.Diagnostics.Debug.WriteLine("theThread: started..."); - try - { - string s = ""; - char[] buf = new char[1]; - int iCount = 0; - DataEventArgs args = new DataEventArgs(); - while (!_bStopThread && _sr!=null) - { - iCount = _sr.Read(buf, 0, 1); - if (iCount != 0) - { - s = buf.ToString(); - args._string = s; - onDataReceivedEvent(this, args); - } - Thread.Sleep(1000); - } - - } - catch (ThreadAbortException tax) - { - System.Diagnostics.Debug.WriteLine("theThread: ThreadAbortException=" + tax.Message); - _bStopThread = true; - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("theThread: Exception=" + ex.Message); - } - System.Diagnostics.Debug.WriteLine("theThread: ...ended"); - } - } -} diff --git a/CommAppCF/serialSet.cs b/CommAppCF/serialSet.cs deleted file mode 100644 index 08d5f4b..0000000 --- a/CommAppCF/serialSet.cs +++ /dev/null @@ -1,512 +0,0 @@ -using System; -using System.IO.Ports; -using System.Collections.Generic; -using System.Text; -using Microsoft.Win32; -using System.Diagnostics; - -namespace CommAppCF -{ - class serialSet : IDisposable - { - // Track whether Dispose has been called. - private bool disposed = false; - - private const string _regSubKey = @"Software\CommAppCF"; - private RegistryKey _regKey; - - private RegistryValueKind[] _regValueTypes = - { RegistryValueKind.String, - RegistryValueKind.DWord , - RegistryValueKind.DWord , - RegistryValueKind.DWord , - RegistryValueKind.DWord , - RegistryValueKind.DWord - }; - private string[] _regValueNames = - { "port", - "baudrate" , - "parity", - "databits", - "stopbits", - "handshake" - }; - - private const string _regValueNameTimeInterval = "TimeInterval"; - private const string _regValueLog2File = "Log2File"; - - public serialSet() - { - //try to read settings from Reg - if (regOpenKey()) - { - regReadSettings(); - } - else - this.Dispose(); - - } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - private void Dispose(bool disposing) - { - // Check to see if Dispose has already been called. - if (!this.disposed) - { - // If disposing equals true, dispose all managed - // and unmanaged resources. - if (disposing) - { - // Dispose managed resources. - //save settings? - regWriteSettings(); - regCloseKey(); - //component.Dispose(); - } - - // Call the appropriate methods to clean up - // unmanaged resources here. - // If disposing is false, - // only the following code is executed. - //CloseHandle(handle); - //handle = IntPtr.Zero; - - // Note disposing has been done. - disposed = true; - - } - } - - private bool regReadSettings() - { - if (_regKey == null) - return false; - - string s = ""; - uint d = 0; - //try to read settings - for (int x = 0; x < _regValueNames.Length; x++) - { - if (_regValueTypes[x] == RegistryValueKind.String) - { - s = regReadString(_regValueNames[x]); - } - else if (_regValueTypes[x] == RegistryValueKind.DWord) - { - d = regReadUInt(_regValueNames[x]); - } - switch (x) - { - case 0: if(s.Length>0) - _sPort = s; - break; - case 1: if(d>0) - _baudRate = d; - break; - case 2: if (d >= 0) - _parity = d; - break; - case 3: if (d > 0) - _databits = d; - break; - case 4: if (d > 0) - _stopBits = d; - break; - case 5: if (d >= 0) - _handshake = d; - break; - } - } - - return true; - } - public int saveSettings() - { - if (this.regWriteSettings()) - return 0; - else - return -1; - } - private bool regWriteSettings() - { - regWriteString(_regValueNames[0], _sPort); - regWriteInt(_regValueNames[1], _baudRate); - regWriteInt(_regValueNames[2], _parity); - regWriteInt(_regValueNames[3], _databits); - regWriteInt(_regValueNames[4], _stopBits); - regWriteInt(_regValueNames[5], _handshake); - - return true; - } - #region REGISTRY - private int regReadInt(string sValuename) - { - if (_regKey == null) - return -1; - try - { - int i = (int)_regKey.GetValue(sValuename, -1); - return i; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return -1; - } - private uint regReadUInt(string sValuename) - { - if (_regKey == null) - return 0; - try - { - int i = (int)_regKey.GetValue(sValuename, 0); - return (uint)i; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadUInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return 0; - } - private bool regWriteInt(string sValuename, uint i) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, i, RegistryValueKind.DWord); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteUInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return false; - } - private bool regWriteInt(string sValuename, int i) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, i, RegistryValueKind.DWord); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return false; - } - - private string regReadString(string sValuename) - { - if (_regKey == null) - return null; - try - { - string s = (string)_regKey.GetValue(sValuename, ""); - return s; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadStrings for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return null; - } - - private string[] regReadStrings(string sValuename) - { - if (_regKey == null) - return null; - try - { - string[] s = (string[])_regKey.GetValue(sValuename, ""); - return s; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadStrings for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return null; - } - private bool regWriteString(string sValuename, string s) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, s); - _regKey.Flush(); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteStrings for '" + _regSubKey + "'. " + x.Message); - return false; - } - } - - private bool regWriteStrings(string sValuename, string[] s) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, s); - _regKey.Flush(); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteStrings for '" + _regSubKey + "'. " + x.Message); - return false; - } - } - private bool regOpenKey() - { - try - { - _regKey = Registry.LocalMachine.CreateSubKey(_regSubKey); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in OpenSubKey/CreateSubKey for '" + _regSubKey + "'. " + x.Message); - } - return false; - } - private void regCloseKey() - { - if (_regKey != null) - { - try - { - Registry.LocalMachine.Close(); - } - catch (Exception x) - { - Debug.WriteLine("Exception in CloseKey for '" + _regSubKey + "'. " + x.Message); - } - } - } -#endregion - #region FIELDS - private string _sPort="COM0"; - public string sPort - { - get { return _sPort; } - set { _sPort = value; } - } - private uint[] _baudRates = { 1200, 2400, 4800, 9600, 19200, 38200, 57600, 115200, 230400, 460800, 921600 }; - public uint[] baudRates - { - get { return _baudRates; } - } - private uint _baudRate = 1200; - public uint baudRate - { - get { return _baudRate; } - set { _baudRate = value; } - } - private uint _parity = 0; - public uint parity - { - get { return _parity; } - set { _parity = value; } - } - private uint _databits = 8; - public uint databits - { - get { return _databits; } - set { _databits = value; } - } - private uint _stopBits = 1; - public uint stopBits - { - get { return _stopBits; } - set { _stopBits = value; } - } - private uint _handshake = 0; - public uint handshake - { - get { return _handshake; } - set { _handshake = value; } - } - #endregion - - } - public static class myParity - { - public static string[] parity = { "None", "Odd", "Even", "Mark", "Space" }; - public static int ToInt(string s) - { - for (int i = 0; i < parity.Length; i++) - { - if(s.Equals(parity[i],StringComparison.OrdinalIgnoreCase)) - return i; - } - return 0; - } - public static string ToString(int i) - { - return parity[i]; - } - public static Parity ToParity(int i) - { - switch (i) - { - case 0: - return Parity.None; - case 1: - return Parity.Odd; - case 2: - return Parity.Even; - case 3: - return Parity.Mark; - case 4: - return Parity.Space; - } - return Parity.None; - } - public static Parity ToParity(string text) - { - if (text.Equals("None", StringComparison.OrdinalIgnoreCase)) - return Parity.None; - if (text.Equals("Odd", StringComparison.OrdinalIgnoreCase)) - return Parity.Odd; - if (text.Equals("Even", StringComparison.OrdinalIgnoreCase)) - return Parity.Even; - if (text.Equals("Mark", StringComparison.OrdinalIgnoreCase)) - return Parity.Mark; - if (text.Equals("Space", StringComparison.OrdinalIgnoreCase)) - return Parity.Space; - - return Parity.None; - } - }//class myParity - public static class myStopBits - { - public static StopBits ToStopBits(string text) - { - if (text.Equals("None", StringComparison.OrdinalIgnoreCase)) - return StopBits.None; - if (text.Equals("One", StringComparison.OrdinalIgnoreCase)) - return StopBits.One; - if (text.Equals("Two", StringComparison.OrdinalIgnoreCase)) - return StopBits.Two; - if (text.Equals("OnePointFive", StringComparison.OrdinalIgnoreCase)) - return StopBits.OnePointFive; - - return StopBits.One; - } - public static StopBits ToStopBits(int i) - { - switch (i) - { - case 0: return StopBits.None; - case 1: return StopBits.One; - case 2: return StopBits.Two; - case 3: return StopBits.OnePointFive; - } - return StopBits.One; - } - public static string ToString(StopBits sb) - { - switch (sb) - { - case StopBits.None: return "None"; - case StopBits.One: return "One"; - case StopBits.Two: return "Two"; - case StopBits.OnePointFive: return "OnePointFive"; - } - return "One"; - } - public static string ToString(int i) - { - switch (i) - { - case 0: return "None"; - case 1: return "One"; - case 2: return "Two"; - case 3: return "OnePointFive"; - } - return "One"; - } - public static int ToInt(StopBits sb) - { - switch (sb) - { - case StopBits.None: return 0; - case StopBits.One: return 1; - case StopBits.Two: return 2; - case StopBits.OnePointFive: return 3; - } - return 1; - } - }//class myStopbits - public static class myHandshake - { - public static string[] handshakes = { "None", "XOnXOff", "RequestToSend", "RequestToSendXOnXOff" }; - public static Handshake ToHandshake(int i) - { - switch (i) - { - case 0: return Handshake.None; - case 1: return Handshake.XOnXOff; - case 2: return Handshake.RequestToSend; - case 3: return Handshake.RequestToSendXOnXOff; - } - return Handshake.None; - } - public static Handshake ToHandshake(string text) - { - if (text.Equals("None", StringComparison.OrdinalIgnoreCase)) - return Handshake.None; - if (text.Equals("XOnXOff", StringComparison.OrdinalIgnoreCase)) - return Handshake.XOnXOff; - if (text.Equals("RequestToSend", StringComparison.OrdinalIgnoreCase)) - return Handshake.RequestToSend; - if (text.Equals("RequestToSendXOnXOff", StringComparison.OrdinalIgnoreCase)) - return Handshake.RequestToSendXOnXOff; - return Handshake.None; - } - public static int ToInt(Handshake hs) - { - switch (hs) - { - case Handshake.None: return 0; - case Handshake.XOnXOff: return 1; - case Handshake.RequestToSend: return 2; - case Handshake.RequestToSendXOnXOff: return 3; - } - return 0; - } - public static string ToString(Handshake hs) - { - switch (hs) - { - case Handshake.None: return "None"; - case Handshake.XOnXOff: return "XOnXOff"; - case Handshake.RequestToSend: return "RequestToSend"; - case Handshake.RequestToSendXOnXOff: return "RequestToSendXOnXOff"; - } - return "None"; - } - public static string ToString(int i) - { - switch (i) - { - case 0: return "None"; - case 1: return "XOnXOff"; - case 2: return "RequestToSend"; - case 3: return "RequestToSendXOnXOff"; - } - return "None"; - } - }//class myHandshake -} diff --git a/CommAppCFSerial/CommAppCF.csproj b/CommAppCFSerial/CommAppCF.csproj deleted file mode 100644 index b04ada3..0000000 --- a/CommAppCFSerial/CommAppCF.csproj +++ /dev/null @@ -1,113 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {151322CC-139B-455B-8B84-1A21D3D81834} - WinExe - Properties - CommAppCF - CommAppCF - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.01 - CommAppCF - v2.0 - - - - - - - 2.0 - Windows Mobile 5.0 Pocket PC SDK - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - Form - - - ConnectDlg.cs - - - Form - - - Form1.cs - - - - - - Designer - ConnectDlg.cs - - - Designer - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/CommAppCFSerial/CommAppCF.csproj.user b/CommAppCFSerial/CommAppCF.csproj.user deleted file mode 100644 index 1f8508e..0000000 --- a/CommAppCFSerial/CommAppCF.csproj.user +++ /dev/null @@ -1,5 +0,0 @@ - - - 4118C335-430C-497f-BE48-11C3316B135Ed6518ffb-710f-11d3-99f2-00105a0df099 - - \ No newline at end of file diff --git a/CommAppCFSerial/CommAppCF.sln b/CommAppCFSerial/CommAppCF.sln deleted file mode 100644 index 5e4b065..0000000 --- a/CommAppCFSerial/CommAppCF.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommAppCF", "CommAppCF.csproj", "{151322CC-139B-455B-8B84-1A21D3D81834}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Any CPU.Build.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Any CPU.ActiveCfg = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Any CPU.Build.0 = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/CommAppCFSerial/CommAppCF.suo b/CommAppCFSerial/CommAppCF.suo deleted file mode 100644 index c2a36ef..0000000 Binary files a/CommAppCFSerial/CommAppCF.suo and /dev/null differ diff --git a/CommAppCFSerial/ConnectDlg.Designer.cs b/CommAppCFSerial/ConnectDlg.Designer.cs deleted file mode 100644 index 7c7d867..0000000 --- a/CommAppCFSerial/ConnectDlg.Designer.cs +++ /dev/null @@ -1,218 +0,0 @@ -namespace CommAppCF -{ - partial class ConnectDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuCancel = new System.Windows.Forms.MenuItem(); - this.mnuConnect = new System.Windows.Forms.MenuItem(); - this.lblComPort = new System.Windows.Forms.Label(); - this.cmbPortName = new System.Windows.Forms.ComboBox(); - this.cmbBaudRate = new System.Windows.Forms.ComboBox(); - this.lblBaudRate = new System.Windows.Forms.Label(); - this.cmbParity = new System.Windows.Forms.ComboBox(); - this.label1 = new System.Windows.Forms.Label(); - this.lblStopBits = new System.Windows.Forms.Label(); - this.cmbStopBits = new System.Windows.Forms.ComboBox(); - this.lblDataBits = new System.Windows.Forms.Label(); - this.cmbDataBits = new System.Windows.Forms.ComboBox(); - this.cmbHandshake = new System.Windows.Forms.ComboBox(); - this.label2 = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuCancel); - this.mainMenu1.MenuItems.Add(this.mnuConnect); - // - // mnuCancel - // - this.mnuCancel.Text = "Cancel"; - this.mnuCancel.Click += new System.EventHandler(this.mnuCancel_Click); - // - // mnuConnect - // - this.mnuConnect.Text = "Connect"; - this.mnuConnect.Click += new System.EventHandler(this.mnuConnect_Click); - // - // lblComPort - // - this.lblComPort.Location = new System.Drawing.Point(27, 11); - this.lblComPort.Name = "lblComPort"; - this.lblComPort.Size = new System.Drawing.Size(74, 13); - this.lblComPort.Text = "COM Port:"; - // - // cmbPortName - // - this.cmbPortName.Items.Add("COM0"); - this.cmbPortName.Items.Add("COM1"); - this.cmbPortName.Items.Add("COM2"); - this.cmbPortName.Items.Add("COM3"); - this.cmbPortName.Items.Add("COM4"); - this.cmbPortName.Location = new System.Drawing.Point(112, 3); - this.cmbPortName.Name = "cmbPortName"; - this.cmbPortName.Size = new System.Drawing.Size(68, 22); - this.cmbPortName.TabIndex = 18; - // - // cmbBaudRate - // - this.cmbBaudRate.Items.Add("1200"); - this.cmbBaudRate.Items.Add("2400"); - this.cmbBaudRate.Items.Add("4800"); - this.cmbBaudRate.Items.Add(""); - this.cmbBaudRate.Location = new System.Drawing.Point(112, 39); - this.cmbBaudRate.Name = "cmbBaudRate"; - this.cmbBaudRate.Size = new System.Drawing.Size(68, 22); - this.cmbBaudRate.TabIndex = 19; - // - // lblBaudRate - // - this.lblBaudRate.Location = new System.Drawing.Point(27, 47); - this.lblBaudRate.Name = "lblBaudRate"; - this.lblBaudRate.Size = new System.Drawing.Size(79, 13); - this.lblBaudRate.Text = "Baud Rate:"; - // - // cmbParity - // - this.cmbParity.Items.Add("None"); - this.cmbParity.Items.Add("1"); - this.cmbParity.Items.Add("2"); - this.cmbParity.Items.Add("3"); - this.cmbParity.Items.Add("4"); - this.cmbParity.Items.Add("5"); - this.cmbParity.Items.Add("6"); - this.cmbParity.Location = new System.Drawing.Point(112, 79); - this.cmbParity.Name = "cmbParity"; - this.cmbParity.Size = new System.Drawing.Size(68, 22); - this.cmbParity.TabIndex = 21; - // - // label1 - // - this.label1.Location = new System.Drawing.Point(27, 79); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(54, 13); - this.label1.Text = "Parity:"; - // - // lblStopBits - // - this.lblStopBits.Location = new System.Drawing.Point(27, 158); - this.lblStopBits.Name = "lblStopBits"; - this.lblStopBits.Size = new System.Drawing.Size(70, 13); - this.lblStopBits.Text = "Stop Bits:"; - // - // cmbStopBits - // - this.cmbStopBits.Items.Add("1"); - this.cmbStopBits.Items.Add("2"); - this.cmbStopBits.Items.Add("3"); - this.cmbStopBits.Location = new System.Drawing.Point(112, 155); - this.cmbStopBits.Name = "cmbStopBits"; - this.cmbStopBits.Size = new System.Drawing.Size(69, 22); - this.cmbStopBits.TabIndex = 26; - // - // lblDataBits - // - this.lblDataBits.Location = new System.Drawing.Point(27, 119); - this.lblDataBits.Name = "lblDataBits"; - this.lblDataBits.Size = new System.Drawing.Size(71, 13); - this.lblDataBits.Text = "Data Bits:"; - // - // cmbDataBits - // - this.cmbDataBits.Items.Add("5"); - this.cmbDataBits.Items.Add("6"); - this.cmbDataBits.Items.Add("7"); - this.cmbDataBits.Items.Add("8"); - this.cmbDataBits.Location = new System.Drawing.Point(112, 119); - this.cmbDataBits.Name = "cmbDataBits"; - this.cmbDataBits.Size = new System.Drawing.Size(68, 22); - this.cmbDataBits.TabIndex = 25; - // - // cmbHandshake - // - this.cmbHandshake.Items.Add("1"); - this.cmbHandshake.Items.Add("2"); - this.cmbHandshake.Items.Add("3"); - this.cmbHandshake.Location = new System.Drawing.Point(111, 192); - this.cmbHandshake.Name = "cmbHandshake"; - this.cmbHandshake.Size = new System.Drawing.Size(69, 22); - this.cmbHandshake.TabIndex = 26; - // - // label2 - // - this.label2.Location = new System.Drawing.Point(26, 195); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(70, 13); - this.label2.Text = "Handshake:"; - // - // ConnectDlg - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.label2); - this.Controls.Add(this.lblStopBits); - this.Controls.Add(this.cmbHandshake); - this.Controls.Add(this.cmbStopBits); - this.Controls.Add(this.lblDataBits); - this.Controls.Add(this.cmbDataBits); - this.Controls.Add(this.lblComPort); - this.Controls.Add(this.cmbPortName); - this.Controls.Add(this.cmbBaudRate); - this.Controls.Add(this.lblBaudRate); - this.Controls.Add(this.cmbParity); - this.Controls.Add(this.label1); - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "ConnectDlg"; - this.Text = "ConnectDlg"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuCancel; - private System.Windows.Forms.MenuItem mnuConnect; - private System.Windows.Forms.Label lblComPort; - private System.Windows.Forms.ComboBox cmbPortName; - private System.Windows.Forms.ComboBox cmbBaudRate; - private System.Windows.Forms.Label lblBaudRate; - private System.Windows.Forms.ComboBox cmbParity; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label lblStopBits; - private System.Windows.Forms.ComboBox cmbStopBits; - private System.Windows.Forms.Label lblDataBits; - private System.Windows.Forms.ComboBox cmbDataBits; - private System.Windows.Forms.ComboBox cmbHandshake; - private System.Windows.Forms.Label label2; - } -} \ No newline at end of file diff --git a/CommAppCFSerial/ConnectDlg.cs b/CommAppCFSerial/ConnectDlg.cs deleted file mode 100644 index 8710e36..0000000 --- a/CommAppCFSerial/ConnectDlg.cs +++ /dev/null @@ -1,153 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.IO.Ports; - -namespace CommAppCF -{ - public partial class ConnectDlg : Form - { - private SerialPort _serialPort; - private uint[] baudRates = { 1200, 2400, 4800, 9600, 19200, 38200, 57600, 115200, 230400, 460800, 921600 }; - - private serialSet _mySettings = new serialSet(); - - public ConnectDlg(ref SerialPort sp) - { - InitializeComponent(); - - //port list - cmbPortName.Items.Clear(); - for (int i = 0; i < 10; i++) - { - cmbPortName.Items.Insert(i, "COM" + i.ToString()); - } - int ix = cmbPortName.Items.IndexOf(_mySettings.sPort); - if (ix != -1) - cmbPortName.SelectedIndex = ix; - else - cmbPortName.SelectedIndex = 0; - - //baud list - cmbBaudRate.Items.Clear(); - int j = 0; - foreach (uint u in _mySettings.baudRates) - { - cmbBaudRate.Items.Insert(j, u.ToString()); - j++; - } - ix = findInCombo(cmbBaudRate, _mySettings.baudRate.ToString()); - if (ix != -1) - cmbBaudRate.SelectedIndex = ix; - else - cmbBaudRate.SelectedIndex = 0; - - //databits - cmbDataBits.Items.Clear(); - for (int i = 6; i < 9; i++) - { - cmbDataBits.Items.Add(i.ToString()); - } - ix = findInCombo(cmbDataBits, _mySettings.databits.ToString()); - if (ix != -1) - cmbDataBits.SelectedIndex = ix; - else - cmbDataBits.SelectedIndex = 0; - - //parity - cmbParity.Items.Clear(); - for (int i = 0; i < myParity.parity.Length; i++) - { - cmbParity.Items.Insert(i, myParity.ToString(i)); - } - - cmbParity.SelectedIndex = (int)_mySettings.parity; - - //stopBits - cmbStopBits.Items.Clear(); - for (int i = 0; i < 3; i++) - { - cmbStopBits.Items.Insert(i, myStopBits.ToString(i)); - } - ix = findInCombo(cmbStopBits, _mySettings.stopBits.ToString()); - if (ix != -1) - cmbStopBits.SelectedIndex = ix; - else - cmbStopBits.SelectedIndex = 1; -// cmbStopBits.SelectedIndex = cmbStopBits.Items.IndexOf(_mySettings.stopBits); - - //handshake - cmbHandshake.Items.Clear(); - for (int i = 0; i < myHandshake.handshakes.Length; i++) - { - cmbHandshake.Items.Insert(i, myHandshake.ToString(i)); - } - cmbHandshake.SelectedIndex = (int)_mySettings.handshake; - - this._serialPort = sp; - - } - - private int findInCombo(ComboBox cbo, string s) - { - for (int j = 0; j < cbo.Items.Count; j++) - { - if (cbo.Items[j].ToString().Equals(s, StringComparison.OrdinalIgnoreCase)) - return j; - } - return -1; - } - private void mnuCancel_Click(object sender, EventArgs e) - { - this.Close(); - } - - private void mnuConnect_Click(object sender, EventArgs e) - { - if (_serialPort.IsOpen) - _serialPort.Close(); - else - { - // Set the port's settings - _serialPort.PortName = cmbPortName.Text; - _serialPort.BaudRate = int.Parse(cmbBaudRate.Text); - _serialPort.DataBits = int.Parse(cmbDataBits.Text); - - if(myStopBits.ToStopBits(cmbStopBits.Text) != StopBits.None) - _serialPort.StopBits = myStopBits.ToStopBits(cmbStopBits.Text); - - _serialPort.Parity = myParity.ToParity(cmbParity.Text); - _serialPort.Handshake = myHandshake.ToHandshake(cmbHandshake.Text); - _serialPort.ReadTimeout = 100; - - _mySettings.baudRate = (uint)_serialPort.BaudRate; - _mySettings.parity = (uint)_serialPort.Parity; - _mySettings.databits = (uint)_serialPort.DataBits; - _mySettings.stopBits = (uint)_serialPort.StopBits; - - _mySettings.sPort = _serialPort.PortName; - - _mySettings.saveSettings(); - - try - { - Cursor.Current = Cursors.WaitCursor; - _serialPort.Open(); - } - catch (Exception x) - { - System.Diagnostics.Debug.WriteLine("Exception in OpenPort: " + x.Message); - } - finally - { - Cursor.Current = Cursors.Default; - } - } - this.Close(); - } - } -} \ No newline at end of file diff --git a/CommAppCFSerial/ConnectDlg.resx b/CommAppCFSerial/ConnectDlg.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/CommAppCFSerial/ConnectDlg.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/CommAppCFSerial/Form1.Designer.cs b/CommAppCFSerial/Form1.Designer.cs deleted file mode 100644 index 01ea2a0..0000000 --- a/CommAppCFSerial/Form1.Designer.cs +++ /dev/null @@ -1,171 +0,0 @@ -namespace CommAppCF -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.mnuConnect = new System.Windows.Forms.MenuItem(); - this.txtSend = new System.Windows.Forms.TextBox(); - this.label1 = new System.Windows.Forms.Label(); - this.btnSend = new System.Windows.Forms.Button(); - this.txtReceive = new System.Windows.Forms.TextBox(); - this.btnSendFile = new System.Windows.Forms.Button(); - this.btnSendLine = new System.Windows.Forms.Button(); - this.btnClear = new System.Windows.Forms.Button(); - this.chkUseHexEncoder = new System.Windows.Forms.CheckBox(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuExit); - this.mainMenu1.MenuItems.Add(this.mnuConnect); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // mnuConnect - // - this.mnuConnect.Text = "Connect"; - this.mnuConnect.Click += new System.EventHandler(this.mnuConnect_Click); - // - // txtSend - // - this.txtSend.AcceptsReturn = true; - this.txtSend.AcceptsTab = true; - this.txtSend.Location = new System.Drawing.Point(3, 31); - this.txtSend.Multiline = true; - this.txtSend.Name = "txtSend"; - this.txtSend.Size = new System.Drawing.Size(234, 91); - this.txtSend.TabIndex = 0; - // - // label1 - // - this.label1.Location = new System.Drawing.Point(3, 10); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(72, 18); - this.label1.Text = "SEND:"; - // - // btnSend - // - this.btnSend.Location = new System.Drawing.Point(175, 126); - this.btnSend.Name = "btnSend"; - this.btnSend.Size = new System.Drawing.Size(62, 23); - this.btnSend.TabIndex = 2; - this.btnSend.Text = "Send"; - this.btnSend.Click += new System.EventHandler(this.btnSend_Click); - // - // txtReceive - // - this.txtReceive.AcceptsReturn = true; - this.txtReceive.AcceptsTab = true; - this.txtReceive.Location = new System.Drawing.Point(3, 180); - this.txtReceive.Multiline = true; - this.txtReceive.Name = "txtReceive"; - this.txtReceive.ReadOnly = true; - this.txtReceive.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtReceive.Size = new System.Drawing.Size(234, 85); - this.txtReceive.TabIndex = 0; - // - // btnSendFile - // - this.btnSendFile.Location = new System.Drawing.Point(3, 126); - this.btnSendFile.Name = "btnSendFile"; - this.btnSendFile.Size = new System.Drawing.Size(72, 23); - this.btnSendFile.TabIndex = 2; - this.btnSendFile.Text = "Send File"; - this.btnSendFile.Click += new System.EventHandler(this.btnSendFile_Click); - // - // btnSendLine - // - this.btnSendLine.Location = new System.Drawing.Point(96, 126); - this.btnSendLine.Name = "btnSendLine"; - this.btnSendLine.Size = new System.Drawing.Size(73, 23); - this.btnSendLine.TabIndex = 2; - this.btnSendLine.Text = "Send Line"; - this.btnSendLine.Click += new System.EventHandler(this.btnSendLine_Click); - // - // btnClear - // - this.btnClear.Location = new System.Drawing.Point(175, 5); - this.btnClear.Name = "btnClear"; - this.btnClear.Size = new System.Drawing.Size(62, 23); - this.btnClear.TabIndex = 2; - this.btnClear.Text = "Clear"; - this.btnClear.Click += new System.EventHandler(this.btnClear_Click); - // - // chkUseHexEncoder - // - this.chkUseHexEncoder.Location = new System.Drawing.Point(3, 155); - this.chkUseHexEncoder.Name = "chkUseHexEncoder"; - this.chkUseHexEncoder.Size = new System.Drawing.Size(234, 19); - this.chkUseHexEncoder.TabIndex = 4; - this.chkUseHexEncoder.Text = "use \\xAB en/decoding"; - this.chkUseHexEncoder.CheckStateChanged += new System.EventHandler(this.chkUseHexEncoder_CheckStateChanged); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.chkUseHexEncoder); - this.Controls.Add(this.btnSendFile); - this.Controls.Add(this.btnSendLine); - this.Controls.Add(this.btnClear); - this.Controls.Add(this.btnSend); - this.Controls.Add(this.label1); - this.Controls.Add(this.txtReceive); - this.Controls.Add(this.txtSend); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "CommApp"; - this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuExit; - private System.Windows.Forms.MenuItem mnuConnect; - private System.Windows.Forms.TextBox txtSend; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Button btnSend; - private System.Windows.Forms.TextBox txtReceive; - private System.Windows.Forms.Button btnSendFile; - private System.Windows.Forms.Button btnSendLine; - private System.Windows.Forms.Button btnClear; - private System.Windows.Forms.CheckBox chkUseHexEncoder; - } -} - diff --git a/CommAppCFSerial/Form1.cs b/CommAppCFSerial/Form1.cs deleted file mode 100644 index 45b2f72..0000000 --- a/CommAppCFSerial/Form1.cs +++ /dev/null @@ -1,239 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.IO.Ports; - -namespace CommAppCF -{ - public partial class Form1 : Form - { - private SerialPort comport = new SerialPort(); - private bool bUseHexDecode = false; - - public Form1() - { - InitializeComponent(); - comport.DataReceived += new SerialDataReceivedEventHandler(comport_DataReceived); - comport.ErrorReceived += new SerialErrorReceivedEventHandler(comport_ErrorReceived); - - } - - void comport_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) - { - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += e.ToString(); })); - } - - void comport_DataReceived(object sender, SerialDataReceivedEventArgs e) - { - // This method will be called when there is data waiting in the port's buffer - - // Determain which mode (string or binary) the user is in - // Read all the data waiting in the buffer - try - { - string data = ""; - data = comport.ReadLine();//.ReadExisting(); - string s = ""; - // Display the text to the user in the terminal - if (bUseHexDecode) - s = Utility.HexEncoding.ToMixedString(data); - else - s = data; - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += s + "\r\n"; })); - } - catch (Exception ex) - { - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += ex.Message + "\r\n"; })); - //MessageBox.Show(ex.Message); - } - //label2.Invoke(new EventHandler(delegate{label2.Text = data;})); - - //Log(LogMsgType.Incoming, data); - } - - private void mnuConnect_Click(object sender, EventArgs e) - { - if (mnuConnect.Text == "Disconnect") - { - comport.ReadExisting(); - comport.Close(); - mnuConnect.Text = "Connect"; - return; - } - - ConnectDlg dlg = new ConnectDlg(ref comport); - dlg.ShowDialog(); - if (comport.IsOpen) - { - mnuConnect.Text = "Disconnect"; - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += comport.PortName + " opened\r\n"; })); - } - else - mnuConnect.Text = "Connect"; - } - - delegate void SetTextCallback(string text); - private void updateTxtRcv(string text) - { - if (this.txtReceive.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(updateTxtRcv); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtReceive.Text.Length > 2000) - txtReceive.Text = ""; - txtReceive.Text += text + "\r\n"; - txtReceive.SelectionLength = text.Length; - txtReceive.SelectionStart = txtReceive.Text.Length - text.Length; - txtReceive.ScrollToCaret(); - } - - } - private void Form1_Closing(object sender, CancelEventArgs e) - { - try - { - //comport.DiscardOutBuffer(); - //comport.DiscardInBuffer(); - //comport.Dispose(); - if (comport.IsOpen) - { - comport.ReadExisting(); - comport.Close(); - } - } - catch (Exception ex) - { - MessageBox.Show(ex.Message); - } - - } - - private void mnuExit_Click(object sender, EventArgs e) - { - this.Close(); - } - - private void btnSend_Click(object sender, EventArgs e) - { - try - { - if (txtSend.Text.Length > 0) - { - string s = txtSend.Text; - if (chkUseHexEncoder.Checked) - { - byte[] b = Utility.HexEncoding.FromHexedString(s); - comport.Write(b, 0, b.Length); - } - else - comport.Write(s); - } - } - catch (Exception) - { - - } - } - - private void btnSendLine_Click(object sender, EventArgs e) - { - try - { - if (txtSend.Text.Length > 0) - { - string s = txtSend.Text; - if (chkUseHexEncoder.Checked) - { - byte[] b = Utility.HexEncoding.FromHexedString(s); - comport.Write(b, 0, b.Length); - comport.WriteLine(""); - } - else - comport.WriteLine(s); - } - } - catch (Exception) - { - - } - - } - - private void btnSendFile_Click(object sender, EventArgs e) - { - try - { - if (comport.IsOpen) - { - OpenFileDialog ofd = new OpenFileDialog(); - ofd.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; - ofd.FilterIndex = 0; - if (ofd.ShowDialog()==DialogResult.OK){ - string filename = ofd.FileName; - if (System.IO.File.Exists(filename)) - { - Cursor.Current = Cursors.WaitCursor; - sendFile(filename); - Cursor.Current = Cursors.Default; - } - } - } - - } - catch (Exception x) - { - updateTxtRcv(x.Message); - } - } - private void sendFile(string filename) - { - try - { - updateTxtRcv("Starting sendFile(" + filename + ")"); - - System.IO.StreamReader sr = new System.IO.StreamReader(filename); - int r; - int blockSize = 4096; - char[] buf = new char[blockSize]; - //how many blocks to send? - System.IO.FileInfo fi = new System.IO.FileInfo(filename); - long lBlocks = (long)(fi.Length / blockSize); - if (lBlocks == 0) - lBlocks = 1; - updateTxtRcv("Need to send " + lBlocks.ToString() + " blocks..."); - long lBlockNr = 1; - do - { - updateTxtRcv("Sending block " + lBlockNr.ToString() + " ..."); - r = sr.Read(buf, 0, blockSize); //r = number of bytes read - comport.Write(buf, 0, r); - } - while (r!=-1 && !sr.EndOfStream); - sr.Close(); - updateTxtRcv("Finished sendFile(" + filename + ")"); - } - catch (Exception x) - { - updateTxtRcv("sendFile exception:" + x.Message); - System.Diagnostics.Debug.WriteLine(x.Message); - } - } - - private void btnClear_Click(object sender, EventArgs e) - { - txtSend.Text = ""; - } - - private void chkUseHexEncoder_CheckStateChanged(object sender, EventArgs e) - { - bUseHexDecode = chkUseHexEncoder.Checked; - } - } -} \ No newline at end of file diff --git a/CommAppCFSerial/Form1.resx b/CommAppCFSerial/Form1.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/CommAppCFSerial/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/CommAppCFSerial/HexEncoding.cs b/CommAppCFSerial/HexEncoding.cs deleted file mode 100644 index 41ff565..0000000 --- a/CommAppCFSerial/HexEncoding.cs +++ /dev/null @@ -1,206 +0,0 @@ -using System; -using System.Text; -using System.Globalization; - -namespace Utility -{ - /// - /// Summary description for HexEncoding. - /// - public static class HexEncoding - { - //public HexEncoding() - //{ - //} - /// - /// helper to get count of hex chars in a string - /// - /// - /// only hex chars are counted - public static int GetByteCount(string hexString) - { - int numHexChars = 0; - char c; - // remove all none A-F, 0-9, characters - for (int i=0; i - /// Creates a byte array from the hexadecimal string. Each two characters are combined - /// to create one byte. First two hexadecimal characters become first byte in returned array. - /// Non-hexadecimal characters are ignored. - /// - /// string to convert to byte array - /// number of characters in string ignored - /// byte array, in the same left-to-right order as the hexString - public static byte[] GetBytes(string hexString, out int discarded) - { - discarded = 0; - string newString = ""; - char c; - // remove all none A-F, 0-9, characters - for (int i=0; i - /// convert a byte array to a sequence of hex chars - /// - /// - /// - public static string ToString(byte[] bytes) - { - string hexString = ""; - for (int i=0; i - /// convert a mixed string with \xAB encoded hex chars back to a byte array - /// - /// - /// - public static byte[] FromHexedString(string val){ - //replace \xHH with char of before using getbytes - int iPos = val.IndexOf("\\x"); - while(iPos>=0){ - string s = val.Substring(iPos, 4); - byte b = byte.Parse(val.Substring(iPos+2,2), NumberStyles.HexNumber); - //string c = Convert.ToString(b,16); - char ch = (char)b; - //test - //byte[] bTest = Encoding.ASCII.GetBytes(ch.ToString()); - //System.Diagnostics.Debug.WriteLine(string.Format("Encoded {0:x} as '{1}'", bTest,ch)); - string o = val.Substring(0, iPos) + ch + val.Substring(iPos + 4); - val = o; - iPos = val.IndexOf("\\x"); - } - byte[] valAsByteArray = Encoding.ASCII.GetBytes(val); - return valAsByteArray; - } - /// - /// convert a string with chars to a string that uses \xAB encoding for non-printable chars - /// - /// - /// - public static string ToMixedString(string s) - { - byte[] bytes = Encoding.ASCII.GetBytes(s); - string sReturn = ToMixedString(bytes); - return sReturn; - } - /// - /// convert a byte array to a string that uses \xAB encoding for non-printable chars - /// - /// - /// - public static string ToMixedString(byte[] bytes) - { - string hexString = ""; - for (int i = 0; i < bytes.Length; i++) - { - if (bytes[i] >= 0x20) - { - //hexString += bytes[i].ToString(); - hexString += ASCIIEncoding.ASCII.GetString(bytes, i, 1); - } - else - { - hexString += "\\x"; // "<" - hexString += bytes[i].ToString("X2"); - //if (i <= bytes.Length - 1) hexString += "-"; - //hexString += ">"; - } - } - return hexString; - } - - /// - /// Determines if given string is in proper hexadecimal string format - /// - /// - /// - public static bool InHexFormat(string hexString) - { - bool hexFormat = true; - - foreach (char digit in hexString) - { - if (!IsHexDigit(digit)) - { - hexFormat = false; - break; - } - } - return hexFormat; - } - - /// - /// Returns true is c is a hexadecimal digit (A-F, a-f, 0-9) - /// - /// Character to test - /// true if hex digit, false if not - public static bool IsHexDigit(Char c) - { - int numChar; - int numA = Convert.ToInt32('A'); - int num1 = Convert.ToInt32('0'); - c = Char.ToUpper(c); - numChar = Convert.ToInt32(c); - if (numChar >= numA && numChar < (numA + 6)) - return true; - if (numChar >= num1 && numChar < (num1 + 10)) - return true; - return false; - } - /// - /// Converts 1 or 2 character string into equivalant byte value - /// - /// 1 or 2 character string - /// byte - private static byte HexToByte(string hex) - { - if (hex.Length > 2 || hex.Length <= 0) - throw new ArgumentException("hex must be 1 or 2 characters in length"); - byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber); - return newByte; - } - } -} diff --git a/CommAppCFSerial/Program.cs b/CommAppCFSerial/Program.cs deleted file mode 100644 index fe09bd9..0000000 --- a/CommAppCFSerial/Program.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; - -namespace CommAppCF -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/CommAppCFSerial/Properties/AssemblyInfo.cs b/CommAppCFSerial/Properties/AssemblyInfo.cs deleted file mode 100644 index 3f89d9c..0000000 --- a/CommAppCFSerial/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("CommAppCF")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("CommAppCF")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("7c366247-0f89-4894-9690-a8ee15533cb7")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - diff --git a/CommAppCFSerial/Properties/Resources.Designer.cs b/CommAppCFSerial/Properties/Resources.Designer.cs deleted file mode 100644 index f87532b..0000000 --- a/CommAppCFSerial/Properties/Resources.Designer.cs +++ /dev/null @@ -1,60 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.4952 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace CommAppCF.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CommAppCF.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/CommAppCFSerial/Properties/Resources.resx b/CommAppCFSerial/Properties/Resources.resx deleted file mode 100644 index 451318b..0000000 --- a/CommAppCFSerial/Properties/Resources.resx +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 diff --git a/CommAppCFSerial/bin/CommAppCF.exe b/CommAppCFSerial/bin/CommAppCF.exe deleted file mode 100644 index dbe257e..0000000 Binary files a/CommAppCFSerial/bin/CommAppCF.exe and /dev/null differ diff --git a/CommAppCFSerial/escp_test.txt b/CommAppCFSerial/escp_test.txt deleted file mode 100644 index 4570d88..0000000 --- a/CommAppCFSerial/escp_test.txt +++ /dev/null @@ -1,33 +0,0 @@ -w1G -w! -ROUTE# 227 11/08/01 08:35 - - Food City #3212 - 1500 E Lincoln Way - Hamilton OH - TAX ID# A32102 - - ITEM# DESCRIPTION NET - QTY PRICE DEPOS ALLOW - - SALES - - 1001 Reg Cola 6pk 12cn 63.50 - 5 11.50 1.20 0.00 - - 1002 Diet Cola 6pk 12cn 38.10 - 3 11.50 1.20 0.00 - - CREDITS SALES -PRODUCT 0.00 101.60 -SUBTOTAL 101.60 -5% State Tax 5.08 - ------------- -BALANCE DUE: CHARGE 106.68 - ============= - - Thank You For Your Business - - - - diff --git a/CommAppCFSerial/fp_test.txt b/CommAppCFSerial/fp_test.txt deleted file mode 100644 index 74a6a98..0000000 --- a/CommAppCFSerial/fp_test.txt +++ /dev/null @@ -1,12 +0,0 @@ -NEW -1 BARFONT ON -2 BARFONT "Swiss 721 BT", 6 -10 PRPOS 10,10 -20 PRBOX 430,340,15 -50 PRPOS 75,27060 BARTYPE "CODE39"70 PRBAR "ABC"80 PRPOS 25,220 -90 FONT "Swiss 721 BT", 6 -100 PRTXT "My FIRST label" -200 PRINTFEED -300 END -RUN - diff --git a/CommAppCFSerial/serialSet.cs b/CommAppCFSerial/serialSet.cs deleted file mode 100644 index 08d5f4b..0000000 --- a/CommAppCFSerial/serialSet.cs +++ /dev/null @@ -1,512 +0,0 @@ -using System; -using System.IO.Ports; -using System.Collections.Generic; -using System.Text; -using Microsoft.Win32; -using System.Diagnostics; - -namespace CommAppCF -{ - class serialSet : IDisposable - { - // Track whether Dispose has been called. - private bool disposed = false; - - private const string _regSubKey = @"Software\CommAppCF"; - private RegistryKey _regKey; - - private RegistryValueKind[] _regValueTypes = - { RegistryValueKind.String, - RegistryValueKind.DWord , - RegistryValueKind.DWord , - RegistryValueKind.DWord , - RegistryValueKind.DWord , - RegistryValueKind.DWord - }; - private string[] _regValueNames = - { "port", - "baudrate" , - "parity", - "databits", - "stopbits", - "handshake" - }; - - private const string _regValueNameTimeInterval = "TimeInterval"; - private const string _regValueLog2File = "Log2File"; - - public serialSet() - { - //try to read settings from Reg - if (regOpenKey()) - { - regReadSettings(); - } - else - this.Dispose(); - - } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - private void Dispose(bool disposing) - { - // Check to see if Dispose has already been called. - if (!this.disposed) - { - // If disposing equals true, dispose all managed - // and unmanaged resources. - if (disposing) - { - // Dispose managed resources. - //save settings? - regWriteSettings(); - regCloseKey(); - //component.Dispose(); - } - - // Call the appropriate methods to clean up - // unmanaged resources here. - // If disposing is false, - // only the following code is executed. - //CloseHandle(handle); - //handle = IntPtr.Zero; - - // Note disposing has been done. - disposed = true; - - } - } - - private bool regReadSettings() - { - if (_regKey == null) - return false; - - string s = ""; - uint d = 0; - //try to read settings - for (int x = 0; x < _regValueNames.Length; x++) - { - if (_regValueTypes[x] == RegistryValueKind.String) - { - s = regReadString(_regValueNames[x]); - } - else if (_regValueTypes[x] == RegistryValueKind.DWord) - { - d = regReadUInt(_regValueNames[x]); - } - switch (x) - { - case 0: if(s.Length>0) - _sPort = s; - break; - case 1: if(d>0) - _baudRate = d; - break; - case 2: if (d >= 0) - _parity = d; - break; - case 3: if (d > 0) - _databits = d; - break; - case 4: if (d > 0) - _stopBits = d; - break; - case 5: if (d >= 0) - _handshake = d; - break; - } - } - - return true; - } - public int saveSettings() - { - if (this.regWriteSettings()) - return 0; - else - return -1; - } - private bool regWriteSettings() - { - regWriteString(_regValueNames[0], _sPort); - regWriteInt(_regValueNames[1], _baudRate); - regWriteInt(_regValueNames[2], _parity); - regWriteInt(_regValueNames[3], _databits); - regWriteInt(_regValueNames[4], _stopBits); - regWriteInt(_regValueNames[5], _handshake); - - return true; - } - #region REGISTRY - private int regReadInt(string sValuename) - { - if (_regKey == null) - return -1; - try - { - int i = (int)_regKey.GetValue(sValuename, -1); - return i; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return -1; - } - private uint regReadUInt(string sValuename) - { - if (_regKey == null) - return 0; - try - { - int i = (int)_regKey.GetValue(sValuename, 0); - return (uint)i; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadUInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return 0; - } - private bool regWriteInt(string sValuename, uint i) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, i, RegistryValueKind.DWord); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteUInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return false; - } - private bool regWriteInt(string sValuename, int i) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, i, RegistryValueKind.DWord); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return false; - } - - private string regReadString(string sValuename) - { - if (_regKey == null) - return null; - try - { - string s = (string)_regKey.GetValue(sValuename, ""); - return s; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadStrings for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return null; - } - - private string[] regReadStrings(string sValuename) - { - if (_regKey == null) - return null; - try - { - string[] s = (string[])_regKey.GetValue(sValuename, ""); - return s; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadStrings for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return null; - } - private bool regWriteString(string sValuename, string s) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, s); - _regKey.Flush(); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteStrings for '" + _regSubKey + "'. " + x.Message); - return false; - } - } - - private bool regWriteStrings(string sValuename, string[] s) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, s); - _regKey.Flush(); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteStrings for '" + _regSubKey + "'. " + x.Message); - return false; - } - } - private bool regOpenKey() - { - try - { - _regKey = Registry.LocalMachine.CreateSubKey(_regSubKey); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in OpenSubKey/CreateSubKey for '" + _regSubKey + "'. " + x.Message); - } - return false; - } - private void regCloseKey() - { - if (_regKey != null) - { - try - { - Registry.LocalMachine.Close(); - } - catch (Exception x) - { - Debug.WriteLine("Exception in CloseKey for '" + _regSubKey + "'. " + x.Message); - } - } - } -#endregion - #region FIELDS - private string _sPort="COM0"; - public string sPort - { - get { return _sPort; } - set { _sPort = value; } - } - private uint[] _baudRates = { 1200, 2400, 4800, 9600, 19200, 38200, 57600, 115200, 230400, 460800, 921600 }; - public uint[] baudRates - { - get { return _baudRates; } - } - private uint _baudRate = 1200; - public uint baudRate - { - get { return _baudRate; } - set { _baudRate = value; } - } - private uint _parity = 0; - public uint parity - { - get { return _parity; } - set { _parity = value; } - } - private uint _databits = 8; - public uint databits - { - get { return _databits; } - set { _databits = value; } - } - private uint _stopBits = 1; - public uint stopBits - { - get { return _stopBits; } - set { _stopBits = value; } - } - private uint _handshake = 0; - public uint handshake - { - get { return _handshake; } - set { _handshake = value; } - } - #endregion - - } - public static class myParity - { - public static string[] parity = { "None", "Odd", "Even", "Mark", "Space" }; - public static int ToInt(string s) - { - for (int i = 0; i < parity.Length; i++) - { - if(s.Equals(parity[i],StringComparison.OrdinalIgnoreCase)) - return i; - } - return 0; - } - public static string ToString(int i) - { - return parity[i]; - } - public static Parity ToParity(int i) - { - switch (i) - { - case 0: - return Parity.None; - case 1: - return Parity.Odd; - case 2: - return Parity.Even; - case 3: - return Parity.Mark; - case 4: - return Parity.Space; - } - return Parity.None; - } - public static Parity ToParity(string text) - { - if (text.Equals("None", StringComparison.OrdinalIgnoreCase)) - return Parity.None; - if (text.Equals("Odd", StringComparison.OrdinalIgnoreCase)) - return Parity.Odd; - if (text.Equals("Even", StringComparison.OrdinalIgnoreCase)) - return Parity.Even; - if (text.Equals("Mark", StringComparison.OrdinalIgnoreCase)) - return Parity.Mark; - if (text.Equals("Space", StringComparison.OrdinalIgnoreCase)) - return Parity.Space; - - return Parity.None; - } - }//class myParity - public static class myStopBits - { - public static StopBits ToStopBits(string text) - { - if (text.Equals("None", StringComparison.OrdinalIgnoreCase)) - return StopBits.None; - if (text.Equals("One", StringComparison.OrdinalIgnoreCase)) - return StopBits.One; - if (text.Equals("Two", StringComparison.OrdinalIgnoreCase)) - return StopBits.Two; - if (text.Equals("OnePointFive", StringComparison.OrdinalIgnoreCase)) - return StopBits.OnePointFive; - - return StopBits.One; - } - public static StopBits ToStopBits(int i) - { - switch (i) - { - case 0: return StopBits.None; - case 1: return StopBits.One; - case 2: return StopBits.Two; - case 3: return StopBits.OnePointFive; - } - return StopBits.One; - } - public static string ToString(StopBits sb) - { - switch (sb) - { - case StopBits.None: return "None"; - case StopBits.One: return "One"; - case StopBits.Two: return "Two"; - case StopBits.OnePointFive: return "OnePointFive"; - } - return "One"; - } - public static string ToString(int i) - { - switch (i) - { - case 0: return "None"; - case 1: return "One"; - case 2: return "Two"; - case 3: return "OnePointFive"; - } - return "One"; - } - public static int ToInt(StopBits sb) - { - switch (sb) - { - case StopBits.None: return 0; - case StopBits.One: return 1; - case StopBits.Two: return 2; - case StopBits.OnePointFive: return 3; - } - return 1; - } - }//class myStopbits - public static class myHandshake - { - public static string[] handshakes = { "None", "XOnXOff", "RequestToSend", "RequestToSendXOnXOff" }; - public static Handshake ToHandshake(int i) - { - switch (i) - { - case 0: return Handshake.None; - case 1: return Handshake.XOnXOff; - case 2: return Handshake.RequestToSend; - case 3: return Handshake.RequestToSendXOnXOff; - } - return Handshake.None; - } - public static Handshake ToHandshake(string text) - { - if (text.Equals("None", StringComparison.OrdinalIgnoreCase)) - return Handshake.None; - if (text.Equals("XOnXOff", StringComparison.OrdinalIgnoreCase)) - return Handshake.XOnXOff; - if (text.Equals("RequestToSend", StringComparison.OrdinalIgnoreCase)) - return Handshake.RequestToSend; - if (text.Equals("RequestToSendXOnXOff", StringComparison.OrdinalIgnoreCase)) - return Handshake.RequestToSendXOnXOff; - return Handshake.None; - } - public static int ToInt(Handshake hs) - { - switch (hs) - { - case Handshake.None: return 0; - case Handshake.XOnXOff: return 1; - case Handshake.RequestToSend: return 2; - case Handshake.RequestToSendXOnXOff: return 3; - } - return 0; - } - public static string ToString(Handshake hs) - { - switch (hs) - { - case Handshake.None: return "None"; - case Handshake.XOnXOff: return "XOnXOff"; - case Handshake.RequestToSend: return "RequestToSend"; - case Handshake.RequestToSendXOnXOff: return "RequestToSendXOnXOff"; - } - return "None"; - } - public static string ToString(int i) - { - switch (i) - { - case 0: return "None"; - case 1: return "XOnXOff"; - case 2: return "RequestToSend"; - case 3: return "RequestToSendXOnXOff"; - } - return "None"; - } - }//class myHandshake -} diff --git a/CommAppCFbtSearch/BluetoothCode/BluetoothAddress.cs b/CommAppCFbtSearch/BluetoothCode/BluetoothAddress.cs deleted file mode 100644 index db3a9f9..0000000 --- a/CommAppCFbtSearch/BluetoothCode/BluetoothAddress.cs +++ /dev/null @@ -1,61 +0,0 @@ -#region Using - -using System; - -#endregion - -namespace OpenNETCF.Net.Bluetooth { - /// - /// BluetoothAddress - /// - public sealed class BluetoothAddress : IComparable { - - private byte[] data; - public const int Giac = 0x9e8b33; - internal const int IacFirst = 0x9e8b00; - internal const int IacLast = 0x9e8b3f; - public const int Liac = 0x9e8b00; - public static readonly BluetoothAddress None = new BluetoothAddress(); - - static BluetoothAddress() { - None = new BluetoothAddress(); - } - - internal BluetoothAddress() { - this.data = new byte[8]; - } - - public BluetoothAddress(byte[] address) : this() { - if (address.Length != 6) { - throw new ArgumentException("address"); - } - Buffer.BlockCopy(address, 0, this.data, 0, 6); - } - public BluetoothAddress(long address) : this() { - BitConverter.GetBytes(address).CopyTo(this.data, 0); - } - - #region IComparable - - int IComparable.CompareTo(object obj) { - BluetoothAddress address = obj as BluetoothAddress; - if (address != null) { - return this.ToInt64().CompareTo(address.ToInt64()); - } - return -1; - - } - #endregion - - public long ToInt64() { - return BitConverter.ToInt64(this.data, 0); - } - - public byte[] ToByteArray() { - return this.data; - } - - - - } -} diff --git a/CommAppCFbtSearch/BluetoothCode/BluetoothClient.cs b/CommAppCFbtSearch/BluetoothCode/BluetoothClient.cs deleted file mode 100644 index 8de7b45..0000000 --- a/CommAppCFbtSearch/BluetoothCode/BluetoothClient.cs +++ /dev/null @@ -1,309 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.BluetoothClient -// Copyright (C) 2003-2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Collections; -using System.Data; -using System.Runtime.InteropServices; -using System.Windows.Forms; -using System.Net.Sockets; -using System.Net; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Contains functionality to control the state of the Bluetooth hardware on a Smart Device. - /// - /// This class currently only supports devices which use the Microsoft Bluetooth stack such as the Orange SPV E200, devices which use the WidComm stack will not work. - public class BluetoothClient { - /*add by qiuq*/ - private bool authenticate; - private bool encrypt; - private short queryLength; - private Socket socket; - - /// - /// Creates a new instance of BluetoothClient. - /// - public BluetoothClient() { - //want to initialise winsock 2.2 - short ver = 0x0202; - - byte[] data = new byte[512]; - int result = WSAStartup(ver, data); - - //MessageBox.Show(System.Text.Encoding.ASCII.GetString(data, 4, 257)); - - if (result != 0) { - throw new Exception(result.ToString()); - } - /*add by qiuq*/ - try { - this.socket = new BluetoothSocket(); - } - catch (SocketException) { - throw new PlatformNotSupportedException("Bluetooth.NET is not supported on this device."); - } - - } - /// - /// Creates a new instance of BluetoothClient.(add by qiuq) - /// - /// - internal BluetoothClient(Socket s) { - this.authenticate = false; - this.encrypt = false; - this.queryLength = 0x10; - this.socket = s; - } - - public void CloseSocket() { - if ((this.socket != null) && this.socket.Connected) { - this.socket.Close(); - } - } - - public void Connect(BluetoothEndPoint ep) { - this.CloseSocket(); - if (this.socket == null) { - this.socket = new BluetoothSocket(); - } - this.socket.Connect(ep); - } - - public NetworkStream GetStream() { - if (this.socket == null) { - throw new ObjectDisposedException("Client", "The BluetoothClient has been closed."); - } - return new NetworkStream(this.socket); - } - - - - /// - /// Gets or Sets the current mode of operation of the Bluetooth radio. - /// - /// This setting will be persisted when the device is reset. - /// An Icon will be displayed in the tray on the Home screen and the device will emit a blue LED when Bluetooth is enabled. - public static RadioMode RadioMode { - get { - RadioMode mode = 0; - //get the mode - int result = BthGetMode(ref mode); - - //if successful return retrieved value - if (result != 0) { - throw new ExternalException("Error getting Bluetooth mode"); - - } - - //return setting - return mode; - } - set { - //set the status - int result = BthSetMode(value); - - //check for error - if (result != 0) { - throw new ExternalException("Error setting Bluetooth mode"); - } - } - } - - /// - /// Discovers accessible Bluetooth devices and returns their names and addresses. - /// - /// An array of BluetoothDeviceInfo objects describing the devices discovered. - public BluetoothDeviceInfo[] DiscoverDevices() { - ArrayList al = new ArrayList(); - try { - int handle = 0; - byte[] queryset = new byte[1024]; - BitConverter.GetBytes((int)60).CopyTo(queryset, 0); - BitConverter.GetBytes((int)16).CopyTo(queryset, 20); - - int bufferlen = 1024; - - int lookupresult = 0; - - //start looking for Bluetooth devices - lookupresult = BthNsLookupServiceBegin(queryset, LookupFlags.Containers, ref handle); - - while (lookupresult != -1) { - - lookupresult = BthNsLookupServiceNext(handle, LookupFlags.ReturnAddr | LookupFlags.ReturnName, ref bufferlen, queryset); - if (lookupresult != -1) { - //pointer to outputbuffer - int bufferptr = BitConverter.ToInt32(queryset, 48); - //remote socket address - int sockaddrptr = Marshal.ReadInt32((IntPtr)bufferptr, 8); - //remote socket len - int sockaddrlen = Marshal.ReadInt32((IntPtr)bufferptr, 12); - - BluetoothSocketAddress btsa = new BluetoothSocketAddress(); - - Marshal.Copy((IntPtr)sockaddrptr, btsa.ToByteArray(), 0, BluetoothSocketAddress.Length); - - //new deviceinfo - BluetoothDeviceInfo newdevice = new BluetoothDeviceInfo(btsa.Address, Marshal.PtrToStringUni((IntPtr)BitConverter.ToInt32(queryset, 4))); - - //add to discovered list - al.Add(newdevice); - - } - } - - //stop looking - lookupresult = BthNsLookupServiceEnd(handle); - - //return results - - } - catch (Exception ex) { - System.Diagnostics.Debug.WriteLine("Exception in DiscoverDevices(): " + ex.Message); - } - return (BluetoothDeviceInfo[])al.ToArray(typeof(BluetoothDeviceInfo)); - } - - public void Close() { - int result = WSACleanup(); - - if (result != 0) { - throw new Exception(result.ToString()); - } - } - - public static int ConnectSerial(int portindex, PortEmuParams pep) { - return RegisterDevice("COM", portindex, "btd.dll", pep.ToByteArray()); - } - - [DllImport("coredll.dll", SetLastError = true)] - private static extern int RegisterDevice( - string lpszType, - int dwIndex, - string lpszLib, - byte[] dwInfo); - - [DllImport("coredll.dll")] - private static extern bool DeregisterDevice( - int handle); - - [DllImport("BthUtil.dll")] - private static extern int BthSetMode( - RadioMode dwMode); - - [DllImport("BthUtil.dll")] - private static extern int BthGetMode( - ref RadioMode dwMode); - - - [DllImport("ws2.dll")] - private static extern int WSAStartup( - short versionrequested, - byte[] wsadata); - [DllImport("ws2.dll")] - private static extern int WSACleanup(); - - - [DllImport("Btdrt.dll")] - private static extern int BthNsLookupServiceBegin( - byte[] pQuerySet, - LookupFlags dwFlags, - ref int lphLookup); - - [DllImport("Btdrt.dll")] - private static extern int BthNsLookupServiceNext( - int hLookup, - LookupFlags dwFlags, - ref int lpdwBufferLength, - byte[] pResults); - - [DllImport("Btdrt.dll")] - private static extern int BthNsLookupServiceEnd( - int hLookup); - - #region Hardware Status - /// - /// Returns the current status of the Bluetooth radio hardware. - /// - /// A member of the enumeration. - public static HardwareStatus HardwareStatus { - get { - HardwareStatus status = 0; - int result = BthGetHardwareStatus(ref status); - - if (result != 0) { - throw new ExternalException("Error retrieving Bluetooth hardware status"); - } - return status; - } - } - [DllImport("Btdrt.dll")] - private static extern int BthGetHardwareStatus(ref HardwareStatus pistatus); - - #endregion - - #region LocalAddress - /// - /// Returns the address of the local Bluetooth device. - /// - public static BluetoothSocketAddress LocalAddress { - get { - BluetoothSocketAddress bsa = new BluetoothSocketAddress(); - - int result = BthReadLocalAddr(bsa.ToByteArray()); - - if (result != 0) { - throw new ExternalException("Error retrieving local Bluetooth address"); - } - - return bsa; - } - } - [DllImport("Btdrt.dll")] - private static extern int BthReadLocalAddr(byte[] pba); - - #endregion - - [DllImport("Btdrt.dll")] - private static extern int BthReadLocalVersion( - ref ushort phci_version, - ref ushort phci_revision, - ref ushort plmp_version, - ref ushort plmp_subversion, - ref ushort pmanufacturer, - ref ushort plmp_features); - - } - - - - public enum LookupFlags : uint { - Containers = 0x0002, - ReturnName = 0x0010, - ReturnAddr = 0x0100, - ReturnBlob = 0x0200, - } - - -} diff --git a/CommAppCFbtSearch/BluetoothCode/BluetoothDeviceInfo.cs b/CommAppCFbtSearch/BluetoothCode/BluetoothDeviceInfo.cs deleted file mode 100644 index 7f643ca..0000000 --- a/CommAppCFbtSearch/BluetoothCode/BluetoothDeviceInfo.cs +++ /dev/null @@ -1,58 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.BluetoothDeviceInfo -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== - -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Summary description for BluetoothDeviceInfo. - /// - public class BluetoothDeviceInfo { - private byte[] m_id; - private string m_name; - - internal BluetoothDeviceInfo(byte[] id, string name) { - m_id = id; - m_name = name; - } - - /// - /// Gets the device identifier. - /// - public byte[] DeviceID { - get { - return m_id; - } - } - - /// - /// Gets a name of a device. - /// - public string DeviceName { - get { - return m_name; - } - } - } -} diff --git a/CommAppCFbtSearch/BluetoothCode/BluetoothEndPoint.cs b/CommAppCFbtSearch/BluetoothCode/BluetoothEndPoint.cs deleted file mode 100644 index 096793b..0000000 --- a/CommAppCFbtSearch/BluetoothCode/BluetoothEndPoint.cs +++ /dev/null @@ -1,138 +0,0 @@ -#region Using - -using System; -using System.Net; -using System.Net.Sockets; - -#endregion - -namespace OpenNETCF.Net.Bluetooth { - /// - /// BluetoothEndPoint - /// - public class BluetoothEndPoint : EndPoint{ - private static int m_addressoffset; - private static int m_defaultport; - private BluetoothAddress m_id; - private int m_port; - private static int m_portoffset; - private static int m_salength; - private Guid m_service; - private static int m_serviceoffset; - public const int MaxPort = 0xffff; - public const int MinPort = 1; - - public BluetoothAddress Address { - get { - return this.m_id; - } - set { - this.m_id = value; - } - } - - public override AddressFamily AddressFamily { - get { - return (AddressFamily)0x20; - } - } - - public int Port { - get { - return this.m_port; - } - set { - this.m_port = value; - } - } - - public Guid Service { - get { - return this.m_service; - } - set { - this.m_service = value; - } - } - - - static BluetoothEndPoint() { - m_addressoffset = 8; - m_serviceoffset = 0x10; - m_portoffset = 0x20; - m_salength = 40; - } - - - public BluetoothEndPoint(BluetoothAddress address, Guid service) - : this(address, service, m_defaultport) { - } - - public BluetoothEndPoint(BluetoothAddress address, Guid service, int port) { - this.m_id = address; - this.m_service = service; - this.m_port = port; - } - - public override EndPoint Create(SocketAddress socketAddress) { - int index; - if (socketAddress == null) { - throw new ArgumentNullException("socketAddress"); - } - if (socketAddress[0] != 0x20) { - return base.Create(socketAddress); - } - byte[] address = new byte[6]; - for (index = 0; index < 6; index++) { - address[index] = socketAddress[m_addressoffset + index]; - } - byte[] b = new byte[0x10]; - for (index = 0; index < 0x10; index++) { - b[index] = socketAddress[m_serviceoffset + index]; - } - byte[] buffer3 = new byte[4]; - for (index = 0; index < 4; index++) { - buffer3[index] = socketAddress[m_portoffset + index]; - } - return new BluetoothEndPoint(new BluetoothAddress(address), new Guid(b), BitConverter.ToInt32(buffer3, 0)); - } - - public override bool Equals(object obj) { - BluetoothEndPoint point = obj as BluetoothEndPoint; - if (point == null) { - return base.Equals(obj); - } - if (this.Address.Equals(point.Address)) { - return this.Service.Equals(point.Service); - } - return false; - } - - public override int GetHashCode() { - return this.Address.GetHashCode(); - } - - public override SocketAddress Serialize() { - SocketAddress address = new SocketAddress((AddressFamily)0x20, m_salength); - address[0] = 0x20; - if (this.m_id != null) { - byte[] buffer = this.m_id.ToByteArray(); - for (int i = 0; i < 6; i++) { - address[i + m_addressoffset] = buffer[i]; - } - } - if (this.m_service != Guid.Empty) { - byte[] buffer2 = this.m_service.ToByteArray(); - for (int j = 0; j < 0x10; j++) { - address[j + m_serviceoffset] = buffer2[j]; - } - } - byte[] bytes = BitConverter.GetBytes(this.m_port); - for (int k = 0; k < 4; k++) { - address[k + m_portoffset] = bytes[k]; - } - return address; - } - - } -} diff --git a/CommAppCFbtSearch/BluetoothCode/BluetoothService.cs b/CommAppCFbtSearch/BluetoothCode/BluetoothService.cs deleted file mode 100644 index a85c490..0000000 --- a/CommAppCFbtSearch/BluetoothCode/BluetoothService.cs +++ /dev/null @@ -1,97 +0,0 @@ -#region Using - -using System; - -#endregion - -namespace OpenNETCF.Net.Bluetooth { - /// - /// BluetoothService - /// - public class BluetoothService { - public BluetoothService() { - // - // TODO: - // - } - - public static readonly Guid AdvancedAudioDistribution = new Guid(0x110d, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AudioSink = new Guid(0x110b, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AudioSource = new Guid(0x110a, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AudioVideo = new Guid(0x112c, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AVRemoteControl = new Guid(0x110e, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid AVRemoteControlTarget = new Guid(0x110c, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid BasicPrinting = new Guid(0x1122, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid BluetoothBase = new Guid(0, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid BrowseGroupDescriptor = new Guid(0x1001, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid CommonIsdnAccess = new Guid(0x1128, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid CordlessTelephony = new Guid(0x1109, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid DialupNetworking = new Guid(0x1103, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid DirectPrinting = new Guid(0x1118, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid DirectPrintingReferenceObjects = new Guid(0x1120, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Empty = Guid.Empty; - public static readonly Guid Fax = new Guid(0x1111, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid FtpProtocol = new Guid(10, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GenericAudio = new Guid(0x1203, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GenericFileTransfer = new Guid(0x1202, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GenericNetworking = new Guid(0x1201, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GenericTelephony = new Guid(0x1204, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid GN = new Guid(0x1117, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Handsfree = new Guid(0x111e, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HandsfreeAudioGateway = new Guid(0x111f, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HardcopyCableReplacement = new Guid(0x1125, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HardcopyCableReplacementPrint = new Guid(0x1126, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HardcopyCableReplacementScan = new Guid(0x1127, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Headset = new Guid(0x1108, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HeadsetAudioGateway = new Guid(0x1112, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HttpProtocol = new Guid(12, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid HumanInterfaceDevice = new Guid(0x1124, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Imaging = new Guid(0x111a, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ImagingAutomaticArchive = new Guid(0x111c, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ImagingReferenceObjects = new Guid(0x111d, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ImagingResponder = new Guid(0x111b, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Intercom = new Guid(0x1110, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid IPProtocol = new Guid(9, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid IrMCSync = new Guid(0x1104, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid IrMCSyncCommand = new Guid(0x1107, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid L2CapProtocol = new Guid(0x100, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid LanAccessUsingPpp = new Guid(0x1102, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Nap = new Guid(0x1116, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ObexFileTransfer = new Guid(0x1106, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ObexObjectPush = new Guid(0x1105, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ObexProtocol = new Guid(8, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Panu = new Guid(0x1115, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PhonebookAccessPce = new Guid(0x112e, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PhonebookAccessPse = new Guid(0x112f, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PnPInformation = new Guid(0x1200, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PrintingStatus = new Guid(0x1123, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid PublicBrowseGroup = new Guid(0x1002, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ReferencePrinting = new Guid(0x1119, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ReflectedUI = new Guid(0x1121, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid RFCommProtocol = new Guid(3, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid SdpProtocol = new Guid(1, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid SerialPort = new Guid(0x1101, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid ServiceDiscoveryServer = new Guid(0x1000, 0, 0x1000, 0x80, 8, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid SimAccess = new Guid(0x112d, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid TcpProtocol = new Guid(4, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid TcsAtProtocol = new Guid(6, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid TcsBinProtocol = new Guid(5, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UdiMT = new Guid(0x112a, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UdiTA = new Guid(0x112b, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UdpProtocol = new Guid(2, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnp = new Guid(0x1205, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnpIP = new Guid(0x1206, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnpIPL2Cap = new Guid(0x1302, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnpIPLap = new Guid(0x1301, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid UPnpIPPan = new Guid(0x1300, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoConferencing = new Guid(0x110f, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoConferencingGW = new Guid(0x1129, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoDistribution = new Guid(0x1305, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoSink = new Guid(0x1304, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid VideoSource = new Guid(0x1303, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid Wap = new Guid(0x1113, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid WapClient = new Guid(0x1114, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - public static readonly Guid WspProtocol = new Guid(14, 0, 0x1000, 0x80, 0, 0, 0x80, 0x5f, 0x9b, 0x34, 0xfb); - - } -} diff --git a/CommAppCFbtSearch/BluetoothCode/BluetoothSocket.cs b/CommAppCFbtSearch/BluetoothCode/BluetoothSocket.cs deleted file mode 100644 index 4eb674c..0000000 --- a/CommAppCFbtSearch/BluetoothCode/BluetoothSocket.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region Using - -using System; -using System.Net.Sockets; - -#endregion - -namespace OpenNETCF.Net.Bluetooth { - /// - /// BluetoothSocket - /// - public class BluetoothSocket : Socket{ - public BluetoothSocket() : base((AddressFamily)0x20, SocketType.Stream, ProtocolType.Ggp) { - } - } -} - - diff --git a/CommAppCFbtSearch/BluetoothCode/BluetoothSocketAddress.cs b/CommAppCFbtSearch/BluetoothCode/BluetoothSocketAddress.cs deleted file mode 100644 index 50848a7..0000000 --- a/CommAppCFbtSearch/BluetoothCode/BluetoothSocketAddress.cs +++ /dev/null @@ -1,83 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.BluetoothSocketAddress -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== - -using System; -using System.Net; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Summary description for BluetoothSocketAddress. - /// - public class BluetoothSocketAddress { - //USHORT addressFamily; //2 - //bt_addr btAddr; //6 - //GUID serviceClassId; //16 - //ULONG port; //4 - - private byte[] m_data; - public const int Length = 40; - private const ushort AF_BTH = 32; - - public BluetoothSocketAddress() { - m_data = new byte[Length]; - BitConverter.GetBytes(AF_BTH).CopyTo(m_data, 0); - } - - public BluetoothSocketAddress(byte[] data) { - if (data.Length == Length) { - m_data = data; - } - else { - throw new ArgumentOutOfRangeException("Data length not expected"); - } - } - - public byte[] ToByteArray() { - return m_data; - } - - public override string ToString() { - string result = ""; - - result += m_data[13].ToString("X") + ":"; - result += m_data[12].ToString("X") + ":"; - result += m_data[11].ToString("X") + ":"; - result += m_data[10].ToString("X") + ":"; - result += m_data[9].ToString("X") + ":"; - result += m_data[8].ToString("X"); - - return result; - } - - - public byte[] Address { - get { - byte[] addr = new byte[6]; - Buffer.BlockCopy(m_data, 8, addr, 0, 6); - return addr; - //return BitConverter.ToInt64(m_data, 0); - } - } - } -} diff --git a/CommAppCFbtSearch/BluetoothCode/ClassOfDevice.cs b/CommAppCFbtSearch/BluetoothCode/ClassOfDevice.cs deleted file mode 100644 index ae513f0..0000000 --- a/CommAppCFbtSearch/BluetoothCode/ClassOfDevice.cs +++ /dev/null @@ -1,76 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.ClassOfDevice -// Copyright (C) 2003-2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Collections; -using System.Data; -using System.Runtime.InteropServices; -using System.Windows.Forms; - -namespace OpenNETCF.Net.Bluetooth { - [Flags()] - public enum ClassOfDevice : int { - MAJOR_SERVICE_CLASS_INFORMATION = 0x800000, - MAJOR_SERVICE_CLASS_TELEPHONY = 0x400000, - MAJOR_SERVICE_CLASS_AUDIO = 0x200000, - MAJOR_SERVICE_CLASS_OBEX = 0x100000, - MAJOR_SERVICE_CLASS_CAPTURE = 0x080000, - MAJOR_SERVICE_CLASS_RENDERING = 0x040000, - MAJOR_SERVICE_CLASS_NETWORK = 0x020000, - MAJOR_SERVICE_CLASS_LIMITED_DISC = 0x002000, - - BTH_COD_MAJOR_DEVICE_CLASS_MISC = 0x000000, - BTH_COD_MAJOR_DEVICE_CLASS_COMPUTER = 0x000100, - BTH_COD_MAJOR_DEVICE_CLASS_PHONE = 0x000200, - BTH_COD_MAJOR_DEVICE_CLASS_LAP = 0x000300, - BTH_COD_MAJOR_DEVICE_CLASS_AUDIO = 0x000400, - BTH_COD_MAJOR_DEVICE_CLASS_PERIPHERAL = 0x000500, - BTH_COD_MAJOR_DEVICE_CLASS_UNCLASSIFIED = 0x001f00, - - BTH_COD_MINOR_COMPUTER_UNCLASSIFIED = 0x000000, - BTH_COD_MINOR_COMPUTER_DESKTOP = 0x000004, - BTH_COD_MINOR_COMPUTER_SERVER = 0x000008, - BTH_COD_MINOR_COMPUTER_LAPTOP = 0x00000c, - BTH_COD_MINOR_COMPUTER_HANDHELD = 0x000010, - BTH_COD_MINOR_COMPUTER_PDA = 0x000014, - - BTH_COD_MINOR_PHONE_UNCLASSIFIED = 0x000000, - BTH_COD_MINOR_PHONE_CELL = 0x000004, - BTH_COD_MINOR_PHONE_CORDLESS = 0x000008, - BTH_COD_MINOR_PHONE_SMART = 0x00000c, - BTH_COD_MINOR_PHONE_WIRED = 0x000010, - - BTH_COD_MINOR_LAP_AVAILABLE = 0x000000, - BTH_COD_MINOR_LAP_1_17 = 0x000004, - BTH_COD_MINOR_LAP_17_33 = 0x000008, - BTH_COD_MINOR_LAP_33_50 = 0x00000c, - BTH_COD_MINOR_LAP_50_67 = 0x000010, - BTH_COD_MINOR_LAP_67_83 = 0x000014, - BTH_COD_MINOR_LAP_83_99 = 0x000018, - BTH_COD_MINOR_LAP_NO_SERVICE = 0x00001c, - - BTH_COD_MINOR_AUDIO_UNCLASSIFIED = 0x000000, - BTH_COD_MINOR_AUDIO_HEADSET = 0x000004, - } -} - diff --git a/CommAppCFbtSearch/BluetoothCode/HardwareStatus.cs b/CommAppCFbtSearch/BluetoothCode/HardwareStatus.cs deleted file mode 100644 index 760469b..0000000 --- a/CommAppCFbtSearch/BluetoothCode/HardwareStatus.cs +++ /dev/null @@ -1,56 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.HardwareStatus -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Specifies the current status of the Bluetooth hardware. - /// - public enum HardwareStatus : int { - /// - /// Status cannot be determined. - /// - Unknown = 0, - /// - /// Bluetooth radio not present. - /// - NotPresent = 1, - /// - /// Bluetooth radio is in the process of starting up. - /// - Initializing = 2, - /// - /// Bluetooth radio is active. - /// - Running = 3, - /// - /// Bluetooth radio is in the process of shutting down. - /// - Shutdown = 4, - /// - /// Bluetooth radio is in an error state. - /// - Error = 5, - } -} diff --git a/CommAppCFbtSearch/BluetoothCode/PortEmuParams.cs b/CommAppCFbtSearch/BluetoothCode/PortEmuParams.cs deleted file mode 100644 index c399de1..0000000 --- a/CommAppCFbtSearch/BluetoothCode/PortEmuParams.cs +++ /dev/null @@ -1,83 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.PortEmuParams -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== - -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Summary description for PortEmuParams. - /// - public class PortEmuParams { - /*int channel; - int flocal; - //BD_ADDR device 48bits; - uint LAP; - //uint UAP; - ushort NAP; - - int imtu; - int iminmtu; - int imaxmtu; - int isendquota; - int irecvquota; - Guid uuidService; - uint uiportflags;*/ - - byte[] m_data; - - public PortEmuParams() { - m_data = new byte[50]; - - BitConverter.GetBytes((int)1).CopyTo(m_data, 46); - } - - public byte[] ToByteArray() { - return m_data; - } - - public bool Local { - get { - return Convert.ToBoolean(BitConverter.ToInt32(m_data, 4)); - } - set { - int val = 0; - if (value) { - val = -1; - } - BitConverter.GetBytes(val).CopyTo(m_data, 4); - } - } - - public byte[] Address { - get { - byte[] addrbytes = new byte[6]; - Buffer.BlockCopy(m_data, 8, addrbytes, 0, 6); - return addrbytes; - } - set { - Buffer.BlockCopy(value, 0, m_data, 8, 6); - } - } - } -} diff --git a/CommAppCFbtSearch/BluetoothCode/RadioMode.cs b/CommAppCFbtSearch/BluetoothCode/RadioMode.cs deleted file mode 100644 index e1e3d5e..0000000 --- a/CommAppCFbtSearch/BluetoothCode/RadioMode.cs +++ /dev/null @@ -1,44 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.RadioMode -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Determine all the possible modes of operation of the Bluetooth radio. - /// - public enum RadioMode { - /// - /// Bluetooth is disabled on the device. - /// - PowerOff, - /// - /// Bluetooth is connectable but your device cannot be discovered by other devices. - /// - Connectable, - /// - /// Bluetooth is activated and fully discoverable. - /// - Discoverable, - } -} diff --git a/CommAppCFbtSearch/BluetoothCode/SdpError.cs b/CommAppCFbtSearch/BluetoothCode/SdpError.cs deleted file mode 100644 index 7ef4c16..0000000 --- a/CommAppCFbtSearch/BluetoothCode/SdpError.cs +++ /dev/null @@ -1,41 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.Sdp.SdpError -// Copyright (C) 2003-2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Collections; -using System.Data; -using System.Runtime.InteropServices; -using System.Windows.Forms; - -namespace OpenNETCF.Net.Bluetooth { - - public enum SdpError : short { - INVALID_SDP_VERSION = 0x0001, - INVALID_RECORD_HANDLE = 0x0002, - INVALID_REQUEST_SYNTAX = 0x0003, - INVALID_PDU_SIZE = 0x0004, - INVALID_CONTINUATION_STATE = 0x0005, - INSUFFICIENT_RESOURCES = 0x0006, - } - -} diff --git a/CommAppCFbtSearch/BluetoothCode/SdpQueryUuidUnion.cs b/CommAppCFbtSearch/BluetoothCode/SdpQueryUuidUnion.cs deleted file mode 100644 index 43e5cb4..0000000 --- a/CommAppCFbtSearch/BluetoothCode/SdpQueryUuidUnion.cs +++ /dev/null @@ -1,60 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Net.Bluetooth.SdpQueryUuidUnion -// Copyright (C) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; - -namespace OpenNETCF.Net.Bluetooth { - /// - /// Summary description for SdpQueryUuidUnion. - /// - public class SdpQueryUuidUnion { - private byte[] m_data; - - public SdpQueryUuidUnion() { - m_data = new byte[18]; - } - - public Guid Uuid { - get { - byte[] guidbytes = new byte[16]; - - Buffer.BlockCopy(m_data, 0, guidbytes, 0, 16); - - return new Guid(guidbytes); - } - } - - /// - /// Uuid Type. - /// - public short UuidType { - get { - return BitConverter.ToInt16(m_data, 16); - } - /*set - { - BitConverter.GetBytes(value).CopyTo(m_data, 16); - }*/ - } - } -} diff --git a/CommAppCFbtSearch/BluetoothConnect.Designer.cs b/CommAppCFbtSearch/BluetoothConnect.Designer.cs deleted file mode 100644 index 618db99..0000000 --- a/CommAppCFbtSearch/BluetoothConnect.Designer.cs +++ /dev/null @@ -1,124 +0,0 @@ -namespace CommAppCFbtSearch -{ - partial class BluetoothConnect - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuCancel = new System.Windows.Forms.MenuItem(); - this.mnuOK = new System.Windows.Forms.MenuItem(); - this.label1 = new System.Windows.Forms.Label(); - this.txtBTAddress = new System.Windows.Forms.TextBox(); - this.label2 = new System.Windows.Forms.Label(); - this.btnSearch = new System.Windows.Forms.Button(); - this.comboBox1 = new System.Windows.Forms.ComboBox(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuCancel); - this.mainMenu1.MenuItems.Add(this.mnuOK); - // - // mnuCancel - // - this.mnuCancel.Text = "Cancel"; - this.mnuCancel.Click += new System.EventHandler(this.mnuCancel_Click); - // - // mnuOK - // - this.mnuOK.Text = "OK"; - this.mnuOK.Click += new System.EventHandler(this.mnuOK_Click); - // - // label1 - // - this.label1.Location = new System.Drawing.Point(11, 15); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(216, 21); - this.label1.Text = "Scan or type BT MAC address:"; - // - // txtBTAddress - // - this.txtBTAddress.Location = new System.Drawing.Point(12, 39); - this.txtBTAddress.Name = "txtBTAddress"; - this.txtBTAddress.Size = new System.Drawing.Size(215, 21); - this.txtBTAddress.TabIndex = 1; - // - // label2 - // - this.label2.Location = new System.Drawing.Point(11, 63); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(216, 21); - this.label2.Text = "Example: \"0006660309E8\""; - // - // btnSearch - // - this.btnSearch.Location = new System.Drawing.Point(11, 96); - this.btnSearch.Name = "btnSearch"; - this.btnSearch.Size = new System.Drawing.Size(215, 22); - this.btnSearch.TabIndex = 5; - this.btnSearch.Text = "Search Bluetooth devices"; - this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click); - // - // comboBox1 - // - this.comboBox1.Location = new System.Drawing.Point(11, 124); - this.comboBox1.Name = "comboBox1"; - this.comboBox1.Size = new System.Drawing.Size(215, 22); - this.comboBox1.TabIndex = 6; - this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); - // - // BluetoothConnect - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.comboBox1); - this.Controls.Add(this.btnSearch); - this.Controls.Add(this.txtBTAddress); - this.Controls.Add(this.label2); - this.Controls.Add(this.label1); - this.Menu = this.mainMenu1; - this.Name = "BluetoothConnect"; - this.Text = "BluetoothConnect"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuCancel; - private System.Windows.Forms.MenuItem mnuOK; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.TextBox txtBTAddress; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Button btnSearch; - private System.Windows.Forms.ComboBox comboBox1; - } -} \ No newline at end of file diff --git a/CommAppCFbtSearch/BluetoothConnect.cs b/CommAppCFbtSearch/BluetoothConnect.cs deleted file mode 100644 index 53931d5..0000000 --- a/CommAppCFbtSearch/BluetoothConnect.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Runtime.InteropServices; - -using OpenNETCF.Net.Bluetooth; - -namespace CommAppCFbtSearch -{ - public partial class BluetoothConnect : Form - { - //using intermec bluetooth tool - [DllImport("ibt.dll", SetLastError = true)] - private static extern bool IBT_SetPrinter(StringBuilder AddrString, bool Register); - [DllImport("ibt.dll", SetLastError = true)] - private static extern UInt32 IBT_On (); - - //using SetBtPrinter.DLL, needs pswdm0c.cab (pswdm0cDll.dll) installed on intermec! - [DllImport("SetBtPrinter.dll", SetLastError = true)] - private static extern int registerPrinter(StringBuilder AddrString); - - public bool bUseSocket = false; - public byte[] bdAddress; - - public BluetoothConnect() - { - InitializeComponent(); -#if DEBUG - txtBTAddress.Text = "0006660309E8"; -#endif - } - /* - */ - private bool serialPortConnect() - { - bool bSuccess = false; - int iRes = -1; - try - { - Cursor.Current = Cursors.WaitCursor; - StringBuilder sb = new StringBuilder(txtBTAddress.Text); - if (System.IO.File.Exists(@"\Windows\pswdm0cDLL.dll")) - { - iRes = registerPrinter(sb); //this may take a while... - if (iRes != 0) - { - System.Diagnostics.Debug.WriteLine("registerPrinter failed:" + Marshal.GetLastWin32Error().ToString("x")); - bSuccess = false; - } - else - bSuccess = true; - } - else if (System.IO.File.Exists(@"\Windows\ibt.dll")) - { - bSuccess = IBT_SetPrinter(sb, true); - if (!bSuccess) - System.Diagnostics.Debug.WriteLine("IBT_SetPrinter failed:" + Marshal.GetLastWin32Error().ToString("x")); - } - } - catch (Exception) - { - bSuccess = false; - } - finally - { - Cursor.Current = Cursors.Default; - } - - if (bSuccess) - { - MessageBox.Show("Connection success"); - this.DialogResult = DialogResult.OK; - } - else - { - MessageBox.Show("Connection failed"); - this.DialogResult = DialogResult.Abort; - } - return bSuccess; - } - private void mnuOK_Click(object sender, EventArgs e) - { - serialPortConnect(); - this.Close(); - } - - private void mnuCancel_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.Cancel; - this.Close(); - } - - private void btnSearch_Click(object sender, EventArgs e) - { - this.Enabled = false; - Cursor.Current = Cursors.WaitCursor; - BluetoothDeviceInfo[] bdi; - BluetoothClient bc = new BluetoothClient(); - bdi = bc.DiscoverDevices(); - comboBox1.DisplayMember = "DeviceName"; - comboBox1.ValueMember = "DeviceID"; - comboBox1.DataSource = bdi; - bc.Close(); - if (comboBox1.Items.Count > 0) - comboBox1.SelectedIndex = 0; - Cursor.Current = Cursors.Default; - this.Enabled = true; - } - - private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) - { - int x = comboBox1.SelectedIndex; - if (x == -1) - return; - - BluetoothDeviceInfo BDI = (BluetoothDeviceInfo)(comboBox1.Items[x]); - bdAddress = BDI.DeviceID; - byte[] bDisplay = hexHelper.reverseBytes(bdAddress); - txtBTAddress.Text = hexHelper.ToString(bDisplay); - } - } -} \ No newline at end of file diff --git a/CommAppCFbtSearch/BluetoothConnect.resx b/CommAppCFbtSearch/BluetoothConnect.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/CommAppCFbtSearch/BluetoothConnect.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/CommAppCFbtSearch/CommAppCF.csproj.user b/CommAppCFbtSearch/CommAppCF.csproj.user deleted file mode 100644 index 1f8508e..0000000 --- a/CommAppCFbtSearch/CommAppCF.csproj.user +++ /dev/null @@ -1,5 +0,0 @@ - - - 4118C335-430C-497f-BE48-11C3316B135Ed6518ffb-710f-11d3-99f2-00105a0df099 - - \ No newline at end of file diff --git a/CommAppCFbtSearch/CommAppCF.suo b/CommAppCFbtSearch/CommAppCF.suo deleted file mode 100644 index 381d6bf..0000000 Binary files a/CommAppCFbtSearch/CommAppCF.suo and /dev/null differ diff --git a/CommAppCFbtSearch/CommAppCFbtSearch.csproj b/CommAppCFbtSearch/CommAppCFbtSearch.csproj deleted file mode 100644 index 88ebd73..0000000 --- a/CommAppCFbtSearch/CommAppCFbtSearch.csproj +++ /dev/null @@ -1,144 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {151322CC-139B-455B-8B84-1A21D3D81834} - WinExe - Properties - CommAppCFbtSearch - CommAppCFbtSearch - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.01 - CommAppCFbtSearch - v2.0 - - - - - - - 2.0 - Windows Mobile 5.0 Pocket PC SDK - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - - - - - - - - - - - - Form - - - BluetoothConnect.cs - - - Form - - - ConnectDlg.cs - - - Form - - - Form1.cs - - - - - - - BluetoothConnect.cs - - - Designer - ConnectDlg.cs - - - Designer - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - - - - Always - - - Always - - - - - - - - - - - - - - \ No newline at end of file diff --git a/CommAppCFbtSearch/CommAppCFbtSearch.sln b/CommAppCFbtSearch/CommAppCFbtSearch.sln deleted file mode 100644 index 3b93e97..0000000 --- a/CommAppCFbtSearch/CommAppCFbtSearch.sln +++ /dev/null @@ -1,50 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommAppCFbtSearch", "CommAppCFbtSearch.csproj", "{151322CC-139B-455B-8B84-1A21D3D81834}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SetBTprinter", "SetBTprinter\SetBTprinter.vcproj", "{D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Any CPU.Build.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Mixed Platforms.Deploy.0 = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Any CPU.ActiveCfg = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Any CPU.Build.0 = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Any CPU.Deploy.0 = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Mixed Platforms.Deploy.0 = Release|Any CPU - {151322CC-139B-455B-8B84-1A21D3D81834}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Any CPU - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D375ADCA-6C4E-4FB8-B2AD-C64CD423A15E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/CommAppCFbtSearch/ConnectDlg.Designer.cs b/CommAppCFbtSearch/ConnectDlg.Designer.cs deleted file mode 100644 index 559c59d..0000000 --- a/CommAppCFbtSearch/ConnectDlg.Designer.cs +++ /dev/null @@ -1,230 +0,0 @@ -namespace CommAppCFbtSearch -{ - partial class ConnectDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuCancel = new System.Windows.Forms.MenuItem(); - this.mnuConnect = new System.Windows.Forms.MenuItem(); - this.lblComPort = new System.Windows.Forms.Label(); - this.cmbPortName = new System.Windows.Forms.ComboBox(); - this.cmbBaudRate = new System.Windows.Forms.ComboBox(); - this.lblBaudRate = new System.Windows.Forms.Label(); - this.cmbParity = new System.Windows.Forms.ComboBox(); - this.label1 = new System.Windows.Forms.Label(); - this.lblStopBits = new System.Windows.Forms.Label(); - this.cmbStopBits = new System.Windows.Forms.ComboBox(); - this.lblDataBits = new System.Windows.Forms.Label(); - this.cmbDataBits = new System.Windows.Forms.ComboBox(); - this.cmbHandshake = new System.Windows.Forms.ComboBox(); - this.label2 = new System.Windows.Forms.Label(); - this.btnBTPrinter = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuCancel); - this.mainMenu1.MenuItems.Add(this.mnuConnect); - // - // mnuCancel - // - this.mnuCancel.Text = "Cancel"; - this.mnuCancel.Click += new System.EventHandler(this.mnuCancel_Click); - // - // mnuConnect - // - this.mnuConnect.Text = "Connect"; - this.mnuConnect.Click += new System.EventHandler(this.mnuConnect_Click); - // - // lblComPort - // - this.lblComPort.Location = new System.Drawing.Point(27, 11); - this.lblComPort.Name = "lblComPort"; - this.lblComPort.Size = new System.Drawing.Size(74, 13); - this.lblComPort.Text = "COM Port:"; - // - // cmbPortName - // - this.cmbPortName.Items.Add("COM0"); - this.cmbPortName.Items.Add("COM1"); - this.cmbPortName.Items.Add("COM2"); - this.cmbPortName.Items.Add("COM3"); - this.cmbPortName.Items.Add("COM4"); - this.cmbPortName.Location = new System.Drawing.Point(112, 3); - this.cmbPortName.Name = "cmbPortName"; - this.cmbPortName.Size = new System.Drawing.Size(68, 22); - this.cmbPortName.TabIndex = 18; - // - // cmbBaudRate - // - this.cmbBaudRate.Items.Add("1200"); - this.cmbBaudRate.Items.Add("2400"); - this.cmbBaudRate.Items.Add("4800"); - this.cmbBaudRate.Items.Add(""); - this.cmbBaudRate.Location = new System.Drawing.Point(112, 39); - this.cmbBaudRate.Name = "cmbBaudRate"; - this.cmbBaudRate.Size = new System.Drawing.Size(68, 22); - this.cmbBaudRate.TabIndex = 19; - // - // lblBaudRate - // - this.lblBaudRate.Location = new System.Drawing.Point(27, 47); - this.lblBaudRate.Name = "lblBaudRate"; - this.lblBaudRate.Size = new System.Drawing.Size(79, 13); - this.lblBaudRate.Text = "Baud Rate:"; - // - // cmbParity - // - this.cmbParity.Items.Add("None"); - this.cmbParity.Items.Add("1"); - this.cmbParity.Items.Add("2"); - this.cmbParity.Items.Add("3"); - this.cmbParity.Items.Add("4"); - this.cmbParity.Items.Add("5"); - this.cmbParity.Items.Add("6"); - this.cmbParity.Location = new System.Drawing.Point(112, 79); - this.cmbParity.Name = "cmbParity"; - this.cmbParity.Size = new System.Drawing.Size(68, 22); - this.cmbParity.TabIndex = 21; - // - // label1 - // - this.label1.Location = new System.Drawing.Point(27, 79); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(54, 13); - this.label1.Text = "Parity:"; - // - // lblStopBits - // - this.lblStopBits.Location = new System.Drawing.Point(27, 158); - this.lblStopBits.Name = "lblStopBits"; - this.lblStopBits.Size = new System.Drawing.Size(70, 13); - this.lblStopBits.Text = "Stop Bits:"; - // - // cmbStopBits - // - this.cmbStopBits.Items.Add("1"); - this.cmbStopBits.Items.Add("2"); - this.cmbStopBits.Items.Add("3"); - this.cmbStopBits.Location = new System.Drawing.Point(112, 155); - this.cmbStopBits.Name = "cmbStopBits"; - this.cmbStopBits.Size = new System.Drawing.Size(69, 22); - this.cmbStopBits.TabIndex = 26; - // - // lblDataBits - // - this.lblDataBits.Location = new System.Drawing.Point(27, 119); - this.lblDataBits.Name = "lblDataBits"; - this.lblDataBits.Size = new System.Drawing.Size(71, 13); - this.lblDataBits.Text = "Data Bits:"; - // - // cmbDataBits - // - this.cmbDataBits.Items.Add("5"); - this.cmbDataBits.Items.Add("6"); - this.cmbDataBits.Items.Add("7"); - this.cmbDataBits.Items.Add("8"); - this.cmbDataBits.Location = new System.Drawing.Point(112, 119); - this.cmbDataBits.Name = "cmbDataBits"; - this.cmbDataBits.Size = new System.Drawing.Size(68, 22); - this.cmbDataBits.TabIndex = 25; - // - // cmbHandshake - // - this.cmbHandshake.Items.Add("1"); - this.cmbHandshake.Items.Add("2"); - this.cmbHandshake.Items.Add("3"); - this.cmbHandshake.Location = new System.Drawing.Point(111, 192); - this.cmbHandshake.Name = "cmbHandshake"; - this.cmbHandshake.Size = new System.Drawing.Size(69, 22); - this.cmbHandshake.TabIndex = 26; - // - // label2 - // - this.label2.Location = new System.Drawing.Point(26, 195); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(70, 13); - this.label2.Text = "Handshake:"; - // - // btnBTPrinter - // - this.btnBTPrinter.Location = new System.Drawing.Point(27, 230); - this.btnBTPrinter.Name = "btnBTPrinter"; - this.btnBTPrinter.Size = new System.Drawing.Size(181, 22); - this.btnBTPrinter.TabIndex = 31; - this.btnBTPrinter.Text = "Bluetooth Printer"; - this.btnBTPrinter.Click += new System.EventHandler(this.btnBTPrinter_Click); - // - // ConnectDlg - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.btnBTPrinter); - this.Controls.Add(this.label2); - this.Controls.Add(this.lblStopBits); - this.Controls.Add(this.cmbHandshake); - this.Controls.Add(this.cmbStopBits); - this.Controls.Add(this.lblDataBits); - this.Controls.Add(this.cmbDataBits); - this.Controls.Add(this.lblComPort); - this.Controls.Add(this.cmbPortName); - this.Controls.Add(this.cmbBaudRate); - this.Controls.Add(this.lblBaudRate); - this.Controls.Add(this.cmbParity); - this.Controls.Add(this.label1); - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "ConnectDlg"; - this.Text = "ConnectDlg"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuCancel; - private System.Windows.Forms.MenuItem mnuConnect; - private System.Windows.Forms.Label lblComPort; - private System.Windows.Forms.ComboBox cmbPortName; - private System.Windows.Forms.ComboBox cmbBaudRate; - private System.Windows.Forms.Label lblBaudRate; - private System.Windows.Forms.ComboBox cmbParity; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label lblStopBits; - private System.Windows.Forms.ComboBox cmbStopBits; - private System.Windows.Forms.Label lblDataBits; - private System.Windows.Forms.ComboBox cmbDataBits; - private System.Windows.Forms.ComboBox cmbHandshake; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Button btnBTPrinter; - } -} \ No newline at end of file diff --git a/CommAppCFbtSearch/ConnectDlg.cs b/CommAppCFbtSearch/ConnectDlg.cs deleted file mode 100644 index 1bc8d32..0000000 --- a/CommAppCFbtSearch/ConnectDlg.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.IO.Ports; - -namespace CommAppCFbtSearch -{ - public partial class ConnectDlg : Form - { - private SerialPort _serialPort; - private uint[] baudRates = { 1200, 2400, 4800, 9600, 19200, 38200, 57600, 115200, 230400, 460800, 921600 }; - - private serialSet _mySettings = new serialSet(); - - public ConnectDlg(ref SerialPort sp) - { - InitializeComponent(); - - if(System.IO.File.Exists("\\windows\\ibt.dll")) - btnBTPrinter.Enabled=true; - else - btnBTPrinter.Enabled=false; - - //port list - cmbPortName.Items.Clear(); - for (int i = 0; i < 10; i++) - { - cmbPortName.Items.Insert(i, "COM" + i.ToString()); - } - int ix = cmbPortName.Items.IndexOf(_mySettings.sPort); - if (ix != -1) - cmbPortName.SelectedIndex = ix; - else - cmbPortName.SelectedIndex = 0; - - //baud list - cmbBaudRate.Items.Clear(); - int j = 0; - foreach (uint u in _mySettings.baudRates) - { - cmbBaudRate.Items.Insert(j, u.ToString()); - j++; - } - ix = findInCombo(cmbBaudRate, _mySettings.baudRate.ToString()); - if (ix != -1) - cmbBaudRate.SelectedIndex = ix; - else - cmbBaudRate.SelectedIndex = 0; - - //databits - cmbDataBits.Items.Clear(); - for (int i = 6; i < 9; i++) - { - cmbDataBits.Items.Add(i.ToString()); - } - ix = findInCombo(cmbDataBits, _mySettings.databits.ToString()); - if (ix != -1) - cmbDataBits.SelectedIndex = ix; - else - cmbDataBits.SelectedIndex = 0; - - //parity - cmbParity.Items.Clear(); - for (int i = 0; i < myParity.parity.Length; i++) - { - cmbParity.Items.Insert(i, myParity.ToString(i)); - } - - cmbParity.SelectedIndex = (int)_mySettings.parity; - - //stopBits - cmbStopBits.Items.Clear(); - for (int i = 0; i < 3; i++) - { - cmbStopBits.Items.Insert(i, myStopBits.ToString(i)); - } - ix = findInCombo(cmbStopBits, _mySettings.stopBits.ToString()); - if (ix != -1) - cmbStopBits.SelectedIndex = ix; - else - cmbStopBits.SelectedIndex = 1; -// cmbStopBits.SelectedIndex = cmbStopBits.Items.IndexOf(_mySettings.stopBits); - - //handshake - cmbHandshake.Items.Clear(); - for (int i = 0; i < myHandshake.handshakes.Length; i++) - { - cmbHandshake.Items.Insert(i, myHandshake.ToString(i)); - } - cmbHandshake.SelectedIndex = (int)_mySettings.handshake; - - this._serialPort = sp; - - } - - private int findInCombo(ComboBox cbo, string s) - { - for (int j = 0; j < cbo.Items.Count; j++) - { - if (cbo.Items[j].ToString().Equals(s, StringComparison.OrdinalIgnoreCase)) - return j; - } - return -1; - } - private void mnuCancel_Click(object sender, EventArgs e) - { - this.Close(); - } - - private void mnuConnect_Click(object sender, EventArgs e) - { - if (_serialPort.IsOpen) - _serialPort.Close(); - else - { - // Set the port's settings - _serialPort.PortName = cmbPortName.Text; - _serialPort.BaudRate = int.Parse(cmbBaudRate.Text); - _serialPort.DataBits = int.Parse(cmbDataBits.Text); - - if(myStopBits.ToStopBits(cmbStopBits.Text) != StopBits.None) - _serialPort.StopBits = myStopBits.ToStopBits(cmbStopBits.Text); - - _serialPort.Parity = myParity.ToParity(cmbParity.Text); - _serialPort.Handshake = myHandshake.ToHandshake(cmbHandshake.Text); - _serialPort.ReadTimeout = 100; - - _mySettings.baudRate = (uint)_serialPort.BaudRate; - _mySettings.parity = (uint)_serialPort.Parity; - _mySettings.databits = (uint)_serialPort.DataBits; - _mySettings.stopBits = (uint)_serialPort.StopBits; - - _mySettings.sPort = _serialPort.PortName; - - _mySettings.saveSettings(); - - try - { - Cursor.Current = Cursors.WaitCursor; - _serialPort.Open(); - } - catch (Exception x) - { - System.Diagnostics.Debug.WriteLine("Exception in OpenPort: " + x.Message); - } - finally - { - Cursor.Current = Cursors.Default; - } - } - this.Close(); - } - - private void btnBTPrinter_Click(object sender, EventArgs e) - { - BluetoothConnect dlg = new BluetoothConnect(); - dlg.ShowDialog(); - } - } -} \ No newline at end of file diff --git a/CommAppCFbtSearch/ConnectDlg.resx b/CommAppCFbtSearch/ConnectDlg.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/CommAppCFbtSearch/ConnectDlg.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/CommAppCFbtSearch/Form1.Designer.cs b/CommAppCFbtSearch/Form1.Designer.cs deleted file mode 100644 index 902b854..0000000 --- a/CommAppCFbtSearch/Form1.Designer.cs +++ /dev/null @@ -1,171 +0,0 @@ -namespace CommAppCFbtSearch -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.mnuConnect = new System.Windows.Forms.MenuItem(); - this.txtSend = new System.Windows.Forms.TextBox(); - this.label1 = new System.Windows.Forms.Label(); - this.btnSend = new System.Windows.Forms.Button(); - this.txtReceive = new System.Windows.Forms.TextBox(); - this.btnSendFile = new System.Windows.Forms.Button(); - this.btnSendLine = new System.Windows.Forms.Button(); - this.btnClear = new System.Windows.Forms.Button(); - this.chkUseHexEncoder = new System.Windows.Forms.CheckBox(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuExit); - this.mainMenu1.MenuItems.Add(this.mnuConnect); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // mnuConnect - // - this.mnuConnect.Text = "Connect"; - this.mnuConnect.Click += new System.EventHandler(this.mnuConnect_Click); - // - // txtSend - // - this.txtSend.AcceptsReturn = true; - this.txtSend.AcceptsTab = true; - this.txtSend.Location = new System.Drawing.Point(3, 31); - this.txtSend.Multiline = true; - this.txtSend.Name = "txtSend"; - this.txtSend.Size = new System.Drawing.Size(234, 91); - this.txtSend.TabIndex = 0; - // - // label1 - // - this.label1.Location = new System.Drawing.Point(3, 10); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(72, 18); - this.label1.Text = "SEND:"; - // - // btnSend - // - this.btnSend.Location = new System.Drawing.Point(175, 126); - this.btnSend.Name = "btnSend"; - this.btnSend.Size = new System.Drawing.Size(62, 23); - this.btnSend.TabIndex = 2; - this.btnSend.Text = "Send"; - this.btnSend.Click += new System.EventHandler(this.btnSend_Click); - // - // txtReceive - // - this.txtReceive.AcceptsReturn = true; - this.txtReceive.AcceptsTab = true; - this.txtReceive.Location = new System.Drawing.Point(3, 180); - this.txtReceive.Multiline = true; - this.txtReceive.Name = "txtReceive"; - this.txtReceive.ReadOnly = true; - this.txtReceive.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtReceive.Size = new System.Drawing.Size(234, 85); - this.txtReceive.TabIndex = 0; - // - // btnSendFile - // - this.btnSendFile.Location = new System.Drawing.Point(3, 126); - this.btnSendFile.Name = "btnSendFile"; - this.btnSendFile.Size = new System.Drawing.Size(72, 23); - this.btnSendFile.TabIndex = 2; - this.btnSendFile.Text = "Send File"; - this.btnSendFile.Click += new System.EventHandler(this.btnSendFile_Click); - // - // btnSendLine - // - this.btnSendLine.Location = new System.Drawing.Point(96, 126); - this.btnSendLine.Name = "btnSendLine"; - this.btnSendLine.Size = new System.Drawing.Size(73, 23); - this.btnSendLine.TabIndex = 2; - this.btnSendLine.Text = "Send Line"; - this.btnSendLine.Click += new System.EventHandler(this.btnSendLine_Click); - // - // btnClear - // - this.btnClear.Location = new System.Drawing.Point(175, 5); - this.btnClear.Name = "btnClear"; - this.btnClear.Size = new System.Drawing.Size(62, 23); - this.btnClear.TabIndex = 2; - this.btnClear.Text = "Clear"; - this.btnClear.Click += new System.EventHandler(this.btnClear_Click); - // - // chkUseHexEncoder - // - this.chkUseHexEncoder.Location = new System.Drawing.Point(3, 155); - this.chkUseHexEncoder.Name = "chkUseHexEncoder"; - this.chkUseHexEncoder.Size = new System.Drawing.Size(234, 19); - this.chkUseHexEncoder.TabIndex = 4; - this.chkUseHexEncoder.Text = "use \\xAB en/decoding"; - this.chkUseHexEncoder.CheckStateChanged += new System.EventHandler(this.chkUseHexEncoder_CheckStateChanged); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.chkUseHexEncoder); - this.Controls.Add(this.btnSendFile); - this.Controls.Add(this.btnSendLine); - this.Controls.Add(this.btnClear); - this.Controls.Add(this.btnSend); - this.Controls.Add(this.label1); - this.Controls.Add(this.txtReceive); - this.Controls.Add(this.txtSend); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "CommApp"; - this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuExit; - private System.Windows.Forms.MenuItem mnuConnect; - private System.Windows.Forms.TextBox txtSend; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Button btnSend; - private System.Windows.Forms.TextBox txtReceive; - private System.Windows.Forms.Button btnSendFile; - private System.Windows.Forms.Button btnSendLine; - private System.Windows.Forms.Button btnClear; - private System.Windows.Forms.CheckBox chkUseHexEncoder; - } -} - diff --git a/CommAppCFbtSearch/Form1.cs b/CommAppCFbtSearch/Form1.cs deleted file mode 100644 index ada54af..0000000 --- a/CommAppCFbtSearch/Form1.cs +++ /dev/null @@ -1,253 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.IO.Ports; -using OpenNETCF.Net.Bluetooth; - -namespace CommAppCFbtSearch -{ - public partial class Form1 : Form - { - private SerialPort comport = new SerialPort(); - private bool bUseHexDecode = false; - - public Form1() - { - InitializeComponent(); - comport.DataReceived += new SerialDataReceivedEventHandler(comport_DataReceived); - comport.ErrorReceived += new SerialErrorReceivedEventHandler(comport_ErrorReceived); - enableControls(false); - } - - void comport_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) - { - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += e.ToString(); })); - } - - void comport_DataReceived(object sender, SerialDataReceivedEventArgs e) - { - // This method will be called when there is data waiting in the port's buffer - - // Determain which mode (string or binary) the user is in - // Read all the data waiting in the buffer - try - { - string data = ""; - data = comport.ReadLine();//.ReadExisting(); - string s = ""; - // Display the text to the user in the terminal - if (bUseHexDecode) - s = Utility.HexEncoding.ToMixedString(data); - else - s = data; - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += "<" + s + "\r\n"; })); //added < to mark incoming data - } - catch (Exception ex) - { - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += ex.Message + "\r\n"; })); - //MessageBox.Show(ex.Message); - } - //label2.Invoke(new EventHandler(delegate{label2.Text = data;})); - - //Log(LogMsgType.Incoming, data); - } - - private void mnuConnect_Click(object sender, EventArgs e) - { - if (mnuConnect.Text == "Disconnect") - { - comport.ReadExisting(); - comport.Close(); - mnuConnect.Text = "Connect"; - return; - } - - ConnectDlg dlg = new ConnectDlg(ref comport); - dlg.ShowDialog(); - if (comport.IsOpen) - { - mnuConnect.Text = "Disconnect"; - txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += comport.PortName + " opened\r\n"; })); - enableControls(true); - } - else - { - mnuConnect.Text = "Connect"; - enableControls(false); - } - } - /// - /// enable controls based on active connection - /// - /// - private void enableControls(bool bEnable) - { - btnSend.Enabled = bEnable; - btnSendFile.Enabled = bEnable; - btnSendLine.Enabled = bEnable; - } - delegate void SetTextCallback(string text); - private void updateTxtRcv(string text) - { - if (this.txtReceive.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(updateTxtRcv); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtReceive.Text.Length > 2000) - txtReceive.Text = ""; - txtReceive.Text += text + "\r\n"; - txtReceive.SelectionLength = text.Length; - txtReceive.SelectionStart = txtReceive.Text.Length - text.Length; - txtReceive.ScrollToCaret(); - } - - } - private void Form1_Closing(object sender, CancelEventArgs e) - { - try - { - //comport.DiscardOutBuffer(); - //comport.DiscardInBuffer(); - //comport.Dispose(); - if (comport.IsOpen) - { - comport.ReadExisting(); - comport.Close(); - } - } - catch (Exception ex) - { - MessageBox.Show(ex.Message); - } - - } - - private void mnuExit_Click(object sender, EventArgs e) - { - this.Close(); - } - - private void btnSend_Click(object sender, EventArgs e) - { - try - { - if (txtSend.Text.Length > 0) - { - string s = txtSend.Text; - if (chkUseHexEncoder.Checked) - { - byte[] b = Utility.HexEncoding.FromHexedString(s); - comport.Write(b, 0, b.Length); - } - else - comport.Write(s); - } - } - catch (Exception) - { - - } - } - - private void btnSendLine_Click(object sender, EventArgs e) - { - try - { - if (txtSend.Text.Length > 0) - { - string s = txtSend.Text; - if (chkUseHexEncoder.Checked) - { - byte[] b = Utility.HexEncoding.FromHexedString(s); - comport.Write(b, 0, b.Length); - comport.WriteLine(""); - } - else - comport.WriteLine(s); - } - } - catch (Exception) - { - - } - - } - - private void btnSendFile_Click(object sender, EventArgs e) - { - try - { - if (comport.IsOpen) - { - OpenFileDialog ofd = new OpenFileDialog(); - ofd.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; - ofd.FilterIndex = 0; - if (ofd.ShowDialog()==DialogResult.OK){ - string filename = ofd.FileName; - if (System.IO.File.Exists(filename)) - { - Cursor.Current = Cursors.WaitCursor; - sendFile(filename); - Cursor.Current = Cursors.Default; - } - } - } - - } - catch (Exception x) - { - updateTxtRcv(x.Message); - } - } - private void sendFile(string filename) - { - try - { - updateTxtRcv("Starting sendFile(" + filename + ")"); - - System.IO.StreamReader sr = new System.IO.StreamReader(filename); - int r; - int blockSize = 4096; - char[] buf = new char[blockSize]; - //how many blocks to send? - System.IO.FileInfo fi = new System.IO.FileInfo(filename); - long lBlocks = (long)(fi.Length / blockSize); - if (lBlocks == 0) - lBlocks = 1; - updateTxtRcv("Need to send " + lBlocks.ToString() + " blocks..."); - long lBlockNr = 1; - do - { - updateTxtRcv("Sending block " + lBlockNr.ToString() + " ..."); - r = sr.Read(buf, 0, blockSize); //r = number of bytes read - comport.Write(buf, 0, r); - } - while (r!=-1 && !sr.EndOfStream); - sr.Close(); - updateTxtRcv("Finished sendFile(" + filename + ")"); - } - catch (Exception x) - { - updateTxtRcv("sendFile exception:" + x.Message); - System.Diagnostics.Debug.WriteLine(x.Message); - } - } - - private void btnClear_Click(object sender, EventArgs e) - { - txtSend.Text = ""; - } - - private void chkUseHexEncoder_CheckStateChanged(object sender, EventArgs e) - { - bUseHexDecode = chkUseHexEncoder.Checked; - } - } -} \ No newline at end of file diff --git a/CommAppCFbtSearch/Form1.resx b/CommAppCFbtSearch/Form1.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/CommAppCFbtSearch/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/CommAppCFbtSearch/HexEncoding.cs b/CommAppCFbtSearch/HexEncoding.cs deleted file mode 100644 index 41ff565..0000000 --- a/CommAppCFbtSearch/HexEncoding.cs +++ /dev/null @@ -1,206 +0,0 @@ -using System; -using System.Text; -using System.Globalization; - -namespace Utility -{ - /// - /// Summary description for HexEncoding. - /// - public static class HexEncoding - { - //public HexEncoding() - //{ - //} - /// - /// helper to get count of hex chars in a string - /// - /// - /// only hex chars are counted - public static int GetByteCount(string hexString) - { - int numHexChars = 0; - char c; - // remove all none A-F, 0-9, characters - for (int i=0; i - /// Creates a byte array from the hexadecimal string. Each two characters are combined - /// to create one byte. First two hexadecimal characters become first byte in returned array. - /// Non-hexadecimal characters are ignored. - /// - /// string to convert to byte array - /// number of characters in string ignored - /// byte array, in the same left-to-right order as the hexString - public static byte[] GetBytes(string hexString, out int discarded) - { - discarded = 0; - string newString = ""; - char c; - // remove all none A-F, 0-9, characters - for (int i=0; i - /// convert a byte array to a sequence of hex chars - /// - /// - /// - public static string ToString(byte[] bytes) - { - string hexString = ""; - for (int i=0; i - /// convert a mixed string with \xAB encoded hex chars back to a byte array - /// - /// - /// - public static byte[] FromHexedString(string val){ - //replace \xHH with char of before using getbytes - int iPos = val.IndexOf("\\x"); - while(iPos>=0){ - string s = val.Substring(iPos, 4); - byte b = byte.Parse(val.Substring(iPos+2,2), NumberStyles.HexNumber); - //string c = Convert.ToString(b,16); - char ch = (char)b; - //test - //byte[] bTest = Encoding.ASCII.GetBytes(ch.ToString()); - //System.Diagnostics.Debug.WriteLine(string.Format("Encoded {0:x} as '{1}'", bTest,ch)); - string o = val.Substring(0, iPos) + ch + val.Substring(iPos + 4); - val = o; - iPos = val.IndexOf("\\x"); - } - byte[] valAsByteArray = Encoding.ASCII.GetBytes(val); - return valAsByteArray; - } - /// - /// convert a string with chars to a string that uses \xAB encoding for non-printable chars - /// - /// - /// - public static string ToMixedString(string s) - { - byte[] bytes = Encoding.ASCII.GetBytes(s); - string sReturn = ToMixedString(bytes); - return sReturn; - } - /// - /// convert a byte array to a string that uses \xAB encoding for non-printable chars - /// - /// - /// - public static string ToMixedString(byte[] bytes) - { - string hexString = ""; - for (int i = 0; i < bytes.Length; i++) - { - if (bytes[i] >= 0x20) - { - //hexString += bytes[i].ToString(); - hexString += ASCIIEncoding.ASCII.GetString(bytes, i, 1); - } - else - { - hexString += "\\x"; // "<" - hexString += bytes[i].ToString("X2"); - //if (i <= bytes.Length - 1) hexString += "-"; - //hexString += ">"; - } - } - return hexString; - } - - /// - /// Determines if given string is in proper hexadecimal string format - /// - /// - /// - public static bool InHexFormat(string hexString) - { - bool hexFormat = true; - - foreach (char digit in hexString) - { - if (!IsHexDigit(digit)) - { - hexFormat = false; - break; - } - } - return hexFormat; - } - - /// - /// Returns true is c is a hexadecimal digit (A-F, a-f, 0-9) - /// - /// Character to test - /// true if hex digit, false if not - public static bool IsHexDigit(Char c) - { - int numChar; - int numA = Convert.ToInt32('A'); - int num1 = Convert.ToInt32('0'); - c = Char.ToUpper(c); - numChar = Convert.ToInt32(c); - if (numChar >= numA && numChar < (numA + 6)) - return true; - if (numChar >= num1 && numChar < (num1 + 10)) - return true; - return false; - } - /// - /// Converts 1 or 2 character string into equivalant byte value - /// - /// 1 or 2 character string - /// byte - private static byte HexToByte(string hex) - { - if (hex.Length > 2 || hex.Length <= 0) - throw new ArgumentException("hex must be 1 or 2 characters in length"); - byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber); - return newByte; - } - } -} diff --git a/CommAppCFbtSearch/Program.cs b/CommAppCFbtSearch/Program.cs deleted file mode 100644 index a6bda75..0000000 --- a/CommAppCFbtSearch/Program.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; - -namespace CommAppCFbtSearch -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/CommAppCFbtSearch/Properties/AssemblyInfo.cs b/CommAppCFbtSearch/Properties/AssemblyInfo.cs deleted file mode 100644 index 3f89d9c..0000000 --- a/CommAppCFbtSearch/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("CommAppCF")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("CommAppCF")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("7c366247-0f89-4894-9690-a8ee15533cb7")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - diff --git a/CommAppCFbtSearch/Properties/Resources.Designer.cs b/CommAppCFbtSearch/Properties/Resources.Designer.cs deleted file mode 100644 index a113347..0000000 --- a/CommAppCFbtSearch/Properties/Resources.Designer.cs +++ /dev/null @@ -1,60 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.4952 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace CommAppCFbtSearch.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CommAppCFbtSearch.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/CommAppCFbtSearch/Properties/Resources.resx b/CommAppCFbtSearch/Properties/Resources.resx deleted file mode 100644 index 451318b..0000000 --- a/CommAppCFbtSearch/Properties/Resources.resx +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 diff --git a/CommAppCFbtSearch/SetBTprinter.dll b/CommAppCFbtSearch/SetBTprinter.dll deleted file mode 100644 index 4aca93f..0000000 Binary files a/CommAppCFbtSearch/SetBTprinter.dll and /dev/null differ diff --git a/CommAppCFbtSearch/SetBTprinter/SetBTprinter.cpp b/CommAppCFbtSearch/SetBTprinter/SetBTprinter.cpp deleted file mode 100644 index 562f69d..0000000 --- a/CommAppCFbtSearch/SetBTprinter/SetBTprinter.cpp +++ /dev/null @@ -1,300 +0,0 @@ -// SetBTprinter.cpp : Defines the entry point for the DLL application. -// - -#include "stdafx.h" -#include -//#include - -// SetBTPrinter4dll.cpp : Defines the entry point for the DLL application. -// -/* - history - version - 1.1 replaced all DEBUGMSG by nclog - added nclog.h and nclog.cpp - changed log text for ITC_SetDefaultDevice() - addede iResult=-3 before while loop - added iResult=0 for found device below "if(wcsstr(uDeviceName, uBDA)!=NULL)" -*/ -#pragma comment (user, "SetBTprinter.DLL version 1.1") - -//#include "stdafx.h" -#include "SetBTprinter.h" - -#include "nclog.h" - -const TCHAR* szXmlFileName = L"\\Windows\\pswdm0c.xml"; -const LPTSTR szDeviceType = TEXT("Printer"); -const LPTSTR szDeviceSubtype = NULL; - -const TCHAR* csFP = L"NEW\r\n1 BARFONT ON\r\n2 BARFONT \"Swiss 721 BT\", 6\r\n10 PRPOS 10,10\r\n20 PRBOX 430,340,15\r\n50 PRPOS 75,27060 BARTYPE \"CODE39\"70 PRBAR \"ABC\"80 PRPOS 25,220\r\n90 FONT \"Swiss 721 BT\", 6\r\n100 PRTXT \"My FIRST label\"\r\n200 PRINTFEED\r\n300 END\r\nRUN\r\n"; - -const TCHAR* csESCP = L"Intermec Developer Conference 2005\n\n Multiblue Sample Order\n\nProduct Quantity Price\n______________________________\n Delicious Soda 123 $0.49\n\n\n\n\n\n"; - -//test func for pswdmc0 -// registerPrinter(TCHAR* szBDA) -// register and activate the BT device with BDA szBDA -// performs a device discovery and binds the device -// the registry has the BTPort entry as WPort not WPPort as in help doc -// returns -// 0 for success -// -1 for error in ITC_InitializeDeviceUtility -// -2 for failure with ITC_DiscoverDevices -// -3 for if unable to find device in range -// -4 ITC_SetActiveDevice failed -// -5 ITC_SetDefaultDevice failed -// -6 ITC_SaveDeviceUtilityChanges failed -// -7 ITC_CloseDeviceUtility failed -// -8 ITC_AddDevice failed -int registerPrinter(TCHAR* szBDA){ - int iResult = 0; //return code, assume no error - TCHAR uDeviceName[MAX_PATH]; //for upper case compare - TCHAR uBDA[MAX_PATH]; //for upper case compare - - wchar_t fillChar = '\0'; - TCHAR deviceName[MAX_PATH]; //var for ITC_GetDiscoveredDevice - TCHAR strSelectedDevice[MAX_PATH]; //var to be used for Registering - - nclog(L"registerPrinter: ITC_InitializeDeviceUtility()\r\n"); - int iRes = ITC_InitializeDeviceUtility(szXmlFileName); - if(iRes==0){ - ITC_DISCOVERPROC lpDiscoveryComplete=NULL; - DWORD lParam = 0; - nclog(L"registerPrinter: ITC_DiscoverDevices()...\r\n"); - iRes = ITC_DiscoverDevices(szDeviceType, szDeviceSubtype, lpDiscoveryComplete, lParam); - nclog(L"registerPrinter: ITC_DiscoverDevices() finished\r\n"); - if(iRes==0){ - iResult=-3; //assume device not found, v1.1 - BOOL bFirst = TRUE; - while(ITC_GetDiscoveredDevice(deviceName, MAX_PATH, bFirst)==ERROR_SUCCESS){ //find first device - //cDeviceName=deviceName; - nclog(L"registerPrinter: testing '%s'\r\n", deviceName); - //is the BDA in there? - wcscpy(uBDA, szBDA); _wcsupr(uBDA); //all upper case - wcscpy(uDeviceName, deviceName); _wcsupr(uDeviceName); //all upper case - //is this the searched printer - if(wcsstr(uDeviceName, uBDA)!=NULL){ - iResult=0; //found device, v1.1 - nclog(L"registerPrinter: found match '%s'\r\n", deviceName); - //found the printer in question, now set this as default - wsprintf(strSelectedDevice, L"%s", deviceName); - - // Determine if the computer needs to bond with the device. - nclog(L"registerPrinter: ITC_IsBondWithDeviceNeeded for %s...\r\n", strSelectedDevice); - if (ITC_IsBondWithDeviceNeeded(strSelectedDevice)) - { - // TODO: You should show a warning message suggesting - // that bonding should not be performed in a public - // place, because an attacker could eavesdrop and - // steal the Passkey. - - // TODO: If you do not want to use the default Passkey - // prompt for the Bluetooth stack, make sure a Passkey - // is set for the device. This sample just allows the - // default Passkey prompt so it does not use this code. - TCHAR strPasskey[MAX_PATH]; - iRes = ITC_GetDeviceProperty(strSelectedDevice, TEXT("Passkey"), strPasskey, MAX_PATH); - nclog(L"registerPrinter: ITC_GetDeviceProperty for passkey returned %i\r\n", iRes); - if (strPasskey==NULL || wcslen(strPasskey)==0) - { - // TODO: If all of your devices have a common - // Passkey, you could hardcode a value here. - // Otherwise, you could prompt the user for - // the Passkey. - wsprintf(strPasskey, L""); - // Store the Passkey. - iRes = ITC_SetDeviceProperty(strSelectedDevice, TEXT("Passkey"), strPasskey); - nclog(L"registerPrinter: ITC_SetDeviceProperty setting empty passkey returned %i\r\n", iRes); - } - - // Bond the computer and the device. - // TODO: Because radio connections can sometimes fail, - // you should build in retry logic when BondWithDevice - // fails. This sample just tries once. - iRes = ITC_BondWithDevice(strSelectedDevice); - if(iRes!=0) - nclog(L"registerPrinter: ITC_BondWithDevice failed with %i\r\n",iRes); - else - nclog(L"registerPrinter: ITC_BondWithDevice OK\r\n"); - - } - else{ - nclog(L"registerPrinter: ITC_IsBondWithDeviceNeeded not needed\r\n"); - } - - iRes = ITC_AddDevice(szDeviceType, /*szDeviceSubtype*/ NULL, strSelectedDevice); - if (iRes == ERROR_SUCCESS){ - nclog(L"registerPrinter: ITC_AddDevice for '%s' OK\r\n", strSelectedDevice); - } - else{ - nclog(L"registerPrinter: ITC_AddDevice for '%s' failed with error %i\r\n", strSelectedDevice, iRes); - iResult = -8; - } - - // Set up a port to use the selected device. Refer to the BtPort element in the XML file. - // Call ITC_SetActiveDevice to set up a port for accessing the device. Call ITC_SetActiveDevice before - // each attempt to access the device because the port is removed if the computer is rebooted. - - - iRes = ITC_SetActiveDevice(szDeviceType, /*szDeviceSubtype*/ NULL, strSelectedDevice); - if (iRes == ERROR_SUCCESS){ - nclog(L"registerPrinter: ITC_SetActiveDevice to '%s' OK\r\n", strSelectedDevice); - } - else{ - nclog(L"registerPrinter: ITC_SetActiveDevice to '%s' failed with error %i\r\n", strSelectedDevice, iRes); - iResult = -4; - } - // Set the selected device as the default. - iRes = ITC_SetDefaultDevice(szDeviceType, /*szDeviceSubtype*/ NULL, strSelectedDevice); - if (iRes == ERROR_SUCCESS) - nclog(L"registerPrinter: ITC_SetDefaultDevice to '%s' OK\r\n", strSelectedDevice); - else{ - nclog(L"registerPrinter: ITC_SetDefaultDevice to '%s' failed with error %i\r\n", strSelectedDevice, iRes); - iResult=-5; - } - nclog(L"...leaving registerPrinter\r\n"); - break; - }// if BDA found - bFirst=FALSE; - _wcsset(deviceName, fillChar); - }//while - nclog(L"registerPrinter: Leaving loop\r\n"); - }//ITC_DiscoverDevices - else{ - nclog(L"registerPrinter: ITC_DiscoverDevices() failed\r\n"); - iResult=-2; - } - - //save changes to utility - if(iRes = ITC_SaveDeviceUtilityChanges()==0) - nclog(L"registerPrinter: saved changes to '%s'\r\n", szXmlFileName); - else{ - nclog(L"registerPrinter: save to '%s' failed with error %i\r\n", szXmlFileName, iRes); - iResult=-6; - } - - //close device utility - if(iRes = ITC_CloseDeviceUtility()==0) - nclog(L"registerPrinter: ITC_CloseDeviceUtility() OK\r\n", szXmlFileName); - else{ - nclog(L"registerPrinter: ITC_CloseDeviceUtility() failed with error %i\r\n", iRes); - iResult=-7; - } - - nclog(L"registerPrinter: ITC_InitializeDeviceUtility() finished\r\n"); - } - else - { - nclog(L"registerPrinter: ITC_InitializeDeviceUtility() failed\r\n"); - return -1; - }//ITC_InitializeDeviceUtility - - return iResult; -} - -int doTestPrintESCP(TCHAR* szComPort) -{ - int iRet = 0; - nclog(_T("doTestPrint: printing...\r\n")); - - HANDLE hPort; - DWORD dwNumBytesWritten; -// TCHAR buf[1024+1]; // Printers expect regular chars but they'll throw away the nulls in the unicode - - hPort = CreateFile(szComPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - - if(hPort == INVALID_HANDLE_VALUE) - { - iRet=GetLastError(); - nclog(_T("doTestPrint: Unable to connect to printer at '%s', err=%i\r\n"), szComPort, iRet); - nclog(_T("doTestPrint: ...exit printing\r\n")); - //AfxMessageBox(_T("Unable to connect to printer."); - return iRet; - } - - nclog(_T("doTestPrint: connected...\r\n")); - - //TEST with FingerPrint - if (!WriteFile(hPort, csESCP, wcslen(csESCP) * sizeof(TCHAR), &dwNumBytesWritten, NULL)) { - iRet = GetLastError(); - nclog(_T("doTestPrint: Print error: %i\r\n"), iRet); - CloseHandle(hPort); - return iRet; - } - // AfxMessageBox(_T("Print error"); - - nclog(_T("doTestPrint: WriteFile did %i bytes\r\n"), dwNumBytesWritten); - - Sleep(2000); // Allow time to finish printing before closing the handle. Workaround for VM data flush issue - CloseHandle(hPort); - nclog(_T("doTestPrint: ...finished printing\r\n")); - - return 0; -} - -int doTestPrintFP(TCHAR* szComPort) -{ - nclog(L"doTestPrint: printing to '%s'...\r\n", szComPort); - int iRet=0; - - HANDLE hPort; - DWORD dwNumBytesWritten; -// TCHAR buf[1024+1]; // Printers expect regular chars but they'll throw away the nulls in the unicode - - hPort = CreateFile(szComPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - - if(hPort == INVALID_HANDLE_VALUE) - { - iRet=GetLastError(); - nclog(_T("doTestPrint: Unable to connect to printer at '%s', err=%i\r\n"), szComPort, iRet); - nclog(_T("doTestPrint: ...exit printing\r\n")); - return iRet; - } - - nclog(_T("doTestPrint: connected...\r\n")); - - //TEST with FingerPrint - if (!WriteFile(hPort, csFP, wcslen(csFP) * sizeof(TCHAR), &dwNumBytesWritten, NULL)) { - iRet = GetLastError(); - nclog(_T("doTestPrint: Print error: %i\r\n"), iRet); - CloseHandle(hPort); - return iRet; - // AfxMessageBox(_T("Print error"); - } - - nclog(_T("doTestPrint: WriteFile did %i bytes\r\n"), dwNumBytesWritten); - - Sleep(2000); // Allow time to finish printing before closing the handle. Workaround for VM data flush issue - CloseHandle(hPort); - nclog(_T("doTestPrint: ...finished printing\r\n")); - - return 0; -} - -BOOL APIENTRY DllMain( HANDLE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - switch (ul_reason_for_call){ - case DLL_PROCESS_ATTACH: - nclogEnable(FALSE); //enable or disable logging - nclog(L"SetBTPrinter DllMain: DLL_PROCESS_ATTACH\n"); - return TRUE; - case DLL_THREAD_ATTACH: - nclog(L"SetBTPrinter DllMain: DLL_THREAD_ATTACH\n"); - return TRUE; - case DLL_THREAD_DETACH: - nclog(L"SetBTPrinter DllMain: DLL_THREAD_DETACH\n"); - return TRUE; - case DLL_PROCESS_DETACH: - nclog(L"SetBTPrinter DllMain: DLL_PROCESS_DETACH\n"); - return TRUE; - default: - nclog(L"SetBTPrinter DllMain: default\n"); - return TRUE; - - } -} - - diff --git a/CommAppCFbtSearch/SetBTprinter/SetBTprinter.def b/CommAppCFbtSearch/SetBTprinter/SetBTprinter.def deleted file mode 100644 index 83d718a..0000000 --- a/CommAppCFbtSearch/SetBTprinter/SetBTprinter.def +++ /dev/null @@ -1,9 +0,0 @@ -; SetBTprinter.def : Declares the module parameters for the DLL. - -LIBRARY "SetBTprinter" - -EXPORTS - ; Explicit exports can go here - registerPrinter - doTestPrintFP - doTestPrintESCP \ No newline at end of file diff --git a/CommAppCFbtSearch/SetBTprinter/SetBTprinter.h b/CommAppCFbtSearch/SetBTprinter/SetBTprinter.h deleted file mode 100644 index 7611e58..0000000 --- a/CommAppCFbtSearch/SetBTprinter/SetBTprinter.h +++ /dev/null @@ -1,10 +0,0 @@ -//#include "C:/Programme/IBM/DeviceDeveloper/wsdd5.0/ive-2.2/runtimes/linux/x86/ppro10/bin/include/jni.h" -//#include "ijni.h" - -//the pswdm0c API -#include "include/pswdm0c.h" -#pragma comment (lib, "lib/pswdm0cDLL.lib") - -#ifndef _Included_SetBTprinterClass -#define _Included_SetBTprinterClass -#endif \ No newline at end of file diff --git a/CommAppCFbtSearch/SetBTprinter/SetBTprinter.vcproj b/CommAppCFbtSearch/SetBTprinter/SetBTprinter.vcproj deleted file mode 100644 index c989389..0000000 --- a/CommAppCFbtSearch/SetBTprinter/SetBTprinter.vcproj +++ /dev/null @@ -1,250 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/CommAppCFbtSearch/SetBTprinter/nclog.cpp b/CommAppCFbtSearch/SetBTprinter/nclog.cpp deleted file mode 100644 index 728bfe9..0000000 --- a/CommAppCFbtSearch/SetBTprinter/nclog.cpp +++ /dev/null @@ -1,241 +0,0 @@ -// --- nclog.cpp --- - -//#include "winsock.h" -#include "winsock2.h" -#pragma comment (lib, "ws2.lib") - -#include -#include - -static SOCKET wsa_socket=INVALID_SOCKET; -#pragma comment(lib , "winsock") - -static unsigned short theLogPort=9998; - -//file stuff -//global -static char logFileName[MAX_PATH]; -static TCHAR logFileNameW[MAX_PATH]; -static BOOL bFirstFileCall = true; -static int iUseLogging=0; - -//max log file size ~250KByte -#define MAX_LOG_SIZE 0x0002FFFF - -// enable disable logging globally -void nclogEnable(BOOL bEnable){ - if(bEnable) - iUseLogging=1; - else - iUseLogging=0; -} - -// bind the log socket to a specific port. -static bool wsa_bind(unsigned short port) -{ - SOCKADDR_IN addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = htonl(INADDR_ANY); - int r=bind(wsa_socket,(sockaddr*)&addr,sizeof(addr)); - if (r==0) - theLogPort=port; - return (r==0); -} - -// initialize everything, if the socket isn't open. -static bool wsa_init() -{ - //already loaded? - if (wsa_socket != INVALID_SOCKET) return true; - - int r; - WSADATA wd; - BOOL bc=true; - - if (0 != WSAStartup(0x101, &wd)) - goto error; - wsa_socket=socket(PF_INET, SOCK_DGRAM, 0); - if (wsa_socket == INVALID_SOCKET) - goto error; - r=setsockopt(wsa_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bc, sizeof(bc)); - if (r!=0) - goto error; - if (wsa_bind(theLogPort)) - return true; // bind to default port. - error: - if (wsa_socket != INVALID_SOCKET) - closesocket(wsa_socket); -#ifdef DEBUG - OutputDebugString(TEXT("nclog: TCP/IP Problem")); -#endif - return false; - -} - -// can be called externally to select a different port for operations -bool set_nclog_port(unsigned short x) { return wsa_bind(x); } - -static void wsa_send(const char *x) -{ - SOCKADDR_IN sa; - sa.sin_family = AF_INET; - sa.sin_port = htons(theLogPort); - sa.sin_addr.s_addr = htonl(INADDR_BROADCAST); - - if (SOCKET_ERROR == sendto(wsa_socket,x,strlen(x), 0, (sockaddr*) &sa, sizeof(sa))) - { -#ifdef DEBUG - //if (debug_mode) -// OutputDebugString(TEXT("nclog: Send Error")); -#endif - } - -} - -//========================== start of file stuff ============================= -static int initFileNames() -{ - // Get name of executable - TCHAR lpFileName[MAX_PATH+1]; - GetModuleFileName(NULL, lpFileName, MAX_PATH); //lpFileName will contain the exe name of this running app! - //add txt extension - TCHAR txtFileName[MAX_PATH+1]; - wsprintf(txtFileName, L"%s.log.txt", lpFileName); - //store the filename to use in char and tchar - TCHAR logFileNameW[MAX_PATH]; - wsprintf(logFileNameW, txtFileName); - wcstombs(logFileName, logFileNameW, sizeof(logFileNameW)*sizeof(logFileNameW[0])); - - FILE *fp; - fp = fopen(logFileName, "a+"); - //get the file size - if(fseek(fp, 0, SEEK_END)==0){ - long iEnd = ftell(fp); - if(iEnd > MAX_LOG_SIZE) - { - fclose(fp); - fp=fopen(logFileName, "w+"); //creates an empty file - } - } - - fclose(fp); - bFirstFileCall=false; - return 0; -} - -TCHAR* logDateTime(){ - static TCHAR str[64]; - TCHAR lpTimeStr[32]; - TCHAR lpDateStr[32]; - LONG res; - wsprintf(str,L""); - //Read the system time - res = GetTimeFormat(LOCALE_SYSTEM_DEFAULT, - TIME_FORCE24HOURFORMAT, - NULL, - L"hh:mm:ss", - lpTimeStr, - sizeof (lpTimeStr ) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpTimeStr, L"err"); - } - - //Read the system date - res = GetDateFormat( LOCALE_SYSTEM_DEFAULT, - NULL, - NULL, - L"dd.MM.yyyy", - lpDateStr, - sizeof (lpDateStr) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpDateStr, L"err"); - } - - //wsprintf(str, L"Date and Time: %s %s", lpDateStr, lpTimeStr); - wsprintf(str, L"%s %s", lpDateStr, lpTimeStr); - return str; -} - -static int writefile(TCHAR *filetext){ - /* File Write Function, written by professor chemicalX */ - FILE *fp; /* Declare FILE structure */ - TCHAR szTemp[255]; - char szTempA[255]; - - wsprintf(szTemp, L"%s", filetext); - wcstombs(szTempA, szTemp, sizeof(szTemp)/sizeof(TCHAR)); - - if (bFirstFileCall){ - // Get name of executable - initFileNames(); - } - - fp = fopen(logFileName, "a+"); - - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - /* First of we open the file supplied by the filename paremeter */ - - /* - * in the "a+" mode for appending, so if it doesnt exist its created. - * fp = fopen(filename,"w"); // Open using the "w" mode for writing. - */ - long fsize = strlen(szTempA); /* Declare the long fsize with the length of the filetext */ - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - /* paremeter witch stores the text or data to right to the file. */ - fwrite(szTempA, 1, fsize, fp); /* Write File */ - fclose(fp); /* Remember to close the file stream after calling file functions, */ - - /* otherwise the file wont be created. */ - return 0; -} -//========================== end of file stuff ============================= - -// format input, convert to 8-bit and send. -void nclog (const wchar_t *fmt, ...) -{ - if(iUseLogging==1){ - TCHAR StrW[1024]; - va_list vl; - va_start(vl,fmt); - wchar_t buf[1024]; // to bad CE hasn't got wvnsprintf - wvsprintf(buf,fmt,vl); - wsa_init(); - char bufOut[512]; - - //insert data/time - wsprintf(StrW, L"%s: %s", logDateTime(), buf); - wsprintf(buf, L"%s", StrW); - - WideCharToMultiByte(CP_ACP,0,buf,-1,bufOut,400, NULL, NULL); - - wsa_send(bufOut); - - writefile(buf); -#ifdef DEBUG - DEBUGMSG(1, (buf)); -#else - RETAILMSG(1, (buf)); -#endif - }//iUseLogging -} - -// finalize the socket on program termination. -struct _nclog_module -{ - ~_nclog_module() - { - if (wsa_socket!=INVALID_SOCKET) - { - nclog(L"nclog goes down\n"); - shutdown(wsa_socket,2); - closesocket(wsa_socket); - } - } - -}; - -static _nclog_module module; diff --git a/CommAppCFbtSearch/SetBTprinter/nclog.h b/CommAppCFbtSearch/SetBTprinter/nclog.h deleted file mode 100644 index 854c0bf..0000000 --- a/CommAppCFbtSearch/SetBTprinter/nclog.h +++ /dev/null @@ -1,24 +0,0 @@ -//nclog.h - - -extern void nclog (const wchar_t *fmt, ...); -//extern bool set_nclog_port(unsigned short x) { return wsa_bind(x); } -extern TCHAR* logDateTime(); -extern void nclogEnable(BOOL bEnable); - -/* -usage: - nclog(L"The Window Handle is: %x\n",hwnd); - -On your desktop, you need netcat to capture the output from your -program, i.e. you open a console and type: - -netcat -lup 9998 - -This will instruct netcat to show you everything that comes to your UDP -socket 9998 (which is the default for netcat). Since nclog opens the -socket in broadcast mode, you don't have to give an target adress. (Be -sure to select a port which does not interfer with the network you are -living in) - -*/ \ No newline at end of file diff --git a/CommAppCFbtSearch/SetBTprinter/stdafx.cpp b/CommAppCFbtSearch/SetBTprinter/stdafx.cpp deleted file mode 100644 index b6d406b..0000000 --- a/CommAppCFbtSearch/SetBTprinter/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// SetBTprinter.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/CommAppCFbtSearch/SetBTprinter/stdafx.h b/CommAppCFbtSearch/SetBTprinter/stdafx.h deleted file mode 100644 index 57ae26c..0000000 --- a/CommAppCFbtSearch/SetBTprinter/stdafx.h +++ /dev/null @@ -1,54 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include -#pragma comment(lib, "aygshell.lib") - - -// Windows Header Files: -#include - - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here diff --git a/CommAppCFbtSearch/bin/CommAppCFbtSearch.exe b/CommAppCFbtSearch/bin/CommAppCFbtSearch.exe deleted file mode 100644 index 305ba9e..0000000 Binary files a/CommAppCFbtSearch/bin/CommAppCFbtSearch.exe and /dev/null differ diff --git a/CommAppCFbtSearch/bin/SetBTprinter.dll b/CommAppCFbtSearch/bin/SetBTprinter.dll deleted file mode 100644 index 4aca93f..0000000 Binary files a/CommAppCFbtSearch/bin/SetBTprinter.dll and /dev/null differ diff --git a/CommAppCFbtSearch/doc/BluetoothConnect.gif b/CommAppCFbtSearch/doc/BluetoothConnect.gif deleted file mode 100644 index b8171a1..0000000 Binary files a/CommAppCFbtSearch/doc/BluetoothConnect.gif and /dev/null differ diff --git a/CommAppCFbtSearch/doc/FileSelect.gif b/CommAppCFbtSearch/doc/FileSelect.gif deleted file mode 100644 index 472621c..0000000 Binary files a/CommAppCFbtSearch/doc/FileSelect.gif and /dev/null differ diff --git a/CommAppCFbtSearch/doc/connectDlg.gif b/CommAppCFbtSearch/doc/connectDlg.gif deleted file mode 100644 index 4dbba3b..0000000 Binary files a/CommAppCFbtSearch/doc/connectDlg.gif and /dev/null differ diff --git a/CommAppCFbtSearch/doc/screen_01.gif b/CommAppCFbtSearch/doc/screen_01.gif deleted file mode 100644 index 514d1bd..0000000 Binary files a/CommAppCFbtSearch/doc/screen_01.gif and /dev/null differ diff --git a/CommAppCFbtSearch/escp_test.txt b/CommAppCFbtSearch/escp_test.txt deleted file mode 100644 index 4570d88..0000000 --- a/CommAppCFbtSearch/escp_test.txt +++ /dev/null @@ -1,33 +0,0 @@ -w1G -w! -ROUTE# 227 11/08/01 08:35 - - Food City #3212 - 1500 E Lincoln Way - Hamilton OH - TAX ID# A32102 - - ITEM# DESCRIPTION NET - QTY PRICE DEPOS ALLOW - - SALES - - 1001 Reg Cola 6pk 12cn 63.50 - 5 11.50 1.20 0.00 - - 1002 Diet Cola 6pk 12cn 38.10 - 3 11.50 1.20 0.00 - - CREDITS SALES -PRODUCT 0.00 101.60 -SUBTOTAL 101.60 -5% State Tax 5.08 - ------------- -BALANCE DUE: CHARGE 106.68 - ============= - - Thank You For Your Business - - - - diff --git a/CommAppCFbtSearch/fp_test.txt b/CommAppCFbtSearch/fp_test.txt deleted file mode 100644 index 74a6a98..0000000 --- a/CommAppCFbtSearch/fp_test.txt +++ /dev/null @@ -1,12 +0,0 @@ -NEW -1 BARFONT ON -2 BARFONT "Swiss 721 BT", 6 -10 PRPOS 10,10 -20 PRBOX 430,340,15 -50 PRPOS 75,27060 BARTYPE "CODE39"70 PRBAR "ABC"80 PRPOS 25,220 -90 FONT "Swiss 721 BT", 6 -100 PRTXT "My FIRST label" -200 PRINTFEED -300 END -RUN - diff --git a/CommAppCFbtSearch/hexHelper.cs b/CommAppCFbtSearch/hexHelper.cs deleted file mode 100644 index fdf121b..0000000 --- a/CommAppCFbtSearch/hexHelper.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Runtime.InteropServices; - - -public static class hexHelper -{ - public static byte[] reverseBytes(byte[] inB) - { - byte[] bOut = new byte[inB.Length]; - int iLast = inB.Length - 1; - for (int i = 0; i < inB.Length; i++) - { - bOut[i] = inB[iLast - i]; - } - return bOut; - } - public static bool IsHexDigit(Char c) - { - int numChar; - int numA = Convert.ToInt32('A'); - int num1 = Convert.ToInt32('0'); - c = Char.ToUpper(c); - numChar = Convert.ToInt32(c); - if (numChar >= numA && numChar < (numA + 6)) - return true; - if (numChar >= num1 && numChar < (num1 + 10)) - return true; - return false; - } - public static byte[] GetBytes(string hexString, out int discarded) - { - discarded = 0; - string newString = ""; - char c; - // remove all none A-F, 0-9, characters - for (int i = 0; i < hexString.Length; i++) - { - c = hexString[i]; - if (IsHexDigit(c)) - newString += c; - else - discarded++; - } - // if odd number of characters, discard last character - if (newString.Length % 2 != 0) - { - discarded++; - newString = newString.Substring(0, newString.Length - 1); - } - - int byteLength = newString.Length / 2; - byte[] bytes = new byte[byteLength]; - string hex; - int j = 0; - for (int i = 0; i < bytes.Length; i++) - { - hex = new String(new Char[] { newString[j], newString[j + 1] }); - bytes[i] = HexToByte(hex); - j = j + 2; - } - return bytes; - } - private static byte HexToByte(string hex) - { - if (hex.Length > 2 || hex.Length <= 0) - throw new ArgumentException("hex must be 1 or 2 characters in length"); - byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber); - return newByte; - } - public static string ToString(byte[] bytes) - { - string hexString = ""; - for (int i = 0; i < bytes.Length; i++) - { - hexString += bytes[i].ToString("X2"); - //if (i <= bytes.Length - 1) - // hexString += "-"; - } - return hexString; - } - -} - diff --git a/CommAppCFbtSearch/serialSet.cs b/CommAppCFbtSearch/serialSet.cs deleted file mode 100644 index e712d90..0000000 --- a/CommAppCFbtSearch/serialSet.cs +++ /dev/null @@ -1,512 +0,0 @@ -using System; -using System.IO.Ports; -using System.Collections.Generic; -using System.Text; -using Microsoft.Win32; -using System.Diagnostics; - -namespace CommAppCFbtSearch -{ - class serialSet : IDisposable - { - // Track whether Dispose has been called. - private bool disposed = false; - - private const string _regSubKey = @"Software\CommAppCF"; - private RegistryKey _regKey; - - private RegistryValueKind[] _regValueTypes = - { RegistryValueKind.String, - RegistryValueKind.DWord , - RegistryValueKind.DWord , - RegistryValueKind.DWord , - RegistryValueKind.DWord , - RegistryValueKind.DWord - }; - private string[] _regValueNames = - { "port", - "baudrate" , - "parity", - "databits", - "stopbits", - "handshake" - }; - - private const string _regValueNameTimeInterval = "TimeInterval"; - private const string _regValueLog2File = "Log2File"; - - public serialSet() - { - //try to read settings from Reg - if (regOpenKey()) - { - regReadSettings(); - } - else - this.Dispose(); - - } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - private void Dispose(bool disposing) - { - // Check to see if Dispose has already been called. - if (!this.disposed) - { - // If disposing equals true, dispose all managed - // and unmanaged resources. - if (disposing) - { - // Dispose managed resources. - //save settings? - regWriteSettings(); - regCloseKey(); - //component.Dispose(); - } - - // Call the appropriate methods to clean up - // unmanaged resources here. - // If disposing is false, - // only the following code is executed. - //CloseHandle(handle); - //handle = IntPtr.Zero; - - // Note disposing has been done. - disposed = true; - - } - } - - private bool regReadSettings() - { - if (_regKey == null) - return false; - - string s = ""; - uint d = 0; - //try to read settings - for (int x = 0; x < _regValueNames.Length; x++) - { - if (_regValueTypes[x] == RegistryValueKind.String) - { - s = regReadString(_regValueNames[x]); - } - else if (_regValueTypes[x] == RegistryValueKind.DWord) - { - d = regReadUInt(_regValueNames[x]); - } - switch (x) - { - case 0: if(s.Length>0) - _sPort = s; - break; - case 1: if(d>0) - _baudRate = d; - break; - case 2: if (d >= 0) - _parity = d; - break; - case 3: if (d > 0) - _databits = d; - break; - case 4: if (d > 0) - _stopBits = d; - break; - case 5: if (d >= 0) - _handshake = d; - break; - } - } - - return true; - } - public int saveSettings() - { - if (this.regWriteSettings()) - return 0; - else - return -1; - } - private bool regWriteSettings() - { - regWriteString(_regValueNames[0], _sPort); - regWriteInt(_regValueNames[1], _baudRate); - regWriteInt(_regValueNames[2], _parity); - regWriteInt(_regValueNames[3], _databits); - regWriteInt(_regValueNames[4], _stopBits); - regWriteInt(_regValueNames[5], _handshake); - - return true; - } - #region REGISTRY - private int regReadInt(string sValuename) - { - if (_regKey == null) - return -1; - try - { - int i = (int)_regKey.GetValue(sValuename, -1); - return i; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return -1; - } - private uint regReadUInt(string sValuename) - { - if (_regKey == null) - return 0; - try - { - int i = (int)_regKey.GetValue(sValuename, 0); - return (uint)i; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadUInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return 0; - } - private bool regWriteInt(string sValuename, uint i) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, i, RegistryValueKind.DWord); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteUInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return false; - } - private bool regWriteInt(string sValuename, int i) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, i, RegistryValueKind.DWord); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return false; - } - - private string regReadString(string sValuename) - { - if (_regKey == null) - return null; - try - { - string s = (string)_regKey.GetValue(sValuename, ""); - return s; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadStrings for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return null; - } - - private string[] regReadStrings(string sValuename) - { - if (_regKey == null) - return null; - try - { - string[] s = (string[])_regKey.GetValue(sValuename, ""); - return s; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadStrings for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return null; - } - private bool regWriteString(string sValuename, string s) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, s); - _regKey.Flush(); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteStrings for '" + _regSubKey + "'. " + x.Message); - return false; - } - } - - private bool regWriteStrings(string sValuename, string[] s) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, s); - _regKey.Flush(); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteStrings for '" + _regSubKey + "'. " + x.Message); - return false; - } - } - private bool regOpenKey() - { - try - { - _regKey = Registry.LocalMachine.CreateSubKey(_regSubKey); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in OpenSubKey/CreateSubKey for '" + _regSubKey + "'. " + x.Message); - } - return false; - } - private void regCloseKey() - { - if (_regKey != null) - { - try - { - Registry.LocalMachine.Close(); - } - catch (Exception x) - { - Debug.WriteLine("Exception in CloseKey for '" + _regSubKey + "'. " + x.Message); - } - } - } -#endregion - #region FIELDS - private string _sPort="COM0"; - public string sPort - { - get { return _sPort; } - set { _sPort = value; } - } - private uint[] _baudRates = { 1200, 2400, 4800, 9600, 19200, 38200, 57600, 115200, 230400, 460800, 921600 }; - public uint[] baudRates - { - get { return _baudRates; } - } - private uint _baudRate = 1200; - public uint baudRate - { - get { return _baudRate; } - set { _baudRate = value; } - } - private uint _parity = 0; - public uint parity - { - get { return _parity; } - set { _parity = value; } - } - private uint _databits = 8; - public uint databits - { - get { return _databits; } - set { _databits = value; } - } - private uint _stopBits = 1; - public uint stopBits - { - get { return _stopBits; } - set { _stopBits = value; } - } - private uint _handshake = 0; - public uint handshake - { - get { return _handshake; } - set { _handshake = value; } - } - #endregion - - } - public static class myParity - { - public static string[] parity = { "None", "Odd", "Even", "Mark", "Space" }; - public static int ToInt(string s) - { - for (int i = 0; i < parity.Length; i++) - { - if(s.Equals(parity[i],StringComparison.OrdinalIgnoreCase)) - return i; - } - return 0; - } - public static string ToString(int i) - { - return parity[i]; - } - public static Parity ToParity(int i) - { - switch (i) - { - case 0: - return Parity.None; - case 1: - return Parity.Odd; - case 2: - return Parity.Even; - case 3: - return Parity.Mark; - case 4: - return Parity.Space; - } - return Parity.None; - } - public static Parity ToParity(string text) - { - if (text.Equals("None", StringComparison.OrdinalIgnoreCase)) - return Parity.None; - if (text.Equals("Odd", StringComparison.OrdinalIgnoreCase)) - return Parity.Odd; - if (text.Equals("Even", StringComparison.OrdinalIgnoreCase)) - return Parity.Even; - if (text.Equals("Mark", StringComparison.OrdinalIgnoreCase)) - return Parity.Mark; - if (text.Equals("Space", StringComparison.OrdinalIgnoreCase)) - return Parity.Space; - - return Parity.None; - } - }//class myParity - public static class myStopBits - { - public static StopBits ToStopBits(string text) - { - if (text.Equals("None", StringComparison.OrdinalIgnoreCase)) - return StopBits.None; - if (text.Equals("One", StringComparison.OrdinalIgnoreCase)) - return StopBits.One; - if (text.Equals("Two", StringComparison.OrdinalIgnoreCase)) - return StopBits.Two; - if (text.Equals("OnePointFive", StringComparison.OrdinalIgnoreCase)) - return StopBits.OnePointFive; - - return StopBits.One; - } - public static StopBits ToStopBits(int i) - { - switch (i) - { - case 0: return StopBits.None; - case 1: return StopBits.One; - case 2: return StopBits.Two; - case 3: return StopBits.OnePointFive; - } - return StopBits.One; - } - public static string ToString(StopBits sb) - { - switch (sb) - { - case StopBits.None: return "None"; - case StopBits.One: return "One"; - case StopBits.Two: return "Two"; - case StopBits.OnePointFive: return "OnePointFive"; - } - return "One"; - } - public static string ToString(int i) - { - switch (i) - { - case 0: return "None"; - case 1: return "One"; - case 2: return "Two"; - case 3: return "OnePointFive"; - } - return "One"; - } - public static int ToInt(StopBits sb) - { - switch (sb) - { - case StopBits.None: return 0; - case StopBits.One: return 1; - case StopBits.Two: return 2; - case StopBits.OnePointFive: return 3; - } - return 1; - } - }//class myStopbits - public static class myHandshake - { - public static string[] handshakes = { "None", "XOnXOff", "RequestToSend", "RequestToSendXOnXOff" }; - public static Handshake ToHandshake(int i) - { - switch (i) - { - case 0: return Handshake.None; - case 1: return Handshake.XOnXOff; - case 2: return Handshake.RequestToSend; - case 3: return Handshake.RequestToSendXOnXOff; - } - return Handshake.None; - } - public static Handshake ToHandshake(string text) - { - if (text.Equals("None", StringComparison.OrdinalIgnoreCase)) - return Handshake.None; - if (text.Equals("XOnXOff", StringComparison.OrdinalIgnoreCase)) - return Handshake.XOnXOff; - if (text.Equals("RequestToSend", StringComparison.OrdinalIgnoreCase)) - return Handshake.RequestToSend; - if (text.Equals("RequestToSendXOnXOff", StringComparison.OrdinalIgnoreCase)) - return Handshake.RequestToSendXOnXOff; - return Handshake.None; - } - public static int ToInt(Handshake hs) - { - switch (hs) - { - case Handshake.None: return 0; - case Handshake.XOnXOff: return 1; - case Handshake.RequestToSend: return 2; - case Handshake.RequestToSendXOnXOff: return 3; - } - return 0; - } - public static string ToString(Handshake hs) - { - switch (hs) - { - case Handshake.None: return "None"; - case Handshake.XOnXOff: return "XOnXOff"; - case Handshake.RequestToSend: return "RequestToSend"; - case Handshake.RequestToSendXOnXOff: return "RequestToSendXOnXOff"; - } - return "None"; - } - public static string ToString(int i) - { - switch (i) - { - case 0: return "None"; - case 1: return "XOnXOff"; - case 2: return "RequestToSend"; - case 3: return "RequestToSendXOnXOff"; - } - return "None"; - } - }//class myHandshake -} diff --git a/HideStartWM61/HideStartWM61.sln b/HideStartWM61/HideStartWM61.sln deleted file mode 100644 index e800e24..0000000 --- a/HideStartWM61/HideStartWM61.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HideStartWM61", "HideStartWM61\HideStartWM61.csproj", "{F8D641A7-1577-4ECC-8C9B-A2A21B30505E}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {F8D641A7-1577-4ECC-8C9B-A2A21B30505E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F8D641A7-1577-4ECC-8C9B-A2A21B30505E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F8D641A7-1577-4ECC-8C9B-A2A21B30505E}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {F8D641A7-1577-4ECC-8C9B-A2A21B30505E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F8D641A7-1577-4ECC-8C9B-A2A21B30505E}.Release|Any CPU.Build.0 = Release|Any CPU - {F8D641A7-1577-4ECC-8C9B-A2A21B30505E}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/HideStartWM61/HideStartWM61.suo b/HideStartWM61/HideStartWM61.suo deleted file mode 100644 index 4640297..0000000 Binary files a/HideStartWM61/HideStartWM61.suo and /dev/null differ diff --git a/HideStartWM61/HideStartWM61/Form1.Designer.cs b/HideStartWM61/HideStartWM61/Form1.Designer.cs deleted file mode 100644 index 3fb9071..0000000 --- a/HideStartWM61/HideStartWM61/Form1.Designer.cs +++ /dev/null @@ -1,64 +0,0 @@ -namespace HideStartWM61 -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.button1 = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // button1 - // - this.button1.Location = new System.Drawing.Point(66, 87); - this.button1.Name = "button1"; - this.button1.Size = new System.Drawing.Size(113, 35); - this.button1.TabIndex = 0; - this.button1.Text = "button1"; - this.button1.Click += new System.EventHandler(this.button1_Click); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.Controls.Add(this.button1); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "Form1"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Button button1; - } -} - diff --git a/HideStartWM61/HideStartWM61/Form1.cs b/HideStartWM61/HideStartWM61/Form1.cs deleted file mode 100644 index 108ccfa..0000000 --- a/HideStartWM61/HideStartWM61/Form1.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace HideStartWM61 -{ - public partial class Form1 : Form - { - bool bToggle = false; - public Form1() - { - InitializeComponent(); - } - void showStart(bool bShowHide) - { - KioskTest.SHAPI.showStart(this.Handle, bToggle); - bToggle = !bToggle; - } - - private void button1_Click(object sender, EventArgs e) - { - showStart(bToggle); - } - } -} \ No newline at end of file diff --git a/HideStartWM61/HideStartWM61/Form1.resx b/HideStartWM61/HideStartWM61/Form1.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/HideStartWM61/HideStartWM61/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/HideStartWM61/HideStartWM61/HideStartWM61.csproj b/HideStartWM61/HideStartWM61/HideStartWM61.csproj deleted file mode 100644 index 58861f2..0000000 --- a/HideStartWM61/HideStartWM61/HideStartWM61.csproj +++ /dev/null @@ -1,94 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {F8D641A7-1577-4ECC-8C9B-A2A21B30505E} - WinExe - Properties - HideStartWM61 - HideStartWM61 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - b2c48bd2-963d-4549-9169-1fa021dce484 - 5.02 - HideStartWM61 - v2.0 - Windows Mobile 6 Professional SDK - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - Form - - - Form1.cs - - - - - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - - - \ No newline at end of file diff --git a/HideStartWM61/HideStartWM61/HideStartWM61.csproj.user b/HideStartWM61/HideStartWM61/HideStartWM61.csproj.user deleted file mode 100644 index 15b7820..0000000 --- a/HideStartWM61/HideStartWM61/HideStartWM61.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - e4fc2bc5-3ac4-452c-a893-ad4f273c3a7c - false - - \ No newline at end of file diff --git a/HideStartWM61/HideStartWM61/Program.cs b/HideStartWM61/HideStartWM61/Program.cs deleted file mode 100644 index 8a7bdab..0000000 --- a/HideStartWM61/HideStartWM61/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace HideStartWM61 -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/HideStartWM61/HideStartWM61/Properties/AssemblyInfo.cs b/HideStartWM61/HideStartWM61/Properties/AssemblyInfo.cs deleted file mode 100644 index 63d3fc4..0000000 --- a/HideStartWM61/HideStartWM61/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("HideStartWM61")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("HideStartWM61")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("27726f1e-f27a-4f73-b406-7c540e9fb8a0")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/HideStartWM61/HideStartWM61/Properties/Resources.Designer.cs b/HideStartWM61/HideStartWM61/Properties/Resources.Designer.cs deleted file mode 100644 index 9af690a..0000000 --- a/HideStartWM61/HideStartWM61/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5477 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace HideStartWM61.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("HideStartWM61.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/HideStartWM61/HideStartWM61/Properties/Resources.resx b/HideStartWM61/HideStartWM61/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/HideStartWM61/HideStartWM61/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/HideStartWM61/HideStartWM61/bin/Debug/HideStartWM61.exe b/HideStartWM61/HideStartWM61/bin/Debug/HideStartWM61.exe deleted file mode 100644 index b9dfc2a..0000000 Binary files a/HideStartWM61/HideStartWM61/bin/Debug/HideStartWM61.exe and /dev/null differ diff --git a/HideStartWM61/HideStartWM61/bin/Debug/HideStartWM61.pdb b/HideStartWM61/HideStartWM61/bin/Debug/HideStartWM61.pdb deleted file mode 100644 index 6805857..0000000 Binary files a/HideStartWM61/HideStartWM61/bin/Debug/HideStartWM61.pdb and /dev/null differ diff --git a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.Form1.resources b/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.Form1.resources deleted file mode 100644 index 06c24d0..0000000 Binary files a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.Form1.resources and /dev/null differ diff --git a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.Properties.Resources.resources b/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.Properties.Resources.resources deleted file mode 100644 index 06c24d0..0000000 Binary files a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.Properties.Resources.resources and /dev/null differ diff --git a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.csproj.FileListAbsolute.txt b/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.csproj.FileListAbsolute.txt deleted file mode 100644 index 76b9781..0000000 --- a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.csproj.FileListAbsolute.txt +++ /dev/null @@ -1,8 +0,0 @@ -D:\c-source\Active\HideStartWM61\HideStartWM61\bin\Debug\HideStartWM61.exe -D:\c-source\Active\HideStartWM61\HideStartWM61\bin\Debug\HideStartWM61.pdb -D:\c-source\Active\HideStartWM61\HideStartWM61\obj\Debug\ResolveAssemblyReference.cache -D:\c-source\Active\HideStartWM61\HideStartWM61\obj\Debug\HideStartWM61.Form1.resources -D:\c-source\Active\HideStartWM61\HideStartWM61\obj\Debug\HideStartWM61.Properties.Resources.resources -D:\c-source\Active\HideStartWM61\HideStartWM61\obj\Debug\HideStartWM61.csproj.GenerateResource.Cache -D:\c-source\Active\HideStartWM61\HideStartWM61\obj\Debug\HideStartWM61.exe -D:\c-source\Active\HideStartWM61\HideStartWM61\obj\Debug\HideStartWM61.pdb diff --git a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.csproj.GenerateResource.Cache b/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.csproj.GenerateResource.Cache deleted file mode 100644 index bea115c..0000000 Binary files a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.csproj.GenerateResource.Cache and /dev/null differ diff --git a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.exe b/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.exe deleted file mode 100644 index b9dfc2a..0000000 Binary files a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.exe and /dev/null differ diff --git a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.pdb b/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.pdb deleted file mode 100644 index 6805857..0000000 Binary files a/HideStartWM61/HideStartWM61/obj/Debug/HideStartWM61.pdb and /dev/null differ diff --git a/HideStartWM61/HideStartWM61/shFullScreen.cs b/HideStartWM61/HideStartWM61/shFullScreen.cs deleted file mode 100644 index fc7e002..0000000 --- a/HideStartWM61/HideStartWM61/shFullScreen.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using System.Drawing; -using System.Collections; -using System.Windows.Forms; -using System.Data; -using System.Runtime.InteropServices; - -namespace KioskTest -{ - public class SHAPI - { - public const int SHFS_SHOWTASKBAR = 1; - public const int SHFS_HIDETASKBAR = 2; - public const int SHFS_SHOWSIPBUTTON = 4; - public const int SHFS_HIDESIPBUTTON = 8; - public const int SHFS_SHOWSTARTICON = 16; - public const int SHFS_HIDESTARTICON = 32; - - [DllImport("aygshell.dll")] - private extern static bool SHFullScreen(IntPtr hWnd, int dwState); - - public static bool showStart(IntPtr wHandle, bool bShowHide) - { - bool bRet = false; - IntPtr hwnd = wHandle; - if (!bShowHide) - bRet = SHFullScreen(hwnd, SHFS_HIDESTARTICON); - else - bRet = SHFullScreen(hwnd, SHFS_SHOWSTARTICON); - return bRet; - } - - public static bool FullScreen(IntPtr hWnd) - { - return SHFullScreen(hWnd, SHFS_HIDESTARTICON | SHFS_HIDETASKBAR); - } - } - - public class API - { - [DllImport("coredll.dll", EntryPoint = "FindWindow")] - private extern static IntPtr FindWindow(string lpClassName, string - lpWindowName); - - public static IntPtr FindWindow(string windowName) - { - return FindWindow(null, windowName); - } - } - /* - public class Form1 : System.Windows.Forms.Form - { - public Form1() - { - System.Windows.Forms.Button button1 = new - System.Windows.Forms.Button(); - button1.Location = new System.Drawing.Point(48, 80); - button1.Size = new System.Drawing.Size(128, 48); - button1.Text = "button1"; - button1.Click += new System.EventHandler(this.button1_Click); - this.Controls.Add(button1); - - this.ClientSize = new System.Drawing.Size(240, 320); - this.Text = "KioskMode"; - - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - } - - static void Main() - { - System.Windows.Forms.Application.Run(new Form1()); - } - - private void button1_Click(object sender, System.EventArgs e) - { - IntPtr hWnd = API.FindWindow(this.Text); - if (hWnd != IntPtr.Zero) - { - this.MaximizeBox = false; - - this.MinimizeBox = false; - - this.Focus(); - - SHAPI.SetForegroundWindow(hWnd); - SHAPI.FullScreen(hWnd); - } - } - } - */ -} \ No newline at end of file diff --git a/HideStartWM61/doc/with_starticon.gif b/HideStartWM61/doc/with_starticon.gif deleted file mode 100644 index bc84cfa..0000000 Binary files a/HideStartWM61/doc/with_starticon.gif and /dev/null differ diff --git a/HideStartWM61/doc/without_starticon.gif b/HideStartWM61/doc/without_starticon.gif deleted file mode 100644 index 8baaecc..0000000 Binary files a/HideStartWM61/doc/without_starticon.gif and /dev/null differ diff --git a/KeyWedge/KeyWedge/Data_1.bin b/KeyWedge/KeyWedge/Data_1.bin deleted file mode 100644 index 35a0387..0000000 Binary files a/KeyWedge/KeyWedge/Data_1.bin and /dev/null differ diff --git a/KeyWedge/KeyWedge/KeyWedge.ICO b/KeyWedge/KeyWedge/KeyWedge.ICO deleted file mode 100644 index a5669a6..0000000 Binary files a/KeyWedge/KeyWedge/KeyWedge.ICO and /dev/null differ diff --git a/KeyWedge/KeyWedge/KeyWedge.cpp b/KeyWedge/KeyWedge/KeyWedge.cpp deleted file mode 100644 index e018a8f..0000000 --- a/KeyWedge/KeyWedge/KeyWedge.cpp +++ /dev/null @@ -1,1823 +0,0 @@ -// KeyWedge.cpp : Defines the entry point for the application. - -#pragma warning ( disable : 4244 4068 ) - -#define USE_SSAPI -#undef USE_SSAPI - -// -/* - REGEDIT4 - - [HKEY_LOCAL_MACHINE\SOFTWARE\HGO\KeyWedge] - "parity"=dword:00000000 - ; 0 NOPARITY - ; 1 ODDPARITY - ; 2 EVENPARITY - ; 3 MARKPARITY - ; 4 SPACEPARITY - "stopbits"=dword:00000000 - ; 0 ONESTOPBIT - ; 1 ONE5STOPBITS - ; 2 TWOSTOPBITS - "databits"=dword:00000008 - ; 7 - ; 8 - ; 16 - "handshake"=dword:00000003 - ; 1 Xon/Xoff - ; 2 Hardware - ; 3 None - "baudrate"=dword:0000e100 - ; 9600 - ; 19200 - ; 38400 - ; 57600 - ; 115200 - "comport"="COM4:" - ; string with trailing : - "sendcharbychar"=dword:00000000 - ; 1 send byte for byte as received, Post- and Preamble will not be used! - ; 0 send keys when \n received - "keytab"=hex:\ - 00,4e,55,4c,00,00,00,00,00,00,00,00,00,00,00,00,00,00,01,53,4f,48,00,00,00,\ - 00,00,00,00,00,00,00,00,00,00,00,02,53,54,58,00,00,00,00,00,00,00,00,00,00,\ - 00,00,00,00,03,45,54,58,00,00,00,00,00,00,00,00,00,00,00,00,00,00,04,45,4f,\ - 54,00,00,00,00,00,00,00,00,00,00,00,00,00,00,05,45,4e,51,00,00,00,00,00,00,....... - "postamble"="\r\n" - "preamble"="" - "BeepAfterRead"=dword:00000001 - "usecharsend"=dword:00000000 -*/ - -#ifdef USE_SSAPI - #pragma comment (user, "##### Compiled for use with SSAPI #####") - #pragma message ("##### Compiled for use with SSAPI #####") - #pragma exestr ("##### Compiled for use with SSAPI #####") -#else - #pragma comment (user, "##### Compiled for use without SSAPI #####") - #pragma message ("##### Compiled for use without SSAPI #####") - #pragma exestr ("##### Compiled for use without SSAPI #####") -#endif - -//#include "stdafx.h" - -#include // For all that Windows stuff -#include // Command bar includes -#include // Pocket PC includes -#pragma comment (lib, "aygshell.lib") - -#include "KeyWedge.h" - -#include "keymap.h" // a map with a translation table -#include "RegRW.h" -// #include "UIHelper.h" -#include "./common/nclog.h" - -#include "PowerMsgQueue.h" - -#define MAX_LOADSTRING 100 -#define BUFF_SIZE 1024 - -//fuer SmartSystems -// #define SSKEYWEDGE L"SSKeyWedge" // not used - const LPCWSTR pSubKey = L"SOFTWARE\\Intermec\\SSKeyWedge"; - -// Global Variables: -HKEY m_hKey; // the handle to the registry -HINSTANCE hInst; // The current instance -HWND hwndCB; // The command bar handle -HWND hwndMenuBar; // handle for menubar - -//removed in v1.3: BOOL b_MainWindowVisible=false; //new in v1.2 to track window is already loaded - -NOTIFYICONDATA nid; -TCHAR szAppName[MAX_LOADSTRING]; - -// Our DDB handle is a global variable. -HBITMAP hbm; - -HANDLE g_hSendEvent = INVALID_HANDLE_VALUE; -HANDLE hReadThread = INVALID_HANDLE_VALUE; - -// Forward declarations of functions included in this code module: -ATOM MyRegisterClass (HINSTANCE, LPTSTR); -BOOL InitInstance (HINSTANCE, int); -LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); -LRESULT CALLBACK About (HWND, UINT, WPARAM, LPARAM); -LRESULT CALLBACK OptionsDlgProc (HWND, UINT, WPARAM, LPARAM) ; - -BOOL InWideMode(); - -//================================================================ -int TermInstance (HINSTANCE , int ); -DWORD WINAPI SendThread (PVOID pArg); - -//================================================================ -DWORD WINAPI CommReadThreadFunc(LPVOID ); // thread to receive comm input -HANDLE g_hCommReadThread=NULL; // global handle to thread - -DWORD WINAPI CommWatchdog(LPVOID ); // thread to retry OpenCOMM -HANDLE g_hThreadWatchdog=NULL; // global handle to CommWatchDog - -BOOL g_bUseCharSend = FALSE; // use SendChars or SendKeys? -void SendChars(char* szTxt); // send data as char messages - -void WriteCOM(TCHAR *txt); // function to write txt to COMM port -void CloseCOMM(); // function to Close COMM port -void OpenCOMM(TCHAR *szPort); // function to open COMM port -void showError(long er); // function to show error txt for error er - -#define KEYEVENTF_KEYDOWN 0x0000 // defines the code for KEYEVENTF_KEYDOWN - -void SendKeys(char * szTxt); // this sends szTxt as keystrokes -void ReportCommError(LPTSTR lpszMessage); // function to show CommErrors - -BOOL g_bContinue = TRUE; // global to stopp all threads! -HANDLE g_hCommPort = INVALID_HANDLE_VALUE; // global handle to com port - -void resumeCOMM(); // function which resumes threads -void suspendCOMM(); // function to resume threads - -extern int ReadReg(); // function to read values from reg to global vars -BOOL bsendcharbychar = false; // global to store if receive will be done char by char - -bool LaunchNotes(HWND hNotes); // function launches notes.exe for testing purpose - -//================================================================ -// defines for setup dialog -struct st_txtval -{ TCHAR txt[15]; - /*WORD*/unsigned char val; -}; - -struct st_txtvald -{ TCHAR txt[15]; - DWORD val; -}; -//Baudrates -struct st_txtvald baud[5]={ - {TEXT("9600"), CBR_9600}, - {TEXT("19200"), CBR_19200}, - {TEXT("38400"), CBR_38400}, - {TEXT("57600"), CBR_57600}, - {TEXT("115200"), CBR_115200}}; - -struct st_txtval stopbits[3]={ - {TEXT("ONESTOPBIT"), ONESTOPBIT }, - {TEXT("ONE5STOPBITS"), ONE5STOPBITS }, - {TEXT("TWOSTOPBITS"), TWOSTOPBITS }}; - -struct st_txtval parity[5]= - { {TEXT("NOPARITY"), NOPARITY}, - {TEXT("ODDPARITY"), ODDPARITY}, - {TEXT("EVENPARITY"), EVENPARITY}, - {TEXT("MARKPARITY"), MARKPARITY}, - {TEXT("SPACEPARITY"), SPACEPARITY}}; -//databits -struct st_txtval databits[3]= - { - {TEXT("7 Bit"), 7}, - {TEXT("8 Bit"), 8}, - {TEXT("16 Bit"), 16}}; -//handshake -struct st_txtval handshake[3]= -{ {TEXT("Xon/Xoff"), 1}, - {TEXT("Hardware"), 2}, - {TEXT("None"), 3}}; - -//Globale Variablen fr SetCommState -DWORD nBaud = CBR_57600; -unsigned char - nParity = NOPARITY, - nStopbits = ONESTOPBIT, - nDatabits = 8, - nHandshake = 3; - -TCHAR g_szCOM[32]=L"COM1:"; - -//TCHAR* g_szPostamble=NULL; //internally we will use printable control codes -TCHAR g_szPostamble[32]; -TCHAR* g_szPreamble=NULL; -TCHAR* g_szPostambleDecoded=NULL; -TCHAR* g_szPreambleDecoded=NULL; - -DWORD g_dwBeepAfterRead=0; - -//BOOL bPAmblesConverted=false; -typedef std::basic_string,std::allocator > tstring; - -//================================================================ -void ShowError(LONG er) -{ - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - er, - 0, // Default language - (LPTSTR) &lpMsgBuf, - 0, - NULL - ); - TCHAR temp[MAX_PATH]; - wsprintf(temp, (LPTSTR)lpMsgBuf); - // Process any inserts in lpMsgBuf. - // ... -#ifdef DEBUG - DEBUGMSG( 1, ( temp ) ); - nclog(L"ShowError: '%s'\r\n", temp); -#else - // Display the string. - RETAILMSG( 1,(temp)); -#endif - // Free the buffer. - LocalFree( lpMsgBuf ); -} - -#ifdef USE_SSAPI -//watches the event and updates settings from registry -DWORD UpdateFields( LPVOID pParam ) -{ - while( TRUE ) - { - WaitForSingleObject( m_hEvent, INFINITE ); - ReadReg(); - } -} -#endif - -//================================================================ - -// -// FUNCTION: WinMain(...) -// -// PURPOSE: main entry point -// -// COMMENTS: -// -int WINAPI WinMain( HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - MSG msg; - HACCEL hAccelTable; - - // Perform application initialization: - if (!InitInstance (hInstance, nCmdShow)) - { - return FALSE; - } - - hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_KEYWEDGE); - -#ifdef DEBUG - //dump vkTable - byte vCode; - bool bShift; - for (int j=0; j0) - { - SendDlgItemMessage(hDlg, IDC_CHECK2, BM_SETCHECK, (WPARAM) BST_CHECKED, 0); - } - else - { - SendDlgItemMessage(hDlg, IDC_CHECK2, BM_SETCHECK, (WPARAM) BST_UNCHECKED, 0); - } - - return TRUE; - - case WM_COMMAND: - switch (LOWORD (wParam)) { - - case IDC_BAUD: - // Get the position of the selected item - i = SendDlgItemMessage(hDlg, IDC_BAUD, CB_GETCURSEL, 0, 0); - // Get the ItemData from Control ************ - nBaud = (DWORD)SendDlgItemMessage(hDlg, IDC_BAUD, CB_GETITEMDATA, i,0); - - return TRUE; - - case IDC_DATABITS: - // Get the position of the selected item - i = SendDlgItemMessage(hDlg, IDC_DATABITS, CB_GETCURSEL, 0, 0); - nDatabits = (UCHAR)SendDlgItemMessage(hDlg, IDC_DATABITS, CB_GETITEMDATA, i,0); - //test it - /*wsprintf(szOut, TEXT("%lu"), nDatabits); - SetDlgItemText(hDlg, IDC_EDIT1, szOut); - */ - return TRUE; - - case IDC_STOPBITS: - // Get the position of the selected item - i = SendDlgItemMessage(hDlg, IDC_STOPBITS, CB_GETCURSEL, 0, 0); - nStopbits = (UCHAR)SendDlgItemMessage(hDlg, IDC_STOPBITS, CB_GETITEMDATA, i,0); - - return TRUE; - - case IDC_PARITY: - // Get the position of the selected item - i = SendDlgItemMessage(hDlg, IDC_PARITY, CB_GETCURSEL, 0, 0); - nParity = (UCHAR)SendDlgItemMessage(hDlg, IDC_PARITY, CB_GETITEMDATA, i,0); - - return TRUE; - - case IDC_HANDSHAKE: - // Get the position of the selected item - i = SendDlgItemMessage(hDlg, IDC_HANDSHAKE, CB_GETCURSEL, 0, 0); - nHandshake = (UCHAR)SendDlgItemMessage(hDlg, IDC_HANDSHAKE, CB_GETITEMDATA, i,0); - - return TRUE; - case IDC_CHECK1: //Send Char by Char - i = SendDlgItemMessage(hDlg, IDC_CHECK1, BM_GETCHECK, 0, 0); - if (i == BST_CHECKED){ - bsendcharbychar=true; - EnableWindow(GetDlgItem(hDlg, IDC_Pre), FALSE); - EnableWindow(GetDlgItem(hDlg, IDC_Post), FALSE); - } - else{ - bsendcharbychar=false; - EnableWindow(GetDlgItem(hDlg, IDC_Pre), TRUE); - EnableWindow(GetDlgItem(hDlg, IDC_Post), TRUE); - } - return true; - case IDC_CHECK2: //BeepAfterRead - i = SendDlgItemMessage(hDlg, IDC_CHECK2, BM_GETCHECK, 0, 0); - if (i == BST_CHECKED) - oBeepAfterRead=1; - else - oBeepAfterRead=0; - return true; - case IDOK: - //read the com port - if (GetDlgItemText(hDlg, IDC_COMPORT, szTxt, dim(szTxt)) != 0) - wsprintf(g_szCOM, szTxt); - - //read the Preamble - if (GetDlgItemText(hDlg, IDC_Pre, szTxt, dim(szTxt)) != 0) - wsprintf(g_szPreamble, szTxt); - else{ - wsprintf(g_szPreamble, L"");//=NULL; - wsprintf(g_szPreambleDecoded, L"");//=NULL; - } - //read the Postamble - if (GetDlgItemText(hDlg, IDC_Post, szTxt, dim(szTxt)) != 0) - wsprintf(g_szPostamble, szTxt); - else{ - wsprintf(g_szPostamble,L"");//=NULL; - wsprintf(g_szPostambleDecoded, L"");//=NULL; - } - - //BeepAfterRead setting - g_dwBeepAfterRead=oBeepAfterRead; - // Get the position of the selected item - // i = SendDlgItemMessage(hDlg, IDC_BAUD, CB_GETCURSEL, 0, 0); - // Get the name of the selected item - // SendDlgItemMessage(hDlg, IDC_BAUD, CB_GETLBTEXT, i, (LPARAM)szOut); - //i = lstrlen (szOut); - wsprintf(szOut,TEXT("You selected: Port='%s', Baud=%lu, Databits=%lu, Stopbits=%lu, Parity=%lu, Handshake=%lu"), - g_szCOM, nBaud,nDatabits,nStopbits,nParity,nHandshake); - MessageBox(hDlg, szOut, TEXT("Information"),0); - EndDialog (hDlg, 0); - return TRUE; - - case IDCANCEL: - //restore old values - nBaud=oBaud; - nDatabits=oDatabits; - nStopbits=oStopbits; - nParity=oParity; - nHandshake=oHandshake; - bsendcharbychar=obsendcharbychar; - EndDialog (hDlg, 0); - return TRUE; - default: - return FALSE; - } - - break; - } - return FALSE; -} - -// Mesage handler for the About box. -LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - RECT rt, rt1; - int DlgWidth, DlgHeight; // dialog width and height in pixel units - int NewPosX, NewPosY; - - switch (message) - { - case WM_INITDIALOG: - // trying to center the About dialog - if (GetWindowRect(hDlg, &rt1)) { - GetClientRect(GetParent(hDlg), &rt); - DlgWidth = rt1.right - rt1.left; - DlgHeight = rt1.bottom - rt1.top ; - NewPosX = (rt.right - rt.left - DlgWidth)/2; - NewPosY = (rt.bottom - rt.top - DlgHeight)/2; - - // if the About box is larger than the physical screen - if (NewPosX < 0) NewPosX = 0; - if (NewPosY < 0) NewPosY = 0; - SetWindowPos(hDlg, 0, NewPosX, NewPosY, - 0, 0, SWP_NOZORDER | SWP_NOSIZE); - } - return TRUE; - case WM_COMMAND: - if ((LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL)) - { - EndDialog(hDlg, LOWORD(wParam)); - return TRUE; - } - break; - case WM_QUIT: - PostQuitMessage (0); - break; - } - return FALSE; -} - -//====================================================================== -// SendThread - Sends characters to the serial port -// -DWORD WINAPI SendThread (PVOID pArg) { - HWND hWnd; - //HGO , hwndSText; - INT rc; - DWORD cBytes; - TCHAR szText[TEXTSIZE]; - - DEBUGMSG(1, (L"### Entering SendThread\r\n")); - hWnd = (HWND)pArg; - //HGO hwndSText = GetDlgItem (hWnd, ID_SENDTEXT); - while (1) { - rc = WaitForSingleObject (g_hSendEvent, INFINITE); - if (rc == WAIT_OBJECT_0) { - if (!g_bContinue) - break; - // Disable send button while sending - //HGO EnableWindow (GetDlgItem (hWnd, ID_SENDBTN), FALSE); - //HGO GetWindowText (hwndSText, szText, dim(szText)); - lstrcat (szText, TEXT ("\r\n")); - rc = WriteFile (g_hCommPort, szText, - lstrlen (szText)*sizeof (TCHAR), &cBytes, 0); - if (rc) - { - // Copy sent text to output window - //HGO SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0, (LPARAM)TEXT (" >")); - //HGO SetWindowText (hwndSText, TEXT ("")); // Clear text box - } - else - { - // Else, print error message - wsprintf (szText, TEXT ("Send failed rc=%d\r\n"), GetLastError()); - DEBUGMSG(1, (szText)); - // Put text in receive text box - //HGO SendDlgItemMessage (hWnd, ID_RCVTEXT, EM_REPLACESEL, 0, (LPARAM)szText); - //HGO EnableWindow (GetDlgItem (hWnd, ID_SENDBTN), TRUE); - } - } else - break; - } - DEBUGMSG(1, (L"### Leaving SendThread\r\n")); - return 0; -} - -void showYellowIcon() -{ - //Notification icon - HICON hIcon; - hIcon=(HICON) LoadImage (hInst, MAKEINTRESOURCE (IWEDGE_WAITING), IMAGE_ICON, 16,16,0); - nid.cbSize = sizeof (NOTIFYICONDATA); - //nid.hWnd = hWnd; - //nid.uID = 1; - //nid.uFlags = NIF_ICON | NIF_MESSAGE; - // NIF_TIP not supported - //nid.uCallbackMessage = MYMSG_TASKBARNOTIFY; - nid.hIcon = hIcon; - //nid.szTip[0] = '\0'; - BOOL res = Shell_NotifyIcon(NIM_MODIFY, &nid); -} - -void showGreenIcon() -{ - //Notification icon - HICON hIcon; - hIcon=(HICON) LoadImage (hInst, MAKEINTRESOURCE (IWEDGE_STARTED), IMAGE_ICON, 16,16,0); - nid.cbSize = sizeof (NOTIFYICONDATA); - //nid.hWnd = hWnd; - //nid.uID = 1; - //nid.uFlags = NIF_ICON | NIF_MESSAGE; - // NIF_TIP not supported - //nid.uCallbackMessage = MYMSG_TASKBARNOTIFY; - nid.hIcon = hIcon; - //nid.szTip[0] = '\0'; - BOOL res = Shell_NotifyIcon(NIM_MODIFY, &nid); -} - -void showRedIcon() -{ - //Notification icon - HICON hIcon; - hIcon=(HICON) LoadImage (hInst, MAKEINTRESOURCE (IDI_COMMERROR), IMAGE_ICON, 16,16,0); - nid.cbSize = sizeof (NOTIFYICONDATA); - //nid.hWnd = hWnd; - //nid.uID = 1; - //nid.uFlags = NIF_ICON | NIF_MESSAGE; - // NIF_TIP not supported - //nid.uCallbackMessage = MYMSG_TASKBARNOTIFY; - nid.hIcon = hIcon; - //nid.szTip[0] = '\0'; - BOOL res = Shell_NotifyIcon(NIM_MODIFY, &nid); -} - -// -// OpenCOMM(szPort) -// -// opens the COM port and fills the global COM handle -// -void OpenCOMM(TCHAR *szPort) -{ - g_hCommPort = CreateFile ( - szPort, // Port Name (Unicode compatible) - GENERIC_READ | GENERIC_WRITE, // Open for Read-Write - 0, // COM port cannot be shared - NULL, // Always NULL for Windows CE - OPEN_EXISTING, // For communication resource - 0, // Non-overlapped operation only - NULL); // Always NULL for Windows CE - if(g_hCommPort == INVALID_HANDLE_VALUE) - { - nclog(L"OpenCOMM error: %i\r\n", GetLastError()); - ReportCommError(_T("Opening Comms Port.")); - showRedIcon(); - return; - } - // set the timeouts to specify the behavor of reads and writes. - COMMTIMEOUTS ct; - ct.ReadIntervalTimeout = MAXDWORD; - ct.ReadTotalTimeoutMultiplier = 0; - ct.ReadTotalTimeoutConstant = 0; - ct.WriteTotalTimeoutMultiplier = 10; - ct.WriteTotalTimeoutConstant = 1000; - if(!SetCommTimeouts(g_hCommPort, &ct)) - { - ReportCommError(_T("Setting comm. timeouts.")); - CloseCOMM(); // close comm port - return; - } - // get the current communications parameters, and configure baud rate - DCB dcb; - dcb.DCBlength = sizeof(DCB); - if(!GetCommState(g_hCommPort, &dcb)) - { - ReportCommError(_T("Getting Comms. State.")); - CloseCOMM(); // close comm port - return; - } - - dcb.BaudRate = nBaud; //CBR_19200; // set baud rate to 19,200 - - switch (nHandshake) - { - case 1: //xon/xoff - //RTS/DTR Hardware handshake - dcb.fRtsControl = RTS_CONTROL_DISABLE; - dcb.fDtrControl = DTR_CONTROL_DISABLE; - dcb.fOutxDsrFlow = FALSE; - dcb.fOutxCtsFlow = FALSE; - dcb.fDsrSensitivity = FALSE; - // XON/XOFF software handshake - dcb.fOutX = TRUE; // no XON/XOFF control - dcb.fInX = TRUE; - - break; - case 2: //hardware - //RTS/DTR Hardware handshake - dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; - dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; - dcb.fOutxDsrFlow = TRUE; - dcb.fOutxCtsFlow = TRUE; - dcb.fDsrSensitivity = TRUE; - // XON/XOFF software handshake - dcb.fOutX = FALSE; // no XON/XOFF control - dcb.fInX = FALSE; - - break; - case 3: - // no handshake - dcb.fRtsControl = RTS_CONTROL_DISABLE; - dcb.fDtrControl = DTR_CONTROL_DISABLE; - dcb.fOutxDsrFlow = FALSE; - dcb.fOutxCtsFlow = FALSE; - dcb.fDsrSensitivity = FALSE; - // XON/XOFF software handshake - dcb.fOutX = FALSE; // no XON/XOFF control - dcb.fInX = FALSE; - break; - } -/* - //RTS/DTR Hardware handshake - dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; - dcb.fDtrControl = DTR_CONTROL_ENABLE; - dcb.fOutxDsrFlow = FALSE; - dcb.fOutxCtsFlow = TRUE; - // XON/XOFF software handshake - dcb.fOutX = FALSE; // no XON/XOFF control - dcb.fInX = FALSE; -*/ - dcb.ByteSize = nDatabits; // 8; - dcb.Parity = nParity; //NOPARITY; - dcb.StopBits = nStopbits; //ONESTOPBIT; - - if(!SetCommState(g_hCommPort, &dcb)) - { - ReportCommError(_T("Setting Comms. State.")); - CloseCOMM(); // close comm port - return; - } - - DEBUGMSG(1, (L"COM port opened. Starting thread now...\r\n")); - WriteCOM(L"hello\r\n"); - showGreenIcon(); - - // now need to create the thread that will be reading the comms port - DWORD dwThreadID=0; - g_hCommReadThread = CreateThread(NULL, 0, CommReadThreadFunc, NULL, 0, &dwThreadID); - if(g_hCommReadThread == NULL) - { - ReportCommError(_T("Creating Thread.")); - CloseCOMM(); // close comm port - return; - } - else{ - nclog(L"Created CommThread with id=0x%x\r\n", dwThreadID); - } -} - -// -// reports any errors encountered in these communications functions. -// -void ReportCommError(LPTSTR lpszMessage) -{ - TCHAR szBuffer[200]; - DWORD lastErr=GetLastError(); - - wsprintf(szBuffer, _T("Communications Error %d \r\n%s"), - lastErr, - lpszMessage); - DEBUGMSG (1, (szBuffer)); - ShowError(lastErr); -} - -// Thread function to read communications port. This thread is responsible -// for reading any incoming text and adding it to the text box. -// reads byte by byte until \n -DWORD WINAPI CommReadThreadFunc(LPVOID lpParam) -{ - DWORD dwBytesRead; - char szSentence[MAX_BUFSIZE], c; - memset(&szSentence, 0, MAX_BUFSIZE); - TCHAR szwcsSentence[MAX_BUFSIZE]; - BYTE nc = 0; - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); - - while(g_hCommPort != INVALID_HANDLE_VALUE) - { - //DWORD dwCommModemStatus = EV_BREAK | EV_CTS | EV_DSR | EV_ERR | EV_RLSD | EV_RXCHAR | EV_RXFLAG; - DWORD dwCommModemStatus = EV_RXCHAR; - //setup comm wait events - SetCommMask(g_hCommPort, dwCommModemStatus); - // Wait for an event to occur for the port. - WaitCommEvent (g_hCommPort, &dwCommModemStatus, 0); //blocks until event state changes - - //// Re-specify the set of events to be monitored for the port. - //SetCommMask (g_hCommPort, dwCommModemStatus); - - if (dwCommModemStatus & EV_RXCHAR) { - do{ - if(!ReadFile(g_hCommPort, &c, 1, &dwBytesRead, NULL)) - { - ReportCommError(_T("Reading comms port.")); - return 0; - } - if(dwBytesRead==0){ - DEBUGMSG(1, (L"no more chars\r\n")); - continue; - } - if(!bsendcharbychar) - { - if( (c == 0x0A /*'\n'*/) || nc==MAX_BUFSIZE-2 ) // LF marks end of sentence - { - //add the return char - szSentence[nc++] = c; //sprintf(szSentence, "%s", c); // - // add term char - szSentence[nc] = '\0'; - //send the keys - mbstowcs(szwcsSentence, szSentence, MAX_BUFSIZE); - DEBUGMSG(1, (L"received: '%s'\r\n", szwcsSentence)); - if(g_bUseCharSend) - SendChars(szSentence); - else - SendKeys(szSentence); - //reset buffer - nc = 0; - memset(&szSentence,0,MAX_BUFSIZE); - //sprintf(szSentence,""); - } - else - szSentence[nc++] = c; - } - else - { - if(g_bUseCharSend) - SendChars(&c); - else - SendKeys(&c); - }//bsendcharbychar - }while (dwBytesRead==1); - }//dwCommModemStatus - }//while - return 0; -} - -// *** Listing 9.2 -// -// Closes comm serial port. -// -// this will also stop threads waiting for CommEvents, -// as the handle gets inavlid -// -void CloseCOMM() -{ -// DeleteCriticalSection(&g_cs); - if(g_hCommPort != INVALID_HANDLE_VALUE) - { - CloseHandle(g_hCommPort); - g_hCommPort = INVALID_HANDLE_VALUE; - DEBUGMSG(1, (L"Com. port closed")); - } - else - DEBUGMSG(1, (L"Com. port %s was not open\r\n", g_szCOM)); - showRedIcon(); -} - -// *** Listing 9.3 -// -// Write text to serial port. -// -void WriteCOM(TCHAR *txt) -{ - DWORD dwBytesToWrite; - DWORD dwBytesWritten; - - TCHAR szwcsBuffer[BUFF_SIZE]; - char szBuffer[BUFF_SIZE]; - - wsprintf(szwcsBuffer, txt); - - // convert to ANSI character set - dwBytesToWrite = wcstombs(szBuffer, szwcsBuffer, BUFF_SIZE); - // append a carrage return/line feed pair - //szBuffer[dwBytesToWrite++] = '\r'; - //szBuffer[dwBytesToWrite++] = '\n'; - if(!WriteFile(g_hCommPort, // where to write to (the open comm port) - szBuffer, // what to write - dwBytesToWrite, // number of bytes to be written to port - &dwBytesWritten, // number of bytes that were actually written - NULL)) // overlapped I/O not supported - { - ReportCommError(_T("Sending text.")); - return; - } - else{ - if(g_dwBeepAfterRead>0) - MessageBeep(MB_OK); - } -} - -// -// showError(LONG er) -// -// will show error text for err number 'er' -// -void showError(LONG er) -{ - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - er, - 0, // Default language - (LPTSTR) &lpMsgBuf, - 0, - NULL - ); - TCHAR temp[MAX_PATH]; - wsprintf(temp, (LPTSTR)lpMsgBuf); - // Process any inserts in lpMsgBuf. - // ... -#ifdef DEBUG - DEBUGMSG( 1, ( temp ) ); -#else - // Display the string. - RETAILMSG(1, (temp)); - //MessageBox( NULL, (LPCTSTR)lpMsgBuf, L"Error", MB_OK | MB_ICONINFORMATION ); -#endif - // Free the buffer. - LocalFree( lpMsgBuf ); -} - -// for future use -// simulate keystrokes by synthesizing the real world :-) -// send input data as char messages -void SendChars(char* szTxt){ - HWND hTarget = GetForegroundWindow(); - if (hTarget == INVALID_HANDLE_VALUE) - { - DEBUGMSG(1, (L"SendChars: No Foreground Window found.\r\n")); - return; - } - TCHAR txt[MAX_PATH]; - if(GetWindowText(hTarget, txt, MAX_PATH)) - DEBUGMSG(1, (L"SendChars: Foreground Window is '%s'.\r\n", txt)); - - TCHAR* szTxtW = (TCHAR*)malloc(strlen(szTxt)*2); - memset(szTxtW,0,strlen(szTxt)*2); - mbstowcs(szTxtW, szTxt, strlen(szTxt)); - - KEYBDINPUT _keyinputDown; - //_keyinputDown.wVk=vkTable[szTxt[i]]; - _keyinputDown.wScan=0; - _keyinputDown.dwExtraInfo=0x00; - _keyinputDown.time=0x00; - _keyinputDown.dwFlags=KEYEVENTF_KEYDOWN; - - KEYBDINPUT _keyinputUp; - //_keyinputUp.wVk=vkTable[szTxt[i]]; - _keyinputUp.wScan=0; - _keyinputUp.dwExtraInfo=0x00; - _keyinputUp.time=0x00; - _keyinputUp.dwFlags=KEYEVENTF_KEYUP; - - INPUT _input[2]; - - for (uint i=0; i < strlen(szTxt); i++) - { - if ( (szTxt[i] >= 0x20) || (szTxt[i] == 0x09) || (szTxt[i] == 0x0A) || (szTxt[i] == 0x0D) && - (szTxt[i] < 255) - ) - { - //DEBUGMSG(1, (L"SendChars: 0x%2x '%s'\r\n", szTxt[i], szTxtW[i])); - DEBUGMSG(1, (L"SendChars: 0x%2x \r\n", szTxt[i])); - //PostMessage(hTarget, WM_KEYDOWN, (WPARAM)szTxt[i], (LPARAM)0x01); - //PostMessage(hTarget, WM_CHAR, (WPARAM)szTxtW[i], (LPARAM)0x01); - //PostMessage(hTarget, WM_KEYUP, (WPARAM)szTxt[i], (LPARAM)0xc0000001); - - _input[0].type=INPUT_KEYBOARD; - _input[0].ki=_keyinputDown; - _input[1].type=INPUT_KEYBOARD; - _input[1].ki=_keyinputUp; - _keyinputDown.wVk=vkTable[szTxt[i]].kVKval; - _keyinputUp.wVk=vkTable[szTxt[i]].kVKval; - SendInput(2, _input, sizeof(INPUT)); - } - } - free(szTxtW); -} - -// for future use -// simulate keystrokes by synthesizing the real world :-) -// -void SendKeysToWnd(char * szTxt) -{ - /* VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */ - /* VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */ - DEBUGMSG(1, (L"\r\nSending Key...\r\n")); - HWND hTarget = FindWindow(NULL, L"Notes"); - if (hTarget == INVALID_HANDLE_VALUE) - { - DEBUGMSG(1, (L"SendKeysToWnd: Target Window not found.\r\n")); - return; - } - for (uint i=0; i < strlen(szTxt); i++) - { - if ( ((char)szTxt[i] >= 0x20) && ((char)szTxt[i] < KTAB_SIZE) ) - { - DEBUGMSG(1, (L"(0x%2x )", (char)szTxt[i])); -//#ifndef DEBUG - //for WM_KEYxxx, WM_CHAR the lParam has the following flags - //Bit 0-15 = repeat count, set to 1 - // always 1 for 1 for WM_KEYUP - // always one for a WM_KEYUP message - //bit 16-23 = hardware scan code, dont used, set to 0 - //bit 24 = extended key, set to 1 for ALT, CTRL - //bit 25-28 = not used, reserved - //Bit 29 = context code, - // set to 1 for ALT key pressed - // always 0 for KEYDOWN - // always 0 for a WM_KEYUP message - //Bit 30 = previous key state, set to 1 if key previously down - // WM_KEYDOWN: the value is 1 if the key is down before the message is sent, or it is 0 if the key is up. - // the value is always 1 for a WM_KEYUP message. - //Bit 31 = transition state, set to 1 if key is being released - // always 0 for a WM_KEYDOWN message. - // always 1 for a WM_KEYUP message - /* // possible other funtion to send keys - BOOL PostKeybdMessage (HWND hwnd, UINT VKey, - KEY_STATE_FLAGS KeyStateFlags, - UINT cCharacters, UINT *pShiftStateBuffer, - UINT *pCharacterBuffer ); - This function sends a series of keys to the specified window. - The hwnd parameter is the target window. - This window must be owned by the calling thread. - The VKey parameter should be zero. KeyStateFlags specifies - the key state for all the keys being sent. The - cCharacters parameter specifies the number of keys being sent. - The pShiftStateBuffer parameter points to an array that - contains a shift state for each key sent, while pCharacterBuffer - points to the VK codes of the keys being sent. - Unlike keybd_event, this function doesnt change - the global state of the keyboard. - */ - /* - press key '1' - KEYDOWN 00000031 00160001 - CHAR 1(0x31) 00160001 - KEYUP 00000031 c0160001 - - press key 'a' - KEYDOWN 00000041 001c0001 - CHAR A(0x41) 001c0001 - KEYUP 00000041 c01c0001 - - 0x01000000 extended code? - 0x20000000 alt pressed? - 0x40000000 previously pressed? - 0x80000000 now pressed? - - 0x0000yyyy repeat count - - so a capital A becomes: - - KEYDOWN VK_SHIFT 0x00000001 - KEYDOWN VK_A 0x00000001 - CHAR A 0x00000001 - KEYUP VK_A 0x80000001 - KEYUP VK_SHIFT 0xC0000001 - - */ - SendMessage(hTarget, WM_KEYDOWN, (WPARAM)(char)szTxt[i], (LPARAM)0); - keybd_event((char)szTxt[i], 0, KEYEVENTF_KEYDOWN | KEYEVENTF_SILENT, 0); - keybd_event((char)szTxt[i], 0, KEYEVENTF_KEYUP | KEYEVENTF_SILENT, 0); - Sleep(100); -//#endif - } - } - DEBUGMSG(1, (L"\r\n")); -} - - -static wstring stringDecoded(wstring csIN){ - if(csIN.length()==0) - return csIN; - - while (csIN.find(L"\\r")!=string::npos){ - csIN.replace(csIN.find(L"\\r"), 2, L"\r"); - } - while(csIN.find(L"\\n")!=string::npos) - csIN.replace(csIN.find(L"\\n"), 2, L"\n"); - - while(csIN.find(L"\\t")!=string::npos) - csIN.replace(csIN.find(L"\\t"), 2, L"\t"); - - //wsprintf(sRet, L"%s", csIN.c_str()); - return csIN; -} - -/* -// convert a input string with \r, \n\, \t encoding -// to a string with these vals decoded -static TCHAR* stringDecoded(TCHAR * szSringIn){ - - if(szSringIn==NULL || wcslen(szSringIn)==0) - return L""; - - static TCHAR* sRet = new TCHAR[MAX_BUFSIZE]; - memset(sRet, 0, MAX_BUFSIZE); - wsprintf(sRet, L""); - int i=0; - - tstring cString(szSringIn); - - while (cString.find(L"\\r")!=string::npos){ - cString.replace(cString.find(L"\\r"), 2, L"\r"); - } - while(cString.find(L"\\n")!=string::npos) - cString.replace(cString.find(L"\\n"), 2, L"\n"); - - while(cString.find(L"\\t")!=string::npos) - cString.replace(cString.find(L"\\t"), 2, L"\t"); - - wsprintf(sRet, L"%s", cString.c_str()); - - return sRet; -} -*/ - -void myReplace(std::string& str, const std::string& oldStr, const std::string& newStr) -{ - size_t pos = 0; - while((pos = str.find(oldStr, pos)) != std::string::npos) - { - str.replace(pos, oldStr.length(), newStr); - pos += newStr.length(); - } -} -void replaceCrLf(char* szIN){ - string csIN(szIN); - size_t pos=0; - while(pos = csIN.find("\n\r") != string::npos){ - csIN.replace(pos, 4, "\n"); - pos+=1; - } - sprintf(szIN, csIN.c_str()); - return; -} - -// -// SendKeys (szTxt) -// -// sends the keystrokes for szTxt -// -// invoked by ReadCommThread -// -void SendKeys(char * szTxt) -{ - /* VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */ - /* VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */ - /* small ASCII letters are 'a' thru 'z', 0x61 - 0x7A */ - byte bCode; - byte vCode; - bool bShift; - TCHAR szwTxt[MAX_BUFSIZE]; - char sTempA[MAX_BUFSIZE]; - TCHAR sTempW[MAX_BUFSIZE]; - - mbstowcs(szwTxt, szTxt, MAX_BUFSIZE); - DEBUGMSG(1, (L"\r\nSendKeys: called with '%s'\r\n", szwTxt)); - - //to remember, only convert once - //g_szPreamble and g_szPostamble are the untranslated strings - //get the decoded string - //TCHAR* szPostamble; szPostamble = (TCHAR*)malloc(MAX_BUFSIZE * sizeof(TCHAR)); - //wstring sPostamble= stringDecoded(wstring(g_szPostamble)); - - //TCHAR* szPreamble; szPreamble = (TCHAR*)malloc(MAX_BUFSIZE*sizeof(TCHAR)); - //szPreamble = stringDecoded(g_szPreamble); - //szPostamble = stringDecoded(g_szPostamble); - - DEBUGMSG(1, (L"Preamble: g_szPreamble ='%s', decoded='%s'\r\n", g_szPreamble, g_szPreambleDecoded)); - DEBUGMSG(1, (L"Postamble: g_szPostamble='%s', decoded='%s'\r\n", g_szPostamble, g_szPostambleDecoded)); - - //using a temp copy of what to send - strcpy(sTempA, szTxt); - mbstowcs(szwTxt, sTempA, MAX_BUFSIZE); - DEBUGMSG(1, (L"processing '%s'\n", szwTxt)); - - if(!bsendcharbychar){ - //add the Postamble if set - if( g_szPreambleDecoded==NULL && g_szPostambleDecoded!=NULL) - wsprintf(sTempW, L"%s%s", szwTxt, g_szPostambleDecoded); - //add the Preamble if set only - else if(g_szPreambleDecoded!=NULL && g_szPostambleDecoded==NULL) - wsprintf(sTempW, L"%s%s", g_szPreambleDecoded, szwTxt); - //add post and preamble - else if(g_szPreambleDecoded!=NULL && g_szPostambleDecoded!=NULL) - wsprintf(sTempW, L"%s%s%s", g_szPreambleDecoded, szwTxt, g_szPostambleDecoded); - //no Pre and Postamble - else if(g_szPreambleDecoded==NULL && g_szPostambleDecoded==NULL) - wsprintf(sTempW, L"%s", szwTxt); - - wcstombs(sTempA, sTempW, MAX_BUFSIZE); - } - else - sprintf(sTempA, "%s", szTxt); - - mbstowcs(szwTxt, sTempA, MAX_BUFSIZE); - DEBUGMSG(1, (L"After Pre/Postamble '%s'\n", szwTxt)); - - for (uint i=0; i < strlen(sTempA); i++) - { - //chars ' ' thru z - //WARNING only 0-9, a-z is equal to VK_0-VK_9 and VK_A-VK_Z - //the REST must be translated! ie - //ASCII ';' 0x3B to VK_SEMICOLON 0xBA !!!!!!!!! - //ASCII '$' to VK_SHIFT + VK_4 !!!!!!!! - //lookup for the VK code to send - bCode=(char)sTempA[i]; - - //do not send VK_RETURN for 0x0d AND 0x0a - if(bCode==0x0d) - continue; - - vCode=vkTable[bCode].kVKval; - bShift=vkTable[bCode].kShift; - if ((char)sTempA[i] < KTAB_SIZE) // ( ((char)szTxt[i] >= 0x30) && ((char)szTxt[i] <= 0x7F) ) - { - DEBUGMSG(1, (L"Char=(0x%2x)\tbCode=%2x\tvCode=%2x\tShift=%2x\r\n", (char)sTempA[i], bCode, vCode, bShift)); -#ifndef DEBUG1 - if (bShift) //has to be shifted? - keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYDOWN | KEYEVENTF_SILENT, 0); - - //send the code with key down and then key up - keybd_event(vCode, 0, KEYEVENTF_KEYDOWN | KEYEVENTF_SILENT, 0); - keybd_event(vCode, 0, KEYEVENTF_KEYUP | KEYEVENTF_SILENT, 0); - DEBUGMSG(1, (L"keybd_event: %c\r\n", vCode)); - - if (bShift) //has to be unshifted? - keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP | KEYEVENTF_SILENT, 0); - -#else - DEBUGMSG(1, (L"keybd_event: %c\r\n", vCode)); -#endif - Sleep(1); - } - } - if(!bsendcharbychar){ - if(g_dwBeepAfterRead>0) - MessageBeep(MB_OK); - } - - DEBUGMSG(1, (L"\r\n")); -} - -// -// Thread to retry openCOMM(szPrt) -DWORD WINAPI CommWatchdog(LPVOID lpParam) -{ - TCHAR sComPort[32]; - wsprintf(sComPort, (TCHAR *)lpParam); - DEBUGMSG(1, (L"### CommWatchdog started with %s\r\n", sComPort)); - nclog(L"### CommWatchdog started with %s\r\n", sComPort); - while(g_bContinue) - { - if(g_hCommPort==INVALID_HANDLE_VALUE){ - DEBUGMSG(1, (L"### CommWatchdog trying to open comm port\r\n")); - nclog(L"### CommWatchdog trying to open comm port\r\n"); - OpenCOMM(sComPort); - } - else{ - DEBUGMSG(1, (L"### CommWatchdog comm port is already open\r\n")); - nclog(L"### CommWatchdog comm port is already open\r\n"); - } - Sleep(3000); - } - DEBUGMSG(1, (L"### CommWatchdog ended\r\n")); - nclog(L"### CommWatchdog ended\r\n"); - return 0; -} - -//for testing -bool LaunchNotes(HWND hNotes) -{ - - HWND hTarget = FindWindow(L"Notes", L"Notes"); - hNotes=NULL; - if (hTarget == NULL) - { - PROCESS_INFORMATION pi; - int rc; - TCHAR *szFileName = L"\\Windows\\Notes.exe"; - TCHAR *szCmdLine = L"\\notes.txt"; - DWORD dwCreationFlags = 0; - rc = CreateProcess (szFileName, szCmdLine, NULL, NULL, FALSE, - dwCreationFlags, NULL, NULL, NULL, &pi); - if (rc) { - CloseHandle (pi.hThread); - CloseHandle (pi.hProcess); - hTarget = FindWindow(NULL, L"Notes"); - hNotes = hTarget; - return true; - } - else - return false; - } - else - { - hNotes = hTarget; - return true; - } -} - -void suspendCOMM(void) -{ - nclog(L"### suspendCOMM\r\n"); - SuspendThread(g_hThreadWatchdog); - SuspendThread(g_hCommReadThread); - CloseCOMM(); - showYellowIcon(); -} - -void resumeCOMM(void) -{ - nclog(L"### resumeCOMM\r\n"); - OpenCOMM(g_szCOM); - ResumeThread(g_hCommReadThread); - ResumeThread(g_hThreadWatchdog); - //showGreenIcon(); -} - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: InWideMode() -// -// PURPOSE: returns true if there is not enough space to display the -// crossword in "tall mode". -// -BOOL InWideMode() -{ - int height = GetSystemMetrics(SM_CYSCREEN); - int width = GetSystemMetrics(SM_CXSCREEN); - if (width > height) - return TRUE; - else - return FALSE; - //return (height < SCALEY(320)) ? TRUE : FALSE; -} diff --git a/KeyWedge/KeyWedge/KeyWedge.h b/KeyWedge/KeyWedge/KeyWedge.h deleted file mode 100644 index ae35a50..0000000 --- a/KeyWedge/KeyWedge/KeyWedge.h +++ /dev/null @@ -1,21 +0,0 @@ - -#if !defined(AFX_KEYWEDGE_H__EA5DD0C4_7BFB_41F8_91B3_1F7F6DBB03CE__INCLUDED_) -#define AFX_KEYWEDGE_H__EA5DD0C4_7BFB_41F8_91B3_1F7F6DBB03CE__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "resource.h" -//#include "registry.h" - -#define MYMSG_TASKBARNOTIFY (WM_USER + 100) - -// Returns number of elements -#define dim(x) (sizeof(x) / sizeof(x[0])) - -HANDLE m_hEvent; - -#define TEXTSIZE 256 - -#endif // !defined(AFX_KEYWEDGE_H__EA5DD0C4_7BFB_41F8_91B3_1F7F6DBB03CE__INCLUDED_) diff --git a/KeyWedge/KeyWedge/KeyWedge.rc b/KeyWedge/KeyWedge/KeyWedge.rc deleted file mode 100644 index 909fdd2..0000000 --- a/KeyWedge/KeyWedge/KeyWedge.rc +++ /dev/null @@ -1,292 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "newres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// German (Germany) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -#ifdef _WIN32 -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_KEYWEDGE ICON "KeyWedge.ICO" -IWEDGE_STARTED ICON "iwedge_s.ico" -IDI_COMMERROR ICON "icon1.ico" -IDI_ICON1 ICON "scan_off.ico" -IDI_ICON2 ICON "scan_ok.ico" -IDI_ICON3 ICON "scanwarn.ico" - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""newres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// CEUX -// - -HI_RES_AWARE CEUX "Data_1.bin" - -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDM_MENU MENU -BEGIN - POPUP "File" - BEGIN - MENUITEM "Exit", IDM_FILE_EXIT - MENUITEM "Options", IDM_OPTIONS - MENUITEM "Hide", IDM_HIDE - END - POPUP "Help" - BEGIN - MENUITEM "About", IDM_HELP_ABOUT - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_ABOUTBOX DIALOG 0, 0, 125, 55 -STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -EXSTYLE 0x80000000L -CAPTION "About KeyWedge" -FONT 8, "System" -BEGIN - ICON IDI_KEYWEDGE,IDC_STATIC,11,17,20,20 - LTEXT "KeyWedge Version 1.4",IDC_STATIC,38,10,80,8,SS_NOPREFIX - LTEXT "Copyright (C) 2010",IDC_STATIC,38,25,70,8 -END - -IDD_OPTIONSBOX DIALOG 0, 0, 124, 140 -STYLE DS_SETFONT | DS_MODALFRAME | DS_SETFOREGROUND | DS_CENTER | WS_POPUP | WS_CAPTION -CAPTION "Options" -FONT 7, "MS Shell Dlg" -BEGIN - DEFPUSHBUTTON "OK",IDOK,70,124,50,14 - PUSHBUTTON "Cancel",IDCANCEL,0,124,50,14 - COMBOBOX IDC_BAUD,50,17,48,44,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - RTEXT "Baudrate:",IDC_STATIC_1,5,18,43,12 - RTEXT "Datenbits:",IDC_STATIC_2,5,33,43,12 - RTEXT "Parit:",IDC_STATIC_3,5,48,43,12 - RTEXT "Stopbits:",IDC_STATIC_4,6,62,43,12 - RTEXT "Handshake:",IDC_STATIC_5,6,77,43,12 - COMBOBOX IDC_DATABITS,50,32,37,43,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - COMBOBOX IDC_PARITY,50,47,65,43,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - COMBOBOX IDC_STOPBITS,50,62,72,46,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - COMBOBOX IDC_HANDSHAKE,50,77,72,48,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - EDITTEXT IDC_EDIT1,91,33,31,12,ES_AUTOHSCROLL - RTEXT "COM port:",IDC_STATIC_6,5,3,43,12 - EDITTEXT IDC_COMPORT,50,3,45,12,ES_AUTOHSCROLL - CONTROL "Chars",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,1,95,36,10 - CONTROL "Beep",IDC_CHECK2,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,1,107,34,10 - EDITTEXT IDC_Pre,70,92,52,12,ES_AUTOHSCROLL - EDITTEXT IDC_Post,70,106,52,12,ES_AUTOHSCROLL - RTEXT "Pre:",IDC_STATIC_7,47,95,22,10 - RTEXT "Post:",IDC_STATIC_8,46,107,22,10 -END - -IDD_OPTIONSBOX_WIDE DIALOG 0, 0, 186, 103 -STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION -CAPTION "Options" -FONT 8, "MS Shell Dlg" -BEGIN - DEFPUSHBUTTON "OK",IDOK,128,85,50,14 - PUSHBUTTON "Cancel",IDCANCEL,128,67,50,14 - COMBOBOX IDC_BAUD,131,2,48,44,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - RTEXT "Baudrate:",IDC_STATIC_1,90,4,38,12 - RTEXT "Datenbits:",IDC_STATIC_2,0,17,43,12 - RTEXT "Parit:",IDC_STATIC_3,0,33,43,12 - RTEXT "Stopbits:",IDC_STATIC_4,1,47,43,12 - RTEXT "Handshake:",IDC_STATIC_5,1,62,43,12 - COMBOBOX IDC_DATABITS,45,17,37,43,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - COMBOBOX IDC_PARITY,45,32,65,43,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - COMBOBOX IDC_STOPBITS,45,47,72,46,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - COMBOBOX IDC_HANDSHAKE,45,62,72,48,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - EDITTEXT IDC_EDIT1,86,17,31,12,ES_AUTOHSCROLL - RTEXT "COM port:",IDC_STATIC_6,0,3,43,12 - EDITTEXT IDC_COMPORT,45,3,45,12,ES_AUTOHSCROLL - CONTROL "Chars",IDC_CHECK1,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,5,90,38,10 - CONTROL "Beep",IDC_CHECK2,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,5,79,29,9 - EDITTEXT IDC_Pre,73,78,43,12,ES_AUTOHSCROLL - EDITTEXT IDC_Post,73,90,43,12,ES_AUTOHSCROLL - RTEXT "Pre:",IDC_STATIC_7,51,79,19,9 - RTEXT "Post:",IDC_STATIC_8,52,90,19,9 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_ABOUTBOX, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 118 - TOPMARGIN, 7 - BOTTOMMARGIN, 48 - END - - IDD_OPTIONSBOX, DIALOG - BEGIN - BOTTOMMARGIN, 124 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Accelerator -// - -IDC_KEYWEDGE ACCELERATORS -BEGIN - "/", IDM_HELP_ABOUT, ASCII, ALT, NOINVERT - VK_F4, IDM_FILE_EXIT, VIRTKEY, ALT, NOINVERT -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_BITMAP1 BITMAP "bitmap1.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040704b0" - BEGIN - VALUE "FileDescription", "KeyWedge Application" - VALUE "FileVersion", "1, 0, 0, 1" - VALUE "InternalName", "KeyWedge" - VALUE "LegalCopyright", "Copyright (C) 2012" - VALUE "OriginalFilename", "KeyWedge.exe" - VALUE "ProductName", "KeyWedge Application" - VALUE "ProductVersion", "1, 0, 0, 1" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x407, 1200 - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE -BEGIN - IDS_APP_TITLE "KeyWedge" - IDS_HELLO "Use File-Hide to resume WedgeMode" - IDC_KEYWEDGE "KEYWEDGE" -END - -#endif // German (Germany) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IWEDGE_WAITING ICON "iwedge_w.ico" -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/KeyWedge/KeyWedge/KeyWedge.reg b/KeyWedge/KeyWedge/KeyWedge.reg deleted file mode 100644 index a73d906..0000000 --- a/KeyWedge/KeyWedge/KeyWedge.reg +++ /dev/null @@ -1,14 +0,0 @@ -REGEDIT4 - -[HKEY_LOCAL_MACHINE\Software\Intermec\SSKeyWedge] -"BeepAfterRead"=dword:00000001 -"Preamble"="PP\\t" -"Postamble"="AA\\r\\n" -"parity"=dword:00000000 -"stopbits"=dword:00000000 -"databits"=dword:00000008 -"handshake"=dword:00000003 -"baudrate"=dword:00002580 -"comport"="COM4:" -"sendcharbychar"=dword:00000000 - diff --git a/KeyWedge/KeyWedge/KeyWedge.sln b/KeyWedge/KeyWedge/KeyWedge.sln deleted file mode 100644 index 8a470f4..0000000 --- a/KeyWedge/KeyWedge/KeyWedge.sln +++ /dev/null @@ -1,124 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "KeyWedge", "KeyWedge.vcproj", "{575F6903-6A42-45CD-94A0-D4E189C70C2B}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SSKeyWedge", "SSKeyWedge\SSKeyWedge.vcproj", "{97C4EB3F-0500-4E87-8122-51A1F7BA411E}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|iCE50-CK60-A4I (ARMV4I) = Debug|iCE50-CK60-A4I (ARMV4I) - Debug|ITC_CE5.0 (ARMV4I) = Debug|ITC_CE5.0 (ARMV4I) - Debug|Pocket PC 2003 (ARMV4) = Debug|Pocket PC 2003 (ARMV4) - Debug|Smartphone 2003 (ARMV4) = Debug|Smartphone 2003 (ARMV4) - Debug|STANDARDSDK_500 (ARMV4I) = Debug|STANDARDSDK_500 (ARMV4I) - Debug|STANDARDSDK_500 (x86) = Debug|STANDARDSDK_500 (x86) - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Debug|Windows Mobile 6 Professional SDK (ARMV4I) = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - Release|iCE50-CK60-A4I (ARMV4I) = Release|iCE50-CK60-A4I (ARMV4I) - Release|ITC_CE5.0 (ARMV4I) = Release|ITC_CE5.0 (ARMV4I) - Release|Pocket PC 2003 (ARMV4) = Release|Pocket PC 2003 (ARMV4) - Release|Smartphone 2003 (ARMV4) = Release|Smartphone 2003 (ARMV4) - Release|STANDARDSDK_500 (ARMV4I) = Release|STANDARDSDK_500 (ARMV4I) - Release|STANDARDSDK_500 (x86) = Release|STANDARDSDK_500 (x86) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 6 Professional SDK (ARMV4I) = Release|Windows Mobile 6 Professional SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|iCE50-CK60-A4I (ARMV4I).ActiveCfg = Debug|iCE50-CK60-A4I (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|iCE50-CK60-A4I (ARMV4I).Build.0 = Debug|iCE50-CK60-A4I (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|iCE50-CK60-A4I (ARMV4I).Deploy.0 = Debug|iCE50-CK60-A4I (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|ITC_CE5.0 (ARMV4I).ActiveCfg = Debug|ITC_CE5.0 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|ITC_CE5.0 (ARMV4I).Build.0 = Debug|ITC_CE5.0 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|ITC_CE5.0 (ARMV4I).Deploy.0 = Debug|ITC_CE5.0 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Pocket PC 2003 (ARMV4).ActiveCfg = Debug|Pocket PC 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Pocket PC 2003 (ARMV4).Build.0 = Debug|Pocket PC 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Pocket PC 2003 (ARMV4).Deploy.0 = Debug|Pocket PC 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Smartphone 2003 (ARMV4).ActiveCfg = Debug|Smartphone 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Smartphone 2003 (ARMV4).Build.0 = Debug|Smartphone 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Smartphone 2003 (ARMV4).Deploy.0 = Debug|Smartphone 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|STANDARDSDK_500 (ARMV4I).ActiveCfg = Debug|STANDARDSDK_500 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|STANDARDSDK_500 (ARMV4I).Build.0 = Debug|STANDARDSDK_500 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|STANDARDSDK_500 (ARMV4I).Deploy.0 = Debug|STANDARDSDK_500 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|STANDARDSDK_500 (x86).ActiveCfg = Debug|STANDARDSDK_500 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|iCE50-CK60-A4I (ARMV4I).ActiveCfg = Release|iCE50-CK60-A4I (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|iCE50-CK60-A4I (ARMV4I).Build.0 = Release|iCE50-CK60-A4I (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|iCE50-CK60-A4I (ARMV4I).Deploy.0 = Release|iCE50-CK60-A4I (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|ITC_CE5.0 (ARMV4I).ActiveCfg = Release|ITC_CE5.0 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|ITC_CE5.0 (ARMV4I).Build.0 = Release|ITC_CE5.0 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|ITC_CE5.0 (ARMV4I).Deploy.0 = Release|ITC_CE5.0 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Pocket PC 2003 (ARMV4).ActiveCfg = Release|Pocket PC 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Pocket PC 2003 (ARMV4).Build.0 = Release|Pocket PC 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Pocket PC 2003 (ARMV4).Deploy.0 = Release|Pocket PC 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Smartphone 2003 (ARMV4).ActiveCfg = Release|Smartphone 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Smartphone 2003 (ARMV4).Build.0 = Release|Smartphone 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Smartphone 2003 (ARMV4).Deploy.0 = Release|Smartphone 2003 (ARMV4) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|STANDARDSDK_500 (ARMV4I).ActiveCfg = Release|STANDARDSDK_500 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|STANDARDSDK_500 (ARMV4I).Build.0 = Release|STANDARDSDK_500 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|STANDARDSDK_500 (ARMV4I).Deploy.0 = Release|STANDARDSDK_500 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|STANDARDSDK_500 (x86).ActiveCfg = Release|STANDARDSDK_500 (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {575F6903-6A42-45CD-94A0-D4E189C70C2B}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|iCE50-CK60-A4I (ARMV4I).ActiveCfg = Debug|iCE50-CK60-A4I (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|iCE50-CK60-A4I (ARMV4I).Build.0 = Debug|iCE50-CK60-A4I (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|iCE50-CK60-A4I (ARMV4I).Deploy.0 = Debug|iCE50-CK60-A4I (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|ITC_CE5.0 (ARMV4I).ActiveCfg = Debug|ITC_CE5.0 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|ITC_CE5.0 (ARMV4I).Build.0 = Debug|ITC_CE5.0 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|ITC_CE5.0 (ARMV4I).Deploy.0 = Debug|ITC_CE5.0 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Pocket PC 2003 (ARMV4).ActiveCfg = Debug|Pocket PC 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Pocket PC 2003 (ARMV4).Build.0 = Debug|Pocket PC 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Pocket PC 2003 (ARMV4).Deploy.0 = Debug|Pocket PC 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Smartphone 2003 (ARMV4).ActiveCfg = Debug|Smartphone 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Smartphone 2003 (ARMV4).Build.0 = Debug|Smartphone 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Smartphone 2003 (ARMV4).Deploy.0 = Debug|Smartphone 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|STANDARDSDK_500 (ARMV4I).ActiveCfg = Debug|STANDARDSDK_500 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|STANDARDSDK_500 (ARMV4I).Build.0 = Debug|STANDARDSDK_500 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|STANDARDSDK_500 (ARMV4I).Deploy.0 = Debug|STANDARDSDK_500 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|STANDARDSDK_500 (x86).ActiveCfg = Debug|STANDARDSDK_500 (x86) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|STANDARDSDK_500 (x86).Build.0 = Debug|STANDARDSDK_500 (x86) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|STANDARDSDK_500 (x86).Deploy.0 = Debug|STANDARDSDK_500 (x86) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|iCE50-CK60-A4I (ARMV4I).ActiveCfg = Release|iCE50-CK60-A4I (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|iCE50-CK60-A4I (ARMV4I).Build.0 = Release|iCE50-CK60-A4I (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|iCE50-CK60-A4I (ARMV4I).Deploy.0 = Release|iCE50-CK60-A4I (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|ITC_CE5.0 (ARMV4I).ActiveCfg = Release|ITC_CE5.0 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|ITC_CE5.0 (ARMV4I).Build.0 = Release|ITC_CE5.0 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|ITC_CE5.0 (ARMV4I).Deploy.0 = Release|ITC_CE5.0 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Pocket PC 2003 (ARMV4).ActiveCfg = Release|Pocket PC 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Pocket PC 2003 (ARMV4).Build.0 = Release|Pocket PC 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Pocket PC 2003 (ARMV4).Deploy.0 = Release|Pocket PC 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Smartphone 2003 (ARMV4).ActiveCfg = Release|Smartphone 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Smartphone 2003 (ARMV4).Build.0 = Release|Smartphone 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Smartphone 2003 (ARMV4).Deploy.0 = Release|Smartphone 2003 (ARMV4) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|STANDARDSDK_500 (ARMV4I).ActiveCfg = Release|STANDARDSDK_500 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|STANDARDSDK_500 (ARMV4I).Build.0 = Release|STANDARDSDK_500 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|STANDARDSDK_500 (ARMV4I).Deploy.0 = Release|STANDARDSDK_500 (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|STANDARDSDK_500 (x86).ActiveCfg = Release|STANDARDSDK_500 (x86) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|STANDARDSDK_500 (x86).Build.0 = Release|STANDARDSDK_500 (x86) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|STANDARDSDK_500 (x86).Deploy.0 = Release|STANDARDSDK_500 (x86) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {97C4EB3F-0500-4E87-8122-51A1F7BA411E}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/KeyWedge/KeyWedge/KeyWedge.vcproj b/KeyWedge/KeyWedge/KeyWedge.vcproj deleted file mode 100644 index 4af881e..0000000 --- a/KeyWedge/KeyWedge/KeyWedge.vcproj +++ /dev/null @@ -1,1947 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/KeyWedge/KeyWedge/PowerMsgQueue.cpp b/KeyWedge/KeyWedge/PowerMsgQueue.cpp deleted file mode 100644 index 83779a9..0000000 --- a/KeyWedge/KeyWedge/PowerMsgQueue.cpp +++ /dev/null @@ -1,463 +0,0 @@ -//PowerMsgQueue.cpp - -#include "PowerMsgQueue.h" -#include "./common/nclog.h" - -HANDLE hExitPwrMsgThreadEvent; -TCHAR szExitPwrMsgThreadEventName[MAX_PATH] = L"szExitPwrMsgThreadEventName"; - -HANDLE hPwrMsgThreadHasStoppedEvent; -TCHAR szPwrMsgThreadHasStoppedEventName[MAX_PATH] = L"szPwrMsgThreadHasStoppedEventName"; - -HANDLE hPwrMsgQueue; -HANDLE hPwrMsgQueueThread; - -HWND hwndMain; - -char* logDateTimeA(){ - static char cDateTimeStr[64]; - TCHAR str[64]; - wsprintf(str, L"%s", logDateTime()); - wcstombs(cDateTimeStr, str, wcslen(str)); - return cDateTimeStr; -} -// -//int InitTransitionsPowerNotification(void) -//{ -// int iRet=0; -// nclog(L"\tInitTransitionsPowerNotification()...\n"); -// MSGQUEUEOPTIONS mqoQueueOptions; -// mqoQueueOptions.dwSize = sizeof(mqoQueueOptions); -// mqoQueueOptions.dwFlags = MSGQUEUE_NOPRECOMMIT; -// mqoQueueOptions.dwMaxMessages = 0; -// mqoQueueOptions.cbMaxMessage = sizeof(POWER_BROADCAST) + MAX_NAMELEN; -// mqoQueueOptions.bReadAccess = TRUE; -// -// hTransitionsStatusQueue = CreateMsgQueue(NULL, &mqoQueueOptions); -// if(hTransitionsStatusQueue==NULL){ -// nclog(L"\tCreateMsgQueue failed.\n"); -// iRet=-1; -// } -// else{ -// if(RequestPowerNotifications(hTransitionsStatusQueue, PBT_TRANSITION)==0){ //PBT_TRANSITION PBT_RESUME -// nclog(L"\tRequestPowerNotifications failed.\n"); -// iRet=-2; -// } -// } -// nclog(L"\tInitTransitionsPowerNotification() done with ret=%i\n", iRet); -// return iRet; -//} - -void dumpPowerFlags(POWER_BROADCAST* ppb, TCHAR* szPPB){ - wsprintf(szPPB, L""); - if(ppb->Flags & POWER_STATE_ON) - wcscat(szPPB, L"ON|"); - if(ppb->Flags & POWER_STATE_OFF) - wcscat(szPPB, L"OFF|"); - if(ppb->Flags & POWER_STATE_BOOT) - wcscat(szPPB, L"ON|"); - if(ppb->Flags & POWER_STATE_CRITICAL) - wcscat(szPPB, L"CRITICAL|"); - if(ppb->Flags & POWER_STATE_IDLE) - wcscat(szPPB, L"IDLE|"); - if(ppb->Flags & POWER_STATE_PASSWORD) - wcscat(szPPB, L"PASSWORD|"); -#if _WIN32_WCE > 0x501 - if(ppb->Flags & POWER_STATE_BACKLIGHTON) - wcscat(szPPB, L"BACKLIGHTON|"); -#endif - if(ppb->Flags & POWER_STATE_SUSPEND) - wcscat(szPPB, L"SUSPEND|"); - if(ppb->Flags & POWER_STATE_UNATTENDED) - wcscat(szPPB, L"UNATTENDED|"); - if(ppb->Flags & POWER_STATE_RESET) - wcscat(szPPB, L"RESET|"); - if(ppb->Flags & POWER_STATE_USERIDLE) - wcscat(szPPB, L"USERIDLE|"); - wcscat(szPPB, L"\0"); -} - -//*************************************************************************** -// Function Name: PowerNotificationThread -// -// Purpose: listens for power change notifications -// -DWORD PowerMsgsThread(LPVOID pVoid) -{ - // size of a POWER_BROADCAST message - DWORD cbPowerMsgSize = sizeof POWER_BROADCAST + (MAX_PATH * sizeof TCHAR); - - // Initialize our MSGQUEUEOPTIONS structure - MSGQUEUEOPTIONS mqo; - mqo.dwSize = sizeof(MSGQUEUEOPTIONS); - mqo.dwFlags = MSGQUEUE_NOPRECOMMIT; - mqo.dwMaxMessages = 4; - mqo.cbMaxMessage = cbPowerMsgSize; - mqo.bReadAccess = TRUE; - - // Create a message queue to receive power notifications - HANDLE hPowerMsgQ = CreateMsgQueue(NULL, &mqo); - if (NULL == hPowerMsgQ) - { - RETAILMSG(1, (L"CreateMsgQueue failed: %x\n", GetLastError())); - goto Error; - } - - // Request power notifications - HANDLE hPowerNotifications = RequestPowerNotifications(hPowerMsgQ, - PBT_TRANSITION | - PBT_RESUME | - PBT_POWERINFOCHANGE); - if (NULL == hPowerNotifications) - { - nclog(L"RequestPowerNotifications failed: %x\n", GetLastError()); - goto Error; - } - - //create exit thread handle event - hExitPwrMsgThreadEvent = CreateEvent(NULL, FALSE, FALSE, szExitPwrMsgThreadEventName); - hPwrMsgThreadHasStoppedEvent = CreateEvent(NULL, FALSE, FALSE, szPwrMsgThreadHasStoppedEventName); - - HANDLE rgHandles[2] = {0}; - rgHandles[0] = hPowerMsgQ; //will be signaled on power changes - rgHandles[1] = hExitPwrMsgThreadEvent; //used to signal the thread to exit - int iPost=0; - - // Wait for a power notification or for the app to exit - while(WaitForMultipleObjects(2, rgHandles, FALSE, INFINITE) == WAIT_OBJECT_0) - { - DWORD cbRead; - DWORD dwFlags; - POWER_BROADCAST *ppb = (POWER_BROADCAST*) new BYTE[cbPowerMsgSize]; - TCHAR* szPPB = new TCHAR[MAX_PATH]; - memset(szPPB, 0, MAX_PATH * 2); - TCHAR* szPBtype=new TCHAR[MAX_PATH]; - memset(szPBtype, 0, MAX_PATH * 2); - TCHAR szOut[MAX_PATH]; - // loop through in case there is more than 1 msg - while(ReadMsgQueue(hPowerMsgQ, ppb, cbPowerMsgSize, &cbRead, - 0, &dwFlags)) - { - wsprintf(szPPB, L""); - wsprintf(szPBtype, L""); - nclog(L"ReadMsgQueue: %s\n", ppb->SystemPowerState); - switch (ppb->Message) - { - case PBT_POWERSTATUSCHANGE: - nclog(L"Power Notification Message: PBT_POWERSTATUSCHANGE\n"); - wsprintf(szPBtype, L"change: "); - //Add2Log(L"Power Notification Message: PBT_POWERSTATUSCHANGE\n",TRUE); - break; - case PBT_SUSPENDKEYPRESSED: - nclog(L"Power Notification Message: PBT_SUSPENDKEYPRESSED\n"); - wsprintf(szPBtype, L"keypress: "); - //Add2Log(L"Power Notification Message: PBT_SUSPENDKEYPRESSED\n",TRUE); - break; - case PBT_TRANSITION: - nclog(L"Power Notification Message: PBT_TRANSITION\n"); - //Add2Log(L"Power Notification Message: PBT_TRANSITION\n",TRUE); - nclog(L"Flags: %lx\n", ppb->Flags); - nclog(L"Length: %d\n", ppb->Length); - wsprintf(szPBtype, L"trans.: "); -/* -Flags: 12010000 -Length: 6 -trans.: ON|PASSWORD|BACKLIGHTON| -*/ - // 0x10000000 0x00010000 0x02000000 - if( ((ppb->Flags & POWER_STATE_PASSWORD) == POWER_STATE_PASSWORD) || - ((ppb->Flags & POWER_STATE_ON) == POWER_STATE_ON) -#if _WIN32_WCE > 0x501 - || - ((ppb->Flags & POWER_STATE_BACKLIGHTON) == POWER_STATE_BACKLIGHTON) -#endif - ) - { - nclog(L"PwrMsgQueue: got 'ON|PASSWORD|BACKLIGHTON'...\n"); - //send a message to main window - iPost = PostMessage(hwndMain, WM_USER_RESUMECOMM, 0, 0); - nclog(L"PostMessage WM_USER_RESUMECOMM returned %i\n", iPost); - } - break; - - case PBT_RESUME: - nclog(L"Power Notification Message: PBT_RESUME\n"); - //Add2Log(L"Power Notification Message: PBT_RESUME\n",TRUE); - wsprintf(szPBtype, L"resume: "); - //send a message to main window - iPost = PostMessage(hwndMain, WM_USER_RESUMECOMM, 0, 0); - nclog(L"PostMessage WM_USER_RESUMECOMM returned %i\n", iPost); - nclog(L"Power: PBT_RESUME\n"); - - break; - - case PBT_POWERINFOCHANGE: - { - nclog(L"Power Notification Message: PBT_POWERINFOCHANGE\n"); - //Add2Log(L"Power Notification Message: PBT_POWERINFOCHANGE\n", TRUE); - // PBT_POWERINFOCHANGE message embeds a - // POWER_BROADCAST_POWER_INFO structure into the - // SystemPowerState field - wsprintf(szPBtype, L"info: "); - - //PPOWER_BROADCAST_POWER_INFO ppbpi = - // (PPOWER_BROADCAST_POWER_INFO) ppb->SystemPowerState; - //if (ppbpi) - //{ - // RETAILMSG(1,(L"Length: %d\n", ppb->Length)); - // RETAILMSG(1,(L"BatteryLifeTime = %d\n",ppbpi->dwBatteryLifeTime)); - // RETAILMSG(1,(L"BatterFullLifeTime = %d\n", - // ppbpi->dwBatteryFullLifeTime)); - // RETAILMSG(1,(L"BackupBatteryLifeTime = %d\n", - // ppbpi->dwBackupBatteryLifeTime)); - // RETAILMSG(1,(L"BackupBatteryFullLifeTime = %d\n", - // ppbpi->dwBackupBatteryFullLifeTime)); - // RETAILMSG(1,(L"ACLineStatus = %d\n",ppbpi->bACLineStatus)); - // RETAILMSG(1,(L"BatteryFlag = %d\n",ppbpi->bBatteryFlag)); - // RETAILMSG(1,(L"BatteryLifePercent = %d\n", - // ppbpi->bBatteryLifePercent)); - // RETAILMSG(1,(L"BackupBatteryFlag = %d\n", - // ppbpi->bBackupBatteryFlag)); - // RETAILMSG(1,(L"BackupBatteryLifePercent = %d\n", - // ppbpi->bBackupBatteryLifePercent)); - //} - break; - } - - default: - nclog(L"Unknown PwrMsg: 0x%08x", ppb->Message); - break; - } - //dumpBattery(); - dumpPowerFlags(ppb, szPPB); - wsprintf(szOut, L"%s%s\n", szPBtype, szPPB); - nclog(szOut); - //dumpBattery(szOut); - } - delete[] ppb; - delete(szPPB); - delete(szPBtype); - } - SetEvent(hPwrMsgThreadHasStoppedEvent); -Error: - if (hPowerNotifications) - StopPowerNotifications(hPowerNotifications); - - if (hPowerMsgQ) - CloseMsgQueue(hPowerMsgQ); - CloseHandle(hExitPwrMsgThreadEvent); //no more needed - return NULL; -} - -//DWORD WINAPI TransitionsUpdateThread(LPVOID pvarg) -//{ -// writefile(L"Thread starting...\n"); -// DWORD dwRet=0; -// -// HANDLE hWaitHandles[2]; -// DWORD dwWaitStatus; -// DWORD dwBytesRead; -// DWORD dwFlags; -// DWORD dwStateNumber = 0; -// DWORD dwOnCount = 0; -// FILE *fp; -// -// union -// { -// UCHAR buf[sizeof(POWER_BROADCAST) + MAX_NAMELEN]; -// POWER_BROADCAST powerBroadcast; -// } qData; -// -// if((dwRet = InitTransitionsPowerNotification()) != 0){ -// writefile(L"InitTransitionsPowerNotification failed\nEnding Thread."); -// ExitThread(dwRet); -// } -// //hPwrMsgThreadHasStoppedEvent = CreateEvent(NULL, FALSE, FALSE, NULL); -// hPwrMsgThreadHasStoppedEvent = CreateEvent(NULL, FALSE, FALSE, szPwrMsgThreadHasStoppedEventName); -// if(hPwrMsgThreadHasStoppedEvent==NULL){ -// writefile(L"CreateEvent: hPwrMsgThreadHasStoppedEvent failed\nEnding Thread."); -// ExitThread(GetLastError()); -// } -// -// hExitPwrMsgThreadEvent = CreateEvent(NULL, FALSE, FALSE, szExitPwrMsgThreadEventName ); -// if(hExitPwrMsgThreadEvent==NULL){ -// writefile(L"CreateEvent: hExitPwrMsgThreadEvent failed\nEnding Thread."); -// ExitThread(GetLastError()); -// } -// -// hWaitHandles[0] = hPwrMsgQueue; -// hWaitHandles[1] = hExitPwrMsgThreadEvent; -// -// writefile(L"Starting thread loop...\nFurther thread infos write to '\\power.txt'\n"); -// BOOL bRunThread=TRUE; -// -// do -// { -// dwWaitStatus = WaitForMultipleObjects(2, hWaitHandles, FALSE, INFINITE); -// if (dwWaitStatus == WAIT_OBJECT_0) -// { -// if (ReadMsgQueue(hPwrMsgQueue, &qData, sizeof(qData), &dwBytesRead, INFINITE, &dwFlags)) -// { -// fp = fopen("\\power.txt", "a+"); -// fprintf(fp, logDateTimeA()); fprintf(fp, "\t"); -// char cChar[64]; sprintf(cChar, "0x%08x\t", (qData.powerBroadcast).Flags); -// fprintf(fp, cChar); -// -// if ((qData.powerBroadcast).Flags & POWER_STATE_ON) -// { -// /* -// will be done now by BattSaveWakeUp.exe itself -// */ -// //if(!_bTestMode){ -// // if(clearTimedEvent()==0) -// // fprintf(fp, "Power: POWER_STATE_ON, Timed event cleared\n"); -// // else -// // fprintf(fp, "Power: POWER_STATE_ON, Timed event clear failed\n"); -// //} -// } -// -// if ((qData.powerBroadcast).Flags & POWER_STATE_SUSPEND) -// { -// fprintf(fp, "Power: POWER_STATE_SUSPEND\n"); -// //if(addTimedEvent()==0) -// //fprintf(fp, "Power: POWER_STATE_SUSPEND with WakeUp event set\n"); -// //else -// // fprintf(fp, "Power: POWER_STATE_SUSPEND with WakeUp event set FAILED\n"); -// } -// if ((qData.powerBroadcast).Flags & POWER_STATE_IDLE) -// { -// fprintf(fp, "Power: POWER_STATE_IDLE\n"); -// } -// if ((qData.powerBroadcast).Flags & POWER_STATE_OFF) -// { -// fprintf(fp, "Power: POWER_STATE_OFF\n"); -// } -// if ((qData.powerBroadcast).Flags & POWER_STATE_UNATTENDED) -// { -// fprintf(fp, "Power: POWER_STATE_UNATTENDED\n"); -// } -// if ((qData.powerBroadcast).Flags & POWER_STATE_USERIDLE) -// { -// fprintf(fp, "Power: POWER_STATE_USERIDLE\n"); -// } -// if ((qData.powerBroadcast).Flags & POWER_STATE_BOOT) -// { -// fprintf(fp, "Power: POWER_STATE_BOOT\n"); -// } -// if ((qData.powerBroadcast).Flags & POWER_STATE_CRITICAL) -// { -// fprintf(fp, "Power: POWER_STATE_CRITICAL\n"); -// } -// if ((qData.powerBroadcast).Flags & POWER_STATE_PASSWORD) -// { -// //send a message to main window -// int iPost = PostMessage(hwndMain, WM_USER_RESUMECOMM, 0, 0); -// writefile(L"PostMessage WM_USER_RESUMECOMM returned %i\n", iPost); -// fprintf(fp, "Power: POWER_STATE_PASSWORD\n"); -// } -// if ((qData.powerBroadcast).Flags & POWER_STATE_RESET) -// { -// fprintf(fp, "Power: POWER_STATE_RESET\n"); -// } -// fflush(fp); -// fclose(fp); -// } -// } -// if (dwWaitStatus == WAIT_OBJECT_0 + 1) -// { -// fprintf(fp, "PowerThread exit requested\n"); -// bRunThread=FALSE; -// } -// else -// { -// break; -// } -// }while (bRunThread); -// writefile(L"...Thread loop ended\n"); -// CloseHandle(hExitPwrMsgThreadEvent); -// SetEvent(hPwrMsgThreadHasStoppedEvent); -// DEBUGMSG(1, (L"Thread stopped\n")); -// writefile(L"Thread stopped\n"); -// return(0); -//} -// -//int startMsgThread(){ -// hPwrMsgQueueThread = CreateThread(NULL, 0, &TransitionsUpdateThread, NULL, 0, 0); -// if(hPwrMsgQueueThread!=NULL){ -// SetThreadPriority(hPwrMsgQueueThread, THREAD_PRIORITY_ABOVE_NORMAL); -// return 0; -// } -// else -// return -1; -//} - -int startMsgThread(){ - DWORD rc=0; - hPwrMsgQueueThread = CreateThread(NULL, 0, &PowerMsgsThread, NULL, 0, &rc); - if(hPwrMsgQueueThread!=NULL){ - SetThreadPriority(hPwrMsgQueueThread, THREAD_PRIORITY_ABOVE_NORMAL); - nclog(L"Started MessageThread with id=0x%x", rc); - return 0; - } - else - return -1; -} - -int stopMsgThread(){ - int iResult=0; - hPwrMsgThreadHasStoppedEvent = CreateEvent(NULL, FALSE, FALSE, szPwrMsgThreadHasStoppedEventName); //hopefully an exisiting event as thread is started - if(GetLastError()==ERROR_ALREADY_EXISTS){ - nclog(L"stopMsgThread: using existing hPwrMsgThreadHasStoppedEvent handle to wait for PwrMsgThread End...\n"); - if(hExitPwrMsgThreadEvent!=NULL){ - nclog(L"stopMsgThread: using existing hExitPwrMsgThreadEvent handle to signal Exit to PwrMsgThread...\n"); - PulseEvent(hExitPwrMsgThreadEvent); - - nclog(L"stopMsgThread: Waiting for thread end...\n"); - - DWORD dwStat = WaitForSingleObject(hPwrMsgThreadHasStoppedEvent, INFINITE); - switch(dwStat){ - case WAIT_OBJECT_0: - nclog(L"stopMsgThread: PwrMsgThread signaled it has ended\n"); - iResult = 1; - break; - case WAIT_ABANDONED: - RETAILMSG(1, (L"stopMsgThread: WaitForSingleObject abondoned!\n")); - iResult = -1; - break; - case WAIT_FAILED: - RETAILMSG(1, (L"stopMsgThread: WaitForSingleObject failed!\n")); - iResult = -2; - break; - } - } - else - RETAILMSG(1, (L"stopMsgThread: No hExitPwrMsgThreadEvent handle found! PwrMsgThread running?\n")); - } - else - RETAILMSG(1, (L"stopMsgThread: hPwrMsgThreadHasStoppedEvent not found! PwrMsgThread running?\n")); - CloseHandle(hExitPwrMsgThreadEvent); - CloseHandle(hPwrMsgQueueThread); - CloseHandle(hPwrMsgThreadHasStoppedEvent); - return iResult; -} - -//int stopMsgThread(){ -// int iResult=0; -// hPwrMsgThreadHasStoppedEvent = CreateEvent(NULL, FALSE, FALSE, szPwrMsgThreadHasStoppedEventName); //hopefully an exisiting event as thread is started -// PulseEvent(hExitPwrMsgThreadEvent); -// -// nclog(L"Waiting for thread end...\n"); -// DWORD dwStat = WaitForSingleObject(hPwrMsgThreadHasStoppedEvent, INFINITE); -// switch(dwStat){ -// case WAIT_OBJECT_0: -// iResult = 1; -// break; -// case WAIT_ABANDONED: -// iResult = -1; -// break; -// case WAIT_FAILED: -// iResult = -2; -// break; -// } -// return iResult; -//} \ No newline at end of file diff --git a/KeyWedge/KeyWedge/PowerMsgQueue.h b/KeyWedge/KeyWedge/PowerMsgQueue.h deleted file mode 100644 index 5baa4bd..0000000 --- a/KeyWedge/KeyWedge/PowerMsgQueue.h +++ /dev/null @@ -1,25 +0,0 @@ -//PowerMsgQueue.h -#pragma once - -#if !defined(PowerMsgQueue__INCLUDED_) -#define PowerMsgQueue__INCLUDED_ -#pragma message ("##### PowerMsgQueue included #####") - - -//#include "stdafx.h" -#include -#include -#include -#include - -extern HWND hwndMain; - -#define WM_USER_RESUMECOMM (WM_USER + 101) - -#define MAX_NAMELEN 200 - - -int startMsgThread(); -int stopMsgThread(); - -#endif //PowerMsgQueue__INCLUDED_ \ No newline at end of file diff --git a/KeyWedge/KeyWedge/ReadMe.txt b/KeyWedge/KeyWedge/ReadMe.txt deleted file mode 100644 index f5dd303..0000000 --- a/KeyWedge/KeyWedge/ReadMe.txt +++ /dev/null @@ -1,59 +0,0 @@ -======================================================================== - Windows CE APPLICATION : KeyWedge -======================================================================== - - -AppWizard has created this KeyWedge application for you. - -This file contains a summary of what you will find in each of the files that -make up your KeyWedge application. - -KeyWedge.cpp - This is the main application source file. - -KeyWedge.h - This is the main header file for the application. It includes other - project specific headers (including Resource.h). - -KeyWedge.vcp - This file (the project file) contains information at the project level and - is used to build a single project or subproject. Other users can share the - project (.vcp) file, but they should export the makefiles locally. - - -///////////////////////////////////////////////////////////////////////////// -AppWizard has created the following resources: - -KeyWedge.rc - This is a listing of all of the Microsoft Windows CE resources that the - program uses. This file can be directly edited in Microsoft - eMbedded Visual C++. - -KeyWedge.ico - This is an icon file, which is used as the application's icon (32x32). - This icon is included by the main resource file KeyWedge.rc. - - -///////////////////////////////////////////////////////////////////////////// -Other standard files: - -StdAfx.h, StdAfx.cpp - These files are used to build a precompiled header (PCH) file - named KeyWedge.pch and a precompiled types file named StdAfx.obj. - -Resource.h - This is the standard header file, which defines new resource IDs. - Microsoft eMbedded Visual C++ reads and updates this file. - -Newres.h - This header file is used to replace the ..\mfc\include\afxres.h. - - -///////////////////////////////////////////////////////////////////////////// -Other notes: - -AppWizard uses "TODO:" to indicate parts of the source code you -should add to or customize. - - -///////////////////////////////////////////////////////////////////////////// diff --git a/KeyWedge/KeyWedge/RegEntry.h b/KeyWedge/KeyWedge/RegEntry.h deleted file mode 100644 index 4a877c4..0000000 --- a/KeyWedge/KeyWedge/RegEntry.h +++ /dev/null @@ -1,119 +0,0 @@ -// CRegEntry: interface for the CRegEntry class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(_REGENTRY_H_INCLUDED) -#define _REGENTRY_H_INCLUDED - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -class CRegistry; - -class CRegEntry -{ -public: - - CRegEntry(CRegistry* Owner = NULL); - virtual ~CRegEntry() { if (lpszName) delete [] lpszName; if (lpszStr) delete [] lpszStr; }; - - /* -----------------------------------------* - * Operators * - * -----------------------------------------*/ - - CRegEntry& operator =( CRegEntry& cregValue ); - CRegEntry& operator =( LPCTSTR lpszValue ); - CRegEntry& operator =( LPDWORD lpdwValue ); - CRegEntry& operator =( DWORD dwValue ) { return (*this = &dwValue); } - operator LPTSTR(); - operator DWORD(); - - - // Data types without implemented conversions - // NOTE: I realize these will only check asserts - // when a value is set and retrieved during the - // same session. But it is better than no check. - - REGENTRY_NONCONV_STORAGETYPE(POINT); - REGENTRY_NONCONV_STORAGETYPE(RECT); - - // Numeric types with conversions - // If you'd like to add more, follow this form: - // data type, max string length + 1, format specification, from string, from DWORD - - REGENTRY_CONV_NUMERIC_STORAGETYPE(__int64, 28, %I64d, _ttoi64(lpszStr), (__int64)dwDWORD) - REGENTRY_CONV_NUMERIC_STORAGETYPE(double, 18, %f, _tcstod(lpszStr, NULL), (double)dwDWORD) - REGENTRY_CONV_NUMERIC_STORAGETYPE(bool, 2, %d, (_ttoi(lpszStr) != 0), (dwDWORD != 0)) - REGENTRY_CONV_NUMERIC_STORAGETYPE(int, 12, %d, _ttoi(lpszStr), (int)dwDWORD) - REGENTRY_CONV_NUMERIC_STORAGETYPE(UINT, 11, %d, (UINT)_tcstoul(lpszStr, NULL, NULL), (UINT)dwDWORD) - - // Types with conversions: type to/from string, type from unsigned long - - REGENTRY_CONV_STORAGETYPE(tstring, _R_BUF(_MAX_REG_VALUE); _tcscpy(buffer, Value.c_str());, - lpszStr, _ultot(dwDWORD, lpszStr, NULL), _T("")) - - - /* -----------------------------------------* - * Member Variables and Functions * - * -----------------------------------------*/ - - LPTSTR lpszName; // The value name - UINT iType; // Value data type - - void InitData(CRegistry* Owner = NULL); - void ForceStr(); - bool Delete(); - - - /* The following six functions handle REG_MULTI_SZ support: */ - - void SetMulti(LPCTSTR lpszValue, size_t nLen, bool bInternal = false); - void MultiRemoveAt(size_t nIndex); - void MultiSetAt(size_t nIndex, LPCTSTR lpszVal); - LPTSTR GetMulti(LPTSTR lpszDest, size_t nMax = _MAX_REG_VALUE); - LPCTSTR MultiGetAt(size_t nIndex); - size_t MultiLength(bool bInternal = false); - size_t MultiCount(); - - - void SetBinary(LPBYTE lpbValue, size_t nLen); - void GetBinary(LPBYTE lpbDest, size_t nMaxLen); - size_t GetBinaryLength(); - bool Convertible() { return __bConvertable; } - - __inline void SetOwner(CRegistry* Owner) { __cregOwner = Owner; } - - template void SetStruct(T &type) { SetBinary((LPBYTE) &type, sizeof(T)); } - template void GetStruct(T &type) { GetBinary((LPBYTE) &type, sizeof(T)); } - - __inline UINT IsString() { return (iType == REG_SZ); } - __inline UINT IsDWORD() { return (iType == REG_DWORD); } - __inline UINT IsBinary() { return (iType == REG_BINARY); } - __inline UINT IsMultiString() { return (iType == REG_MULTI_SZ); } - - __inline BOOL IsStored() { return __bStored; } - __inline BOOL Exists() { return __bStored; } - - __inline void MultiClear() { SetMulti(_T("\0"), 2); } - __inline void MultiAdd(LPCTSTR lpszVal) { MultiSetAt(MultiCount(), lpszVal); } - -protected: - - CRegistry* __cregOwner; - bool __bConvertable; - bool __bStored; - -private: - - /* Create a variable for each prominent data type */ - - DWORD dwDWORD; - LPTSTR lpszStr; - - std::vector vBytes; - std::vector vMultiString; -}; - - -#endif \ No newline at end of file diff --git a/KeyWedge/KeyWedge/RegRW.cpp b/KeyWedge/KeyWedge/RegRW.cpp deleted file mode 100644 index 3cb738a..0000000 --- a/KeyWedge/KeyWedge/RegRW.cpp +++ /dev/null @@ -1,251 +0,0 @@ -//regRW.cpp - -#include "RegRW.h" - -// convert a input string with \r, \n\, \t encoding -// to a string with these vals decoded -static TCHAR* stringDecoded(TCHAR* szSringIn, int maxlen){ - - if(szSringIn==NULL || wcslen(szSringIn)==0) - return L""; - - static TCHAR* sRet = new TCHAR[MAX_BUFSIZE]; - memset(sRet, 0, MAX_BUFSIZE); - wsprintf(sRet, L""); - int i=0; - - tstring cString(szSringIn); - - while (cString.find(L"\\r")!=string::npos){ - cString.replace(cString.find(L"\\r"), 2, L"\r"); - } - while(cString.find(L"\\n")!=string::npos) - cString.replace(cString.find(L"\\n"), 2, L"\n"); - - while(cString.find(L"\\t")!=string::npos) - cString.replace(cString.find(L"\\t"), 2, L"\t"); - - wsprintf(sRet, L"%s", cString.c_str()); - - return sRet; -} - -// convert a input string with control codes -// to a string with \r, \n\, \t encoding -TCHAR* stringEncoded(TCHAR * szSringIn, int maxLen){ - - if(wcslen(szSringIn)==0) - return L""; - - static TCHAR* sRet = new TCHAR[maxLen]; - TCHAR wIn[32] ={ 0 }; - TCHAR* szIn = wIn; - wsprintf(szIn, L"%s", szSringIn); - wsprintf(sRet, L""); - int i=0; - while(szIn != L'\0') - { - if(szIn == L"\r") - wcscat(sRet, L"\\r"); - else if(szIn == L"\n") - wcscat(sRet, L"\\n"); - else if(szIn == L"\t") - wcscat(sRet, L"\\t"); - else - { - //sRet[i] = szIn; - wcsncat(sRet, szIn, 1); - } - szIn++; - i++; - } - sRet[i] = L'\0'; - return sRet; -} - -int ReadReg() -{ - CRegistry regMyReg( CREG_CREATE ); // No special flags - if ( regMyReg.Open(pSubKey, HKEY_LOCAL_MACHINE) ) - { -// TCHAR str[MAX_PATH+1]; - byte b=0; -// LONG rc; - DWORD dw=0; - - //Read if send char by char - if ( regMyReg[L"sendcharbychar"].Exists() ) - { - dw = regMyReg[L"sendcharbychar"]; - if (dw==0) - bsendcharbychar=false; - else if (dw==1) - bsendcharbychar=true; - } - else - { - bsendcharbychar=true; - } - - //Read if send via SendChars() - if ( regMyReg[L"usecharsend"].Exists() ) - { - dw = regMyReg[L"usecharsend"]; - if (dw==0) - g_bUseCharSend=FALSE; - else if (dw==1) - g_bUseCharSend=TRUE; - } - else - { - g_bUseCharSend=FALSE; - } - - //Read COM port - if ( regMyReg[L"comport"].Exists() ) - wsprintf(g_szCOM, regMyReg[L"comport"]); - else - wsprintf(g_szCOM, L"COM1:"); - - //Read Baudrate - if ( regMyReg[L"baudrate"].Exists() ) - nBaud = regMyReg[L"baudrate"]; - else - nBaud = CBR_9600; - - //Read parity - if ( regMyReg[L"parity"].Exists() ) - nParity = (unsigned short)(DWORD) regMyReg[L"parity"]; - else - nParity = NOPARITY; - - //Read stopbits - if ( regMyReg[L"stopbits"].Exists() ) - nStopbits = (unsigned short)(DWORD) regMyReg[L"stopbits"]; - else - nStopbits = ONESTOPBIT; - - //Read databits - if ( regMyReg[L"databits"].Exists() ) - nDatabits = (unsigned short)(DWORD)regMyReg[L"Databits"]; - else - nDatabits = 8; - - //Read nHandshake - if ( regMyReg[L"handshake"].Exists() ) - nHandshake = (unsigned short)(DWORD)regMyReg[L"handshake"]; - else - nHandshake = 3; - - //the keytable - //regMyReg[L"keytab"].GetBinary((VOID *) vkTable, sizeof(KTABLE)*128); - - //Read postamble - if ( regMyReg[L"Postamble"].Exists() ) { - TCHAR* szTemp = regMyReg[L"Postamble"]; - if(szTemp!=NULL){ - wsprintf(g_szPostamble, L"%s", szTemp); - } - if(wcslen(g_szPostamble)>0){ - wsprintf(g_szPostambleDecoded, L"%s", stringDecoded(g_szPostamble, 32)); - } - else - { - wsprintf(g_szPostamble, L""); - wsprintf(g_szPostambleDecoded, L""); - } - } - else{ - wsprintf(g_szPostamble, L""); - wsprintf(g_szPostambleDecoded, L""); - } - //Read preamble - if ( regMyReg[L"Preamble"].Exists() ) { - wsprintf(g_szPreamble, regMyReg[L"Preamble"]); - if(wcslen(g_szPreamble)>0){ - wsprintf(g_szPreambleDecoded, L"%s", stringDecoded(g_szPreamble, 32)); - } - else{ - wsprintf(g_szPreamble, L"");//=NULL; - wsprintf(g_szPreambleDecoded, L"");//=NULL; - } - } - else{ - wsprintf(g_szPreamble, L"");//=NULL; - wsprintf(g_szPreambleDecoded, L"");//=NULL; - } - //Read BeepAfterRead - if ( regMyReg[L"BeepAfterRead"].Exists() ) - g_dwBeepAfterRead = (unsigned short)(DWORD)regMyReg[L"BeepAfterRead"]; - else - g_dwBeepAfterRead = 1; - - regMyReg.Close(); - } - return 0; -} - -void WriteReg() -{ - CRegistry regMyReg( CREG_CREATE ); // No special flags - if ( regMyReg.Open(pSubKey, HKEY_LOCAL_MACHINE) ) - { - DWORD dw; -// byte b; - - //the keytable - regMyReg[L"keytab"].SetBinary((UCHAR*) &vkTable, sizeof(KTABLE)*KTAB_SIZE); - - // pKTABLE * pvkTable = new pKTABLE[128]; - // *pvkTable = &vkTable[0]; - - if (bsendcharbychar) - dw=1; - else - dw=0; - - regMyReg[L"sendcharbychar"]=dw; - - regMyReg[L"UseCharSend"]=g_bUseCharSend; - - regMyReg[L"comport"]=g_szCOM; - - if(g_szPostambleDecoded != NULL){ - wsprintf(g_szPostamble, stringEncoded(g_szPostambleDecoded, 32)); - regMyReg[L"Postamble"]=g_szPostamble; - } - else - { - regMyReg[L"Postamble"]=L""; - } - if(g_szPreambleDecoded != NULL){ - wsprintf(g_szPreamble, stringEncoded(g_szPreambleDecoded, 32)); - regMyReg[L"Preamble"]=g_szPreamble; - } - else - { - regMyReg[L"Preamble"]=L""; - } - - dw=g_dwBeepAfterRead; - regMyReg[L"BeepAfterRead"]=dw; - - dw=nBaud; - regMyReg[L"baudrate"]=dw; - - dw=nHandshake; - regMyReg[L"handshake"]=dw; - - dw=nDatabits; - regMyReg[L"databits"]=dw; - - dw=nStopbits; - regMyReg[L"stopbits"]=dw; - - dw=nParity; - regMyReg[L"parity"]=dw; - - regMyReg.Close(); - } -} - diff --git a/KeyWedge/KeyWedge/RegRW.h b/KeyWedge/KeyWedge/RegRW.h deleted file mode 100644 index bed26f6..0000000 --- a/KeyWedge/KeyWedge/RegRW.h +++ /dev/null @@ -1,37 +0,0 @@ -//regRW.h -#pragma once - -#ifndef _REGRW_ -#define _REGRW_ - #include "registry.h" - #include "keymap.h" - - #define MAX_BUFSIZE 1000 - - extern DWORD nBaud; - extern unsigned char nParity; - extern unsigned char nStopbits;// = ONESTOPBIT, - extern unsigned char nDatabits; // = 8, - extern unsigned char nHandshake; - extern TCHAR g_szCOM[32]; - - extern BOOL g_bUseCharSend; - extern BOOL bsendcharbychar; - - //extern TCHAR* g_szPostamble; - extern TCHAR g_szPostamble[32]; - extern TCHAR* g_szPreamble; - extern TCHAR* g_szPostambleDecoded; - extern TCHAR* g_szPreambleDecoded; - - extern DWORD g_dwBeepAfterRead; - - extern const LPCWSTR pSubKey; // = L"SOFTWARE\\Intermec\\SSKeyWedge"; - - static TCHAR* stringDecoded(TCHAR* szSringIn, int maxlen); - TCHAR* stringEncoded(TCHAR * szSringIn, int maxLen); - - int ReadReg(); - void WriteReg(); - -#endif //_REGRW_ \ No newline at end of file diff --git a/KeyWedge/KeyWedge/Registry.cpp b/KeyWedge/KeyWedge/Registry.cpp deleted file mode 100644 index 89cc1ea..0000000 --- a/KeyWedge/KeyWedge/Registry.cpp +++ /dev/null @@ -1,898 +0,0 @@ -/*// --- FILE INFORMATION ----------------------------- - - CRegistry.cpp - Classes: CRegEntry and CRegistry - - Author: Stuart Konen - Email: skonen@gmail.com - - Date: 12/1/2004 (MM/DD/YYYY) - Version: 1.00 - - (-!-) If you're going to use these classes please do not - remove these comments... To use these classes, simply #include - Registry.h . In MFC you should also turn off precompiled headers - for this file, in VC++ this can be done by navigating to: - - Project->Settings->Project Name->CRegistry.cpp->C/C++->Precompiled Headers - -*///---------------------------------------------------- - -#include "Registry.h" - -#pragma warning (disable : 4706) - - -/* =================================================== - * CONSTRUCTOR - * =================================================*/ - -CRegEntry::CRegEntry(CRegistry *Owner) { - - assert(Owner); - InitData(Owner); -} - - - -/* =================================================== - * CRegEntry::InitData(CRegistry *Owner) - * - * Initializes the entries default values and sets the entries - * owner (CRegistry). This is only called during construction. - */ - -void CRegEntry::InitData(CRegistry *Owner) { - - dwDWORD = iType = 0; - lpszName = lpszStr = NULL; - - __bStored = false; - __bConvertable = true; - __cregOwner = Owner; -} - - - -/* =================================================== - * CRegEntry::ForceStr() - * - * Forces the memory allocation for the entry's string value, if it - * has not already been allocated. - */ - -void CRegEntry::ForceStr() { - - if (lpszStr == NULL) { lpszStr = new _TCHAR[_MAX_REG_VALUE]; lpszStr[0] = 0; } -} - - -/* =================================================== - * CRegEntry::operator=(LPCTSTR lpszValue) - * - * OPERATOR: Assigns a const character array to the open - * registry value. The registry value type will be REG_SZ. - */ - -CRegEntry& CRegEntry::operator=(LPCTSTR lpszValue) { - - size_t nValueLen = (_tcslen(lpszValue) + 1)*sizeof(TCHAR); - assert(nValueLen <= _MAX_REG_VALUE); - - ForceStr(); iType = REG_SZ; - _tcsncpy(lpszStr, lpszValue, nValueLen > _MAX_REG_VALUE ? _MAX_REG_VALUE : nValueLen); - - REGENTRY_ALLOWCONV(true) - if (REGENTRY_NOTLOADING && REGENTRY_KEYVALID( KEY_SET_VALUE )) - RegSetValueEx(__cregOwner->hKey, lpszName, NULL, REG_SZ, (LPBYTE)lpszValue, nValueLen); - REGENTRY_TRYCLOSE; - - __bStored = true; - - return *this; -} - - - -/* =================================================== - * CRegEntry::operator=(LPDWORD lpdwValue) - * - * OPERATOR: Assigns a DWORD to the open registry value. - * The registry value type will be REG_DWORD. - */ - -CRegEntry& CRegEntry::operator=(LPDWORD lpdwValue) { - - iType = REG_DWORD; - memcpy(&dwDWORD, lpdwValue, sizeof( DWORD )); - - REGENTRY_ALLOWCONV(true) - if (REGENTRY_NOTLOADING && REGENTRY_KEYVALID( KEY_SET_VALUE )) - RegSetValueEx(__cregOwner->hKey, lpszName, NULL, REG_DWORD, (LPBYTE)&dwDWORD, sizeof( DWORD )); - REGENTRY_TRYCLOSE; - - __bStored = true; - - return *this; -} - - - -/* =================================================== - * CRegEntry::operator=(CRegEntry& cregValue) - * - * OPERATOR: Copys value information from the specified - * registry entry (CRegEntry) into this entry. - */ - -CRegEntry& CRegEntry::operator=(CRegEntry& cregValue) { - - if (this == &cregValue) - return *this; - - if (lpszName == NULL) { - size_t nNameLen = _tcslen(cregValue.lpszName) + 1; - lpszName = new _TCHAR[nNameLen]; _tcsncpy(lpszName, cregValue.lpszName, nNameLen); - } - - switch ((iType = cregValue.iType)) { - - case REG_SZ: - return (*this = (ForceStr(), cregValue.lpszStr)); - break; - - case REG_MULTI_SZ: { - LPTSTR lpszBuf = new _TCHAR[_MAX_REG_VALUE]; - SetMulti(cregValue.GetMulti(lpszBuf), cregValue.MultiLength()); - delete [] lpszBuf; return *this; - } - break; - case REG_BINARY: { - size_t n = cregValue.vBytes.size(); LPBYTE buf = new BYTE[n]; - cregValue.GetBinary(buf, n); SetBinary(buf, n); - delete [] buf; return *this; - } - break; - default: - return (*this = cregValue.dwDWORD); - } -} - - - -/* =================================================== - * CRegEntry::operator LPTSTR() - * - * OPERATOR: Converts (if required) and returns the open registry - * value as a null terminated string. - */ - -CRegEntry::operator LPTSTR() { - - /* If caching is disabled, refresh the entries */ - REGENTRY_REFRESH_IF_NOCACHE - - assert(__bConvertable); // Check for conversion implementation - ForceStr(); - - switch (iType) { - - case REG_DWORD: - _stprintf(lpszStr, _T("%lu"), dwDWORD); - break; - case REG_MULTI_SZ: - GetMulti(lpszStr); - break; - case REG_BINARY: { - _tcsncpy(lpszStr, (const _TCHAR*)&vBytes[0], vBytes.size()); - lpszStr[vBytes.size()] = 0; - } - break; - - } - return lpszStr; -} - - - -/* =================================================== - * CRegEntry::operator DWORD() - * - * OPERATOR: Converts (if required) and returns the open registry - * value as an unsigned 32-bit integer (unsigned long). - */ - -CRegEntry::operator DWORD() { - - /* If caching is disabled, refresh the entries */ - REGENTRY_REFRESH_IF_NOCACHE - - assert(__bConvertable); // Check for conversion implementation - - REGENTRY_BINARYTOSTRING - return (REGENTRY_SZ_SAFE ? _tcstoul(lpszStr, NULL, NULL) : dwDWORD); -} - - - -/* =================================================== - * CRegEntry::GetBinary(LPBYTE lpbValue, size_t nLen) - * - * Sets the registry value to a binary value (REG_BINARY) - * - * Important Params: - * - * LPBYTE lpbDest: Pointer to the byte array to store * - * size_t nLen: Elements contained within the byte array. - */ - -void CRegEntry::SetBinary(LPBYTE lpbValue, size_t nLen) { - - if (!nLen) { assert(nLen); return; } - - iType = REG_BINARY; - - if (REGENTRY_NOTLOADING && REGENTRY_KEYVALID ( KEY_SET_VALUE ) ) - RegSetValueEx(__cregOwner->hKey, lpszName, NULL, REG_BINARY, lpbValue, nLen); - REGENTRY_TRYCLOSE; - - __bStored = true; - - if (vBytes.size() < nLen) vBytes.reserve(nLen); - vBytes.clear(); - - do { vBytes.push_back(lpbValue[vBytes.size()]); } - while (vBytes.size() < nLen); -} - - - -/* =================================================== - * CRegEntry::GetBinary(LPBYTE lpbDest, size_t nMaxLen) - * - * Gets the binary value of a value stored as REG_BINARY - * - * Important Params: - * - * LPBYTE lpbDest: Pointer to the byte array to fill - * size_t nMaxLen: The maximum bytes to copy to lpbDest - * - * Notes: This will only work for values that were saved - * using the binary registry type specification (REG_BINARY) - */ - -void CRegEntry::GetBinary(LPBYTE lpbDest, size_t nMaxLen) { - - assert(IsBinary()); // Must be stored as Binary - - REGENTRY_REFRESH_IF_NOCACHE - - if ((size_t)(&vBytes.back() - &vBytes.at(0)+1) == vBytes.size()*sizeof(BYTE)) - memcpy(lpbDest, (LPBYTE)&vBytes.at(0), vBytes.size() > nMaxLen ? nMaxLen : vBytes.size()); - else - for (size_t n=0; n < vBytes.size() && n < nMaxLen; n++) - lpbDest[n] = vBytes[n]; -} - - - -/* =================================================== - * CRegEntry::GetBinaryLength() - * - * Returns the size of the binary value in bytes. - */ - -size_t CRegEntry::GetBinaryLength() { - - assert(IsBinary()); - - REGENTRY_REFRESH_IF_NOCACHE - return vBytes.size(); -} - - - -/* =================================================== - * CRegEntry::SetMulti(LPCTSTR lpszValue, size_t nLen, bool bInternal) - * - * Stores an array of null-terminated string, terminated by two null characters. - * For Example: First String\0Second\Third\0\0 - * - * Important Params: - * - * LPCTSTR lpszValue: The string consisting of the null-terminated string array - * size_t nLen: The number of characters in the string, including null characters - * - * Note: For inserting individual null-terminated strings into the array, - * use MultiAdd or MultiSetAt. - */ - -void CRegEntry::SetMulti(LPCTSTR lpszValue, size_t nLen, bool bInternal) { - - size_t nCur = 0, nPrev = 0, nShortLen = nLen; - - /* When this is internal, there is no need to repopulate the vector. */ - if (bInternal) goto SkipNoInternal; - - iType = REG_MULTI_SZ; vMultiString.clear(); - if (nLen <= 2) goto SkipNoInternal; // The string is empty : \0\0 - if (*(lpszValue + nShortLen-1) == '\0') - nShortLen--; - - /* Populate a vector with each string part for easy and quick access */ - while ((nCur = (int)(_tcschr(lpszValue+nPrev, '\0')-lpszValue)) < nShortLen) { - vMultiString.push_back(lpszValue+nPrev); - nPrev = nCur+1; - } - - SkipNoInternal: - - if (REGENTRY_NOTLOADING && REGENTRY_KEYVALID ( KEY_SET_VALUE ) ) - RegSetValueEx(__cregOwner->hKey, lpszName, NULL, REG_MULTI_SZ, (LPBYTE)lpszValue, nLen*sizeof(TCHAR)); - REGENTRY_TRYCLOSE; - - __bStored = true; -} - - - -/* =================================================== - * CRegEntry::MultiLength(bool bInternal = false) - * - * Returns the number of characters (including null) stored - * in the full string. Don't confuse this with MultiCount() - * which returns the number of strings stored in the array. - */ - -size_t CRegEntry::MultiLength(bool bInternal /*false*/) { - - //Ensure correct values with no cache - if (!bInternal) REGENTRY_REFRESH_IF_NOCACHE - - size_t nLen; - UINT nIndex; - for (nLen = 0, nIndex = 0; nIndex < vMultiString.size(); nIndex++) - nLen += vMultiString[nIndex].length() + 1; - - return nLen ? nLen+1 : 0; -} - - - -/* =================================================== - * CRegEntry::MultiCount() - * - * Returns the number of strings located within the array. - */ - -size_t CRegEntry::MultiCount() { - - // Ensure correct values with no cache - REGENTRY_REFRESH_IF_NOCACHE - - return vMultiString.size(); -} - - - -/* =================================================== - * CRegEntry::MultiRemoveAt(size_t nIndex) - * - * Simply removes the string stored at the zero-based index of nIndex - */ - -void CRegEntry::MultiRemoveAt(size_t nIndex) { - - // Ensure correct values with no cache - REGENTRY_REFRESH_IF_NOCACHE - - assert(nIndex < vMultiString.size()); - vMultiString.erase(vMultiString.begin()+nIndex); - - // Update the registry - REGENTRY_UPDATE_MULTISTRING - -} - - - -/* =================================================== - * CRegEntry::MultiSetAt(size_t nIndex, LPCTSTR lpszVal) - * - * Alters the value of a string in the array located at - * the 0 based index of nIndex. The new value is lpszVal. - * The index must be within the bounds of the array, with - * the exception of being == the number of elements in - * which case calling this function is equal to calling - * MultiAdd. - */ - -void CRegEntry::MultiSetAt(size_t nIndex, LPCTSTR lpszVal) { - - // Ensure correct values with no cache - REGENTRY_REFRESH_IF_NOCACHE - - assert(nIndex <= vMultiString.size()); - iType = REG_MULTI_SZ; - - // Add a new string element if == elements+1 - if (nIndex == vMultiString.size()) - vMultiString.push_back(lpszVal); - else - vMultiString[nIndex] = lpszVal; - - // Update the registry - REGENTRY_UPDATE_MULTISTRING -} - - - -/* =================================================== - * CRegEntry::MultiGetAt(size_t nIndex) - * - * Returns a constant pointer to the string located in - * the array at the zero-based index of nIndex. Note that - * the return value is not an STL string. - */ - -LPCTSTR CRegEntry::MultiGetAt(size_t nIndex) { - - // Ensure correct values with no cache - REGENTRY_REFRESH_IF_NOCACHE - - assert(nIndex < vMultiString.size() && IsMultiString()); - return vMultiString[nIndex].c_str(); -} - - - -/* =================================================== - * CRegEntry::GetMulti(LPCTSTR lpszDest, size_t nMax) - * - * Copys the entire null-terminated array string to lpszDest. - * For Example: First String\0Second\Third\0\0 - * - * Important Params: - * - * LPCTSTR lpszDest: Pointer to the character array to fill. - * size_t nMax: The maximum characters to read, including null-characters - * - * Note: By default nMax is set to _MAX_REG_VALUE, you can retrieve - * the length of the entire string by calling MultiLength(). - */ - -LPTSTR CRegEntry::GetMulti(LPTSTR lpszDest, size_t nMax) { - - LPCTSTR strBuf; - size_t nCur = 0, nLen = 0; - - assert(IsMultiString()); - if (!IsMultiString()) return &(lpszDest[0] = 0); - - /* If caching is disabled, refresh the entries */ - REGENTRY_REFRESH_IF_NOCACHE - - for (size_t n=0; n < vMultiString.size() && nCur < nMax; n++) { - - strBuf = vMultiString[n].c_str(); - nLen = vMultiString[n].length()+1; - _tcsncpy(lpszDest + nCur, strBuf, (nLen >= nMax ? (nMax-nCur) : nLen) * sizeof(_TCHAR)); - nCur += nLen; - } - - /* Add the final null termination */ - *(lpszDest + nCur) = 0; - - return lpszDest; -} - - -/* =================================================== - * CRegEntry::Delete() - * - * Removes the value from the open registry key, returns - * true on success and false on failure. - */ - -bool CRegEntry::Delete() { - - __bStored = false; - - if (REGENTRY_KEYVALID (KEY_SET_VALUE) ) - return (__cregOwner->AutoClose(), IS_ES(RegDeleteValue(__cregOwner->hKey, lpszName))); - - return false; -} - - - -// BEGIN CREGISTRY FUNCTIONS - - -/* =================================================== - * CRegistry CONSTRUCTOR - * - * Flags: - * - * CREG_CREATE (default) - When attempting to open a key that - * does not exist, create it. - * - * CREG_AUTOOPEN - Close the open registry key handle - * after an action has been performed with it. Opens the - * key whenever another action needs to be performed. - * - * ===================================================*/ - -CRegistry::CRegistry(DWORD flags) { - InitData(); __dwFlags = flags; -} - - - -/* =================================================== - * CRegistry::InitData() - * Initializes the variables related to key locations to NULL. - */ - -void CRegistry::InitData() { - - _lpszSubKey = NULL; - _hRootKey = hKey = NULL; -} - - - -/* =================================================== - * CRegistry::operator []( LPCTSTR lpszVName) - * - * OPERATOR: This will return the Registry Entry (CRegEntry) associated - * with the given value name. If the value name does not exist in - * the open key, it will be created. - * - * Note: If the value name is created, it is only stored in the actual - * registry when the entry's value has been set. - */ - -CRegEntry& CRegistry::operator []( LPCTSTR lpszVName) { - - size_t nValueNameLen = _tcslen(lpszVName) + 1; - assert(nValueNameLen <= _MAX_REG_VALUE); - - for (int i = _reEntries.size()-1; i >=0; i--) { - if (!_tcsicmp(lpszVName, _reEntries[i]->lpszName)) - return *_reEntries[i]; - } - - /* Entry not found */ - _reEntries.push_back(new CRegEntry(this)); - _reEntries.back()->lpszName = new _TCHAR[nValueNameLen]; - _tcsncpy(_reEntries.back()->lpszName, lpszVName, (nValueNameLen > _MAX_REG_VALUE ? _MAX_REG_VALUE : nValueNameLen)); - - return *_reEntries.back(); -} - - - -/* =================================================== - * CRegistry::KeyExists() - * - * Returns true if the key exists and returns false if the key - * does not exist or could not be opened. This may be called - * as a static function. - * - * Example: - * CRegistry::KeyExists("Software\\Something", HKEY_LOCAL_MACHINE); - */ - -bool CRegistry::KeyExists(LPCTSTR lpszRegPath, HKEY hRootKey) { - - CRegistry cregTemp( NULL ); - return cregTemp.Open(lpszRegPath, hRootKey, KEY_QUERY_VALUE, true); -} - - - -/* =================================================== - * CRegistry::SubKeyExists() - * - * Returns true if the subkey exists within the currently - * open key and false if not. - */ - -bool CRegistry::SubKeyExists(LPCTSTR lpszSub) { - - bool bResult; - HKEY hTemp; - - if ((__dwFlags & CREG_AUTOOPEN && !AutoOpen(KEY_QUERY_VALUE)) || hKey == NULL) { - assert(hKey); - return false; - } - - bResult = (RegOpenKeyEx(hKey, lpszSub, 0, KEY_QUERY_VALUE, &hTemp) == ERROR_SUCCESS); - - if (bResult) RegCloseKey(hTemp); - if (__dwFlags & CREG_AUTOOPEN) AutoClose(); - - return bResult; -} - - - -/* =================================================== - * CRegistry::Open(LPCTSTR lpszRegPath, HKEY hRootKey, bool bAuto) - * - * Opens the key in which values will be read and stored, if the key - * is not already existent in the registry, it will be created (if the - * CREG_CREATE) flag is present while constructing the class. - * - * Upon opening the registry key, all of the REG_DWORD and REG_SZ values - * are loaded into a new corresponding CRegEntry for future access. - * - * Important Params: - * - * LPCTSTR lpszRegPath - A NULL terminated const character array containing, - * the location of the subkey. - * For example: "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run" - * - * HKEY hRootKey - An open key handle to the root key. By default - * this value is set as HKEY_LOCAL_MACHINE. - * Another Example: HKEY_CURRENT_USER - * - * Returns true on success and false on failure. - */ - - -bool CRegistry::Open(LPCTSTR lpszRegPath, HKEY hRootKey, DWORD dwAccess, bool bAuto) { - - bool bNew = true; - - - /* If the key is being auto opened, skip directly to opening */ - if (bAuto) goto SkipNoAuto; - - /* The key is being opened manually, if the key location differs - from the last opened location, clear the current entries and - store the path information for future auto opening and key - deletion using DeleteKey() */ - - if (_lpszSubKey){ - - if (_tcsicmp(lpszRegPath, _lpszSubKey)) { - - /* If new key, clear any currently stored entries */ - for (size_t n=0; n<_reEntries.size(); n++) - delete _reEntries[n]; - - _reEntries.clear(); - delete [] _lpszSubKey; - - } else bNew = false; - } - - if (bNew) { - - /* Store path information for auto opening */ - _lpszSubKey = new _TCHAR[_tcslen(lpszRegPath)+1]; - _tcscpy(_lpszSubKey, lpszRegPath); - } - - _hRootKey = hRootKey; - - - SkipNoAuto: - - /* This is where the key is actually opened (if all goes well). - If the key does not exist and the CREG_CREATE flag is present, - it will be created... Any currently opened key will be closed - before opening another one. After opening the key, Refresh() is - called and the key's values are stored in memory for future use. */ - - if (hKey != NULL) Close(); - - - /* If auto opening is set and this is a manual opening - set the appropriate access rights */ - - if (__dwFlags & CREG_AUTOOPEN && !bAuto) { - dwAccess = CREG_CREATE ? KEY_CREATE_SUB_KEY | KEY_QUERY_VALUE : KEY_QUERY_VALUE; - } - - - /* When key creation is enabled and auto opening is disabled, - include key creation in the access rights */ - - else if (__dwFlags & ~CREG_AUTOOPEN && __dwFlags & CREG_CREATE) - dwAccess |= KEY_CREATE_SUB_KEY; - - - - /* Open or create the sub key, and return the result: */ - LONG lResult = (__dwFlags & CREG_CREATE ? - RegCreateKeyEx(hRootKey, lpszRegPath, 0, NULL, REG_OPTION_NON_VOLATILE, dwAccess, NULL, &hKey, NULL) - : RegOpenKeyEx(hRootKey, lpszRegPath, 0, dwAccess, &hKey)); - - return (lResult == ERROR_SUCCESS ? (bAuto ? true : Refresh()) : false); -} - - - -/* =================================================== - * CRegistry::AutoOpen() - * - * If the CREG_AUTOOPEN flag is true, this function is called whenever - * an action needs to be performed involving the registry key. - * - * DWORD dwAccess controls the access required for key use. - */ - -bool CRegistry::AutoOpen(DWORD dwAccess) { - - assert(_lpszSubKey != NULL); - return (hKey == NULL && __dwFlags & CREG_AUTOOPEN ? Open(_lpszSubKey, _hRootKey, dwAccess, true) : true); -} - - - -/* =================================================== - * CRegistry::AutoClose() - * - * If the CREG_AUTOOPEN flag is true, this function is called whenever - * an action has been performed on an open registry key and the key is no longer - * being accessed. - */ - -void CRegistry::AutoClose() { - - if (__dwFlags & CREG_AUTOOPEN) Close(); -} - - - -/* =================================================== - * CRegistry::Refresh() - * - * Enumerates all the REG_SZ, REG_BINARY and REG_DWORD values within the open - * registry key and stores them in a CRegEntry class for future - * access. Returns true on success and false on failure. - */ - -bool CRegistry::Refresh() { - - DWORD dwBufferSize; - DWORD dwType; - DWORD dwNameLen; - DWORD dwValueCount; - LPBYTE lpbBuffer; - - DWORD dwPrevFlags = __dwFlags; - _TCHAR cValueName[_MAX_PATH]; - - - if ((__dwFlags & CREG_AUTOOPEN && !AutoOpen(KEY_QUERY_VALUE)) || hKey == NULL) - return false; - - if (NOT_ES(RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, &dwValueCount, NULL, NULL, NULL, NULL))) - return false; - - lpbBuffer = new BYTE[_MAX_REG_VALUE]; - - - /* Halt auto opening and set loading flag */ - __dwFlags = (__dwFlags | CREG_LOADING) & ~CREG_AUTOOPEN; - - - if (dwValueCount > _reEntries.size()) - _reEntries.reserve(dwValueCount); - - for( DWORD dwIndex = 0; dwIndex < dwValueCount; dwIndex++) { - - dwNameLen = sizeof(cValueName); dwBufferSize = _MAX_REG_VALUE; - cValueName[0] = 0; - - if (NOT_ES(RegEnumValue(hKey, dwIndex, cValueName, &dwNameLen, NULL, &dwType, lpbBuffer, &dwBufferSize))) - continue; - - switch (dwType) { - - case REG_DWORD: - this[0][cValueName] = (LPDWORD)lpbBuffer; - break; - - case REG_SZ: - this[0][cValueName] = (LPCTSTR)lpbBuffer; - break; - - case REG_MULTI_SZ: - this[0][cValueName].SetMulti((LPCTSTR)lpbBuffer, dwBufferSize/sizeof(TCHAR)); - break; - - case REG_BINARY: - this[0][cValueName].SetBinary(lpbBuffer, (size_t)dwBufferSize); - break; - } - } - - if ((__dwFlags = dwPrevFlags) & CREG_AUTOOPEN) AutoClose(); - delete [] lpbBuffer; - - return true; -} - - - -/* =================================================== - * CRegistry::DeleteKey() - * - * Deletes the key which is currently opened, including any - * subkeys and values it may contain. - * - * NOTE: Use extreme caution when calling this function - */ - -void CRegistry::DeleteKey() { - - OSVERSIONINFO osvi; - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - - if (GetVersionEx(&osvi) && osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) - DeleteKey(_hRootKey, _lpszSubKey); - else - RegDeleteKey(_hRootKey, _lpszSubKey); - - Close(); -} - - - -/* =================================================== - * CRegistry::DeleteKey(HKEY hPrimaryKey, LPCTSTR lpszSubKey) - * - * Private member function which is called by DeleteKey() - * This function is designed for NT based systems as it recursively - * deletes any subkeys present. - */ - -void CRegistry::DeleteKey(HKEY hPrimaryKey, LPCTSTR lpszSubKey) { - - DWORD dwKeyLen; - FILETIME ftTemp; - HKEY hTempKey; - - LONG lResult = ERROR_SUCCESS; - LPTSTR lpszKey = new _TCHAR[_MAX_PATH]; - - if (!_tcslen(lpszSubKey) || !hPrimaryKey) { assert(hPrimaryKey != NULL); goto cleanup; } - - if (IS_ES(RegOpenKeyEx(hPrimaryKey, lpszSubKey, 0, KEY_ENUMERATE_SUB_KEYS | KEY_WRITE, &hTempKey))){ - - while (IS_ES(lResult)) { - - dwKeyLen = _MAX_PATH; - lResult = RegEnumKeyEx(hTempKey, 0, lpszKey, &dwKeyLen, NULL, NULL, NULL, &ftTemp); - - if (lResult == ERROR_SUCCESS) DeleteKey(hTempKey, lpszKey); - else if (lResult == ERROR_NO_MORE_ITEMS) RegDeleteKey(hPrimaryKey, lpszSubKey); - } - RegCloseKey(hTempKey); hTempKey = NULL; - } - - cleanup: delete [] lpszKey; -} - - - -/* =================================================== - * CRegistry::Close() - * - * If a key is currently open, it will be closed. This should - * be called when you no longer need to access the registry key - * and the CREG_AUTOOPEN flag is not true. However, Close() is - * called on class deconstruction so it is not required. - */ - -void CRegistry::Close() { - - if (hKey != NULL) { RegCloseKey(hKey); hKey = NULL; } -} - diff --git a/KeyWedge/KeyWedge/Registry.h b/KeyWedge/KeyWedge/Registry.h deleted file mode 100644 index 8fb71c3..0000000 --- a/KeyWedge/KeyWedge/Registry.h +++ /dev/null @@ -1,162 +0,0 @@ - -#if !defined(_REGISTRY_H_INCLUDED) -#define _REGISTRY_H_INCLUDED - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -/* Silence STL warnings */ - -#pragma warning (disable : 4786) -#pragma warning (disable : 4514) -#pragma warning (push, 3) - -#ifdef _UNICODE -#if !defined(UNICODE) -#define UNICODE -#endif -#endif - -#include -#include -#include -#include -#include -#include -#include - - -/* ==================================== - * Begin Preprocessor Definitions - * - * - Ugly, but well worth it. - * ==================================== */ - - -#ifdef _UNICODE -typedef std::wstring tstring; -#else -typedef std::string tstring; -#endif - - -/* CRegistry Open Flags */ - -#define CREG_CREATE 1 -#define CREG_AUTOOPEN 2 -#define CREG_NOCACHE 4 - -/* CRegistry Behaivor flags */ - -#define CREG_LOADING 8 - - -#define _MAX_REG_VALUE 2048 // Maximum Value length, this may be increased - -#define NOT_ES(func) func != ERROR_SUCCESS -#define IS_ES(func) func == ERROR_SUCCESS -#define _R_BUF(size) _TCHAR buffer[size] - -#define REGENTRY_AUTO __cregOwner->GetFlags() & CREG_AUTOOPEN -#define REGENTRY_TRYCLOSE if (REGENTRY_AUTO) __cregOwner->AutoClose() -#define REGENTRY_SZ_SAFE iType == REG_SZ || iType == REG_BINARY -#define REGENTRY_ALLOWCONV(b) __bConvertable = b; - - -#define REGENTRY_REFRESH_IF_NOCACHE \ - if (__cregOwner->GetFlags() & CREG_NOCACHE && \ - REGENTRY_NOTLOADING && REGENTRY_KEYVALID( KEY_QUERY_VALUE ))\ - __cregOwner->Refresh(); - -#define REGENTRY_UPDATE_MULTISTRING \ - LPTSTR lpszBuffer = new _TCHAR[_MAX_REG_VALUE]; \ - REGENTRY_SETLOADING(+); GetMulti(lpszBuffer); REGENTRY_SETLOADING(-); \ - SetMulti(lpszBuffer, MultiLength(true), true); \ - delete [] lpszBuffer; - - -#define REGENTRY_KEYVALID(auto_access) \ - lpszName && ((REGENTRY_AUTO && __cregOwner->AutoOpen(auto_access)) || (!(REGENTRY_AUTO) && __cregOwner->hKey != NULL)) - -#define REGENTRY_NOTLOADING \ - !(__cregOwner->GetFlags() & CREG_LOADING) - -#define REGENTRY_SETLOADING(op) \ - __cregOwner->__dwFlags op= CREG_LOADING - -#define REGENTRY_BINARYTOSTRING \ - if (iType == REG_BINARY) { ForceStr(); lpszStr = *this; } - -#define REGENTRY_NONCONV_STORAGETYPE(type) \ - CRegEntry& operator=( type &Value ){ REGENTRY_ALLOWCONV(false) SetStruct(Value); return *this; } \ - operator type(){ type Return; GetStruct(Return); return Return; } - -#define REGENTRY_CONV_STORAGETYPE(type, to_sz, from_sz, from_dw, no_result) \ - CRegEntry& operator=( type Value ) { to_sz return (*this = (LPCTSTR)(buffer)); } \ - operator type(){ REGENTRY_BINARYTOSTRING return (REGENTRY_SZ_SAFE ? from_sz :(iType == REG_DWORD ? from_dw : no_result)); } - -#define REGENTRY_CONV_NUMERIC_STORAGETYPE(type, maxlen, form, from_sz, from_dw) \ - REGENTRY_CONV_STORAGETYPE(type, _R_BUF(maxlen); _stprintf(buffer, _T(#form), Value);, from_sz, from_dw, 0) - - -/* ==================================== - * Include CRegEntry Class Definition - * ==================================== */ - -#include "RegEntry.h" - -/* ==================================== - * Begin CRegistry Class Definition - * ==================================== */ - -using namespace std; - -class CRegistry { - -public: - - CRegistry (DWORD flags = CREG_CREATE); - virtual ~CRegistry() { Close(); for (UINT i=0; i < _reEntries.size(); ++i) delete _reEntries[i]; delete [] _lpszSubKey; } - - CRegEntry& operator[](LPCTSTR lpszVName); - CRegEntry* GetAt(size_t n) { assert(n < Count()); return _reEntries.at(n); } - - bool Open(LPCTSTR lpszRegPath, HKEY hRootKey = HKEY_LOCAL_MACHINE, - DWORD dwAccess = KEY_QUERY_VALUE | KEY_SET_VALUE, bool bAuto = false); - - bool AutoOpen(DWORD dwAccess); - void AutoClose(); - void Close(); - bool Refresh(); - - static bool KeyExists(LPCTSTR lpszRegPath, HKEY hRootKey = HKEY_LOCAL_MACHINE); - bool SubKeyExists(LPCTSTR lpszSub); - - void DeleteKey(); - - __inline DWORD GetFlags() { return __dwFlags; } - __inline DWORD Count() { return _reEntries.size(); } - - HKEY hKey; /* Registry key handle */ - -protected: - - DWORD __dwFlags; - friend void CRegEntry::MultiSetAt(size_t nIndex, LPCTSTR lpszVal); - friend void CRegEntry::MultiRemoveAt(size_t nIndex); - -private: - - void InitData(); - void DeleteKey(HKEY hPrimaryKey, LPCTSTR lpszSubKey); - - HKEY _hRootKey; - LPTSTR _lpszSubKey; - - std::vector _reEntries; -}; - -#pragma warning(pop) - -#endif diff --git a/KeyWedge/KeyWedge/SSKeyWedge/SSKeyWedge.cpp b/KeyWedge/KeyWedge/SSKeyWedge/SSKeyWedge.cpp deleted file mode 100644 index 52a3dec..0000000 --- a/KeyWedge/KeyWedge/SSKeyWedge/SSKeyWedge.cpp +++ /dev/null @@ -1,646 +0,0 @@ -// DESCRIPTION: -// Configuration configlet implementation of entry points. Rename this file to reflect -// the configlet's feature management set and include configlet2.h -// -// NOTES: -// Assumes that the following registry keys have been created. -// - HKEY_LOCAL_MACHINE\ConfigletTest\Age = some_dword -// - HKEY_LOCAL_MACHINE\ConfigletTest\Name = "some_string" -// - HKEY_LOCAL_MACHINE\ConfigletTest\EyeColor = some_dword -// -// -// COPYRIGHT (c) 2004-2005 INTERMEC TECHNOLOGIES CORPORATION, ALL RIGHTS RESERVED -// - -// I N C L U D E S - -#include "stdafx.h" -#include "configlet2.h" - -// D E F I N E S - -// E N U M S - -// I N T E R N A L C O N S T D A T A -const HKEY hkCFG_ROOT_KEY = HKEY_LOCAL_MACHINE; -const WCHAR sCFG_REG_PATH[ ] = L"\\SOFTWARE\\Intermec\\SSKeyWedge"; -/* - [HKEY_LOCAL_MACHINE\SOFTWARE\HGO\KeyWedge] - "parity"=dword:00000000 - ; 0 NOPARITY - ; 1 ODDPARITY - ; 2 EVENPARITY - ; 3 MARKPARITY - ; 4 SPACEPARITY - "stopbits"=dword:00000000 - ; 0 ONESTOPBIT - ; 1 ONE5STOPBITS - ; 2 TWOSTOPBITS - "databits"=dword:00000008 - ; 7 - ; 8 - ; 16 - "handshake"=dword:00000003 - ; 1 Xon/Xoff - ; 2 Hardware - ; 3 None - "baudrate"=dword:0000e100 - ; 9600 - ; 19200 - ; 38400 - ; 57600 - ; 115200 - "comport"="COM4:" - ; string with trailing : - "sendcharbychar"=dword:00000000 - ; 1 send byte for byte as received - ; 0 send keys when \n received -*/ -const WCHAR sCFG_REG_COMPORT_FIELD[ ] = L"comport"; -const WCHAR sCFG_REG_PARITY_FIELD[ ] = L"parity"; -const WCHAR sCFG_REG_STOPBITS_FIELD[ ] = L"stopbits"; -const WCHAR sCFG_REG_DATABITS_FIELD[ ] = L"databits"; -const WCHAR sCFG_REG_HANDSHAKE_FIELD[ ] = L"handshake"; -const WCHAR sCFG_REG_BAUDRATE_FIELD[ ] = L"baudrate"; -const WCHAR sCFG_REG_SENDCHARBYCHAR_FIELD[ ] = L"sendcharbychar"; - -const WCHAR sCFG_DEFAULT_COMPORT[ ] = L"COM1:"; -const DWORD dwCFG_DEFAULT_PARITY = 0; -const DWORD dwCFG_DEFAULT_STOPBITS = 0; -const DWORD dwCFG_DEFAULT_DATABITS = 8; -const DWORD dwCFG_DEFAULT_HANDSHAKE = 3; -const DWORD dwCFG_DEFAULT_BAUDRATE = 9600; -const DWORD dwCFG_DEFAULT_SENDCHARBYCHAR = 0; - -const DWORD BUFFERSIZE=128; - -// G L O B A L C O N S T D A T A - -// I N T E R N A L D A T A - -// G L O B A L D A T A - -HANDLE g_hEvent = 0; - -// G L O B A L M E T H O D S - -// I N T E R N A L M E T H O D S - -static HRESULT CfgStoreSetString( const HKEY hkRoot, LPCTSTR sStorePath, LPCTSTR sStoreItem, LPTSTR sValue ); -static HRESULT CfgStoreGetString( const HKEY hkRoot, LPCTSTR sStorePath, LPCTSTR sStoreItem, LPTSTR* psValue, DWORD *pdwValueLen ); -static HRESULT CfgRegSetDWORD( const HKEY hKey, LPCTSTR sRegKey, LPCTSTR sValueName, DWORD dwValue ); -static HRESULT CfgRegGetDWORD( const HKEY hKey, LPCTSTR sRegKey, LPCTSTR sValueName, DWORD *pdwValue ); - -// M E T H O D I M P L E M E N T A T I O N - -// Configlet.cpp : Defines the entry point for the DLL application. -// - -BOOL APIENTRY DllMain( HANDLE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved ) -{ - switch( ul_reason_for_call ) - { - case DLL_PROCESS_ATTACH: - { - } // End - DLL_PROCESS_ATTACH - break; - case DLL_THREAD_ATTACH: - { - } // End - DLL_THREAD_ATTACH - break; - case DLL_THREAD_DETACH: - { - } // End - DLL_THREAD_ATTACH - break; - case DLL_PROCESS_DETACH: - { - } // End - DLL_PROCESS_DETACH - break; - } - return( TRUE ); -} // End - DllMain - -// INTERNAL METHOD IMPLEMENTATION - -// EXPORTED METHOD IMPLEMENTATION - -// See configlet2.h for details -CONFIGLET2_INT STDMETHODCALLTYPE IcfgGetInterfaceVersion( VOID ) -{ - HRESULT hr = S_OK; - - const CONFIGLET2_INT iCONFIGLET2_VERSION2 = 2; - - return( iCONFIGLET2_VERSION2 ); -} // End - GetInterfaceVersion - -// See configlet2.h for details -CONFIGLET2_INT STDMETHODCALLTYPE IcfgGetSchemaVersion( CONFIGLET2_CSTR szSubSystem, - CONFIGLET2_INT *pnVersion, - CONFIGLET2_INT *pnVersionMin ) -{ - - HRESULT hr = S_OK; - - *pnVersion = 1; - *pnVersionMin = 0; - - return( hr ); -} // End - IcfgGetSchemaVersion - - -// See configlet2.h for details -CONFIGLET2_INT STDMETHODCALLTYPE IcfgInitialize( VOID ) -{ - HRESULT hr = S_OK; - LONG lResult; - DWORD dwSize; - DWORD dwType; - DWORD dwDisposition; - HKEY hKey; - - // Create the persistent copies of the configuration data. - // If the keys and values already exist, leave them alone and don't overwrite - // If they don't exist, create them and load default values. - lResult = RegCreateKeyEx( - hkCFG_ROOT_KEY, - sCFG_REG_PATH, - 0, - NULL, - 0, - 0, - NULL, - &hKey, - &dwDisposition - ); - - // If comport field doesn't exist, create it and load default value - lResult = RegQueryValueEx( - hKey, - sCFG_REG_COMPORT_FIELD, - NULL, - &dwType, - NULL, - &dwSize - ); - if( lResult != ERROR_SUCCESS ) - { - RegSetValueEx( - hKey, - sCFG_REG_COMPORT_FIELD, - 0, - REG_SZ, - (BYTE*)sCFG_DEFAULT_COMPORT, - sizeof(sCFG_DEFAULT_COMPORT)+2 - ); - } - - // If parity field doesn't exist, create it and load default value - lResult = RegQueryValueEx( - hKey, - sCFG_REG_PARITY_FIELD, - NULL, - &dwType, - NULL, - &dwSize - ); - if( lResult != ERROR_SUCCESS ) - { - lResult = RegSetValueEx( - hKey, - sCFG_REG_PARITY_FIELD, - 0, - REG_DWORD, - (BYTE*)(&dwCFG_DEFAULT_PARITY), - sizeof(dwCFG_DEFAULT_PARITY) - ); - } - - // If stopbits field doesn't exist, create it and load default value - lResult = RegQueryValueEx( - hKey, - sCFG_REG_STOPBITS_FIELD, - NULL, - &dwType, - NULL, - &dwSize - ); - if( lResult != ERROR_SUCCESS ) - { - lResult = RegSetValueEx( - hKey, - sCFG_REG_STOPBITS_FIELD, - 0, - REG_DWORD, - (BYTE*)(&dwCFG_DEFAULT_STOPBITS), - sizeof(dwCFG_DEFAULT_STOPBITS) - ); - } - - // If databits field doesn't exist, create it and load default value - lResult = RegQueryValueEx( - hKey, - sCFG_REG_DATABITS_FIELD, - NULL, - &dwType, - NULL, - &dwSize - ); - if( lResult != ERROR_SUCCESS ) - { - lResult = RegSetValueEx( - hKey, - sCFG_REG_DATABITS_FIELD, - 0, - REG_DWORD, - (BYTE*)(&dwCFG_DEFAULT_DATABITS), - sizeof(dwCFG_DEFAULT_DATABITS) - ); - } - - // If handshake field doesn't exist, create it and load default value - lResult = RegQueryValueEx( - hKey, - sCFG_REG_HANDSHAKE_FIELD, - NULL, - &dwType, - NULL, - &dwSize - ); - if( lResult != ERROR_SUCCESS ) - { - lResult = RegSetValueEx( - hKey, - sCFG_REG_HANDSHAKE_FIELD, - 0, - REG_DWORD, - (BYTE*)(&dwCFG_DEFAULT_HANDSHAKE ), - sizeof(dwCFG_DEFAULT_HANDSHAKE) - ); - } - - // If handshake field doesn't exist, create it and load default value - lResult = RegQueryValueEx( - hKey, - sCFG_REG_BAUDRATE_FIELD, - NULL, - &dwType, - NULL, - &dwSize - ); - if( lResult != ERROR_SUCCESS ) - { - lResult = RegSetValueEx( - hKey, - sCFG_REG_BAUDRATE_FIELD, - 0, - REG_DWORD, - (BYTE*)(&dwCFG_DEFAULT_BAUDRATE ), - sizeof(dwCFG_DEFAULT_BAUDRATE) - ); - } - - // If sendcharbychar field doesn't exist, create it and load default value - lResult = RegQueryValueEx( - hKey, - sCFG_REG_SENDCHARBYCHAR_FIELD, - NULL, - &dwType, - NULL, - &dwSize - ); - if( lResult != ERROR_SUCCESS ) - { - lResult = RegSetValueEx( - hKey, - sCFG_REG_SENDCHARBYCHAR_FIELD, - 0, - REG_DWORD, - (BYTE*)(&dwCFG_DEFAULT_SENDCHARBYCHAR ), - sizeof(dwCFG_DEFAULT_SENDCHARBYCHAR) - ); - } - - RegCloseKey( hKey ); - - // Now create the global named event to communicate with the sample app - g_hEvent = CreateEvent( NULL, FALSE, FALSE, L"SSKeyWedge" ); - - return( hr ); - -} // End - IcfgInitialize - - -// See configlet2.h for details -CONFIGLET2_INT STDMETHODCALLTYPE IcfgUninitialize( VOID ) -{ - HRESULT hr = S_OK; - - return( hr ); -} // End - IcfgUninitialize - - -// See configlet2.h for details -CONFIGLET2_INT STDMETHODCALLTYPE IcfgSetField( CONFIGLET2_CSTR szFieldName, - CONFIGLET2_CSTR szInstance, - CONFIGLET2_CSTR szValue ) -{ - HRESULT hr = S_OK; - LONG lResult = ERROR_SUCCESS; - - // Convert the field name to Unicode - WCHAR* pszFieldName = new WCHAR[BUFFERSIZE]; // to keep it simple, we'll just use a big buffer - MultiByteToWideChar( - CP_UTF8, - 0, - szFieldName, - -1, - pszFieldName, - BUFFERSIZE - ); - - // If the field is the age, we're setting a DWORD - if( 0 == wcscmp( pszFieldName, sCFG_REG_BAUDRATE_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_DATABITS_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_HANDSHAKE_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_PARITY_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_STOPBITS_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_SENDCHARBYCHAR_FIELD ) ) - { - INT iVal = atoi( const_cast< const CHAR * >( szValue ) ); - hr = CfgRegSetDWORD( hkCFG_ROOT_KEY, sCFG_REG_PATH, pszFieldName, ( DWORD )iVal ); - } - - // otherwise, if it's the name or the eye color, we're setting a string - else if( 0 == wcscmp( pszFieldName, sCFG_REG_COMPORT_FIELD ) ) - { - DWORD dwLength = MultiByteToWideChar( - CP_UTF8, - 0, - szValue, - -1, - NULL, - 0 - ); - - WCHAR* pszValue = new WCHAR[dwLength+1]; - - MultiByteToWideChar( - CP_UTF8, - 0, - szValue, - -1, - pszValue, - dwLength+1 - ); - hr = CfgStoreSetString( hkCFG_ROOT_KEY, sCFG_REG_PATH, pszFieldName, pszValue ); - delete[] pszValue; - } - else - { - hr = E_FAIL; - } - delete[] pszFieldName; - return( hr ); -} // End - IcfgSetField - - -// See configlet2.h for details -CONFIGLET2_INT STDMETHODCALLTYPE IcfgGetField( CONFIGLET2_CSTR szFieldName, - CONFIGLET2_CSTR szInstance, - CONFIGLET2_INT nMaxChars, - CONFIGLET2_STR szValue, - CONFIGLET2_INT *pnValueChars ) -{ - HRESULT hr = S_OK; - LONG lResult = ERROR_SUCCESS; - CONFIGLET2_INT iMaxChars = nMaxChars; - - WCHAR* pszFieldName = new WCHAR[BUFFERSIZE]; - DWORD dwLength = MultiByteToWideChar( - CP_UTF8, - 0, - szFieldName, - -1, - pszFieldName, - BUFFERSIZE - ); - - // Age is requested, so get a DWORD - if( 0 == wcscmp( pszFieldName, sCFG_REG_BAUDRATE_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_DATABITS_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_HANDSHAKE_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_PARITY_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_STOPBITS_FIELD ) || - 0 == wcscmp( pszFieldName, sCFG_REG_SENDCHARBYCHAR_FIELD ) ) - { - // Get the value out of the registry - DWORD dwVal = 0; - hr = CfgRegGetDWORD( hkCFG_ROOT_KEY, sCFG_REG_PATH, pszFieldName, &dwVal ); - - // Convert it to text - char digits[11]; // Biggest DWORD is 10 decimal digits, just allocate off the stack - _ltoa( dwVal, digits, 10 ); - *pnValueChars = strlen(digits) + 1; // These are numbers, always ASCII, so strlen works - - // Doesn't fit, return error - if( nMaxChars < *pnValueChars ) - { - hr = E_CONFIGLET2_DATA_TOO_BIG; - } - - // Oh yes it does, return the digit string as instructed - else - { - strcpy( szValue, digits ); - } - - } - - // Name or eye color requested, so get a string - else if( 0 == wcscmp( pszFieldName, sCFG_REG_COMPORT_FIELD ) ) - { - DWORD dwLen = 0; - WCHAR* ppszValue = NULL; - - // If CfgStoreGetString succeeds, returns a buffer pointer in ppszValue. - // WE MUST DELETE IT!! - hr = CfgStoreGetString( hkCFG_ROOT_KEY, sCFG_REG_PATH, pszFieldName, &ppszValue, &dwLen ); - if( SUCCEEDED(hr) ) - { - int nBytes = WideCharToMultiByte( - CP_UTF8, - 0, - ppszValue, - -1, - NULL, - 0, - NULL, - NULL - ); - *pnValueChars = nBytes; - - // Data too big, return error - if( nMaxChars < nBytes ) - { - hr = E_CONFIGLET2_DATA_TOO_BIG; - } - - // No it's not, convert and return result string - else - { - WideCharToMultiByte( - CP_UTF8, - 0, - ppszValue, - -1, - szValue, - nMaxChars, - NULL, - NULL - ); - } - } - if( ppszValue ) - { - delete[] ppszValue; - } - } - else - { - hr = E_FAIL; - } - - delete[] pszFieldName; - - return( hr ); -} // End - IcfgGetField - - - -// U T I L I T Y M E T H O D S - -HRESULT CfgStoreSetString( const HKEY hkRoot, LPCTSTR wsStorePath, LPCTSTR wsStoreItem, LPTSTR wsValue ) -{ - HRESULT hr = S_OK; - DWORD dwErr = ERROR_SUCCESS; - HKEY hLocalKey = NULL; - - - // Open the key - LONG lRet = RegOpenKeyEx( hkRoot, wsStorePath, 0, 0, &hLocalKey ); - if( ERROR_SUCCESS == lRet ) - { - // Set the value - DWORD dwLen = (wcslen(wsValue)+1)*sizeof(WCHAR); - lRet = RegSetValueEx( hLocalKey, wsStoreItem, 0, REG_SZ, ( BYTE * )wsValue, dwLen ); - if( ERROR_SUCCESS != lRet ) - { - hr = HRESULT_FROM_WIN32( lRet ); - } - else - { - SetEvent( g_hEvent ); - } - } // End - RegOpenKeyEx successful - else - { - hr = HRESULT_FROM_WIN32( lRet ); - } // End - RegOpenKeyEx failed - - RegCloseKey( hLocalKey ); - - // Close the key - return( hr ); -} // End - CfgStoreSetString - - -HRESULT CfgStoreGetString( const HKEY hkRoot, LPCTSTR wsStorePath, LPCTSTR wsStoreItem, WCHAR** ppwsValue, DWORD *pdwValueLen ) -{ - - HRESULT hr = S_OK; - DWORD dwErr = ERROR_SUCCESS; - HKEY hLocalKey = NULL; - - // Open the key - LONG lRet = RegOpenKeyEx( hkRoot, wsStorePath, 0, 0, &hLocalKey ); - if( ERROR_SUCCESS == lRet ) - { - // Key opened, get the length of the registry string - DWORD dwType = 0; - DWORD dwReadLen = 0; - lRet = RegQueryValueEx( hLocalKey, wsStoreItem, 0, &dwType, - NULL, &dwReadLen ); - if( ERROR_SUCCESS == lRet ) - { - // Value found, allocate the string (caller will delete) - *ppwsValue = new WCHAR[dwReadLen/2+1]; - - // Read it - lRet = RegQueryValueEx( hLocalKey, wsStoreItem, 0, &dwType, - (BYTE*)(*ppwsValue), &dwReadLen ); - if( ERROR_SUCCESS == lRet ) - { - // Set the length return value - *pdwValueLen = dwReadLen/2; - } - } - } // End - RegOpenKeyEx successful - - hr = HRESULT_FROM_WIN32( lRet ); - RegCloseKey( hLocalKey ); - - return( hr ); -} // End - CfgStoreGetString - - -HRESULT CfgRegSetDWORD( const HKEY hKey, LPCTSTR wsStorePath, LPCTSTR wsStoreItem, DWORD dwValue ) -{ - HRESULT hr = S_OK; - DWORD dwErr = ERROR_SUCCESS; - HKEY hLocalKey = NULL; - - - LONG lRet = RegOpenKeyEx( hKey, wsStorePath, 0, 0, &hLocalKey ); - if( ERROR_SUCCESS == lRet ) - { - DWORD dwType = 0; - DWORD dwSize = sizeof( DWORD ); // indicate that we want sizeof(DWORD) - lRet = RegSetValueEx( hLocalKey, wsStoreItem, NULL, REG_DWORD, - reinterpret_cast< const BYTE * >( &dwValue ), - static_cast< DWORD >( sizeof( dwValue ) ) ); - if( lRet == ERROR_SUCCESS ) - { - SetEvent( g_hEvent ); - } - } // End - RegOpenKeyEx failed - - hr = HRESULT_FROM_WIN32( lRet ); - return( hr ); -} // End - RegSetDWORD - - -HRESULT CfgRegGetDWORD( const HKEY hKey, LPCTSTR wsStorePath, LPCTSTR wsStoreItem, DWORD *pdwValue ) -{ - HRESULT hr = S_OK; - DWORD dwErr = ERROR_SUCCESS; - HKEY hLocalKey = NULL; - - LONG lRet = RegOpenKeyEx( hKey, wsStorePath, 0, 0, &hLocalKey ); - if( ERROR_SUCCESS == lRet ) - { - DWORD dwType = REG_DWORD; - DWORD dwSize = sizeof( DWORD ); - lRet = RegQueryValueEx( hLocalKey, wsStoreItem, NULL, &dwType, - reinterpret_cast< BYTE * >( pdwValue ), &dwSize ); - } // End - RegOpenKeyEx failed - - hr = HRESULT_FROM_WIN32( lRet ); - - return( hr ); -} // End - RegGetDWORD - - -// E N D O F F I L E diff --git a/KeyWedge/KeyWedge/SSKeyWedge/SSKeyWedge.vcproj b/KeyWedge/KeyWedge/SSKeyWedge/SSKeyWedge.vcproj deleted file mode 100644 index 9fc866b..0000000 --- a/KeyWedge/KeyWedge/SSKeyWedge/SSKeyWedge.vcproj +++ /dev/null @@ -1,1995 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/KeyWedge/KeyWedge/SSKeyWedge/StdAfx.cpp b/KeyWedge/KeyWedge/SSKeyWedge/StdAfx.cpp deleted file mode 100644 index af42efc..0000000 --- a/KeyWedge/KeyWedge/SSKeyWedge/StdAfx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// SerialConfiglet.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/KeyWedge/KeyWedge/SSKeyWedge/StdAfx.h b/KeyWedge/KeyWedge/SSKeyWedge/StdAfx.h deleted file mode 100644 index bf825b1..0000000 --- a/KeyWedge/KeyWedge/SSKeyWedge/StdAfx.h +++ /dev/null @@ -1,25 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#if !defined(AFX_STDAFX_H__39109822_0C82_413A_B479_FCAA086CE96C__INCLUDED_) -#define AFX_STDAFX_H__39109822_0C82_413A_B479_FCAA086CE96C__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - - -// Insert your headers here -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -#include -#include - -// TODO: reference additional headers your program requires here - -//{{AFX_INSERT_LOCATION}} -// Microsoft eMbedded Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STDAFX_H__39109822_0C82_413A_B479_FCAA086CE96C__INCLUDED_) diff --git a/KeyWedge/KeyWedge/StdAfx.cpp b/KeyWedge/KeyWedge/StdAfx.cpp deleted file mode 100644 index bee3ea4..0000000 --- a/KeyWedge/KeyWedge/StdAfx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// KeyWedge.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/KeyWedge/KeyWedge/StdAfx.h b/KeyWedge/KeyWedge/StdAfx.h deleted file mode 100644 index 9d98dc8..0000000 --- a/KeyWedge/KeyWedge/StdAfx.h +++ /dev/null @@ -1,25 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#if !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_) -#define AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include - -// Local Header Files - -// TODO: reference additional headers your program requires here - -//{{AFX_INSERT_LOCATION}} -// Microsoft eMbedded Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_) diff --git a/KeyWedge/KeyWedge/UIHelper.h b/KeyWedge/KeyWedge/UIHelper.h deleted file mode 100644 index 8baab4a..0000000 --- a/KeyWedge/KeyWedge/UIHelper.h +++ /dev/null @@ -1,348 +0,0 @@ -/*++ - -Copyright (c) 2003 Microsoft Corporation - -Module Name: - - uihelper.h - -Abstract: - - Include file for HIDPI / orientation / font change helper functions. - ---*/ - -#ifndef __UIHELPER_H__ -#define __UIHELPER_H__ - -#include -#include -#include "shguim.h" - -#ifdef __cplusplus -extern "C" { -#endif - -//////////////////////////////////////////////////////////////////////////////// -// HIDPI functions and constants. -//////////////////////////////////////////////////////////////////////////////// - -#ifndef ILC_COLORMASK -#define ILC_COLORMASK 0x00FE -#endif - -// -// The two macros HIDPISIGN and HIDPIABS are there to ensure correct rounding -// for negative numbers passed into HIDPIMulDiv as x (we want -1.5 to round -// to -1, 2.5 to round to 2, etc). So we use the absolute value of x, and then -// multiply the result by the sign of x. Y and z should never be negative, as -// y is the dpi of the device (presumably 192 or 96), and z is always 96, as -// that is our original dpi we developed on. -// - -#define HIDPISIGN(x) (((x)<0)?-1:1) -#define HIDPIABS(x) (((x)<0)?-(x):x) -#define HIDPIMulDiv(x,y,z) ((((HIDPIABS(x)*(y))+((z)>>1))/(z))*HIDPISIGN(x)) - -// -// Cached values of GetDeviceCaps(LOGPIXELSX/Y) for the screen DC. -// -EXTERN_C int g_HIDPI_LogPixelsX; -EXTERN_C int g_HIDPI_LogPixelsY; - -// -// You need to define these somewhere in your .c files only if you make use of -// the scaling macros. (Defined in UIHelper.cpp). -// -#define HIDPI_ENABLE \ - int g_HIDPI_LogPixelsX; \ - int g_HIDPI_LogPixelsY; - -// -// Scaling macros. -// -#define SCALEX(argX) (HIDPIMulDiv(argX,g_HIDPI_LogPixelsX,96)) -#define SCALEY(argY) (HIDPIMulDiv(argY,g_HIDPI_LogPixelsY,96)) - -#define UNSCALEX(argX) (HIDPIMulDiv(argX,96,g_HIDPI_LogPixelsX)) -#define UNSCALEY(argY) (HIDPIMulDiv(argY,96,g_HIDPI_LogPixelsY)) - -#define SCALERECT(rc) { rc.left = SCALEX(rc.left); rc.right = SCALEX(rc.right); rc.top = SCALEY(rc.top); rc.bottom = SCALEY(rc.bottom);} -#define SCALEPT(pt) { pt.x = SCALEX(pt.x); pt.y = SCALEY(pt.y);} - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_InitScaling -// -// PURPOSE: Initializes g_HIDPI_LogPixelsX and g_HIDPI_LogPixelsY. This -// should be called once at the beginning of any HIDPI-aware application. -// -__inline void HIDPI_InitScaling() -{ - HDC screen; - - if( g_HIDPI_LogPixelsX ) - return; - - screen = GetDC(NULL); - g_HIDPI_LogPixelsX = GetDeviceCaps(screen, LOGPIXELSX); - g_HIDPI_LogPixelsY = GetDeviceCaps(screen, LOGPIXELSY); - ReleaseDC(NULL, screen); -} - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_StretchBitmap -// -// PURPOSE: Stretches a bitmap containing a grid of images. There are -// cImagesX images per row and cImagesY rows per bitmap. Each image is -// scaled individually, so that there are no artifacts with non-integral -// scaling factors. If the bitmap contains only one image, set cImagesX -// and cImagesY to 1. -// -// ON ENTRY: -// HBITMAP* phbm: a pointer to the bitmap to be scaled. -// INT cxDstImg: the width of each image after scaling. -// INT cyDstImg: the height of each image after scaling. -// INT cImagesX: the number of images per row. This value should -// evenly divide the width of the bitmap. -// INT cImagesY: the number of rows in the bitmap. This value should -// evenly divide the height of the bitmap. -// -// ON EXIT: -// Returns TRUE on success, FALSE on failure. -// -// If any scaling has occured, the bitmap pointed to by phbm is deleted -// and is replaced by a new bitmap handle. -// -BOOL HIDPI_StretchBitmap( - HBITMAP* phbm, - int cxDstImg, - int cyDstImg, - int cImagesX, - int cImagesY - ); - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_GetBitmapLogPixels -// -// PURPOSE: retrieves the DPI fields of the specified bitmap. -// -// ON ENTRY: -// HINSTANCE hinst: the HINSTANCE of the bitmap resource. -// LPCTSTR lpbmp: the ID of the bitmap resource. The MAKEINTRESOURCE -// macro can be used for integer IDs. -// INT* pnLogPixelsX: the returned value for the horizontal DPI field of -// the bitmap. This value is never less than 96. -// INT* pnLogPixelsY: the returned value for the vertical DPI field of -// the bitmap. This value is never less than 96. -// -// ON EXIT: -// Returns TRUE on success, FALSE on failure. -// -BOOL HIDPI_GetBitmapLogPixels( - HINSTANCE hinst, - LPCTSTR lpbmp, - int* pnLogPixelsX, - int* pnLogPixelsY - ); - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_StretchIcon -// -// PURPOSE: stretches an icon to the specified size on 4.21 devices and later. -// On 4.20 and previous revisions of the OS, this is a no-op. -// -// ON ENTRY: -// HICON* phic: the icon to stretch. -// INT cxIcon: the desired width of the icon. -// INT cyIcon: the desired height of the icon. -// -// ON EXIT: -// Returns TRUE on success, FALSE on failure. -// -// If any stretching occurred, the icon pointed to by phic is deleted and -// is replaced by a new icon handle. -// -BOOL HIDPI_StretchIcon( - HICON* phic, - int cxIcon, - int cyIcon - ); - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_ImageList_LoadImage -// -// PURPOSE: This function operates identically to ImageList_LoadImage, except -// that it first checks the DPI fields of the bitmap (using -// HIDPI_GetBitmapLogPixels); compares it to the DPI of the screen -// (using g_HIDPI_LogPixelsX and g_HIDPI_LogPixelsY), and performs scaling -// (using HIDPI_StretchBitmap) if the values are different. -// -// ON ENTRY: -// See the MSDN documentation for ImageList_LoadImage. -// -// ON EXIT: -// See the MSDN documentation for ImageList_LoadImage. -// -HIMAGELIST HIDPI_ImageList_LoadImage( - HINSTANCE hinst, - LPCTSTR lpbmp, - int cx, - int cGrow, - COLORREF crMask, - UINT uType, - UINT uFlags - ); - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_ImageList_ReplaceIcon -// -// PURPOSE: Replaces an icon in an ImageList, scaling it from its original size -// to the size of the images in the ImageList. -// -// ON ENTRY: -// See the MSDN documentation for ImageList_ReplaceIcon. -// -// ON EXIT: -// See the MSDN documentation for ImageList_ReplaceIcon. -// -int HIDPI_ImageList_ReplaceIcon( - HIMAGELIST himl, - int i, - HICON hicon - ); - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_ImageList_AddIcon -// -// PURPOSE: Adds an icon to an ImageList, scaling it from its original size -// to the size of the images in the ImageList. -// -// ON ENTRY: -// See the MSDN documentation for ImageList_AddIcon. -// -// ON EXIT: -// See the MSDN documentation for ImageList_AddIcon. -// -#define HIDPI_ImageList_AddIcon(himl, hicon) HIDPI_ImageList_ReplaceIcon(himl, -1, hicon) - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_Rectangle -// -// PURPOSE: Draws a rectangle using the currently selected pen. Drawing occurs -// completely within the drawing rectangle (the rectangle has an "inside -// frame" drawing style). -// -// ON ENTRY: -// HDC hdc: the display context of the drawing surface. -// INT nLeft: left bound of rectangle -// INT nTop: top bound of rectangle -// INT nRight: right bound of rectangle plus one. -// INT nBottom: bottom bound of rectangle plus one. -// -// ON EXIT: -// Returns TRUE on success, FALSE on failure. -// -BOOL HIDPI_Rectangle(HDC hdc, int nLeft, int nTop, int nRight, int nBottom); - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_BorderRectangle -// -// PURPOSE: Draws a rectangle with the system border pen. Drawing occurs -// completely within the drawing rectangle (the rectangle has an "inside -// frame" drawing style). -// -// ON ENTRY: -// HDC hdc: the display context of the drawing surface. -// INT nLeft: left bound of rectangle -// INT nTop: top bound of rectangle -// INT nRight: right bound of rectangle plus one. -// INT nBottom: bottom bound of rectangle plus one. -// -// ON EXIT: -// Returns TRUE on success, FALSE on failure. -// -BOOL HIDPI_BorderRectangle(HDC hdc, int nLeft, int nTop, int nRight, int nBottom); - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_Polyline -// -// PURPOSE: Draws a polyline using the currently selected pen. In addition, -// this function provides control over how the line will be drawn. -// -// ON ENTRY: -// HDC hdc: the display context of the drawing surface. -// const POINT* lppt: array of POINTS that specify line to draw. -// INT cPoints: number of points in array. -// INT nStyle: the style the pen should be drawn in. This may be an -// existing pen style, such as PS_SOLID, or one of the following styles: -// -// PS_LEFTBIAS PS_UPBIAS PS_UPLEFT -// PS_RIGHTBIAS PS_DOWNBIAS PS_DOWNRIGHT -// -// These styles indicate how the pen should "hang" from each line -// segment. By default, the pen is centered along the line, but with -// these line styles the developer can draw lines above, below, to the -// left or to the right of the line segment. -// -// ON EXIT: -// Returns TRUE on success, FALSE on failure. -// - -#define PS_RIGHTBIAS 0x10 -#define PS_LEFTBIAS 0x20 -#define PS_DOWNBIAS 0x40 -#define PS_UPBIAS 0x80 -#define PS_DOWNRIGHT (PS_DOWNBIAS | PS_RIGHTBIAS) -#define PS_UPLEFT (PS_UPBIAS | PS_LEFTBIAS) -#define PS_BIAS_MASK (PS_RIGHTBIAS | PS_LEFTBIAS | PS_DOWNBIAS | PS_UPBIAS) - -BOOL HIDPI_Polyline(HDC hdc, const POINT *lppt, int cPoints, int nStyle); - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: HIDPI_BorderPolyline -// -// PURPOSE: Draws a polyline, but with the system border pen. In addition, -// this function provides control over how the line will be drawn. -// -// ON ENTRY: -// HDC hdc: the display context of the drawing surface. -// const POINT* lppt: array of POINTS that specify line to draw. -// INT cPoints: number of points in array. -// INT nStyle: the style the pen should be drawn in. See HIDPI_Polyline -// for more details. -// -// ON EXIT: -// Returns TRUE on success, FALSE on failure. -// -BOOL HIDPI_BorderPolyline(HDC hdc, const POINT *lppt, int cPoints, int nStyle); - -//////////////////////////////////////////////////////////////////////////////// -// Orientation functions. -//////////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////////// -// FUNCTION: RelayoutDialog -// -// PURPOSE: Re-lays out a dialog based on a dialog template. This function -// iterates through all the child window controls and does a SetWindowPos -// for each. It also does a SetWindowText for each static text control -// and updates the selected bitmap or icon in a static image control. -// This assumes that the current dialog and the new template have all the -// same controls, with the same IDCs. -// -// ON ENTRY: -// HINSTANCE hInst: the hInstance of the current module. -// HWND hDlg: the dialog to layout. -// LPCWSTR iddTemplate: the new template for the dialog (can use -// the MAKEINTRESOURCE macro). -// -// ON EXIT: TRUE if success; FALSE if failure (either the iddTemplate is -// invalid, or there are two or more IDC_STATICs in the template). -// -BOOL RelayoutDialog(HINSTANCE hInst, HWND hDlg, LPCWSTR iddTemplate); - -#ifdef __cplusplus -} -#endif - -#endif // __UIHELPER_H__ diff --git a/KeyWedge/KeyWedge/Windows Mobile 5.0 Pocket PC SDK (ARMV4I)/Release/KeyWedge.exe b/KeyWedge/KeyWedge/Windows Mobile 5.0 Pocket PC SDK (ARMV4I)/Release/KeyWedge.exe deleted file mode 100644 index fea744a..0000000 Binary files a/KeyWedge/KeyWedge/Windows Mobile 5.0 Pocket PC SDK (ARMV4I)/Release/KeyWedge.exe and /dev/null differ diff --git a/KeyWedge/KeyWedge/Windows Mobile 6 Professional SDK (ARMV4I)/Release/KeyWedge.exe b/KeyWedge/KeyWedge/Windows Mobile 6 Professional SDK (ARMV4I)/Release/KeyWedge.exe deleted file mode 100644 index 5de54f1..0000000 Binary files a/KeyWedge/KeyWedge/Windows Mobile 6 Professional SDK (ARMV4I)/Release/KeyWedge.exe and /dev/null differ diff --git a/KeyWedge/KeyWedge/bitmap1.bmp b/KeyWedge/KeyWedge/bitmap1.bmp deleted file mode 100644 index 653b4ec..0000000 Binary files a/KeyWedge/KeyWedge/bitmap1.bmp and /dev/null differ diff --git a/KeyWedge/KeyWedge/common/nclog.cpp b/KeyWedge/KeyWedge/common/nclog.cpp deleted file mode 100644 index 3b56718..0000000 --- a/KeyWedge/KeyWedge/common/nclog.cpp +++ /dev/null @@ -1,254 +0,0 @@ -// --- nclog.cpp --- -#pragma once - -#include -#include "winsock2.h" -#pragma comment (lib, "ws2.lib") - -#include -#include -#include "nclog.h" - -static SOCKET wsa_socket=INVALID_SOCKET; -#pragma comment(lib , "winsock") - -static unsigned short theLogPort; - -//file stuff -//global -static char logFileName[MAX_PATH]; -static TCHAR logFileNameW[MAX_PATH]; -static BOOL bFirstFileCall = true; - -bool bUseFileLog=FALSE; - -// bind the log socket to a specific port. -static bool wsa_bind(unsigned short port) -{ - SOCKADDR_IN addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = htonl(INADDR_ANY); - int r=bind(wsa_socket,(sockaddr*)&addr,sizeof(addr)); - if (r==0) - theLogPort=port; - return (r==0); -} - -// initialize everything, if the socket isn't open. -static bool wsa_init() -{ - if (wsa_socket != INVALID_SOCKET) return true; - int r; - WSADATA wd; - BOOL bc=true; - - if (0 != WSAStartup(0x101, &wd)) - goto error; - wsa_socket=socket(PF_INET, SOCK_DGRAM, 0); - if (wsa_socket == INVALID_SOCKET) - goto error; - r=setsockopt(wsa_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bc, sizeof(bc)); - if (r!=0) - goto error; - if (wsa_bind(9998)) - return true; // bind to default port. - error: - if (wsa_socket != INVALID_SOCKET) - closesocket(wsa_socket); -#ifdef DEBUG - OutputDebugString(TEXT("nclog: TCP/IP Problem")); -#endif - return false; - -} - -// can be called externally to select a different port for operations -bool set_nclog_port(unsigned short x) { return wsa_bind(x); } - -static void wsa_send(const char *x) -{ - SOCKADDR_IN sa; - sa.sin_family = AF_INET; - sa.sin_port = htons(theLogPort); - sa.sin_addr.s_addr = htonl(INADDR_BROADCAST); - - if (SOCKET_ERROR == sendto(wsa_socket,x,strlen(x), 0, (sockaddr*) &sa, sizeof(sa))) - { -#ifdef DEBUG - //if (debug_mode) -// OutputDebugString(TEXT("nclog: Send Error")); -#endif - } - -} - -//========================== start of file stuff ============================= -static int initFileNames() -{ - // Get name of executable - TCHAR lpFileName1[MAX_PATH+1]; - GetModuleFileName(NULL, lpFileName1, MAX_PATH); //lpFileName will contain the exe name of this running app! - - //add txt extension - TCHAR txtFileName[MAX_PATH+1]; - wsprintf(txtFileName, L"%s.log.txt", lpFileName1); - //store the filename to use in char and tchar - TCHAR logFileNameW[MAX_PATH]; - - //#### we maintain two log files, an actual and a bak one - //get file size - HANDLE hFile = CreateFile(txtFileName, - GENERIC_READ, // open for writing - FILE_SHARE_READ, // share - NULL, // default security - OPEN_EXISTING, // open existing - FILE_ATTRIBUTE_NORMAL, // normal file - NULL); // no attr. template - DWORD dwFileSize = GetFileSize(hFile, NULL); - CloseHandle(hFile); - - if(dwFileSize != 0xFFFFFFFF){ //no error - if(dwFileSize>0x100000){ //more than 1MB? - //make a backup - //delete previous bak - TCHAR txtFileNameBAK[MAX_PATH]; - wsprintf(txtFileNameBAK, L"%s.bak", txtFileName); - DeleteFile(txtFileNameBAK); - //rename old file to .BAK - MoveFile(txtFileName, txtFileNameBAK); - } - } - - //copy filename to global char and tchar var - wsprintf(logFileNameW, txtFileName); - wcstombs(logFileName, logFileNameW, sizeof(logFileNameW)*sizeof(logFileNameW[0])); - - FILE *fp; - fp = fopen(logFileName, "a+"); - fclose(fp); - bFirstFileCall=false; - return 0; -} - -TCHAR* logDateTime(){ - static TCHAR str[64]; - TCHAR lpTimeStr[32]; - TCHAR lpDateStr[32]; - LONG res; - wsprintf(str,L""); - //Read the system time - res = GetTimeFormat(LOCALE_SYSTEM_DEFAULT, - TIME_FORCE24HOURFORMAT, - NULL, - L"hh:mm:ss", - lpTimeStr, - sizeof (lpTimeStr ) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpTimeStr, L"err"); - } - - //Read the system date - res = GetDateFormat( LOCALE_SYSTEM_DEFAULT, - NULL, - NULL, - L"dd.MM.yyyy", - lpDateStr, - sizeof (lpDateStr) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpDateStr, L"err"); - } - - wsprintf(str, L"Date and Time: %s %s", lpDateStr, lpTimeStr); - return str; -} - -static int writefile(TCHAR *filetext){ - /* File Write Function, written by professor chemicalX */ - FILE *fp; /* Declare FILE structure */ - TCHAR szTemp[1024]; - char szTempA[1024]; - - wsprintf(szTemp, L"%s", filetext); - wcstombs(szTempA, szTemp, sizeof(szTemp)/sizeof(TCHAR)); - - if (bFirstFileCall){ - // Get name of executable - initFileNames(); - } - - fp = fopen(logFileName, "a+"); - - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - /* First of we open the file supplied by the filename paremeter */ - - /* - * in the "a+" mode for appending, so if it doesnt exist its created. - * fp = fopen(filename,"w"); // Open using the "w" mode for writing. - */ - long fsize = strlen(szTempA); /* Declare the long fsize with the length of the filetext */ - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - /* paremeter witch stores the text or data to right to the file. */ - fwrite(szTempA, 1, fsize, fp); /* Write File */ - DEBUGMSG(1, (L"%s", filetext)); - fclose(fp); /* Remember to close the file stream after calling file functions, */ - - /* otherwise the file wont be created. */ - return 0; -} - -int writefile (const wchar_t *fmt ...){ - va_list vl; - va_start(vl,fmt); - wchar_t buf[1024]; // to bad CE hasn't got wvnsprintf - wvsprintf(buf,fmt,vl); - writefile(buf); - return 0; -} - -//========================== end of file stuff ============================= - -// format input, convert to 8-bit and send. -void nclog (const wchar_t *fmt, ...) -{ - va_list vl; - va_start(vl,fmt); - wchar_t buf[1024]; // to bad CE hasn't got wvnsprintf - wvsprintf(buf,fmt,vl); - -#ifdef DEBUG - DEBUGMSG(1, (buf)); -#else - RETAILMSG(1, (buf)); -#endif - if(bUseFileLog==FALSE) - return; - - - wsa_init(); - char bufOut[512]; - WideCharToMultiByte(CP_ACP,0,buf,-1,bufOut,400, NULL, NULL); - wsa_send(bufOut); - - writefile(buf); -} - -// finalize the socket on program termination. -struct _nclog_module -{ - ~_nclog_module() - { - if (wsa_socket!=INVALID_SOCKET) - { - nclog(L"nclog goes down\n"); - shutdown(wsa_socket,2); - closesocket(wsa_socket); - } - } - -}; - -static _nclog_module module; diff --git a/KeyWedge/KeyWedge/common/nclog.h b/KeyWedge/KeyWedge/common/nclog.h deleted file mode 100644 index a1eef86..0000000 --- a/KeyWedge/KeyWedge/common/nclog.h +++ /dev/null @@ -1,31 +0,0 @@ -//nclog.h - -#ifndef NCLOGINCLUDED -#define NCLOGINCLUDED - -void nclog (const wchar_t *fmt, ...); -//extern bool set_nclog_port(unsigned short x) { return wsa_bind(x); } -TCHAR* logDateTime(); - -int writefile(TCHAR *filetext); -int writefile(const wchar_t *fmt ...); - -extern bool bUseFileLog; -/* -usage: - nclog(L"The Window Handle is: %x\n",hwnd); - -On your desktop, you need netcat to capture the output from your -program, i.e. you open a console and type: - -netcat -lup 9998 - -This will instruct netcat to show you everything that comes to your UDP -socket 9998 (which is the default for netcat). Since nclog opens the -socket in broadcast mode, you don't have to give an target adress. (Be -sure to select a port which does not interfer with the network you are -living in) - -*/ - -#endif \ No newline at end of file diff --git a/KeyWedge/KeyWedge/icon1.ico b/KeyWedge/KeyWedge/icon1.ico deleted file mode 100644 index eea41a6..0000000 Binary files a/KeyWedge/KeyWedge/icon1.ico and /dev/null differ diff --git a/KeyWedge/KeyWedge/iwedge_s.ico b/KeyWedge/KeyWedge/iwedge_s.ico deleted file mode 100644 index 4254ae7..0000000 Binary files a/KeyWedge/KeyWedge/iwedge_s.ico and /dev/null differ diff --git a/KeyWedge/KeyWedge/iwedge_w.ico b/KeyWedge/KeyWedge/iwedge_w.ico deleted file mode 100644 index dbdb8ff..0000000 Binary files a/KeyWedge/KeyWedge/iwedge_w.ico and /dev/null differ diff --git a/KeyWedge/KeyWedge/keymap.cpp b/KeyWedge/KeyWedge/keymap.cpp deleted file mode 100644 index 645ca3e..0000000 --- a/KeyWedge/KeyWedge/keymap.cpp +++ /dev/null @@ -1,266 +0,0 @@ -//keymap.cpp - -#include - -#include "keymap.h" - - // the translation tabel for ASCII to VK_ values - struct KTABLE vkTable[] = { - {0x00, "NUL", VK_NUL, false}, - {0x01, "SOH", VK_SOH, false}, - {0x02, "STX", VK_STX, false}, - {0x03, "ETX", VK_ETX, false}, - {0x04, "EOT", VK_EOT, false}, - {0x05, "ENQ", VK_ENQ, false}, - {0x06, "ACK", VK_ACK, false}, - {0x07, "BEL", VK_BEL, false}, - {0x08, "BS", VK_BACK, false}, - {0x09, "HT", VK_TAB, false}, - {0x0A, "LF", VK_RETURN, false}, - {0x0B, "VT", VK_VT, false}, - {0x0C, "FF", VK_FF, false}, - {0x0D, "CR", VK_RETURN, false}, - {0x0E, "SO", VK_SO, false}, - {0x0F, "SI", VK_SI, false}, - {0x10, "DLE", VK_DLE, false}, - {0x11, "DC1", VK_DC1, false}, - {0x12, "DC2", VK_DC2, false}, - {0x13, "DC3", VK_DC3, false}, - {0x14, "DC4", VK_DC4, false}, - {0x15, "NAK", VK_NAK, false}, - {0x16, "SYN", VK_SYN, false}, - {0x17, "ETB", VK_ETB, false}, - {0x18, "CAN", VK_CAN, false}, - {0x19, "EM", VK_EM, false}, - {0x1A, "SUB", VK_SUB, false}, - {0x1B, "ESC", VK_ESCAPE, false}, - {0x1C, "FS", VK_FS, false}, - {0x1D, "GS", VK_GS, false}, - {0x1E, "RS", VK_RS, false}, - {0x1F, "US", VK_US, false}, - {0x20, " ", VK_SPACE, false}, - {0x21, "!", VK_1, true}, - {0x22, "\"", VK_APOSTROPHE, true}, - {0x23, "#", VK_3, true}, - {0x24, "$", VK_4, true}, - {0x25, "%", VK_5, true}, - {0x26, "&", VK_7, true}, - {0x27, "'", VK_APOSTROPHE, false}, - {0x28, "(", VK_9, true}, - {0x29, ")", VK_0, true}, - {0x2A, "*", VK_8, true}, - {0x2B, "+", VK_EQUAL, true}, - {0x2C, ",", VK_COMMA, false}, - {0x2D, "-", VK_HYPHEN, false}, - {0x2E, ".", VK_PERIOD, false}, - {0x2F, "/", VK_SLASH, false}, - {0x30, "0", VK_0, false}, - {0x31, "1", VK_1, false}, - {0x32, "2", VK_2, false}, - {0x33, "3", VK_3, false}, - {0x34, "4", VK_4, false}, - {0x35, "5", VK_5, false}, - {0x36, "6", VK_6, false}, - {0x37, "7", VK_7, false}, - {0x38, "8", VK_8, false}, - {0x39, "9", VK_9, false}, - {0x3A, ":", VK_SEMICOLON, true}, - {0x3B, ";", VK_SEMICOLON, false}, - {0x3C, "<", VK_COMMA, true}, - {0x3D, "=", VK_EQUAL, false}, - {0x3E, ">", VK_PERIOD, true}, - {0x3F, "?", VK_SLASH, true}, - {0x40, "@", VK_2, true}, - {0x41, "A", VK_A, true}, - {0x42, "B", VK_B, true}, - {0x43, "C", VK_C, true}, - {0x44, "D", VK_D, true}, - {0x45, "E", VK_E, true}, - {0x46, "F", VK_F, true}, - {0x47, "G", VK_G, true}, - {0x48, "H", VK_H, true}, - {0x49, "I", VK_I, true}, - {0x4A, "J", VK_J, true}, - {0x4B, "K", VK_K, true}, - {0x4C, "L", VK_L, true}, - {0x4D, "M", VK_M, true}, - {0x4E, "N", VK_N, true}, - {0x4F, "O", VK_O, true}, - {0x50, "P", VK_P, true}, - {0x51, "Q", VK_Q, true}, - {0x52, "R", VK_R, true}, - {0x53, "S", VK_S, true}, - {0x54, "T", VK_T, true}, - {0x55, "U", VK_U, true}, - {0x56, "V", VK_V, true}, - {0x57, "W", VK_W, true}, - {0x58, "X", VK_X, true}, - {0x59, "Y", VK_Y, true}, - {0x5A, "Z", VK_Z, true}, - {0x5B, "[", VK_LBRACKET, false}, - {0x5C, "\\", VK_BACKSLASH, false}, - {0x5D, "]", VK_RBRACKET, false}, - {0x5E, "^", VK_6, true}, - {0x5F, "_", VK_HYPHEN, true}, - {0x60, "`", VK_BACKQUOTE, false}, - {0x61, "a", VK_A, false}, - {0x62, "b", VK_B, false}, - {0x63, "c", VK_C, false}, - {0x64, "d", VK_D, false}, - {0x65, "e", VK_E, false}, - {0x66, "f", VK_F, false}, - {0x67, "g", VK_G, false}, - {0x68, "h", VK_H, false}, - {0x69, "i", VK_I, false}, - {0x6A, "j", VK_J, false}, - {0x6B, "k", VK_K, false}, - {0x6C, "l", VK_L, false}, - {0x6D, "m", VK_M, false}, - {0x6E, "n", VK_N, false}, - {0x6F, "o", VK_O, false}, - {0x70, "p", VK_P, false}, - {0x71, "q", VK_Q, false}, - {0x72, "r", VK_R, false}, - {0x73, "s", VK_S, false}, - {0x74, "t", VK_T, false}, - {0x75, "u", VK_U, false}, - {0x76, "v", VK_V, false}, - {0x77, "w", VK_W, false}, - {0x78, "x", VK_X, false}, - {0x79, "y", VK_Y, false}, - {0x7A, "z", VK_Z, false}, - {0x7B, "{", VK_LBRACKET, true}, - {0x7C, "|", VK_BACKSLASH, true}, - {0x7D, "}", VK_RBRACKET, true}, - {0x7E, "~", VK_BACKQUOTE, true}, - {0x7F, "DEL", VK_DELETE, false}, - //this will not come from ASCII barcode readers - {0x80, "\x80", 0x80, true}, - {0x81, "\x81", 0x81, true}, - {0x82, "\x82", 0x82, true}, - {0x83, "\x83", 0x83, true}, - {0x84, "\x84", 0x84, true}, - {0x85, "\x85", 0x85, true}, - {0x86, "\x86", 0x86, true}, - {0x87, "\x87", 0x87, true}, - {0x88, "\x88", 0x88, true}, - {0x89, "\x89", 0x89, true}, - {0x8A, "\x8A", 0x8A, true}, - {0x8B, "\x8B", 0x8B, true}, - {0x8C, "\x8C", 0x8C, true}, - {0x8D, "\x8D", 0x8D, true}, - {0x8E, "\x8E", 0x8E, true}, - {0x8F, "\x8F", 0x8F, true}, - {0x90, "\x90", 0x90, true}, - {0x91, "\x91", 0x91, true}, - {0x92, "\x92", 0x92, true}, - {0x93, "\x93", 0x93, true}, - {0x94, "\x94", 0x94, true}, - {0x95, "\x95", 0x95, true}, - {0x96, "\x96", 0x96, true}, - {0x97, "\x97", 0x97, true}, - {0x98, "\x98", 0x98, true}, - {0x99, "\x99", 0x99, true}, - {0x9A, "\x9A", 0x9A, true}, - {0x9B, "\x9B", 0x9B, true}, - {0x9C, "\x9C", 0x9C, true}, - {0x9D, "\x9D", 0x9D, true}, - {0x9E, "\x9E", 0x9E, true}, - {0x9F, "\x9F", 0x9F, true}, - {0xA0, "\xA0", 0xA0, true}, - {0xA1, "", 0xA1, true}, - {0xA2, "", 0xA2, true}, - {0xA3, "", 0xA3, true}, - {0xA4, "", 0xA4, true}, - {0xA5, "", 0xA5, true}, - {0xA6, "", 0xA6, true}, - {0xA7, "", 0xA7, true}, - {0xA8, "", 0xA8, true}, - {0xA9, "", 0xA9, true}, - {0xAA, "", 0xAA, true}, - {0xAB, "", 0xAB, true}, - {0xAC, "", 0xAC, true}, - {0xAD, "", 0xAD, true}, - {0xAE, "", 0xAE, true}, - {0xAF, "", 0xAF, true}, - {0xB0, "", 0xB0, true}, - {0xB1, "", 0xB1, true}, - {0xB2, "", 0xB2, true}, - {0xB3, "", 0xB3, true}, - {0xB4, "", 0xB4, true}, - {0xB5, "", 0xB5, true}, - {0xB6, "", 0xB6, true}, - {0xB7, "", 0xB7, true}, - {0xB8, "", 0xB8, true}, - {0xB9, "", 0xB9, true}, - {0xBA, "", 0xBA, true}, - {0xBB, "", 0xBB, true}, - {0xBC, "", 0xBC, true}, - {0xBD, "", 0xBD, true}, - {0xBE, "", 0xBE, true}, - {0xBF, "", 0xBF, true}, - {0xC0, "", 0xC0, true}, - {0xC1, "", 0xC1, true}, - {0xC2, "", 0xC2, true}, - {0xC3, "", 0xC3, true}, - {0xC4, "", 0xC4, true}, - {0xC5, "", 0xC5, true}, - {0xC6, "", 0xC6, true}, - {0xC7, "", 0xC7, true}, - {0xC8, "", 0xC8, true}, - {0xC9, "", 0xC9, true}, - {0xCA, "", 0xCA, true}, - {0xCB, "", 0xCB, true}, - {0xCC, "", 0xCC, true}, - {0xCD, "", 0xCD, true}, - {0xCE, "", 0xCE, true}, - {0xCF, "", 0xCF, true}, - {0xD0, "", 0xD0, true}, - {0xD1, "", 0xD1, true}, - {0xD2, "", 0xD2, true}, - {0xD3, "", 0xD3, true}, - {0xD4, "", 0xD4, true}, - {0xD5, "", 0xD5, true}, - {0xD6, "", 0xD6, true}, - {0xD7, "", 0xD7, true}, - {0xD8, "", 0xD8, true}, - {0xD9, "", 0xD9, true}, - {0xDA, "", 0xDA, true}, - {0xDB, "", 0xDB, true}, - {0xDC, "", 0xDC, true}, - {0xDD, "", 0xDD, true}, - {0xDE, "", 0xDE, true}, - {0xDF, "", 0xDF, true}, - {0xE0, "", 0xE0, true}, - {0xE1, "", 0xE1, true}, - {0xE2, "", 0xE2, true}, - {0xE3, "", 0xE3, true}, - {0xE4, "", 0xE4, true}, - {0xE5, "", 0xE5, true}, - {0xE6, "", 0xE6, true}, - {0xE7, "", 0xE7, true}, - {0xE8, "", 0xE8, true}, - {0xE9, "", 0xE9, true}, - {0xEA, "", 0xEA, true}, - {0xEB, "", 0xEB, true}, - {0xEC, "", 0xEC, true}, - {0xED, "", 0xED, true}, - {0xEE, "", 0xEE, true}, - {0xEF, "", 0xEF, true}, - {0xF0, "", 0xF0, true}, - {0xF1, "", 0xF1, true}, - {0xF2, "", 0xF2, true}, - {0xF3, "", 0xF3, true}, - {0xF4, "", 0xF4, true}, - {0xF5, "", 0xF5, true}, - {0xF6, "", 0xF6, true}, - {0xF7, "", 0xF7, true}, - {0xF8, "", 0xF8, true}, - {0xF9, "", 0xF9, true}, - {0xFA, "", 0xFA, true}, - {0xFB, "", 0xFB, true}, - {0xFC, "", 0xFC, true}, - {0xFD, "", 0xFD, true}, - {0xFE, "", 0xFE, true}, - {0xFF, "", 0xFF, true} - }; diff --git a/KeyWedge/KeyWedge/keymap.h b/KeyWedge/KeyWedge/keymap.h deleted file mode 100644 index 6e896fd..0000000 --- a/KeyWedge/KeyWedge/keymap.h +++ /dev/null @@ -1,93 +0,0 @@ -//keymap.h - -#include -#pragma once - -#ifndef _KEYMAP_ -#define _KEYMAP_ - #define MAX_BUFSIZE 1000 - - #define KTAB_SIZE 0xFF - - //some undefined VK values - #define VK_UNDEF 0x00 - #define VK_NUL VK_UNDEF - #define VK_SOH VK_UNDEF - #define VK_STX VK_UNDEF - #define VK_ETX VK_UNDEF - #define VK_EOT VK_UNDEF - #define VK_ENQ VK_UNDEF - #define VK_ACK VK_UNDEF - #define VK_BEL VK_UNDEF - #define VK_VT VK_UNDEF - #define VK_FF VK_UNDEF - #define VK_SO VK_UNDEF - #define VK_SI VK_UNDEF - #define VK_DLE VK_UNDEF - #define VK_DC1 VK_UNDEF - #define VK_DC2 VK_UNDEF - #define VK_DC3 VK_UNDEF - #define VK_DC4 VK_UNDEF - #define VK_NAK VK_UNDEF - #define VK_SYN VK_UNDEF - #define VK_ETB VK_UNDEF - #define VK_CAN VK_UNDEF - #define VK_EM VK_UNDEF - #define VK_SUB VK_UNDEF - #define VK_FS VK_UNDEF - #define VK_GS VK_UNDEF - #define VK_RS VK_UNDEF - #define VK_US VK_UNDEF - - // some more undefined vk values - #define VK_0 0x30 - #define VK_1 0x31 - #define VK_2 0x32 - #define VK_3 0x33 - #define VK_4 0x34 - #define VK_5 0x35 - #define VK_6 0x36 - #define VK_7 0x37 - #define VK_8 0x38 - #define VK_9 0x39 - #define VK_A 0x41 - #define VK_B 0x42 - #define VK_C 0x43 - #define VK_D 0x44 - #define VK_E 0x45 - #define VK_F 0x46 - #define VK_G 0x47 - #define VK_H 0x48 - #define VK_I 0x49 - #define VK_J 0x4A - #define VK_K 0x4B - #define VK_L 0x4C - #define VK_M 0x4D - #define VK_N 0x4E - #define VK_O 0x4F - #define VK_P 0x50 - #define VK_Q 0x51 - #define VK_R 0x52 - #define VK_S 0x53 - #define VK_T 0x54 - #define VK_U 0x55 - #define VK_V 0x56 - #define VK_W 0x57 - #define VK_X 0x58 - #define VK_Y 0x59 - #define VK_Z 0x5A - - // the struct used to save a ASCII <-> VK_ table - struct KTABLE{ - byte kByte[1]; - char txt[15]; - byte kVKval; //the VK value to send for kChar/kByte - bool kShift; - }; - - typedef KTABLE* pKTABLE; - - extern struct KTABLE vkTable[]; - -#endif //_KEYMAP_ - diff --git a/KeyWedge/KeyWedge/newres.h b/KeyWedge/KeyWedge/newres.h deleted file mode 100644 index 89e6e23..0000000 --- a/KeyWedge/KeyWedge/newres.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef __NEWRES_H__ -#define __NEWRES_H__ - -#if !defined(UNDER_CE) - #define UNDER_CE _WIN32_WCE -#endif - -#if defined(_WIN32_WCE) - #if !defined(WCEOLE_ENABLE_DIALOGEX) - #define DIALOGEX DIALOG DISCARDABLE - #endif - #include - #define SHMENUBAR RCDATA - #if defined(WIN32_PLATFORM_PSPC) && (_WIN32_WCE >= 300) - #include - #else - #define I_IMAGENONE (-2) - #define NOMENU 0xFFFF - #define IDS_SHNEW 1 - - #define IDM_SHAREDNEW 10 - #define IDM_SHAREDNEWDEFAULT 11 - #endif -#endif // _WIN32_WCE - - -#ifdef RC_INVOKED -#ifndef _INC_WINDOWS -#define _INC_WINDOWS - #include "winuser.h" // extract from windows header -#endif -#endif - -#ifdef IDC_STATIC -#undef IDC_STATIC -#endif -#define IDC_STATIC (-1) - -#endif //__NEWRES_H__ diff --git a/KeyWedge/KeyWedge/resource.h b/KeyWedge/KeyWedge/resource.h deleted file mode 100644 index 6237aa7..0000000 --- a/KeyWedge/KeyWedge/resource.h +++ /dev/null @@ -1,53 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by KeyWedge.rc -// -#define IDS_APP_TITLE 1 -#define IDS_HELLO 2 -#define IDC_KEYWEDGE 3 -#define IDI_KEYWEDGE 101 -#define IDM_MENU 102 -#define IDD_ABOUTBOX 103 -#define IWEDGE_STARTED 104 -#define IDI_COMMERROR 105 -#define IDD_OPTIONSBOX 106 -#define IWEDGE_WAITING 107 -#define IDB_BITMAP1 108 -#define IDI_ICON1 110 -#define IDI_ICON2 111 -#define IDI_ICON3 112 -#define IDD_OPTIONSBOX_WIDE 113 -#define IDC_BAUD 1001 -#define IDC_DATABITS 1002 -#define IDC_PARITY 1003 -#define IDC_STOPBITS 1004 -#define IDC_HANDSHAKE 1005 -#define IDC_EDIT1 1006 -#define IDC_COMPORT 1007 -#define IDC_CHECK1 1008 -#define IDC_CHECK2 1009 -#define IDC_Pre 1010 -#define IDC_Post 1011 -#define IDC_STATIC_1 10001 -#define IDC_STATIC_2 10002 -#define IDC_STATIC_3 10003 -#define IDC_STATIC_4 10004 -#define IDC_STATIC_5 10005 -#define IDC_STATIC_6 10006 -#define IDC_STATIC_7 10007 -#define IDC_STATIC_8 10008 -#define IDM_FILE_EXIT 40002 -#define IDM_HELP_ABOUT 40003 -#define IDM_OPTIONS 40004 -#define IDM_HIDE 40005 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 114 -#define _APS_NEXT_COMMAND_VALUE 40006 -#define _APS_NEXT_CONTROL_VALUE 1011 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/KeyWedge/KeyWedge/scan_off.ico b/KeyWedge/KeyWedge/scan_off.ico deleted file mode 100644 index 8b4a477..0000000 Binary files a/KeyWedge/KeyWedge/scan_off.ico and /dev/null differ diff --git a/KeyWedge/KeyWedge/scan_ok.ico b/KeyWedge/KeyWedge/scan_ok.ico deleted file mode 100644 index 25a1810..0000000 Binary files a/KeyWedge/KeyWedge/scan_ok.ico and /dev/null differ diff --git a/KeyWedge/KeyWedge/scanwarn.ico b/KeyWedge/KeyWedge/scanwarn.ico deleted file mode 100644 index f10f7c9..0000000 Binary files a/KeyWedge/KeyWedge/scanwarn.ico and /dev/null differ diff --git a/MoveableWinForm/MovableForm/MovableForm.sln b/MoveableWinForm/MovableForm/MovableForm.sln deleted file mode 100644 index 50ef10b..0000000 --- a/MoveableWinForm/MovableForm/MovableForm.sln +++ /dev/null @@ -1,32 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MovableForm", "MovableForm\MovableForm.csproj", "{CBFF1208-7627-4902-BEDE-ADF54A285C97}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MoveableFormCF2", "MoveableFormCF2\MoveableFormCF2.csproj", "{F6DAD591-222D-4271-8B7B-C61D613864CD}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {CBFF1208-7627-4902-BEDE-ADF54A285C97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CBFF1208-7627-4902-BEDE-ADF54A285C97}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CBFF1208-7627-4902-BEDE-ADF54A285C97}.Release|Any CPU.Build.0 = Release|Any CPU - {CBFF1208-7627-4902-BEDE-ADF54A285C97}.Release|Any CPU.Deploy.0 = Release|Any CPU - {F6DAD591-222D-4271-8B7B-C61D613864CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F6DAD591-222D-4271-8B7B-C61D613864CD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F6DAD591-222D-4271-8B7B-C61D613864CD}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {F6DAD591-222D-4271-8B7B-C61D613864CD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F6DAD591-222D-4271-8B7B-C61D613864CD}.Release|Any CPU.Build.0 = Release|Any CPU - {F6DAD591-222D-4271-8B7B-C61D613864CD}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/MoveableWinForm/MovableForm/MovableForm/Form1.Designer.cs b/MoveableWinForm/MovableForm/MovableForm/Form1.Designer.cs deleted file mode 100644 index 0fc3505..0000000 --- a/MoveableWinForm/MovableForm/MovableForm/Form1.Designer.cs +++ /dev/null @@ -1,90 +0,0 @@ -namespace MovableForm -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.btnMove = new System.Windows.Forms.Button(); - this.button1 = new System.Windows.Forms.Button(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.inputPanel1 = new Microsoft.WindowsCE.Forms.InputPanel(); - this.SuspendLayout(); - // - // btnMove - // - this.btnMove.Location = new System.Drawing.Point(3, 3); - this.btnMove.Name = "btnMove"; - this.btnMove.Size = new System.Drawing.Size(95, 27); - this.btnMove.TabIndex = 0; - this.btnMove.Text = "moveable"; - this.btnMove.Click += new System.EventHandler(this.btnMove_Click); - // - // button1 - // - this.button1.Location = new System.Drawing.Point(138, 130); - this.button1.Name = "button1"; - this.button1.Size = new System.Drawing.Size(47, 46); - this.button1.TabIndex = 1; - this.button1.Text = "SIP"; - this.button1.Click += new System.EventHandler(this.button1_Click); - // - // textBox1 - // - this.textBox1.Location = new System.Drawing.Point(34, 81); - this.textBox1.Name = "textBox1"; - this.textBox1.Size = new System.Drawing.Size(150, 21); - this.textBox1.TabIndex = 2; - this.textBox1.GotFocus += new System.EventHandler(this.textBox1_GotFocus); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.Controls.Add(this.textBox1); - this.Controls.Add(this.button1); - this.Controls.Add(this.btnMove); - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "Form1"; - this.Text = "Form1"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Button btnMove; - private System.Windows.Forms.Button button1; - private System.Windows.Forms.TextBox textBox1; - private Microsoft.WindowsCE.Forms.InputPanel inputPanel1; - } -} - diff --git a/MoveableWinForm/MovableForm/MovableForm/Form1.cs b/MoveableWinForm/MovableForm/MovableForm/Form1.cs deleted file mode 100644 index 3804753..0000000 --- a/MoveableWinForm/MovableForm/MovableForm/Form1.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace MovableForm -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - - private void btnMove_Click(object sender, EventArgs e) - { - //winapi.moveWindow(this); - winapi.setStyle(this); - } - - //global var - TextBox currentTB = null; - private void button1_Click(object sender, EventArgs e) - { - inputPanel1.Enabled = !inputPanel1.Enabled; - if(currentTB!=null) - currentTB.Focus(); - } - - private void textBox1_GotFocus(object sender, EventArgs e) - { - currentTB = (TextBox)sender; - } - } -} \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MovableForm/Form1.resx b/MoveableWinForm/MovableForm/MovableForm/Form1.resx deleted file mode 100644 index a324186..0000000 --- a/MoveableWinForm/MovableForm/MovableForm/Form1.resx +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - 134, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MovableForm/MovableForm.csproj b/MoveableWinForm/MovableForm/MovableForm/MovableForm.csproj deleted file mode 100644 index a9504d8..0000000 --- a/MoveableWinForm/MovableForm/MovableForm/MovableForm.csproj +++ /dev/null @@ -1,95 +0,0 @@ - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {CBFF1208-7627-4902-BEDE-ADF54A285C97} - WinExe - Properties - MovableForm - MovableForm - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.1 - MovableForm - v2.0 - Windows Mobile 5.0 Pocket PC SDK - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - Form - - - Form1.cs - - - - - Form1.cs - Designer - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - - \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MovableForm/Program.cs b/MoveableWinForm/MovableForm/MovableForm/Program.cs deleted file mode 100644 index 57d9c63..0000000 --- a/MoveableWinForm/MovableForm/MovableForm/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace MovableForm -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MovableForm/Properties/AssemblyInfo.cs b/MoveableWinForm/MovableForm/MovableForm/Properties/AssemblyInfo.cs deleted file mode 100644 index 781a7c2..0000000 --- a/MoveableWinForm/MovableForm/MovableForm/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("MovableForm")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("MovableForm")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("ffe88b4c-1602-4f5f-ab8c-0bc89ff6a2fe")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/MoveableWinForm/MovableForm/MovableForm/Properties/Resources.Designer.cs b/MoveableWinForm/MovableForm/MovableForm/Properties/Resources.Designer.cs deleted file mode 100644 index a617d08..0000000 --- a/MoveableWinForm/MovableForm/MovableForm/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5456 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace MovableForm.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("MovableForm.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/MoveableWinForm/MovableForm/MovableForm/Properties/Resources.resx b/MoveableWinForm/MovableForm/MovableForm/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/MoveableWinForm/MovableForm/MovableForm/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MovableForm/winapi.cs b/MoveableWinForm/MovableForm/MovableForm/winapi.cs deleted file mode 100644 index 2b11073..0000000 --- a/MoveableWinForm/MovableForm/MovableForm/winapi.cs +++ /dev/null @@ -1,243 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; -using System.Reflection; - -//no namespace is global - - class winapi - { - public static void moveWindow(System.Windows.Forms.Form form){ - SetWindowPos(form.Handle, (IntPtr) HWNDPOS.HWND_TOPMOST, form.Left + 10, form.Top + 10, form.Width - 20, form.Height - 20, (uint)SWP.SWP_SHOWWINDOW); - } - - public static void setStyle(System.Windows.Forms.Form frm) - { - uint oldStyle = getStyle(frm); - uint newStyle = (uint)( - WINSTYLES.WS_OVERLAPPED | WINSTYLES.WS_POPUP | WINSTYLES.WS_VISIBLE | - //WINSTYLES.WS_SYSMENU | // add if you need a X to close - WINSTYLES.WS_CAPTION | WINSTYLES.WS_BORDER | //WINSTYLES.WS_DLGFRAME | WINSTYLES.WS_MAXIMIZEBOX | - WINSTYLES.WS_POPUPWINDOW); - int iRet = SetWindowLong(frm.Handle, (int)GWL.GWL_STYLE, (int)newStyle); - //if returned iRet is zero we got an error - - int newExStyle = GetWindowLong(frm.Handle, (int)GWL.GWL_EXSTYLE); - newExStyle = (int)((uint)newExStyle - (uint) WINEXSTYLES.WS_EX_CAPTIONOKBTN); //remove OK button - iRet = SetWindowLong(frm.Handle, (int)GWL.GWL_EXSTYLE, (int)newExStyle); - moveWindow(frm); - frm.Refresh(); - } - - public static uint getStyle(System.Windows.Forms.Form frm) - { - IntPtr hwnd = frm.Handle;// FindWindow(IntPtr.Zero, "[ zero Dump v0.1 ]"); - uint uiStyle = 0xFFffFFff; - if (hwnd != IntPtr.Zero) - { - string sStyles = ""; - uint wStyle = (uint)GetWindowLong(hwnd, (int)GWL.GWL_STYLE); - uiStyle = wStyle; - foreach (WINSTYLES ws in GetValues(new WINSTYLES())) - { - if((uint)((uint)ws & (uint)wStyle)==(uint)ws){ - sStyles += ws.ToString() + ", "; - } - } - System.Diagnostics.Debug.WriteLine(frm.Text + " is " + sStyles); - //zDump is WS_OVERLAPPED, WS_POPUP, WS_VISIBLE, WS_CAPTION, WS_BORDER, WS_DLGFRAME, WS_SYSMENU, WS_MAXIMIZEBOX, WS_POPUPWINDOW, - } - return uiStyle; - } - public static bool setStyle(System.Windows.Forms.Form frm, uint uStyle) - { - int styleOld = 0; - uint currentStyle = getStyle(frm); - uint newStyle = currentStyle | uStyle; - styleOld = SetWindowLong(frm.Handle, (int)(GWL.GWL_STYLE), (int)newStyle); - if (styleOld != 0) - return true; - else - return false; - } - public static bool unsetStyle(System.Windows.Forms.Form frm, uint uStyle) - { - int styleOld = 0; - uint currentStyle = getStyle(frm); - uint newStyle = currentStyle - uStyle; - styleOld = SetWindowLong(frm.Handle, (int)(GWL.GWL_STYLE), (int)newStyle); - if (styleOld != 0) - return true; - else - return false; - } - public static string[] getStyles() - { - List list = new List(); - foreach (WINSTYLES ws in GetValues(new WINSTYLES())) - { - list.Add(ws.ToString()); - } - return list.ToArray(); - } - //############## ex styles ################### - public static uint getStyleEx(System.Windows.Forms.Form frm) - { - IntPtr hwnd = frm.Handle;// FindWindow(IntPtr.Zero, "[ zero Dump v0.1 ]"); - uint uiStyle = 0xFFffFFff; - if (hwnd != IntPtr.Zero) - { - string sStyles = ""; - uint wStyle = (uint)GetWindowLong(hwnd, (int)GWL.GWL_EXSTYLE); - uiStyle = wStyle; - foreach (WINEXSTYLES ws in GetValues(new WINEXSTYLES())) - { - if ((uint)((uint)ws & (uint)wStyle) == (uint)ws) - { - sStyles += ws.ToString() + ", "; - } - } - System.Diagnostics.Debug.WriteLine(frm.Text + " EX is " + sStyles); - //zDump is WS_OVERLAPPED, WS_POPUP, WS_VISIBLE, WS_CAPTION, WS_BORDER, WS_DLGFRAME, WS_SYSMENU, WS_MAXIMIZEBOX, WS_POPUPWINDOW, - } - return uiStyle; - } - public static bool setStyleEx(System.Windows.Forms.Form frm, uint uStyle) - { - int styleOld = 0; - uint currentStyle = getStyleEx(frm); - uint newStyle = currentStyle | uStyle; - styleOld = SetWindowLong(frm.Handle, (int)(GWL.GWL_EXSTYLE), (int)newStyle); - if (styleOld != 0) - return true; - else - return false; - } - public static bool unsetStyleEx(System.Windows.Forms.Form frm, uint uStyle) - { - int styleOld = 0; - uint currentStyle = getStyleEx(frm); - uint newStyle = currentStyle - uStyle; - styleOld = SetWindowLong(frm.Handle, (int)(GWL.GWL_EXSTYLE), (int)newStyle); - if (styleOld != 0) - return true; - else - return false; - } - public static string[] getStylesEx() - { - List list = new List(); - foreach (WINEXSTYLES ws in GetValues(new WINEXSTYLES())) - { - list.Add(ws.ToString()); - } - return list.ToArray(); - } - - //great stuff by http://ideas.dalezak.ca/2008/11/enumgetvalues-in-compact-framework.html - public static IEnumerable GetValues(Enum enumeration) - { - List enumerations = new List(); - foreach (FieldInfo fieldInfo in enumeration.GetType().GetFields( - BindingFlags.Static | BindingFlags.Public)) - { - enumerations.Add((Enum)fieldInfo.GetValue(enumeration)); - } - return enumerations; - } - - [DllImport("coredll.dll", SetLastError = true)] - static extern IntPtr FindWindow(string lpClassName, string lpWindowName); - // For Windows Mobile, replace user32.dll with coredll.dll - [DllImport("coredll.dll", SetLastError = true)] - static extern IntPtr FindWindow(IntPtr ZeroOnly , string lpWindowName); - - [DllImport("coredll.dll", SetLastError = true)] - private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); - [DllImport("coredll.dll", SetLastError = true)] - private static extern int GetWindowLong(IntPtr hWnd, int nIndex); - - //non-fullscreen window (ex zDump) = WS_STYLE=0x90c9004, WS_EX_STYLE=0x00000008 - //WS_POPUP | WS_VISIBLE - enum GWL:int{ - GWL_STYLE = -16, - GWL_EXSTYLE = -20, - } - - [Flags] - public enum WINSTYLES:uint{ - WS_OVERLAPPED = 0x00000000, //#define WS_OVERLAPPED WS_BORDER | WS_CAPTION - WS_POPUP= 0x80000000, - WS_VISIBLE= 0x10000000, - WS_MINIMIZE= 0x20000000, - WS_CLIPSIBLINGS= 0x04000000, - WS_CLIPCHILDREN= 0x02000000, - WS_DISABLED= 0x08000000, - WS_MAXIMIZE= 0x01000000, - WS_CAPTION = 0x00C00000, //#define WS_CAPTION 0x00C00000L /* WS_BORDER | WS_DLGFRAME */ - WS_BORDER= 0x00800000, - WS_DLGFRAME= 0x00400000, - WS_VSCROLL= 0x00200000, - WS_HSCROLL= 0x00100000, - WS_SYSMENU= 0x00080000, - WS_THICKFRAME= 0x00040000, - WS_MINIMIZEBOX= 0x00020000, - WS_MAXIMIZEBOX= 0x00010000, - WS_POPUPWINDOW= 0x80880000, // Creates a pop-up window with WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to make the window menu visible. - } - public enum WINEXSTYLES:uint{ - WS_EX_DLGMODALFRAME = 0x00000001, - WS_EX_TOPMOST = 0x00000008, - WS_EX_TOOLWINDOW = 0x00000080, - WS_EX_WINDOWEDGE = 0x00000100, - WS_EX_CLIENTEDGE = 0x00000200, - WS_EX_CONTEXTHELP = 0x00000400, - WS_EX_RIGHT = 0x00001000, - WS_EX_RTLREADING = 0x00002000, - WS_EX_LEFTSCROLLBAR = 0x00004000, - WS_EX_STATICEDGE = 0x00020000, - WS_EX_NOINHERITLAYOUT = 0x00100000, // Disable inheritence of mirroring by children - WS_EX_LAYOUTRTL = 0x00400000, // Right to left mirroring - WS_EX_OVERLAPPEDWINDOW = 0x00000300, // (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE) - WS_EX_CAPTIONOKBTN = 0x80000000, - WS_EX_NODRAG = 0x40000000, - WS_EX_ABOVESTARTUP = 0x20000000, - WS_EX_INK = 0x10000000, - WS_EX_NOANIMATION = 0x04000000, - } - enum BTNSTYLES{ - BS_CENTER = 0x00000300, - BS_VCENTER = 0x00000C00, - BS_MULTILINE = 0x00002000, - } - [DllImport("coredll.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags); - - enum SWP{ - SWP_ASYNCWINDOWPOS = 0x4000, - SWP_DEFERERASE = 0x2000, - SWP_DRAWFRAME = 0x0020, - SWP_FRAMECHANGED = 0x0020, - SWP_HIDEWINDOW = 0x0080, - SWP_NOACTIVATE = 0x0010, - SWP_NOCOPYBITS = 0x0100, - SWP_NOMOVE = 0x0002, - SWP_NOOWNERZORDER = 0x0200, - SWP_NOREDRAW = 0x0008, - SWP_NOREPOSITION = 0x0200, - SWP_NOSENDCHANGING = 0x0400, - SWP_NOSIZE = 0x0001, - SWP_NOZORDER = 0x0004, - SWP_SHOWWINDOW = 0x0040, - } - enum HWNDPOS{ - HWND_TOP = 0, - HWND_BOTTOM = 1, - HWND_TOPMOST = -1, - HWND_NOTOPMOST = -2, - } - } diff --git a/MoveableWinForm/MovableForm/MoveableFormCF2/Form1.Designer.cs b/MoveableWinForm/MovableForm/MoveableFormCF2/Form1.Designer.cs deleted file mode 100644 index 91a3f32..0000000 --- a/MoveableWinForm/MovableForm/MoveableFormCF2/Form1.Designer.cs +++ /dev/null @@ -1,154 +0,0 @@ -namespace MoveableFormCF2 -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.tabControl1 = new System.Windows.Forms.TabControl(); - this.tabPage1 = new System.Windows.Forms.TabPage(); - this.tabPage2 = new System.Windows.Forms.TabPage(); - this.tabExtras = new System.Windows.Forms.TabPage(); - this.chkMenu = new System.Windows.Forms.CheckBox(); - this.chkMaximized = new System.Windows.Forms.CheckBox(); - this.logTab = new System.Windows.Forms.TabPage(); - this.txtLog = new System.Windows.Forms.TextBox(); - this.tabControl1.SuspendLayout(); - this.tabExtras.SuspendLayout(); - this.logTab.SuspendLayout(); - this.SuspendLayout(); - // - // tabControl1 - // - this.tabControl1.Controls.Add(this.tabPage1); - this.tabControl1.Controls.Add(this.tabPage2); - this.tabControl1.Controls.Add(this.tabExtras); - this.tabControl1.Controls.Add(this.logTab); - this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; - this.tabControl1.Location = new System.Drawing.Point(0, 0); - this.tabControl1.Name = "tabControl1"; - this.tabControl1.SelectedIndex = 0; - this.tabControl1.Size = new System.Drawing.Size(226, 265); - this.tabControl1.TabIndex = 0; - // - // tabPage1 - // - this.tabPage1.AutoScroll = true; - this.tabPage1.Location = new System.Drawing.Point(0, 0); - this.tabPage1.Name = "tabPage1"; - this.tabPage1.Size = new System.Drawing.Size(226, 242); - this.tabPage1.Text = "Styles"; - // - // tabPage2 - // - this.tabPage2.AutoScroll = true; - this.tabPage2.Location = new System.Drawing.Point(0, 0); - this.tabPage2.Name = "tabPage2"; - this.tabPage2.Size = new System.Drawing.Size(218, 239); - this.tabPage2.Text = "EX Styles"; - // - // tabExtras - // - this.tabExtras.Controls.Add(this.chkMenu); - this.tabExtras.Controls.Add(this.chkMaximized); - this.tabExtras.Location = new System.Drawing.Point(0, 0); - this.tabExtras.Name = "tabExtras"; - this.tabExtras.Size = new System.Drawing.Size(218, 239); - this.tabExtras.Text = "Extras"; - // - // chkMenu - // - this.chkMenu.Checked = true; - this.chkMenu.CheckState = System.Windows.Forms.CheckState.Checked; - this.chkMenu.Location = new System.Drawing.Point(18, 56); - this.chkMenu.Name = "chkMenu"; - this.chkMenu.Size = new System.Drawing.Size(100, 22); - this.chkMenu.TabIndex = 0; - this.chkMenu.Text = "MainMenu"; - this.chkMenu.CheckStateChanged += new System.EventHandler(this.chkMenu_CheckStateChanged); - // - // chkMaximized - // - this.chkMaximized.Location = new System.Drawing.Point(18, 28); - this.chkMaximized.Name = "chkMaximized"; - this.chkMaximized.Size = new System.Drawing.Size(100, 22); - this.chkMaximized.TabIndex = 0; - this.chkMaximized.Text = "Maximized"; - this.chkMaximized.CheckStateChanged += new System.EventHandler(this.chkMaximized_CheckStateChanged); - // - // logTab - // - this.logTab.Controls.Add(this.txtLog); - this.logTab.Location = new System.Drawing.Point(0, 0); - this.logTab.Name = "logTab"; - this.logTab.Size = new System.Drawing.Size(226, 242); - this.logTab.Text = "log"; - // - // txtLog - // - this.txtLog.Dock = System.Windows.Forms.DockStyle.Fill; - this.txtLog.Location = new System.Drawing.Point(0, 0); - this.txtLog.Multiline = true; - this.txtLog.Name = "txtLog"; - this.txtLog.ReadOnly = true; - this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtLog.Size = new System.Drawing.Size(226, 242); - this.txtLog.TabIndex = 1; - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(226, 265); - this.Controls.Add(this.tabControl1); - this.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Regular); - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "Form1"; - this.Text = "Form1"; - this.tabControl1.ResumeLayout(false); - this.tabExtras.ResumeLayout(false); - this.logTab.ResumeLayout(false); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.TabControl tabControl1; - private System.Windows.Forms.TabPage tabPage1; - private System.Windows.Forms.TabPage tabPage2; - private System.Windows.Forms.TabPage tabExtras; - private System.Windows.Forms.CheckBox chkMaximized; - private System.Windows.Forms.CheckBox chkMenu; - private System.Windows.Forms.TabPage logTab; - private System.Windows.Forms.TextBox txtLog; - } -} - diff --git a/MoveableWinForm/MovableForm/MoveableFormCF2/Form1.cs b/MoveableWinForm/MovableForm/MoveableFormCF2/Form1.cs deleted file mode 100644 index 11d4741..0000000 --- a/MoveableWinForm/MovableForm/MoveableFormCF2/Form1.cs +++ /dev/null @@ -1,174 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace MoveableFormCF2 -{ - public partial class Form1 : Form - { - uint uiCurrentStyle = 0; - uint uiCurrentStyleEx = 0; - - int offsetY = 36; - int offsetX = 10; - int widthX=200; - int heightX = 32; - winapi.subclassForm subClassedForm; - public Form1() - { - InitializeComponent(); - - subClassedForm = new winapi.subclassForm(this); - subClassedForm.wndProcEvent += new winapi.subclassForm.wndProcEventHandler(subClassedForm_wndProcEvent); - widthX = this.Width - 2 * offsetX; - - uiCurrentStyle = winapi.getStyle(this); - uiCurrentStyleEx = winapi.getStyleEx(this); - System.Diagnostics.Debug.WriteLine("Style =0x" + string.Format("{0:x}", uiCurrentStyle)); - System.Diagnostics.Debug.WriteLine("StyleEx=0x" + string.Format("{0:x}", uiCurrentStyleEx)); - buildOptions(); - buildOptionsEx(); - } - - /// - /// called by every wndproc message - /// - /// - /// - void subClassedForm_wndProcEvent(object sender, winapi.subclassForm.wndprocEventArgs wndProcArgs) - { - //WM_MOVE xPos = (int)LOWORD(lParam); yPos = (int)HIWORD(lParam); - if (wndProcArgs.msg == (uint)winapi.subclassForm.WNDMSGS.WM_MOVE) - addLog("WM_MOVE: X/Y = " + LoWord(wndProcArgs.lParam).ToString() + "/" + HiWord(wndProcArgs.lParam).ToString()); - } - private int LoWord(IntPtr param) - { - return (ushort)(param.ToInt32() & ushort.MaxValue); - } - - private int HiWord(IntPtr param) - { - return (ushort)(param.ToInt32() >> 16); - } - //build a list of chk options for WSYTLES - void buildOptions() - { - string[] stylesList = winapi.getStyles(); - - int iCount=0; - foreach (string s in stylesList) - { - CheckBox chkBox = new CheckBox(); - chkBox.Left = offsetX; - chkBox.Top = iCount * offsetY; - chkBox.Size = new Size(widthX, heightX); - chkBox.Text = s; - uint uStyle = (uint)Enum.Parse(typeof(winapi.WINSTYLES),s,false); - if ((uiCurrentStyle & uStyle) == uStyle) - chkBox.Checked = true; - chkBox.CheckStateChanged += new EventHandler(chkBox_CheckStateChanged); - tabPage1.Controls.Add(chkBox); - iCount++; - } - } - void buildOptionsEx() - { - string[] stylesList = winapi.getStylesEx(); - - int iCount = 0; - foreach (string s in stylesList) - { - CheckBox chkBox = new CheckBox(); - chkBox.Left = offsetX; - chkBox.Top = iCount * offsetY; - chkBox.Size = new Size(widthX, heightX); - chkBox.Text = s; - uint uStyle = (uint)Enum.Parse(typeof(winapi.WINEXSTYLES), s, false); - if ((uiCurrentStyleEx & uStyle) == uStyle) - chkBox.Checked = true; - chkBox.CheckStateChanged += new EventHandler(chkBox_CheckStateChangedEx); - tabPage2.Controls.Add(chkBox); - iCount++; - } - } - - void chkBox_CheckStateChanged(object sender, EventArgs e) - { - string s = ((CheckBox)sender).Text; - uint uStyle = (uint)Enum.Parse(typeof(winapi.WINSTYLES), s, false); - if(((CheckBox)sender).Checked) - winapi.setStyle(this, uStyle); - else - winapi.unsetStyle(this, uStyle); - uiCurrentStyle = winapi.getStyle(this); - - addLog("Style =0x" + string.Format("{0:x}", uiCurrentStyle)); - addLog("StyleEx=0x" + string.Format("{0:x}", uiCurrentStyleEx)); - - this.Refresh(); - } - void chkBox_CheckStateChangedEx(object sender, EventArgs e) - { - string s = ((CheckBox)sender).Text; - uint uStyle = (uint)Enum.Parse(typeof(winapi.WINEXSTYLES), s, false); - if (((CheckBox)sender).Checked) - winapi.setStyleEx(this, uStyle); - else - winapi.unsetStyleEx(this, uStyle); - uiCurrentStyleEx = winapi.getStyleEx(this); - - addLog("Style =0x" + string.Format("{0:x}", uiCurrentStyle)); - addLog("StyleEx=0x" + string.Format("{0:x}", uiCurrentStyleEx)); - - this.Refresh(); - } - - private void chkMaximized_CheckStateChanged(object sender, EventArgs e) - { - if (chkMaximized.Checked) - { - this.WindowState = FormWindowState.Maximized; - //this.Menu = null; - } - else - { - this.WindowState = FormWindowState.Normal; - //this.Menu = mainMenu1; - } - } - - private void chkMenu_CheckStateChanged(object sender, EventArgs e) - { - if (chkMenu.Checked) - this.Menu = mainMenu1; - else - this.Menu = null; - } - delegate void SetTextCallback(string text); - public void addLog(string text) - { - // InvokeRequired required compares the thread ID of the - // calling thread to the thread ID of the creating thread. - // If these threads are different, it returns true. - if (this.txtLog.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(addLog); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtLog.Text.Length > 2000) - txtLog.Text = ""; - txtLog.Text += text + "\r\n"; - txtLog.SelectionLength = 0; - txtLog.SelectionStart = txtLog.Text.Length - 1; - txtLog.ScrollToCaret(); - } - } - } -} \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MoveableFormCF2/Form1.resx b/MoveableWinForm/MovableForm/MoveableFormCF2/Form1.resx deleted file mode 100644 index d239b29..0000000 --- a/MoveableWinForm/MovableForm/MoveableFormCF2/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC_Phone - - - False - - \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MoveableFormCF2/MoveableFormCF2.csproj b/MoveableWinForm/MovableForm/MoveableFormCF2/MoveableFormCF2.csproj deleted file mode 100644 index dccd218..0000000 --- a/MoveableWinForm/MovableForm/MoveableFormCF2/MoveableFormCF2.csproj +++ /dev/null @@ -1,94 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {F6DAD591-222D-4271-8B7B-C61D613864CD} - WinExe - Properties - MoveableFormCF2 - MoveableFormCF2 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 2AC76CE7-3E8C-402d-85E7-AE9C98D7B6BA - 5.02 - MoveableFormCF2 - v2.0 - Windows Mobile 6.5.3 Professional DTK - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - Form - - - Form1.cs - - - - - Form1.cs - Designer - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - - \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MoveableFormCF2/Program.cs b/MoveableWinForm/MovableForm/MoveableFormCF2/Program.cs deleted file mode 100644 index f679cea..0000000 --- a/MoveableWinForm/MovableForm/MoveableFormCF2/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace MoveableFormCF2 -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MoveableFormCF2/Properties/AssemblyInfo.cs b/MoveableWinForm/MovableForm/MoveableFormCF2/Properties/AssemblyInfo.cs deleted file mode 100644 index 9bf29d7..0000000 --- a/MoveableWinForm/MovableForm/MoveableFormCF2/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("MoveableFormCF2")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("MoveableFormCF2")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("daaf8459-8b78-474c-b026-d73a08d6ed66")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/MoveableWinForm/MovableForm/MoveableFormCF2/Properties/Resources.Designer.cs b/MoveableWinForm/MovableForm/MoveableFormCF2/Properties/Resources.Designer.cs deleted file mode 100644 index dda5b27..0000000 --- a/MoveableWinForm/MovableForm/MoveableFormCF2/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5456 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace MoveableFormCF2.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("MoveableFormCF2.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/MoveableWinForm/MovableForm/MoveableFormCF2/Properties/Resources.resx b/MoveableWinForm/MovableForm/MoveableFormCF2/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/MoveableWinForm/MovableForm/MoveableFormCF2/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/MoveableWinForm/MovableForm/MoveableFormCF2/winapi.cs b/MoveableWinForm/MovableForm/MoveableFormCF2/winapi.cs deleted file mode 100644 index 144aab4..0000000 --- a/MoveableWinForm/MovableForm/MoveableFormCF2/winapi.cs +++ /dev/null @@ -1,332 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; -using System.Reflection; - -//no namespace is global - - class winapi - { - public static void moveWindow(System.Windows.Forms.Form form){ - SetWindowPos(form.Handle, (IntPtr) HWNDPOS.HWND_TOPMOST, form.Left + 10, form.Top + 10, form.Width - 20, form.Height - 20, (uint)SWP.SWP_SHOWWINDOW); - } - - public static void setStyle(System.Windows.Forms.Form frm) - { - uint oldStyle = getStyle(frm); - uint newStyle = (uint)( - WINSTYLES.WS_OVERLAPPED | WINSTYLES.WS_POPUP | WINSTYLES.WS_VISIBLE | - //WINSTYLES.WS_SYSMENU | // add if you need a X to close - WINSTYLES.WS_CAPTION | WINSTYLES.WS_BORDER | //WINSTYLES.WS_DLGFRAME | WINSTYLES.WS_MAXIMIZEBOX | - WINSTYLES.WS_POPUPWINDOW); - int iRet = SetWindowLong(frm.Handle, (int)GWL.GWL_STYLE, (int)newStyle); - //if returned iRet is zero we got an error - - int newExStyle = GetWindowLong(frm.Handle, (int)GWL.GWL_EXSTYLE); - newExStyle = (int)((uint)newExStyle - (uint) WINEXSTYLES.WS_EX_CAPTIONOKBTN); //remove OK button - iRet = SetWindowLong(frm.Handle, (int)GWL.GWL_EXSTYLE, (int)newExStyle); - moveWindow(frm); - frm.Refresh(); - } - - public static uint getStyle(System.Windows.Forms.Form frm) - { - IntPtr hwnd = frm.Handle;// FindWindow(IntPtr.Zero, "[ zero Dump v0.1 ]"); - uint uiStyle = 0xFFffFFff; - if (hwnd != IntPtr.Zero) - { - string sStyles = ""; - uint wStyle = (uint)GetWindowLong(hwnd, (int)GWL.GWL_STYLE); - uiStyle = wStyle; - foreach (WINSTYLES ws in GetValues(new WINSTYLES())) - { - if((uint)((uint)ws & (uint)wStyle)==(uint)ws){ - sStyles += ws.ToString() + ", "; - } - } - System.Diagnostics.Debug.WriteLine(frm.Text + " is " + sStyles); - //zDump is WS_OVERLAPPED, WS_POPUP, WS_VISIBLE, WS_CAPTION, WS_BORDER, WS_DLGFRAME, WS_SYSMENU, WS_MAXIMIZEBOX, WS_POPUPWINDOW, - } - return uiStyle; - } - public static bool setStyle(System.Windows.Forms.Form frm, uint uStyle) - { - int styleOld = 0; - uint currentStyle = getStyle(frm); - uint newStyle = currentStyle | uStyle; - styleOld = SetWindowLong(frm.Handle, (int)(GWL.GWL_STYLE), (int)newStyle); - if (styleOld != 0) - return true; - else - return false; - } - public static bool unsetStyle(System.Windows.Forms.Form frm, uint uStyle) - { - int styleOld = 0; - uint currentStyle = getStyle(frm); - uint newStyle = currentStyle - uStyle; - styleOld = SetWindowLong(frm.Handle, (int)(GWL.GWL_STYLE), (int)newStyle); - if (styleOld != 0) - return true; - else - return false; - } - public static string[] getStyles() - { - List list = new List(); - foreach (WINSTYLES ws in GetValues(new WINSTYLES())) - { - list.Add(ws.ToString()); - } - return list.ToArray(); - } - //############## ex styles ################### - public static uint getStyleEx(System.Windows.Forms.Form frm) - { - IntPtr hwnd = frm.Handle;// FindWindow(IntPtr.Zero, "[ zero Dump v0.1 ]"); - uint uiStyle = 0xFFffFFff; - if (hwnd != IntPtr.Zero) - { - string sStyles = ""; - uint wStyle = (uint)GetWindowLong(hwnd, (int)GWL.GWL_EXSTYLE); - uiStyle = wStyle; - foreach (WINEXSTYLES ws in GetValues(new WINEXSTYLES())) - { - if ((uint)((uint)ws & (uint)wStyle) == (uint)ws) - { - sStyles += ws.ToString() + ", "; - } - } - System.Diagnostics.Debug.WriteLine(frm.Text + " EX is " + sStyles); - //zDump is WS_OVERLAPPED, WS_POPUP, WS_VISIBLE, WS_CAPTION, WS_BORDER, WS_DLGFRAME, WS_SYSMENU, WS_MAXIMIZEBOX, WS_POPUPWINDOW, - } - return uiStyle; - } - public static bool setStyleEx(System.Windows.Forms.Form frm, uint uStyle) - { - int styleOld = 0; - uint currentStyle = getStyleEx(frm); - uint newStyle = currentStyle | uStyle; - styleOld = SetWindowLong(frm.Handle, (int)(GWL.GWL_EXSTYLE), (int)newStyle); - if (styleOld != 0) - return true; - else - return false; - } - public static bool unsetStyleEx(System.Windows.Forms.Form frm, uint uStyle) - { - int styleOld = 0; - uint currentStyle = getStyleEx(frm); - uint newStyle = currentStyle - uStyle; - styleOld = SetWindowLong(frm.Handle, (int)(GWL.GWL_EXSTYLE), (int)newStyle); - if (styleOld != 0) - return true; - else - return false; - } - public static string[] getStylesEx() - { - List list = new List(); - foreach (WINEXSTYLES ws in GetValues(new WINEXSTYLES())) - { - list.Add(ws.ToString()); - } - return list.ToArray(); - } - - //great stuff by http://ideas.dalezak.ca/2008/11/enumgetvalues-in-compact-framework.html - public static IEnumerable GetValues(Enum enumeration) - { - List enumerations = new List(); - foreach (FieldInfo fieldInfo in enumeration.GetType().GetFields( - BindingFlags.Static | BindingFlags.Public)) - { - enumerations.Add((Enum)fieldInfo.GetValue(enumeration)); - } - return enumerations; - } - - [DllImport("coredll.dll", SetLastError = true)] - static extern IntPtr FindWindow(string lpClassName, string lpWindowName); - // For Windows Mobile, replace user32.dll with coredll.dll - [DllImport("coredll.dll", SetLastError = true)] - static extern IntPtr FindWindow(IntPtr ZeroOnly , string lpWindowName); - - [DllImport("coredll.dll", SetLastError = true)] - private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); - - [DllImport("coredll.dll", SetLastError = true)] - private static extern int GetWindowLong(IntPtr hWnd, int nIndex); - - #region WndPro - //[DllImport("coredll.dll", SetLastError = true)] - //static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex); - [DllImport("coredll.dll")] - static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); - [DllImport("coredll.dll", SetLastError = true)] - static extern int SetWindowLong(IntPtr hWnd, int nIndex, WndProcDelegate newProc); - delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); - const int GWL_WNDPROC = -4; - #endregion - - //non-fullscreen window (ex zDump) = WS_STYLE=0x90c9004, WS_EX_STYLE=0x00000008 - //WS_POPUP | WS_VISIBLE - enum GWL:int{ - GWL_STYLE = -16, - GWL_EXSTYLE = -20, - } - - [Flags] - public enum WINSTYLES:uint{ - WS_OVERLAPPED = 0x00000000, //#define WS_OVERLAPPED WS_BORDER | WS_CAPTION - WS_POPUP= 0x80000000, - WS_VISIBLE= 0x10000000, - WS_MINIMIZE= 0x20000000, - WS_CLIPSIBLINGS= 0x04000000, - WS_CLIPCHILDREN= 0x02000000, - WS_DISABLED= 0x08000000, - WS_MAXIMIZE= 0x01000000, - WS_CAPTION = 0x00C00000, //#define WS_CAPTION 0x00C00000L /* WS_BORDER | WS_DLGFRAME */ - WS_BORDER= 0x00800000, - WS_DLGFRAME= 0x00400000, - WS_VSCROLL= 0x00200000, - WS_HSCROLL= 0x00100000, - WS_SYSMENU= 0x00080000, - WS_THICKFRAME= 0x00040000, - WS_MINIMIZEBOX= 0x00020000, - WS_MAXIMIZEBOX= 0x00010000, - WS_POPUPWINDOW= 0x80880000, // Creates a pop-up window with WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION and WS_POPUPWINDOW styles must be combined to make the window menu visible. - } - public enum WINEXSTYLES:uint{ - WS_EX_DLGMODALFRAME = 0x00000001, - WS_EX_TOPMOST = 0x00000008, - WS_EX_TOOLWINDOW = 0x00000080, - WS_EX_WINDOWEDGE = 0x00000100, - WS_EX_CLIENTEDGE = 0x00000200, - WS_EX_CONTEXTHELP = 0x00000400, - WS_EX_RIGHT = 0x00001000, - WS_EX_RTLREADING = 0x00002000, - WS_EX_LEFTSCROLLBAR = 0x00004000, - WS_EX_STATICEDGE = 0x00020000, - WS_EX_NOINHERITLAYOUT = 0x00100000, // Disable inheritence of mirroring by children - WS_EX_LAYOUTRTL = 0x00400000, // Right to left mirroring - WS_EX_OVERLAPPEDWINDOW = 0x00000300, // (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE) - WS_EX_CAPTIONOKBTN = 0x80000000, - WS_EX_NODRAG = 0x40000000, - WS_EX_ABOVESTARTUP = 0x20000000, - WS_EX_INK = 0x10000000, - WS_EX_NOANIMATION = 0x04000000, - } - enum BTNSTYLES{ - BS_CENTER = 0x00000300, - BS_VCENTER = 0x00000C00, - BS_MULTILINE = 0x00002000, - } - [DllImport("coredll.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags); - - enum SWP{ - SWP_ASYNCWINDOWPOS = 0x4000, - SWP_DEFERERASE = 0x2000, - SWP_DRAWFRAME = 0x0020, - SWP_FRAMECHANGED = 0x0020, - SWP_HIDEWINDOW = 0x0080, - SWP_NOACTIVATE = 0x0010, - SWP_NOCOPYBITS = 0x0100, - SWP_NOMOVE = 0x0002, - SWP_NOOWNERZORDER = 0x0200, - SWP_NOREDRAW = 0x0008, - SWP_NOREPOSITION = 0x0200, - SWP_NOSENDCHANGING = 0x0400, - SWP_NOSIZE = 0x0001, - SWP_NOZORDER = 0x0004, - SWP_SHOWWINDOW = 0x0040, - } - enum HWNDPOS{ - HWND_TOP = 0, - HWND_BOTTOM = 1, - HWND_TOPMOST = -1, - HWND_NOTOPMOST = -2, - } - - #region subclassing - public class subclassForm:IDisposable - { - #region delegate_event_stuff - public class wndprocEventArgs : EventArgs - { - public IntPtr hWnd; - public uint msg; - public IntPtr lParam; - public IntPtr wParam; - public wndprocEventArgs(IntPtr lphWnd, uint iMsg, IntPtr lpLParam, IntPtr lpWParam) - { - hWnd = lphWnd; - msg = iMsg; - lParam = lpLParam; - wParam = lpWParam; - } - } - - public delegate void wndProcEventHandler(object sender, wndprocEventArgs wndProcArgs); - public event wndProcEventHandler wndProcEvent; - void onWndProcEvent(wndprocEventArgs wa) - { - if (this.wndProcEvent == null) - return; - wndProcEvent(this, wa); - } - #endregion - - public enum WNDMSGS:uint{ - WM_MOVE=0x0003, - WM_SIZE=0x0005, - } - public subclassForm(System.Windows.Forms.Form form) - { - _form = form; - lpPrevWndFunc = _subClassForm(_form); - } - public void Dispose() - { - unsubClassForm(_form); - } - IntPtr lpPrevWndFunc=IntPtr.Zero; - System.Windows.Forms.Form _form; - - static WndProcDelegate persistentWndProc; - IntPtr _subClassForm(System.Windows.Forms.Form form) - { - //avoid multiple subclassing - if (lpPrevWndFunc != IntPtr.Zero) - return IntPtr.Zero; - persistentWndProc = WndProc; - lpPrevWndFunc = (IntPtr)GetWindowLong(form.Handle, GWL_WNDPROC); - SetWindowLong(form.Handle, GWL_WNDPROC, persistentWndProc); - return lpPrevWndFunc; - } - IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) - { - System.Diagnostics.Debug.WriteLine("HWND: " + hWnd + " MSG: " + msg + " WPARAM: " + wParam + " LPARAM: " + lParam); - onWndProcEvent(new wndprocEventArgs(hWnd, msg, lParam, wParam)); - return CallWindowProc(lpPrevWndFunc, hWnd, msg, wParam, lParam); - } - bool unsubClassForm(System.Windows.Forms.Form form) - { - bool bRet = false; - if (lpPrevWndFunc == IntPtr.Zero) - return bRet; - if (SetWindowLong(form.Handle, GWL_WNDPROC, lpPrevWndFunc.ToInt32()) != 0) - { - bRet = true; - lpPrevWndFunc = IntPtr.Zero; - } - return bRet; - } - } - #endregion - } diff --git a/NotificationList/NotificationsList/AddNotification.Designer.cs b/NotificationList/NotificationsList/AddNotification.Designer.cs deleted file mode 100644 index 0297c6b..0000000 --- a/NotificationList/NotificationsList/AddNotification.Designer.cs +++ /dev/null @@ -1,216 +0,0 @@ -namespace NotificationsList -{ - partial class AddNotification - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.menuItem1 = new System.Windows.Forms.MenuItem(); - this.menuItem2 = new System.Windows.Forms.MenuItem(); - this.label1 = new System.Windows.Forms.Label(); - this.txtApp = new System.Windows.Forms.TextBox(); - this.label2 = new System.Windows.Forms.Label(); - this.txtArg = new System.Windows.Forms.TextBox(); - this.btnFile = new System.Windows.Forms.Button(); - this.label3 = new System.Windows.Forms.Label(); - this.txtStart = new System.Windows.Forms.TextBox(); - this.label4 = new System.Windows.Forms.Label(); - this.txtEnd = new System.Windows.Forms.TextBox(); - this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker(); - this.dateTimePicker2 = new System.Windows.Forms.DateTimePicker(); - this.btnSetStart = new System.Windows.Forms.Button(); - this.btnSetEnd = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.menuItem1); - this.mainMenu1.MenuItems.Add(this.menuItem2); - // - // menuItem1 - // - this.menuItem1.Text = "Cancel"; - this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click); - // - // menuItem2 - // - this.menuItem2.Text = "OK"; - this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click); - // - // label1 - // - this.label1.Location = new System.Drawing.Point(3, 8); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(82, 18); - this.label1.Text = "Application:"; - // - // txtApp - // - this.txtApp.Location = new System.Drawing.Point(3, 29); - this.txtApp.Name = "txtApp"; - this.txtApp.Size = new System.Drawing.Size(234, 21); - this.txtApp.TabIndex = 1; - this.txtApp.TextChanged += new System.EventHandler(this.txtApp_TextChanged); - // - // label2 - // - this.label2.Location = new System.Drawing.Point(3, 67); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(82, 18); - this.label2.Text = "Arguments:"; - // - // txtArg - // - this.txtArg.Location = new System.Drawing.Point(3, 88); - this.txtArg.Name = "txtArg"; - this.txtArg.Size = new System.Drawing.Size(234, 21); - this.txtArg.TabIndex = 1; - // - // btnFile - // - this.btnFile.Location = new System.Drawing.Point(203, 4); - this.btnFile.Name = "btnFile"; - this.btnFile.Size = new System.Drawing.Size(34, 19); - this.btnFile.TabIndex = 3; - this.btnFile.Text = "..."; - this.btnFile.Click += new System.EventHandler(this.button1_Click); - // - // label3 - // - this.label3.Location = new System.Drawing.Point(3, 122); - this.label3.Name = "label3"; - this.label3.Size = new System.Drawing.Size(89, 18); - this.label3.Text = "Start:"; - // - // txtStart - // - this.txtStart.Location = new System.Drawing.Point(3, 143); - this.txtStart.Name = "txtStart"; - this.txtStart.Size = new System.Drawing.Size(106, 21); - this.txtStart.TabIndex = 1; - this.txtStart.TextChanged += new System.EventHandler(this.txtStart_TextChanged); - // - // label4 - // - this.label4.Location = new System.Drawing.Point(125, 122); - this.label4.Name = "label4"; - this.label4.Size = new System.Drawing.Size(93, 18); - this.label4.Text = "End:"; - // - // txtEnd - // - this.txtEnd.Location = new System.Drawing.Point(125, 143); - this.txtEnd.Name = "txtEnd"; - this.txtEnd.Size = new System.Drawing.Size(109, 21); - this.txtEnd.TabIndex = 1; - this.txtEnd.TextChanged += new System.EventHandler(this.txtEnd_TextChanged); - // - // dateTimePicker1 - // - this.dateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Short; - this.dateTimePicker1.Location = new System.Drawing.Point(72, 190); - this.dateTimePicker1.Name = "dateTimePicker1"; - this.dateTimePicker1.Size = new System.Drawing.Size(88, 22); - this.dateTimePicker1.TabIndex = 6; - this.dateTimePicker1.ValueChanged += new System.EventHandler(this.dateTimePicker1_ValueChanged); - // - // dateTimePicker2 - // - this.dateTimePicker2.CustomFormat = "hh:mm:ss"; - this.dateTimePicker2.Format = System.Windows.Forms.DateTimePickerFormat.Custom; - this.dateTimePicker2.Location = new System.Drawing.Point(72, 218); - this.dateTimePicker2.Name = "dateTimePicker2"; - this.dateTimePicker2.ShowUpDown = true; - this.dateTimePicker2.Size = new System.Drawing.Size(88, 22); - this.dateTimePicker2.TabIndex = 6; - this.dateTimePicker2.ValueChanged += new System.EventHandler(this.dateTimePicker2_ValueChanged); - // - // btnSetStart - // - this.btnSetStart.Location = new System.Drawing.Point(72, 167); - this.btnSetStart.Name = "btnSetStart"; - this.btnSetStart.Size = new System.Drawing.Size(19, 17); - this.btnSetStart.TabIndex = 7; - this.btnSetStart.Text = "<"; - this.btnSetStart.Click += new System.EventHandler(this.btnSetStart_Click); - // - // btnSetEnd - // - this.btnSetEnd.Location = new System.Drawing.Point(141, 167); - this.btnSetEnd.Name = "btnSetEnd"; - this.btnSetEnd.Size = new System.Drawing.Size(19, 17); - this.btnSetEnd.TabIndex = 7; - this.btnSetEnd.Text = ">"; - this.btnSetEnd.Click += new System.EventHandler(this.btnSetEnd_Click); - // - // AddNotification - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.btnSetEnd); - this.Controls.Add(this.btnSetStart); - this.Controls.Add(this.dateTimePicker2); - this.Controls.Add(this.dateTimePicker1); - this.Controls.Add(this.btnFile); - this.Controls.Add(this.txtEnd); - this.Controls.Add(this.txtStart); - this.Controls.Add(this.txtArg); - this.Controls.Add(this.txtApp); - this.Controls.Add(this.label4); - this.Controls.Add(this.label3); - this.Controls.Add(this.label2); - this.Controls.Add(this.label1); - this.Menu = this.mainMenu1; - this.Name = "AddNotification"; - this.Text = "AddNotification"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem menuItem1; - private System.Windows.Forms.MenuItem menuItem2; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.TextBox txtApp; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.TextBox txtArg; - private System.Windows.Forms.Button btnFile; - private System.Windows.Forms.Label label3; - private System.Windows.Forms.TextBox txtStart; - private System.Windows.Forms.Label label4; - private System.Windows.Forms.TextBox txtEnd; - private System.Windows.Forms.DateTimePicker dateTimePicker1; - private System.Windows.Forms.DateTimePicker dateTimePicker2; - private System.Windows.Forms.Button btnSetStart; - private System.Windows.Forms.Button btnSetEnd; - } -} \ No newline at end of file diff --git a/NotificationList/NotificationsList/AddNotification.cs b/NotificationList/NotificationsList/AddNotification.cs deleted file mode 100644 index 2c20320..0000000 --- a/NotificationList/NotificationsList/AddNotification.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using OpenNETCF.WindowsCE.Notification; - -namespace NotificationsList -{ - public partial class AddNotification : Form - { - public AddNotification() - { - InitializeComponent(); - } - - private void menuItem1_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.Cancel; - this.Close(); - } - - private void menuItem2_Click(object sender, EventArgs e) - { - OpenNETCF.WindowsCE.Notification.UserNotificationTrigger myTrig = new UserNotificationTrigger(); - - if (!System.IO.File.Exists(txtApp.Text)) - { - txtApp.BackColor = Color.Red; - return; - } - myTrig.Application=txtApp.Text; - - myTrig.Arguments=txtArg.Text; - - try - { - myTrig.StartTime=DateTime.Parse(txtStart.Text); - } - catch (Exception) - { - txtStart.BackColor = Color.Red; - return; - } - try - { - myTrig.EndTime = DateTime.Parse(txtEnd.Text); - } - catch (Exception) - { - txtEnd.BackColor = Color.Red; - return; - } - - myTrig.Event= NotificationEvent.None; - - myTrig.Type=NotificationType.Time; - - UserNotification myUN = new UserNotification(); - - - int iRes = OpenNETCF.WindowsCE.Notification.Notify.SetUserNotification(myTrig, null); - if (iRes != 0) - MessageBox.Show("Added new UserNotification"); - else - MessageBox.Show("Adding new UserNotification failed"); - - this.DialogResult = DialogResult.OK; - this.Close(); - } - - private void button1_Click(object sender, EventArgs e) - { - OpenFileDialog ofd = new OpenFileDialog(); - ofd.Filter = "Application|*.exe"; - ofd.FilterIndex = 0; - if (ofd.ShowDialog() == DialogResult.OK) - txtApp.Text = ofd.FileName; - ofd.Dispose(); - } - - private void dateTimePicker2_ValueChanged(object sender, EventArgs e) - { - dateTimePicker1.Value = dateTimePicker2.Value; - } - - private void btnSetStart_Click(object sender, EventArgs e) - { - txtStart.Text = dateTimePicker1.Value.ToString(); - } - - private void dateTimePicker1_ValueChanged(object sender, EventArgs e) - { - - } - - private void txtApp_TextChanged(object sender, EventArgs e) - { - txtApp.BackColor = Color.White; - } - - private void txtStart_TextChanged(object sender, EventArgs e) - { - txtStart.BackColor = Color.White; - } - - private void txtEnd_TextChanged(object sender, EventArgs e) - { - txtEnd.BackColor = Color.White; - } - - private void btnSetEnd_Click(object sender, EventArgs e) - { - txtEnd.Text = dateTimePicker1.Value.ToString(); - } - } -} \ No newline at end of file diff --git a/NotificationList/NotificationsList/AddNotification.resx b/NotificationList/NotificationsList/AddNotification.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/NotificationList/NotificationsList/AddNotification.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/NotificationList/NotificationsList/CeGetUserNotification.cs b/NotificationList/NotificationsList/CeGetUserNotification.cs deleted file mode 100644 index 308d821..0000000 --- a/NotificationList/NotificationsList/CeGetUserNotification.cs +++ /dev/null @@ -1,333 +0,0 @@ -// http://onehourofdevelopment.blogspot.com/2009_10_01_archive.html - -using System; -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; - -using System.Windows.Forms; - -namespace CEGETUSERNOTIFICATION -{ - class CeGetUserNotification - { - /* - CeGetUserNotificationHandles returns an array of notification handles. Each of the handles can then be used as - input for CeGetUserNotification which in turn will return the notification as a byte array. - To determine the size of rghNotifications needed, call CeGetUserNotificationHandless with NULL parameters. - - uint dwHowMany=0; - GetUserNotificationHandles(null, 0 ref dwHowMany); - */ - /* - You then use the value of dwHowMany to create an IntPtr array of the correct size. - - IntPtr rghNotifications = new IntPtr[dwHowMany]; - - Calling CeGetUserNotificationHandles one more time will fill the IntPtr array. - - GetUserNotificationHandles(rghNotifications, dwHowMany, ref dwHowMany); - - Given that GetUserNotificationHandles returned TRUE you should now have an IntPtr array filled with notification handles that can you can use. - */ - [DllImport("CoreDLL.dll", SetLastError = false, EntryPoint = "CeClearUserNotification")] - public static extern bool ClearUserNotification(IntPtr hNotification); - - /* - IntPtr hNotification; - Call CeSetUserNotificationEx and save its output in hNotification - */ - - /* - if ( ClearUserNotification(hNotification) ) - MessageBox.Show("Successfully cleared the notification"); - else - MessageBox.Show("Failed to clear the notification"); - */ - - [DllImport("CoreDLL.dll", SetLastError = false, EntryPoint = "CeGetUserNotificationHandles")] - public static extern bool GetUserNotificationHandles(IntPtr[] rghNotifications, uint cHandles, ref uint pcHandlesNeeded); - - [DllImport("CoreDLL.dll", SetLastError = false, EntryPoint = "CeGetUserNotification")] - public static extern bool GetUserNotification(IntPtr hNotification, uint BufferSize, out uint BytesNeeded, byte[] Buffer); - /* - Calling GetUserNotification passing null values and a valid notification handle will return the bytes needed for the byte - buffer. You then call GetUserNotification once more passing both a notification handle as well as a byte buffer. - - GetUserNotification(hNotification, 0, out Size, null); - Buf = new byte[Size]; - GetUserNotification(hNotification, Size, out Size, Buf); - */ - - [DllImport("CoreDLL.dll", SetLastError = false, EntryPoint = "CeSetUserNotificationEx")] - public static extern uint SetUserNotificationEx([MarshalAs(UnmanagedType.U4)]uint hNotification, CE_NOTIFICATION_TRIGGER Trigger, CE_USER_NOTIFICATION Notification); - - public CE_USER_NOTIFICATION[] getUserNotifications(){ - //how many usernotifications are there? - IntPtr[] unHandles = new IntPtr[1]; - uint iHandleCount = 1; - uint iHandlesNeeded = 0; - if (!GetUserNotificationHandles(unHandles, iHandleCount, ref iHandlesNeeded)) - return null; - //we got some handle count - unHandles = new IntPtr[iHandlesNeeded]; - iHandleCount = iHandlesNeeded; - if (!GetUserNotificationHandles(unHandles, iHandleCount, ref iHandlesNeeded)) - return null; - CE_USER_NOTIFICATION[] userNotifications = new CE_USER_NOTIFICATION[iHandleCount]; - for (int i = 0; i < iHandleCount; i++) - { - uint uBytesNeeded=0; - if (GetUserNotification(unHandles[i], 0, out uBytesNeeded, null)==false) - { - byte[] buf = new byte[uBytesNeeded]; - uint uBufSize = uBytesNeeded; - GetUserNotification(unHandles[i], uBufSize, out uBytesNeeded, buf); - int iIdx = 0; - userNotifications[i] = new CE_USER_NOTIFICATION(buf, (uint)buf.Length, ref iIdx); - } - else - System.Diagnostics.Debug.WriteLine("GetUserNotification: " + Marshal.GetLastWin32Error().ToString()); - } - return userNotifications; - } - public void runAppAtTime(string sApp, SYSTEMTIME stStart, SYSTEMTIME stEnd) - { - CE_NOTIFICATION_TRIGGER cnt = new CE_NOTIFICATION_TRIGGER(); - cnt.Type = CeNotificationType.CNT_TIME; - cnt.StartTime = stStart; - cnt.EndTime = stEnd; - cnt.pApplication = @"\windows\fexplore.exe"; - cnt.pArgs = ""; - cnt.Size = (UInt32)Marshal.SizeOf(cnt); // Needs to compile with /unsafe - - uint hNotificationEx = SetUserNotificationEx(0, cnt, null); - if (hNotificationEx > 0) - MessageBox.Show("Successfully created a notification. Handle: " + hNotificationEx.ToString()); - else - MessageBox.Show("Failed to create a notification"); - } - /* - The following code will create a time based trigger and connect that trigger to a notification that will fire up \windows\fexplore.exe. - Note that you need to compile this sample with the /unsafe switch. You could always hard code the size of CE_NOTIFICATION_TRIGGER in which case /unsafe won't be necessary. If hard coded; the value is 52. - Also don't forget to pass NULL instead of ceun if you change the trigger type to CNT_EVENT. - */ - public void newRunAtTime(SYSTEMTIME stStart, SYSTEMTIME stEnd){ - CE_NOTIFICATION_TRIGGER cnt = new CE_NOTIFICATION_TRIGGER(); - CE_USER_NOTIFICATION ceun = new CE_USER_NOTIFICATION(); - cnt.Type =CeNotificationType.CNT_TIME; - cnt.StartTime = stStart; - cnt.EndTime = stEnd; - cnt.pApplication = @"\windows\fexplore.exe"; - cnt.pArgs = ""; - cnt.Size = (UInt32)Marshal.SizeOf(cnt); // Needs to compile with /unsafe - - ceun.ActionFlags = PUN_FLAGS.PUN_LED; - ceun.sDialogText = "Dialogtext"; - ceun.sDialogTitle = "Title"; - ceun.nMaxSound = 0; - - uint hNotificationEx = SetUserNotificationEx(0, cnt, ceun); - if (hNotificationEx > 0) - MessageBox.Show("Successfully created a notification. Handle: " + hNotificationEx.ToString()); - else - MessageBox.Show("Failed to create a notification"); - } - - public enum CeNotificationType - { - CNT_EVENT = 1, //@flag CNT_EVENT | System event notification - CNT_TIME, //@flag CNT_TIME | Time-based notification - CNT_PERIOD, //@flag CNT_PERIOD | Time-based notification is active for - // time period between stStart and stEnd - CNT_CLASSICTIME //@flag CNT_CLASSICTIME | equivalent to using (obsolete) - // CeSetUserNotification function - standard command line is - // supplied. lpszArguments must be NULL - } - [StructLayout(LayoutKind.Sequential)] - public class CE_NOTIFICATION_INFO_HEADER - { - [MarshalAs(UnmanagedType.U4)] - public uint hNotification; - [MarshalAs(UnmanagedType.U4)] - public uint dwStatus; - public CE_NOTIFICATION_TRIGGER cent; - public CE_USER_NOTIFICATION ceun; - - public CE_NOTIFICATION_INFO_HEADER(byte[] Buf, uint Size) - { - int Index = 0; - try - { - this.hNotification = BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.dwStatus = BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint pcent = BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint pceun = BitConverter.ToUInt32(Buf, Index); - Index += 4; - if (pcent > 0 && Buf[Index] == Marshal.SizeOf(new CE_NOTIFICATION_TRIGGER())) - this.cent = new CE_NOTIFICATION_TRIGGER(Buf, Size, ref Index); - if (pceun > 0) - this.ceun = new CE_USER_NOTIFICATION(Buf, Size, ref Index); - } - catch (Exception ex) - { - throw ex; - } - } - } - [StructLayout(LayoutKind.Sequential)] - public class CE_NOTIFICATION_TRIGGER - { - public UInt32 Size = 0; - [MarshalAs(UnmanagedType.U4)] - public CeNotificationType Type; - [MarshalAs(UnmanagedType.U4)] - public CeNotificationEvent Event; - [MarshalAs(UnmanagedType.LPWStr)] - public string pApplication; - [MarshalAs(UnmanagedType.LPWStr)] - public string pArgs; - public SYSTEMTIME StartTime; - public SYSTEMTIME EndTime; - public CE_NOTIFICATION_TRIGGER() - { - } - - public CE_NOTIFICATION_TRIGGER(byte[] Buf, uint Size, ref int Index) - { - int iEndOfString; - System.Text.UnicodeEncoding enc = new UnicodeEncoding(); - uint lpszApp = 0; - uint lpszArgs = 0; - this.Size = BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.Type = (CeNotificationType)BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.Event = (CeNotificationEvent)BitConverter.ToUInt32(Buf, Index); - Index += 4; - lpszApp = BitConverter.ToUInt32(Buf, Index); - Index += 4; - lpszArgs = BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.StartTime = new SYSTEMTIME(Buf, Index); - Index += 16; - this.EndTime = new SYSTEMTIME(Buf, Index); - Index += 16; - if (lpszApp > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.pApplication = enc.GetString(Buf, Index, iEndOfString - Index - 2); - Index = iEndOfString; - } - if (lpszArgs > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.pArgs = enc.GetString(Buf, Index, iEndOfString - Index - 2); // Stupid solution to double null ending.. - Index = iEndOfString; - } - } - } - public enum CeNotificationEvent - { - NOTIFICATION_EVENT_NONE, - NOTIFICATION_EVENT_TIME_CHANGE, - NOTIFICATION_EVENT_SYNC_END, - NOTIFICATION_EVENT_ON_AC_POWER, - NOTIFICATION_EVENT_OFF_AC_POWER, - NOTIFICATION_EVENT_NET_CONNECT, - NOTIFICATION_EVENT_NET_DISCONNECT, - NOTIFICATION_EVENT_DEVICE_CHANGE, - NOTIFICATION_EVENT_IR_DISCOVERED, - NOTIFICATION_EVENT_RS232_DETECTED, - NOTIFICATION_EVENT_RESTORE_END, - NOTIFICATION_EVENT_WAKEUP, - NOTIFICATION_EVENT_TZ_CHANGE, - NOTIFICATION_EVENT_MACHINE_NAME_CHANGE, - NOTIFICATION_EVENT_RNDIS_FN_DETECTED, - NOTIFICATION_EVENT_INTERNET_PROXY_CHANGE, - NOTIFICATION_EVENT_LAST = NOTIFICATION_EVENT_INTERNET_PROXY_CHANGE - }; - public enum PUN_FLAGS - { - PUN_LED = 1 , //@flag PUN_LED | LED flag. Set if the LED should be - // flashed when the notification occurs. - - PUN_VIBRATE = 2, //@flag PUN_VIBRATE | Vibrate flag. Set if the device should - // be vibrated. - - PUN_DIALOG = 4, //@flag PUN_DIALOG | Dialog flag. Set if a dialog should be - // displayed (the app must provide title and text - // when calling ). - - PUN_SOUND = 8, //@flag PUN_SOUND | Sound flag. Set if the sound specified - // in pwszSound should be played. - - PUN_REPEAT = 16, //@flag PUN_REPEAT | Sound repeat flag. Set if the sound - // specified in pwszSound should be repeated progressively. - - PUN_PRIVATE = 32 //@flag PUN_PRIVATE | Dialog box z-order flag. Set if the - // notification dialog box should come up behind the password. - }; - [StructLayout(LayoutKind.Sequential)] - public class CE_USER_NOTIFICATION - { - [MarshalAs(UnmanagedType.U4)] - public PUN_FLAGS ActionFlags; - [MarshalAs(UnmanagedType.LPTStr)] - public string sDialogTitle; - [MarshalAs(UnmanagedType.LPTStr)] - public string sDialogText; - [MarshalAs(UnmanagedType.LPTStr)] - public string sSound; - [MarshalAs(UnmanagedType.U4)] - public uint nMaxSound; - [MarshalAs(UnmanagedType.U4)] - public uint Reserved; - public CE_USER_NOTIFICATION() - { - } - - public CE_USER_NOTIFICATION(byte[] Buf, uint Size, ref int Index) - { - int iEndOfString; - System.Text.UnicodeEncoding enc = new UnicodeEncoding(); - - this.ActionFlags = (PUN_FLAGS)BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint lpszDialogTitle = BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint lpszDialogText = BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint lpszSound = BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.nMaxSound = BitConverter.ToUInt32(Buf, Index); - Index += 4; - // read Reserved - Index += 4; - if (lpszDialogTitle > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.sDialogTitle = enc.GetString(Buf, Index, iEndOfString - Index - 2); - Index = iEndOfString; - } - if (lpszDialogText > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.sDialogText = enc.GetString(Buf, Index, iEndOfString - Index - 2); - Index = iEndOfString; - } - if (lpszSound > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.sSound = enc.GetString(Buf, Index, iEndOfString - Index - 2); - Index = iEndOfString; - } - } - } - // CE_NOTIFICATION_INFO_HEADER cenih = new Notify.CE_NOTIFICATION_INFO_HEADER(Buf, Size); - } -} diff --git a/NotificationList/NotificationsList/CeUserNotificationsClass.cs b/NotificationList/NotificationsList/CeUserNotificationsClass.cs deleted file mode 100644 index 80ebc9a..0000000 --- a/NotificationList/NotificationsList/CeUserNotificationsClass.cs +++ /dev/null @@ -1,352 +0,0 @@ -using System; -using System.Windows.Forms; -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; - -using System.Data; - -using OpenNETCF.WindowsCE.Notification; - -namespace NotificationsList -{ - public class CeUserNotificationsClass - { - public class EventEntry{ - private string _sApp; - private string _sArg; - private string _sEvent; - private string _sStartTime; - private string _sEndTime; - private string _sType; - private string _sHandle; - - private System.Collections.ArrayList entries = new System.Collections.ArrayList(); - - public EventEntry() - { - _sApp = ""; - _sArg = ""; - _sEvent = ""; - _sStartTime = ""; - _sEndTime = ""; - _sType = ""; - _sHandle = "0"; - } - - public EventEntry(string s) - { - string[] sIn = s.Split('|'); - if (sIn.Length == 7) - { - _sApp = sIn[0]; - _sArg = sIn[1]; - _sEvent = sIn[2]; - _sStartTime = sIn[3]; - _sEndTime = sIn[4]; - _sType = sIn[5]; - _sHandle = sIn[6]; - } - } - public EventEntry(string[] sIn) - { - _sApp = sIn[0]; - _sArg = sIn[1]; - _sEvent = sIn[2]; - _sStartTime = sIn[3]; - _sEndTime = sIn[4]; - _sType = sIn[5]; - _sHandle = sIn[6]; - } - - public string sApp - { - get { return _sApp; } - set { _sApp = value; } - } - public string sArg - { - get { return _sArg; } - set { _sArg = value; } - } - public string sEvent - { - get { return _sEvent; } - set { _sEvent = value; } - } - public string sStartTime - { - get { return _sStartTime; } - set { _sStartTime = value; } - } - public string sEndTime - { - get { return _sEndTime; } - set { _sEndTime = value; } - } - public string sType - { - get { return _sType; } - set { _sType = value; } - } - public string sHandle - { - get { return _sHandle; } - set { _sHandle = value; } - } - public int iHandle - { - get { return Convert.ToInt32(_sHandle); } - } - } - - public EventEntry[] eventEntries; - public DataTable EventDB; - - //[DllImport("coredll.dll", EntryPoint = "CeGetUserNotificationHandles", SetLastError = true)] - //private static extern bool CeGetUserNotificationHandles(IntPtr[] rghNotifications, uint cHandles, ref uint pcHandlesNeeded); - //[DllImport("coredll.dll", EntryPoint = "CeGetUserNotification", SetLastError = true)] - //private static extern bool CeGetUserNotification(IntPtr hNotification, uint cBufferSize, ref uint pcBytesNeeded, IntPtr pBuffer); - - private const uint _maxHandles = 128; - private const uint _bufSize = 8192; - - private List _sList; - - string[][] _strArr; - public string[][] strArr - { - get { return _strArr; } - } - - public string[] sAppList - { - get { return _sList.ToArray(); } - } - - public CeUserNotificationsClass() - { - loadNotifications(); - fillDB(); - } - - public CeUserNotificationsClass(TreeView tv) - { - loadNotifications(); - loadNotifications(tv); - } - private int loadNotifications(TreeView tv) - { - int iCnt = 0; - tv.Nodes.Clear(); - TreeNode tnMain = tv.Nodes.Add("Notifications"); - tnMain.Tag = "root"; - - int[] iHandles = OpenNETCF.WindowsCE.Notification.Notify.GetUserNotificationHandles(); - _sList = new List(); - _sList.Clear(); - - _strArr = new string[iHandles.Length + 1][]; - - _strArr[0] = new string[7] { "App", "Args", "Event", "Start", "End", "Type", "handle" }; - - int i = 0; - - eventEntries = new EventEntry[iHandles.Length]; - - foreach (int iHandle in iHandles) - { - OpenNETCF.WindowsCE.Notification.UserNotificationInfoHeader infoHeader = OpenNETCF.WindowsCE.Notification.Notify.GetUserNotification(iHandle); - string[] strArray = new string[] { infoHeader.UserNotificationTrigger.Application, infoHeader.UserNotificationTrigger.Arguments }; - TreeNode tn = new TreeNode(infoHeader.UserNotificationTrigger.Application); - tnMain.Nodes.Add(tn); - tn.Tag = infoHeader; - TreeNode tnSub = tn.Nodes.Add("Args: " + infoHeader.UserNotificationTrigger.Arguments); - tnSub.Tag = infoHeader; - tnSub = tn.Nodes.Add("Event: " + infoHeader.UserNotificationTrigger.Event.ToString()); - tnSub.Tag = infoHeader; - tnSub = tn.Nodes.Add("Start: " + infoHeader.UserNotificationTrigger.StartTime.ToString("dd.MM.yyyy HH:mm")); - tnSub.Tag = infoHeader; - tnSub = tn.Nodes.Add("End: " + infoHeader.UserNotificationTrigger.EndTime.ToString("dd.MM.yyyy HH:mm")); - tnSub.Tag = infoHeader; - tnSub = tn.Nodes.Add("Type: " + infoHeader.UserNotificationTrigger.Type.ToString()); - tnSub.Tag = infoHeader; - tnSub = tn.Nodes.Add("Handle: " + iHandles[i].ToString()); - tnSub.Tag = infoHeader; - - //eventEntries[i].sApp = infoHeader.UserNotificationTrigger.Application; - //eventEntries[i].sEvent = infoHeader.UserNotificationTrigger.Event.ToString(); - //eventEntries[i].sArg = infoHeader.UserNotificationTrigger.Arguments; - //eventEntries[i].sStartTime = infoHeader.UserNotificationTrigger.StartTime.ToString("dd.MM.yyyy HH:mm"); - //eventEntries[i].sEndTime = infoHeader.UserNotificationTrigger.EndTime.ToString("dd.MM.yyyy HH:mm"); - //eventEntries[i].sType = infoHeader.UserNotificationTrigger.Type.ToString(); - //eventEntries[i].sHandle = iHandles[i].ToString(); - - iCnt++; - } - tv.Refresh(); - return iCnt; - } - private void fillDB() - { - EventDB = new DataTable("Notifications"); - DataColumn[] dc = new DataColumn[7]; - string[] _fieldNames = new string[7] { "App", "Args", "Event", "Start", "End", "Type", "handle" }; - //build the table columns - for (int i = 0; i < 7; i++) - { - dc[i] = new DataColumn(); - dc[i].Caption = _fieldNames[i]; // "App"; - dc[i].ColumnName = _fieldNames[i]; // "App"; - dc[i].DataType = System.Type.GetType("System.String"); - dc[i].MaxLength = 256; - dc[i].Unique = false; - dc[i].AllowDBNull = false; - } - //add header - EventDB.Columns.AddRange(dc); - //add rows - for (int i = 0; i < eventEntries.Length; i++) - { - DataRow dr = EventDB.NewRow(); - object[] o = new object[7]{ eventEntries[i].sApp, eventEntries[i].sArg, eventEntries[i].sEvent, - eventEntries[i].sStartTime, eventEntries[i].sEndTime, eventEntries[i].sType, eventEntries[i].sHandle }; - dr.ItemArray = o; - EventDB.Rows.Add(dr); - } - } - public int deleteEntry(EventEntry evnt) - { - int iRet = 0; - if (this.EventDB != null) - { - var dRows = EventDB.Select("handle='" + evnt.sHandle + "'"); - foreach (var r in dRows) - { - if (CEGETUSERNOTIFICATION.CeGetUserNotification.ClearUserNotification((IntPtr)evnt.iHandle)) - { - r.Delete(); - iRet++; - } - else - System.Diagnostics.Debug.WriteLine("ClearUserNotification failed"); - } - EventDB.AcceptChanges(); - } - return iRet; - } - private int loadNotifications() - { - int[] iHandles = OpenNETCF.WindowsCE.Notification.Notify.GetUserNotificationHandles(); - _sList= new List(); - _sList.Clear(); - - _strArr = new string[iHandles.Length + 1][]; - - _strArr[0] = new string[7] { "App", "Args", "Event", "Start", "End", "Type", "handle" }; - - int i = 0; - - eventEntries = new EventEntry[iHandles.Length]; - //eventEntries[0] = new EventEntry("App|Args|Event|Start|End|Type"); - - //############################### - - //############################### - - foreach (int iHandle in iHandles) - { - OpenNETCF.WindowsCE.Notification.UserNotificationInfoHeader infoHeader = OpenNETCF.WindowsCE.Notification.Notify.GetUserNotification(iHandle); - - _strArr[i]=new string[7]; - - string sApp = infoHeader.UserNotificationTrigger.Application; - _strArr[i][0]="'" + infoHeader.UserNotificationTrigger.Application + "'"; - - sApp += "|'" + infoHeader.UserNotificationTrigger.Arguments + "'"; - _strArr[i][1]=infoHeader.UserNotificationTrigger.Arguments; - - sApp += "|" + infoHeader.UserNotificationTrigger.Event.ToString(); - _strArr[i][2]=infoHeader.UserNotificationTrigger.Event.ToString(); - - sApp += "|" + infoHeader.UserNotificationTrigger.StartTime.ToString("ddMMyyyy HH:mm"); - _strArr[i][3] = infoHeader.UserNotificationTrigger.StartTime.ToString("ddMMyyyy HH:mm"); - - sApp += "|" + infoHeader.UserNotificationTrigger.EndTime.ToString("ddMMyyyy HH:mm"); - _strArr[i][4] = infoHeader.UserNotificationTrigger.EndTime.ToString("ddMMyyyy HH:mm"); - - sApp += "|" + infoHeader.UserNotificationTrigger.Type.ToString(); - _strArr[i][5] = infoHeader.UserNotificationTrigger.Type.ToString(); - - sApp += "|" + iHandles[i].ToString(); - _strArr[i][6] = iHandles[i].ToString(); - - eventEntries[i] = new EventEntry(sApp); - //eventEntries[i] = new EventEntry(_strArr[i]); - - i++; - _sList.Add(sApp); - } - - return _sList.Count; - } - - public void applyTableStyle(DataGrid dataGrid1) - { - // Creates two DataGridTableStyle objects, one for the Machine - // array, and one for the Parts ArrayList. - - DataGridTableStyle EventsTable = new DataGridTableStyle(); - // Sets the MappingName to the class name plus brackets. - EventsTable.MappingName = "EventEntry[]"; - - // Sets the AlternatingBackColor so you can see the difference. - //EventsTable.AlternatingBackColor = System.Drawing.Color.LightBlue; - - // Creates column styles. - DataGridTextBoxColumn eventApp = new DataGridTextBoxColumn(); - eventApp.MappingName = "sApp"; - eventApp.HeaderText = "sApp"; - eventApp.Width = dataGrid1.Width / 6 * 2; - - DataGridTextBoxColumn eventArg = new DataGridTextBoxColumn(); - eventArg.MappingName = "sArg"; - eventArg.HeaderText = "Arg"; - - DataGridTextBoxColumn eventEvent = new DataGridTextBoxColumn(); - eventEvent.MappingName = "sEvent"; - eventEvent.HeaderText = "Event"; - - DataGridTextBoxColumn eventStart = new DataGridTextBoxColumn(); - eventStart.MappingName = "sStartTime"; - eventStart.HeaderText = "Start"; - - DataGridTextBoxColumn eventEnd = new DataGridTextBoxColumn(); - eventEnd.MappingName = "sEndTime"; - eventEnd.HeaderText = "End"; - - DataGridTextBoxColumn eventType = new DataGridTextBoxColumn(); - eventType.MappingName = "sType"; - eventType.HeaderText = "Type"; - - DataGridTextBoxColumn eventHandle = new DataGridTextBoxColumn(); - eventHandle.MappingName = "sHandle"; - eventHandle.HeaderText = "handle"; - - // Adds the column styles to the grid table style. - EventsTable.GridColumnStyles.Add(eventApp); - EventsTable.GridColumnStyles.Add(eventArg); - EventsTable.GridColumnStyles.Add(eventEvent); - EventsTable.GridColumnStyles.Add(eventStart); - EventsTable.GridColumnStyles.Add(eventEnd); - EventsTable.GridColumnStyles.Add(eventType); - EventsTable.GridColumnStyles.Add(eventHandle); - - // Add the table style to the collection, but clear the - // collection first. - dataGrid1.TableStyles.Clear(); - dataGrid1.TableStyles.Add(EventsTable); - - } - } -} diff --git a/NotificationList/NotificationsList/NotificationsList.Designer.cs b/NotificationList/NotificationsList/NotificationsList.Designer.cs deleted file mode 100644 index 67410c2..0000000 --- a/NotificationList/NotificationsList/NotificationsList.Designer.cs +++ /dev/null @@ -1,203 +0,0 @@ -namespace NotificationsList -{ - partial class NotificationsList - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.menuItem1 = new System.Windows.Forms.MenuItem(); - this.mnuOptions = new System.Windows.Forms.MenuItem(); - this.mnuRefresh = new System.Windows.Forms.MenuItem(); - this.mnuSave = new System.Windows.Forms.MenuItem(); - this.menuItem2 = new System.Windows.Forms.MenuItem(); - this.mnuRemove = new System.Windows.Forms.MenuItem(); - this.tabControl1 = new System.Windows.Forms.TabControl(); - this.tabPage1 = new System.Windows.Forms.TabPage(); - this.dataGrid1 = new System.Windows.Forms.DataGrid(); - this.tabPage2 = new System.Windows.Forms.TabPage(); - this.treeView1 = new System.Windows.Forms.TreeView(); - this.tabPage3 = new System.Windows.Forms.TabPage(); - this.txtLog = new System.Windows.Forms.TextBox(); - this.mnuLogPowerChanges = new System.Windows.Forms.MenuItem(); - this.tabControl1.SuspendLayout(); - this.tabPage1.SuspendLayout(); - this.tabPage2.SuspendLayout(); - this.tabPage3.SuspendLayout(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.menuItem1); - this.mainMenu1.MenuItems.Add(this.mnuOptions); - // - // menuItem1 - // - this.menuItem1.Text = "Exit"; - this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click); - // - // mnuOptions - // - this.mnuOptions.MenuItems.Add(this.mnuRefresh); - this.mnuOptions.MenuItems.Add(this.mnuSave); - this.mnuOptions.MenuItems.Add(this.menuItem2); - this.mnuOptions.MenuItems.Add(this.mnuRemove); - this.mnuOptions.MenuItems.Add(this.mnuLogPowerChanges); - this.mnuOptions.Text = "Options"; - // - // mnuRefresh - // - this.mnuRefresh.Text = "Refresh"; - this.mnuRefresh.Click += new System.EventHandler(this.mnuRefresh_Click_1); - // - // mnuSave - // - this.mnuSave.Text = "Save"; - this.mnuSave.Click += new System.EventHandler(this.mnuSave_Click); - // - // menuItem2 - // - this.menuItem2.Text = "Add"; - this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click); - // - // mnuRemove - // - this.mnuRemove.Text = "Remove"; - this.mnuRemove.Click += new System.EventHandler(this.mnuRemove_Click); - // - // tabControl1 - // - this.tabControl1.Controls.Add(this.tabPage1); - this.tabControl1.Controls.Add(this.tabPage2); - this.tabControl1.Controls.Add(this.tabPage3); - this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; - this.tabControl1.Location = new System.Drawing.Point(0, 0); - this.tabControl1.Name = "tabControl1"; - this.tabControl1.SelectedIndex = 0; - this.tabControl1.Size = new System.Drawing.Size(240, 268); - this.tabControl1.TabIndex = 5; - this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged); - // - // tabPage1 - // - this.tabPage1.Controls.Add(this.dataGrid1); - this.tabPage1.Location = new System.Drawing.Point(0, 0); - this.tabPage1.Name = "tabPage1"; - this.tabPage1.Size = new System.Drawing.Size(240, 245); - this.tabPage1.Text = "Table"; - // - // dataGrid1 - // - this.dataGrid1.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); - this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Fill; - this.dataGrid1.Location = new System.Drawing.Point(0, 0); - this.dataGrid1.Name = "dataGrid1"; - this.dataGrid1.Size = new System.Drawing.Size(240, 245); - this.dataGrid1.TabIndex = 4; - this.dataGrid1.CurrentCellChanged += new System.EventHandler(this.dataGrid1_CurrentCellChanged); - // - // tabPage2 - // - this.tabPage2.Controls.Add(this.treeView1); - this.tabPage2.Location = new System.Drawing.Point(0, 0); - this.tabPage2.Name = "tabPage2"; - this.tabPage2.Size = new System.Drawing.Size(232, 242); - this.tabPage2.Text = "Tree"; - // - // treeView1 - // - this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill; - this.treeView1.Location = new System.Drawing.Point(0, 0); - this.treeView1.Name = "treeView1"; - this.treeView1.Size = new System.Drawing.Size(232, 242); - this.treeView1.TabIndex = 5; - // - // tabPage3 - // - this.tabPage3.Controls.Add(this.txtLog); - this.tabPage3.Location = new System.Drawing.Point(0, 0); - this.tabPage3.Name = "tabPage3"; - this.tabPage3.Size = new System.Drawing.Size(240, 245); - this.tabPage3.Text = "PwrNotifications"; - // - // txtLog - // - this.txtLog.AcceptsReturn = true; - this.txtLog.AcceptsTab = true; - this.txtLog.Dock = System.Windows.Forms.DockStyle.Fill; - this.txtLog.Location = new System.Drawing.Point(0, 0); - this.txtLog.Multiline = true; - this.txtLog.Name = "txtLog"; - this.txtLog.ReadOnly = true; - this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtLog.Size = new System.Drawing.Size(240, 245); - this.txtLog.TabIndex = 0; - this.txtLog.WordWrap = false; - // - // mnuLogPowerChanges - // - this.mnuLogPowerChanges.Text = "Log Power Changes"; - this.mnuLogPowerChanges.Click += new System.EventHandler(this.mnuLogPowerChanges_Click); - // - // NotificationsList - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.tabControl1); - this.Menu = this.mainMenu1; - this.Name = "NotificationsList"; - this.Text = "Form1"; - this.tabControl1.ResumeLayout(false); - this.tabPage1.ResumeLayout(false); - this.tabPage2.ResumeLayout(false); - this.tabPage3.ResumeLayout(false); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem menuItem1; - private System.Windows.Forms.MenuItem mnuOptions; - private System.Windows.Forms.TabControl tabControl1; - private System.Windows.Forms.TabPage tabPage1; - private System.Windows.Forms.DataGrid dataGrid1; - private System.Windows.Forms.TabPage tabPage2; - private System.Windows.Forms.TreeView treeView1; - private System.Windows.Forms.MenuItem mnuRefresh; - private System.Windows.Forms.MenuItem mnuSave; - private System.Windows.Forms.MenuItem menuItem2; - private System.Windows.Forms.TabPage tabPage3; - private System.Windows.Forms.TextBox txtLog; - private System.Windows.Forms.MenuItem mnuRemove; - private System.Windows.Forms.MenuItem mnuLogPowerChanges; - } -} - diff --git a/NotificationList/NotificationsList/NotificationsList.cs b/NotificationList/NotificationsList/NotificationsList.cs deleted file mode 100644 index 30cbe69..0000000 --- a/NotificationList/NotificationsList/NotificationsList.cs +++ /dev/null @@ -1,260 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using System.IO; -using OpenNETCF.WindowsCE.Notification; - -namespace NotificationsList -{ - public partial class NotificationsList : Form - { - PWRNOTIFICATIONS.PowerNotifications myPwrNot; - CeUserNotificationsClass clsNoti; - public bool bLogPowerChanges = false; - object lockObject = new object(); - - public NotificationsList() - { - InitializeComponent(); - clsNoti = new CeUserNotificationsClass(); - fillList(); - myPwrNot = new PWRNOTIFICATIONS.PowerNotifications(); - myPwrNot.OnMsg += new PWRNOTIFICATIONS.PowerNotifications.OnMsgHandler(myPwrNot_OnMsg); - myPwrNot.Start(); - - this.treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect); - } - - void treeView1_AfterSelect(object sender, TreeViewEventArgs e) - { - System.Diagnostics.Debug.WriteLine("TreeViewNode clicked: " + e.Node.ToString()); - TreeNode treeNode = (TreeNode)e.Node; - if (treeNode.Tag.ToString() == "root") - return; - - UserNotificationInfoHeader iHead=new UserNotificationInfoHeader(); - iHead = (UserNotificationInfoHeader)treeNode.Tag; - } - - UserNotificationInfoHeader getNotiHandleOfTreeView(TreeNode treeNode) - { - UserNotificationInfoHeader uNoti = new UserNotificationInfoHeader(); - if (treeNode.Tag.ToString() == "root") - return null; - - uNoti = (UserNotificationInfoHeader)treeNode.Tag; - - return uNoti; - } - - void myPwrNot_OnMsg(object sender, PWRNOTIFICATIONS.PowerNotifications.PwrEventArgs e) - { - addLog(DateTime.Now.ToString("hh:mm:ss") + "-" + e.PWRmsg ); - } - delegate void SetTextCallback(string text); - private void addLog(string text) - { - // InvokeRequired required compares the thread ID of the - // calling thread to the thread ID of the creating thread. - // If these threads are different, it returns true. - if (this.txtLog.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(addLog); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtLog.Text.Length > 20000) - txtLog.Text = ""; - txtLog.Text += text + "\r\n"; - txtLog.SelectionLength = text.Length; - txtLog.SelectionStart = txtLog.Text.Length - text.Length; - txtLog.ScrollToCaret(); - lock (lockObject) - { - if (bLogPowerChanges) - { - try - { - using (StreamWriter sr = new StreamWriter(@"\powernotifications.log.txt")) - { - sr.WriteLine(text); - sr.Flush(); - } - } - catch (Exception) - { - } - } - } - } - } - - int fillList() - { - clsNoti = new CeUserNotificationsClass(); - string[] sList = clsNoti.sAppList; - - clsNoti.applyTableStyle(dataGrid1); - dataGrid1.DataSource = clsNoti.eventEntries; - //dataGrid1.DataSource = cls.EventDB; - - CeUserNotificationsClass cls2 = new CeUserNotificationsClass(this.treeView1); - return sList.Length; - } - - private void menuItem1_Click(object sender, EventArgs e) - { - if (myPwrNot != null) - myPwrNot.Dispose(); - this.Close(); - } - - private void btnRefresh_Click(object sender, EventArgs e) - { - fillList(); - } - - private void mnuRefresh_Click_1(object sender, EventArgs e) - { - fillList(); - //CEGETUSERNOTIFICATION.CeGetUserNotification nClass = new CEGETUSERNOTIFICATION.CeGetUserNotification(); - //CEGETUSERNOTIFICATION.CeGetUserNotification.CE_USER_NOTIFICATION[] NotiList = nClass.getUserNotifications(); - } - - private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) - { - //if (tabControl1.SelectedIndex == 0) - //{ - // mnuRemove.Enabled=true; - //} - //else - // mnuRemove.Enabled = false; - } - - private void mnuSave_Click(object sender, EventArgs e) - { - if (saveData()) - MessageBox.Show("Data saved"); - } - private bool saveData() - { - // now, I need to write the contents out - SaveFileDialog sfd=new SaveFileDialog(); - sfd.Filter="Text files (*.txt)|*.txt|All files|*.*"; - sfd.FilterIndex = 0; - if (sfd.ShowDialog() != DialogResult.OK) - return false; - string fileName = sfd.FileName; - sfd.Dispose(); - - int iCount = ((CeUserNotificationsClass.EventEntry[])dataGrid1.DataSource).Length; - - string[] myStrings = new string[iCount + 1]; - myStrings[0] = "App\tArgs\tEvent\tStart\tEnd\tType"; - for (int i = 0; i < iCount; i++) - { - string dataItem = ""; - for (int j = 0; j < 6; j++) //6 = number of columns - dataItem = dataItem + dataGrid1[i, j].ToString() + "\t"; - dataItem = dataItem.Substring(0, dataItem.Length - 1); - myStrings[i+1] = dataItem; - } - - return myAllLineWrite(fileName, myStrings); - } - private bool myAllLineWrite(string fileName, string[] linesToWrite) - { - try - { - using (StreamWriter sr = new StreamWriter(fileName)) - { - for (int i = 0; i < linesToWrite.Length; i++) - sr.WriteLine(linesToWrite[i]); - } - return true; - } - catch (Exception) - { - } - return false; - } - - private void menuItem2_Click(object sender, EventArgs e) - { - AddNotification dlg = new AddNotification(); - dlg.ShowDialog(); - } - - private void dataGrid1_CurrentCellChanged(object sender, EventArgs e) - { - // String variable used to show message. - string myString = "CurrentCellChanged event raised, cell focus is at "; - // Get the co-ordinates of the focussed cell. - string myPoint = dataGrid1.CurrentCell.ColumnNumber + "," + dataGrid1.CurrentCell.RowNumber; - // Create the alert message. - myString = myString + "(" + myPoint + ")"; - // Show Co-ordinates when CurrentCellChanged event is raised. - System.Diagnostics.Debug.WriteLine(myString + "\nCurrent cell co-ordinates"); - - } - - private void mnuRemove_Click(object sender, EventArgs e) - { - if (tabControl1.SelectedIndex == 0)//datagridView - { - CeUserNotificationsClass.EventEntry cNot = new CeUserNotificationsClass.EventEntry(); - if (dataGrid1.CurrentRowIndex != -1) - { - CeUserNotificationsClass.EventEntry[] _entry = (CeUserNotificationsClass.EventEntry[])dataGrid1.DataSource; - cNot = _entry[dataGrid1.CurrentRowIndex]; - if (MessageBox.Show("Are you sure to delete '" + cNot.sApp + "'?", "Remove Entry", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.No) - return; - int iCnt = clsNoti.deleteEntry(cNot); - if (iCnt > 0) - { - MessageBox.Show("Number of deleted entries: " + iCnt.ToString()); - fillList(); - //dataGrid1.Refresh(); - } - else - MessageBox.Show("Nothing deleted"); - } - } - else if (tabControl1.SelectedIndex == 1)//treeView - { - TreeNode tn = this.treeView1.SelectedNode; - if (tn == null) - return; - UserNotificationInfoHeader userNotification = getNotiHandleOfTreeView(tn); - if (userNotification == null) - return; //not found - if (MessageBox.Show("Are you sure to delete '" + userNotification.UserNotificationTrigger.Application + "'?", "Remove Entry", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.No) - return; - bool bRes = CEGETUSERNOTIFICATION.CeGetUserNotification.ClearUserNotification((IntPtr)userNotification.hNotification); - if (bRes) - { - MessageBox.Show("Deleted entry: " + userNotification.UserNotificationTrigger.Application); - fillList(); - //dataGrid1.Refresh(); - } - else - MessageBox.Show("Nothing deleted"); - } - } - - private void mnuLogPowerChanges_Click(object sender, EventArgs e) - { - mnuLogPowerChanges.Checked = !mnuLogPowerChanges.Checked; - lock (lockObject) - { - bLogPowerChanges = mnuLogPowerChanges.Checked; - } - } - } -} \ No newline at end of file diff --git a/NotificationList/NotificationsList/NotificationsList.csproj b/NotificationList/NotificationsList/NotificationsList.csproj deleted file mode 100644 index a2cc85e..0000000 --- a/NotificationList/NotificationsList/NotificationsList.csproj +++ /dev/null @@ -1,116 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {09A016A6-F262-46BA-A6CD-C4410180B164} - WinExe - Properties - NotificationsList - NotificationsList - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.01 - NotificationsList - v3.5 - - - - - - - 2.0 - Windows Mobile 5.0 Pocket PC SDK - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - Form - - - AddNotification.cs - - - - - Form - - - NotificationsList.cs - - - - - - AddNotification.cs - - - Designer - NotificationsList.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/NotificationList/NotificationsList/NotificationsList.resx b/NotificationList/NotificationsList/NotificationsList.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/NotificationList/NotificationsList/NotificationsList.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/NotificationList/NotificationsList/NotificationsList.sln b/NotificationList/NotificationsList/NotificationsList.sln deleted file mode 100644 index cc97d49..0000000 --- a/NotificationList/NotificationsList/NotificationsList.sln +++ /dev/null @@ -1,34 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NotificationsList", "NotificationsList.csproj", "{09A016A6-F262-46BA-A6CD-C4410180B164}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenNetCF_LargeTimer", "..\..\..\Temp\OpenNetCF_LargeTimer\OpenNetCF_LargeTimer.csproj", "{3390D4A0-5ABC-482E-B924-0AF40E92F39C}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {09A016A6-F262-46BA-A6CD-C4410180B164}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {09A016A6-F262-46BA-A6CD-C4410180B164}.Debug|Any CPU.Build.0 = Debug|Any CPU - {09A016A6-F262-46BA-A6CD-C4410180B164}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {09A016A6-F262-46BA-A6CD-C4410180B164}.Release|Any CPU.ActiveCfg = Release|Any CPU - {09A016A6-F262-46BA-A6CD-C4410180B164}.Release|Any CPU.Build.0 = Release|Any CPU - {09A016A6-F262-46BA-A6CD-C4410180B164}.Release|Any CPU.Deploy.0 = Release|Any CPU - {3390D4A0-5ABC-482E-B924-0AF40E92F39C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3390D4A0-5ABC-482E-B924-0AF40E92F39C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3390D4A0-5ABC-482E-B924-0AF40E92F39C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {3390D4A0-5ABC-482E-B924-0AF40E92F39C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3390D4A0-5ABC-482E-B924-0AF40E92F39C}.Release|Any CPU.Build.0 = Release|Any CPU - {3390D4A0-5ABC-482E-B924-0AF40E92F39C}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/NotificationList/NotificationsList/PowerNotifications.cs b/NotificationList/NotificationsList/PowerNotifications.cs deleted file mode 100644 index dfd074c..0000000 --- a/NotificationList/NotificationsList/PowerNotifications.cs +++ /dev/null @@ -1,271 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using System.Runtime.InteropServices; -using System.Threading; - -//PowerNotifications_Queue.cs -/* usage -PowerNotifications pwrNot = new PowerNotifications(); -pwrNot.Resume += new EventHandler(PowerNotifier_OnResume); -pwrNot.Suspend += new EventHandler(PowerNotifier_OnSuspend); -pwrNot.Start(); -*/ -namespace PWRNOTIFICATIONS -{ - public class PowerNotifications:IDisposable - { - public class PwrEventArgs : EventArgs - { - public string PWRmsg; - public UInt32 PWRflags; - public PwrEventArgs(string m, UInt32 f) - { - this.PWRmsg = m; - this.PWRflags = f; - } - } - - #region Events - public event EventHandler OnSuspend; - public event EventHandler OnResume; - public event OnMsgHandler OnMsg; - public delegate void OnMsgHandler(object sender, PwrEventArgs e); - - [StructLayout(LayoutKind.Sequential)] - struct POWER_BROADCAST - { - UInt32 dwMsg; - UInt32 dwFlags; - UInt32 dwLength; - string sSystemPowerState; //WCHAR SystemPowerState[1]; - } - #endregion - - #region const - const uint POWER_NOTIFY_ALL = 0xFFFFFFFF; - - const uint PBT_TRANSITION = 0x00000001; // broadcast specifying system power state transition - const uint PBT_RESUME = 0x00000002; // broadcast notifying a resume, specifies previous state - const uint PBT_POWERSTATUSCHANGE = 0x00000004; // power supply switched to/from AC/DC - const uint PBT_POWERINFOCHANGE = 0x00000008; - - // - // System Power (Source/State/Option) Flags - // - [Flags] - enum PowerState:uint - { - // upper bytes: common power state bits - //#define POWER_STATE(f) ((f) & 0xFFFF0000); // power state mask - POWER_STATE_NA = 0x00, - POWER_STATE_ON = 0x00010000, // on state - POWER_STATE_OFF = 0x00020000, // no power, full off - POWER_STATE_CRITICAL = 0x00040000, // critical off - POWER_STATE_BOOT = 0x00080000, // boot state - POWER_STATE_IDLE = 0x00100000, // idle state - POWER_STATE_SUSPEND = 0x00200000, // suspend state - POWER_STATE_UNATTENDED = 0x00400000, // Unattended state. - POWER_STATE_RESET = 0x00800000, // reset state - POWER_STATE_USERIDLE = 0x01000000, // user idle state - POWER_STATE_BACKLIGHTON = 0x02000000, // device scree backlight on - POWER_STATE_PASSWORD = 0x10000000, // This state is password protected. - } - [Flags] - enum PowerEventType - { - PBT_TRANSITION = 0x00000001, - PBT_RESUME = 0x00000002, - PBT_POWERSTATUSCHANGE = 0x00000004, - PBT_POWERINFOCHANGE = 0x00000008, - } - - [Flags] - enum PowerState1 - { - POWER_STATE_ON = (0x00010000), - POWER_STATE_OFF = (0x00020000), - - POWER_STATE_CRITICAL = (0x00040000), - POWER_STATE_BOOT = (0x00080000), - POWER_STATE_IDLE = (0x00100000), - POWER_STATE_SUSPEND = (0x00200000), - POWER_STATE_RESET = (0x00800000), - } - class POWER_BROADCAST1 - { - public POWER_BROADCAST1(int size) - { - m_data = new byte[size]; - } - byte[] m_data; - public byte[] Data { get { return m_data; } } - public PowerEventType Message { get { return (PowerEventType)BitConverter.ToInt32(m_data, 0); } } - public PowerState1 Flags { get { return (PowerState1)BitConverter.ToInt32(m_data, 4); } } - public int Length { get { return BitConverter.ToInt32(m_data, 8); } } - public byte[] SystemPowerState { get { byte[] data = new byte[Length]; Buffer.BlockCopy(m_data, 12, data, 0, Length); return data; } } - } - #endregion - - #region Variables - IntPtr ptr = IntPtr.Zero; - Thread t = null; - bool done = false; - #endregion - - #region DllImports - [DllImport("coredll.dll")] - private static extern IntPtr RequestPowerNotifications(IntPtr hMsgQ, uint Flags); - [DllImport("coredll.dll")] - private static extern uint WaitForSingleObject(IntPtr hHandle, int wait); - [DllImport("coredll.dll")] - private static extern IntPtr CreateMsgQueue(string name, ref MsgQOptions options); - [DllImport("coredll.dll")] - private static extern bool ReadMsgQueue(IntPtr hMsgQ, byte[] lpBuffer, uint cbBufSize, ref uint lpNumRead, int dwTimeout, ref uint pdwFlags); - #endregion - - public PowerNotifications() - { - MsgQOptions options = new MsgQOptions(); - options.dwFlags = 0; - options.dwMaxMessages = 20; - options.cbMaxMessage = 10000; - options.bReadAccess = true; - options.dwSize = (uint)Marshal.SizeOf(options); - ptr = CreateMsgQueue("Test", ref options); - RequestPowerNotifications(ptr, POWER_NOTIFY_ALL); - t = new Thread(DoWork); - t.Name = "Power events listening thread"; - } - - public void Start() - { - t.Start(); - } - public void Stop() - { - done = true; - if (!t.Join(2500)) - t.Abort(); - } - - public void Dispose(){ - Stop(); - } - - private bool isSet(UInt32 flag, UInt32 bit){ - if((flag & bit)==bit) - return true; - else - return false; - } - private void DoWork() - { - byte[] buf = new byte[10000]; - uint nRead = 0, flags = 0, res = 0; - - System.Diagnostics.Debug.WriteLine("starting loop"); - try - { - while (!done) - { - res = WaitForSingleObject(ptr, 2500); - if (res == 0) - { - ReadMsgQueue(ptr, buf, (uint)buf.Length, ref nRead, -1, ref flags); - //System.Diagnostics.Debug.WriteLine("message: " + ConvertByteArray(buf, 0) + " flag: " + ConvertByteArray(buf, 4)); - uint flag = ConvertByteArray(buf, 4); - string msg = ""; - msg += ((PowerState)flag).ToString(); - /* - if( (flag & POWER_STATE_ON) == POWER_STATE_ON ){// 65536: - msg += " Power On"; - if (OnResume != null) - OnResume(this, EventArgs.Empty); - } - if( (flag & POWER_STATE_OFF) == POWER_STATE_OFF){// 131072: - msg += " Power Off"; - } - if ((flag & POWER_STATE_CRITICAL) == POWER_STATE_CRITICAL){// 262144: - msg += " Power Critical"; - } - if(isSet(flag, POWER_STATE_BOOT)){// 524288: - msg += " Power Boot"; - } - if(isSet(flag, POWER_STATE_IDLE)){// 1048576: - msg += " Power Idle"; - } - if( isSet(flag, POWER_STATE_SUSPEND)){// 2097152: - msg += " Power Suspend"; - if (OnSuspend != null) - OnSuspend(this, EventArgs.Empty); - } - if( isSet(flag, POWER_STATE_RESET)){// 8388608: - msg += " Power Reset"; - } - if( isSet(flag, POWER_STATE_UNATTENDED)){ - msg += " Power Unattended"; - } - if( isSet(flag, POWER_STATE_BACKLIGHTON)){ - msg += " Power BacklightON"; - } - if( isSet(flag, POWER_STATE_USERIDLE)){ - msg += "Power UserIdle"; - } - if( isSet(flag, POWER_STATE_PASSWORD)){ - msg += "Power Password"; - } - //case 0: - // // non power transition messages are ignored - // break; - */ - if (msg=="") - msg = "Unknown Flag: " + flag.ToString(); - if (msg=="0") - msg = "POWER_STATE_NA"; - - if (msg != "") - { - if(OnMsg!=null) - OnMsg(this, new PwrEventArgs(msg, flag)); - System.Diagnostics.Debug.WriteLine(msg); - } - } - } - } - catch (Exception ex) - { - if (!done) - { - System.Diagnostics.Debug.WriteLine("Got exception: " + ex); - } - } - System.Diagnostics.Debug.WriteLine("loop ended"); - } - - uint ConvertByteArray(byte[] array, int offset) - { - uint res = 0; - res += array[offset]; - res += array[offset + 1] * (uint)0x100; - res += array[offset + 2] * (uint)0x10000; - res += array[offset + 3] * (uint)0x1000000; - return res; - } - - [StructLayout(LayoutKind.Sequential)] - public struct MsgQOptions - { - public uint dwSize; - public uint dwFlags; - public uint dwMaxMessages; - public uint cbMaxMessage; - public bool bReadAccess; - } - } -} \ No newline at end of file diff --git a/NotificationList/NotificationsList/Program.cs b/NotificationList/NotificationsList/Program.cs deleted file mode 100644 index f9f6260..0000000 --- a/NotificationList/NotificationsList/Program.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; - -namespace NotificationsList -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new NotificationsList()); - } - } -} \ No newline at end of file diff --git a/NotificationList/NotificationsList/Properties/AssemblyInfo.cs b/NotificationList/NotificationsList/Properties/AssemblyInfo.cs deleted file mode 100644 index be94866..0000000 --- a/NotificationList/NotificationsList/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("NotificationsList")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("NotificationsList")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("e9d453d9-c1c9-4628-85dc-59bf97fba5b8")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - diff --git a/NotificationList/NotificationsList/Properties/Resources.Designer.cs b/NotificationList/NotificationsList/Properties/Resources.Designer.cs deleted file mode 100644 index 5746eda..0000000 --- a/NotificationList/NotificationsList/Properties/Resources.Designer.cs +++ /dev/null @@ -1,60 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5446 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace NotificationsList.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NotificationsList.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/NotificationList/NotificationsList/Properties/Resources.resx b/NotificationList/NotificationsList/Properties/Resources.resx deleted file mode 100644 index 451318b..0000000 --- a/NotificationList/NotificationsList/Properties/Resources.resx +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 diff --git a/NotificationList/NotificationsList/SystemTime.cs b/NotificationList/NotificationsList/SystemTime.cs deleted file mode 100644 index 6dad83b..0000000 --- a/NotificationList/NotificationsList/SystemTime.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; - -namespace CEGETUSERNOTIFICATION -{ - [StructLayout(LayoutKind.Sequential)] - public class SYSTEMTIME - { - public ushort wYear; - public ushort wMonth; - public ushort wDayOfWeek; - public ushort wDay; - public ushort wHour; - public ushort wMinute; - public ushort wSecond; - public ushort wMilliseconds; - - public SYSTEMTIME(DateTime dtDateTime) - { - this.wYear = (ushort)dtDateTime.Year; - this.wMonth = (ushort)dtDateTime.Month; - this.wDayOfWeek = (ushort)dtDateTime.DayOfWeek; - this.wDay = (ushort)dtDateTime.Day; - this.wHour = (ushort)dtDateTime.Hour; - this.wMinute = (ushort)dtDateTime.Minute; - this.wSecond = (ushort)dtDateTime.Second; - this.wMilliseconds = 0; - } - public SYSTEMTIME(byte[] buf, int idx) - { - wYear = BitConverter.ToUInt16(buf, idx); idx += 2; - wMonth = BitConverter.ToUInt16(buf, idx); idx += 2; - wDayOfWeek = BitConverter.ToUInt16(buf, idx); idx += 2; - wDay = BitConverter.ToUInt16(buf, idx); idx += 2; - wHour = BitConverter.ToUInt16(buf, idx); idx += 2; - wMinute = BitConverter.ToUInt16(buf, idx); idx += 2; - wSecond = BitConverter.ToUInt16(buf, idx); idx += 2; - wMilliseconds = BitConverter.ToUInt16(buf, idx); idx += 2; - } - public static DateTime GetAsDateTime(SYSTEMTIME st) - { - return new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); - } - - public static DateTime dtLocalDateTime - { - get{ - SYSTEMTIME sysTime = new SYSTEMTIME(DateTime.Now); - GetLocalTime(sysTime); - DateTime dtLocalTime = GetAsDateTime(sysTime); - return dtLocalDateTime; - } - } - [DllImport("coredll.dll")] - public static extern void GetLocalTime(SYSTEMTIME sysTime); - } - -} diff --git a/NotificationList/NotificationsList/WinCE.cs b/NotificationList/NotificationsList/WinCE.cs deleted file mode 100644 index 4841f52..0000000 --- a/NotificationList/NotificationsList/WinCE.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -namespace WinCE -{ - class WinCE - { - public static int findEndOfString(byte[] buf, int idx, int iSize) - { - int iRet = -1; - int iStart = idx; - int iEnd = iSize; - int iPos=idx; - //search for two zero bytes in sequence - do - { - if (buf[iPos] == 0 && buf[iPos + 1] == 0) - iRet = iPos+1; - iPos++; - } while (iPos < iSize-1 && iRet!=-1); - return iRet; - } - } -} diff --git a/OpenNetCF_LargeTimer/CeGetUserNotification.cs b/OpenNetCF_LargeTimer/CeGetUserNotification.cs deleted file mode 100644 index 308d821..0000000 --- a/OpenNetCF_LargeTimer/CeGetUserNotification.cs +++ /dev/null @@ -1,333 +0,0 @@ -// http://onehourofdevelopment.blogspot.com/2009_10_01_archive.html - -using System; -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; - -using System.Windows.Forms; - -namespace CEGETUSERNOTIFICATION -{ - class CeGetUserNotification - { - /* - CeGetUserNotificationHandles returns an array of notification handles. Each of the handles can then be used as - input for CeGetUserNotification which in turn will return the notification as a byte array. - To determine the size of rghNotifications needed, call CeGetUserNotificationHandless with NULL parameters. - - uint dwHowMany=0; - GetUserNotificationHandles(null, 0 ref dwHowMany); - */ - /* - You then use the value of dwHowMany to create an IntPtr array of the correct size. - - IntPtr rghNotifications = new IntPtr[dwHowMany]; - - Calling CeGetUserNotificationHandles one more time will fill the IntPtr array. - - GetUserNotificationHandles(rghNotifications, dwHowMany, ref dwHowMany); - - Given that GetUserNotificationHandles returned TRUE you should now have an IntPtr array filled with notification handles that can you can use. - */ - [DllImport("CoreDLL.dll", SetLastError = false, EntryPoint = "CeClearUserNotification")] - public static extern bool ClearUserNotification(IntPtr hNotification); - - /* - IntPtr hNotification; - Call CeSetUserNotificationEx and save its output in hNotification - */ - - /* - if ( ClearUserNotification(hNotification) ) - MessageBox.Show("Successfully cleared the notification"); - else - MessageBox.Show("Failed to clear the notification"); - */ - - [DllImport("CoreDLL.dll", SetLastError = false, EntryPoint = "CeGetUserNotificationHandles")] - public static extern bool GetUserNotificationHandles(IntPtr[] rghNotifications, uint cHandles, ref uint pcHandlesNeeded); - - [DllImport("CoreDLL.dll", SetLastError = false, EntryPoint = "CeGetUserNotification")] - public static extern bool GetUserNotification(IntPtr hNotification, uint BufferSize, out uint BytesNeeded, byte[] Buffer); - /* - Calling GetUserNotification passing null values and a valid notification handle will return the bytes needed for the byte - buffer. You then call GetUserNotification once more passing both a notification handle as well as a byte buffer. - - GetUserNotification(hNotification, 0, out Size, null); - Buf = new byte[Size]; - GetUserNotification(hNotification, Size, out Size, Buf); - */ - - [DllImport("CoreDLL.dll", SetLastError = false, EntryPoint = "CeSetUserNotificationEx")] - public static extern uint SetUserNotificationEx([MarshalAs(UnmanagedType.U4)]uint hNotification, CE_NOTIFICATION_TRIGGER Trigger, CE_USER_NOTIFICATION Notification); - - public CE_USER_NOTIFICATION[] getUserNotifications(){ - //how many usernotifications are there? - IntPtr[] unHandles = new IntPtr[1]; - uint iHandleCount = 1; - uint iHandlesNeeded = 0; - if (!GetUserNotificationHandles(unHandles, iHandleCount, ref iHandlesNeeded)) - return null; - //we got some handle count - unHandles = new IntPtr[iHandlesNeeded]; - iHandleCount = iHandlesNeeded; - if (!GetUserNotificationHandles(unHandles, iHandleCount, ref iHandlesNeeded)) - return null; - CE_USER_NOTIFICATION[] userNotifications = new CE_USER_NOTIFICATION[iHandleCount]; - for (int i = 0; i < iHandleCount; i++) - { - uint uBytesNeeded=0; - if (GetUserNotification(unHandles[i], 0, out uBytesNeeded, null)==false) - { - byte[] buf = new byte[uBytesNeeded]; - uint uBufSize = uBytesNeeded; - GetUserNotification(unHandles[i], uBufSize, out uBytesNeeded, buf); - int iIdx = 0; - userNotifications[i] = new CE_USER_NOTIFICATION(buf, (uint)buf.Length, ref iIdx); - } - else - System.Diagnostics.Debug.WriteLine("GetUserNotification: " + Marshal.GetLastWin32Error().ToString()); - } - return userNotifications; - } - public void runAppAtTime(string sApp, SYSTEMTIME stStart, SYSTEMTIME stEnd) - { - CE_NOTIFICATION_TRIGGER cnt = new CE_NOTIFICATION_TRIGGER(); - cnt.Type = CeNotificationType.CNT_TIME; - cnt.StartTime = stStart; - cnt.EndTime = stEnd; - cnt.pApplication = @"\windows\fexplore.exe"; - cnt.pArgs = ""; - cnt.Size = (UInt32)Marshal.SizeOf(cnt); // Needs to compile with /unsafe - - uint hNotificationEx = SetUserNotificationEx(0, cnt, null); - if (hNotificationEx > 0) - MessageBox.Show("Successfully created a notification. Handle: " + hNotificationEx.ToString()); - else - MessageBox.Show("Failed to create a notification"); - } - /* - The following code will create a time based trigger and connect that trigger to a notification that will fire up \windows\fexplore.exe. - Note that you need to compile this sample with the /unsafe switch. You could always hard code the size of CE_NOTIFICATION_TRIGGER in which case /unsafe won't be necessary. If hard coded; the value is 52. - Also don't forget to pass NULL instead of ceun if you change the trigger type to CNT_EVENT. - */ - public void newRunAtTime(SYSTEMTIME stStart, SYSTEMTIME stEnd){ - CE_NOTIFICATION_TRIGGER cnt = new CE_NOTIFICATION_TRIGGER(); - CE_USER_NOTIFICATION ceun = new CE_USER_NOTIFICATION(); - cnt.Type =CeNotificationType.CNT_TIME; - cnt.StartTime = stStart; - cnt.EndTime = stEnd; - cnt.pApplication = @"\windows\fexplore.exe"; - cnt.pArgs = ""; - cnt.Size = (UInt32)Marshal.SizeOf(cnt); // Needs to compile with /unsafe - - ceun.ActionFlags = PUN_FLAGS.PUN_LED; - ceun.sDialogText = "Dialogtext"; - ceun.sDialogTitle = "Title"; - ceun.nMaxSound = 0; - - uint hNotificationEx = SetUserNotificationEx(0, cnt, ceun); - if (hNotificationEx > 0) - MessageBox.Show("Successfully created a notification. Handle: " + hNotificationEx.ToString()); - else - MessageBox.Show("Failed to create a notification"); - } - - public enum CeNotificationType - { - CNT_EVENT = 1, //@flag CNT_EVENT | System event notification - CNT_TIME, //@flag CNT_TIME | Time-based notification - CNT_PERIOD, //@flag CNT_PERIOD | Time-based notification is active for - // time period between stStart and stEnd - CNT_CLASSICTIME //@flag CNT_CLASSICTIME | equivalent to using (obsolete) - // CeSetUserNotification function - standard command line is - // supplied. lpszArguments must be NULL - } - [StructLayout(LayoutKind.Sequential)] - public class CE_NOTIFICATION_INFO_HEADER - { - [MarshalAs(UnmanagedType.U4)] - public uint hNotification; - [MarshalAs(UnmanagedType.U4)] - public uint dwStatus; - public CE_NOTIFICATION_TRIGGER cent; - public CE_USER_NOTIFICATION ceun; - - public CE_NOTIFICATION_INFO_HEADER(byte[] Buf, uint Size) - { - int Index = 0; - try - { - this.hNotification = BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.dwStatus = BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint pcent = BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint pceun = BitConverter.ToUInt32(Buf, Index); - Index += 4; - if (pcent > 0 && Buf[Index] == Marshal.SizeOf(new CE_NOTIFICATION_TRIGGER())) - this.cent = new CE_NOTIFICATION_TRIGGER(Buf, Size, ref Index); - if (pceun > 0) - this.ceun = new CE_USER_NOTIFICATION(Buf, Size, ref Index); - } - catch (Exception ex) - { - throw ex; - } - } - } - [StructLayout(LayoutKind.Sequential)] - public class CE_NOTIFICATION_TRIGGER - { - public UInt32 Size = 0; - [MarshalAs(UnmanagedType.U4)] - public CeNotificationType Type; - [MarshalAs(UnmanagedType.U4)] - public CeNotificationEvent Event; - [MarshalAs(UnmanagedType.LPWStr)] - public string pApplication; - [MarshalAs(UnmanagedType.LPWStr)] - public string pArgs; - public SYSTEMTIME StartTime; - public SYSTEMTIME EndTime; - public CE_NOTIFICATION_TRIGGER() - { - } - - public CE_NOTIFICATION_TRIGGER(byte[] Buf, uint Size, ref int Index) - { - int iEndOfString; - System.Text.UnicodeEncoding enc = new UnicodeEncoding(); - uint lpszApp = 0; - uint lpszArgs = 0; - this.Size = BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.Type = (CeNotificationType)BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.Event = (CeNotificationEvent)BitConverter.ToUInt32(Buf, Index); - Index += 4; - lpszApp = BitConverter.ToUInt32(Buf, Index); - Index += 4; - lpszArgs = BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.StartTime = new SYSTEMTIME(Buf, Index); - Index += 16; - this.EndTime = new SYSTEMTIME(Buf, Index); - Index += 16; - if (lpszApp > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.pApplication = enc.GetString(Buf, Index, iEndOfString - Index - 2); - Index = iEndOfString; - } - if (lpszArgs > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.pArgs = enc.GetString(Buf, Index, iEndOfString - Index - 2); // Stupid solution to double null ending.. - Index = iEndOfString; - } - } - } - public enum CeNotificationEvent - { - NOTIFICATION_EVENT_NONE, - NOTIFICATION_EVENT_TIME_CHANGE, - NOTIFICATION_EVENT_SYNC_END, - NOTIFICATION_EVENT_ON_AC_POWER, - NOTIFICATION_EVENT_OFF_AC_POWER, - NOTIFICATION_EVENT_NET_CONNECT, - NOTIFICATION_EVENT_NET_DISCONNECT, - NOTIFICATION_EVENT_DEVICE_CHANGE, - NOTIFICATION_EVENT_IR_DISCOVERED, - NOTIFICATION_EVENT_RS232_DETECTED, - NOTIFICATION_EVENT_RESTORE_END, - NOTIFICATION_EVENT_WAKEUP, - NOTIFICATION_EVENT_TZ_CHANGE, - NOTIFICATION_EVENT_MACHINE_NAME_CHANGE, - NOTIFICATION_EVENT_RNDIS_FN_DETECTED, - NOTIFICATION_EVENT_INTERNET_PROXY_CHANGE, - NOTIFICATION_EVENT_LAST = NOTIFICATION_EVENT_INTERNET_PROXY_CHANGE - }; - public enum PUN_FLAGS - { - PUN_LED = 1 , //@flag PUN_LED | LED flag. Set if the LED should be - // flashed when the notification occurs. - - PUN_VIBRATE = 2, //@flag PUN_VIBRATE | Vibrate flag. Set if the device should - // be vibrated. - - PUN_DIALOG = 4, //@flag PUN_DIALOG | Dialog flag. Set if a dialog should be - // displayed (the app must provide title and text - // when calling ). - - PUN_SOUND = 8, //@flag PUN_SOUND | Sound flag. Set if the sound specified - // in pwszSound should be played. - - PUN_REPEAT = 16, //@flag PUN_REPEAT | Sound repeat flag. Set if the sound - // specified in pwszSound should be repeated progressively. - - PUN_PRIVATE = 32 //@flag PUN_PRIVATE | Dialog box z-order flag. Set if the - // notification dialog box should come up behind the password. - }; - [StructLayout(LayoutKind.Sequential)] - public class CE_USER_NOTIFICATION - { - [MarshalAs(UnmanagedType.U4)] - public PUN_FLAGS ActionFlags; - [MarshalAs(UnmanagedType.LPTStr)] - public string sDialogTitle; - [MarshalAs(UnmanagedType.LPTStr)] - public string sDialogText; - [MarshalAs(UnmanagedType.LPTStr)] - public string sSound; - [MarshalAs(UnmanagedType.U4)] - public uint nMaxSound; - [MarshalAs(UnmanagedType.U4)] - public uint Reserved; - public CE_USER_NOTIFICATION() - { - } - - public CE_USER_NOTIFICATION(byte[] Buf, uint Size, ref int Index) - { - int iEndOfString; - System.Text.UnicodeEncoding enc = new UnicodeEncoding(); - - this.ActionFlags = (PUN_FLAGS)BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint lpszDialogTitle = BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint lpszDialogText = BitConverter.ToUInt32(Buf, Index); - Index += 4; - uint lpszSound = BitConverter.ToUInt32(Buf, Index); - Index += 4; - this.nMaxSound = BitConverter.ToUInt32(Buf, Index); - Index += 4; - // read Reserved - Index += 4; - if (lpszDialogTitle > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.sDialogTitle = enc.GetString(Buf, Index, iEndOfString - Index - 2); - Index = iEndOfString; - } - if (lpszDialogText > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.sDialogText = enc.GetString(Buf, Index, iEndOfString - Index - 2); - Index = iEndOfString; - } - if (lpszSound > 0) - { - iEndOfString = WinCE.WinCE.findEndOfString(Buf, Index, (int)Size); - this.sSound = enc.GetString(Buf, Index, iEndOfString - Index - 2); - Index = iEndOfString; - } - } - } - // CE_NOTIFICATION_INFO_HEADER cenih = new Notify.CE_NOTIFICATION_INFO_HEADER(Buf, Size); - } -} diff --git a/OpenNetCF_LargeTimer/CeUserNotificationsClass.cs b/OpenNetCF_LargeTimer/CeUserNotificationsClass.cs deleted file mode 100644 index a86dbe9..0000000 --- a/OpenNetCF_LargeTimer/CeUserNotificationsClass.cs +++ /dev/null @@ -1,309 +0,0 @@ -using System; -using System.Windows.Forms; -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; - -using System.Data; - -using OpenNETCF.WindowsCE.Notification; - -namespace CEGETUSERNOTIFICATION -{ - class CeUserNotificationsClass - { - public class EventEntry{ - private string _sApp; - private string _sArg; - private string _sEvent; - private string _sStartTime; - private string _sEndTime; - private string _sType; - private string _sHandle; - - private System.Collections.ArrayList entries = new System.Collections.ArrayList(); - - public EventEntry(string s) - { - string[] sIn = s.Split('|'); - if (sIn.Length == 7) - { - _sApp = sIn[0]; - _sArg = sIn[1]; - _sEvent = sIn[2]; - _sStartTime = sIn[3]; - _sEndTime = sIn[4]; - _sType = sIn[5]; - _sHandle = sIn[6]; - } - } - public EventEntry(string[] sIn) - { - _sApp = sIn[0]; - _sArg = sIn[1]; - _sEvent = sIn[2]; - _sStartTime = sIn[3]; - _sEndTime = sIn[4]; - _sType = sIn[5]; - _sHandle = sIn[6]; - } - - public string sApp - { - get { return _sApp; } - set { _sApp = value; } - } - public string sArg - { - get { return _sArg; } - set { _sArg = value; } - } - public string sEvent - { - get { return _sEvent; } - set { _sEvent = value; } - } - public string sStartTime - { - get { return _sStartTime; } - set { _sStartTime = value; } - } - public string sEndTime - { - get { return _sEndTime; } - set { _sEndTime = value; } - } - public string sType - { - get { return _sType; } - set { _sType = value; } - } - public string sHandle - { - get { return _sHandle; } - set { _sHandle = value; } - } - } - - public EventEntry[] eventEntries; - public DataTable EventDB; - - //[DllImport("coredll.dll", EntryPoint = "CeGetUserNotificationHandles", SetLastError = true)] - //private static extern bool CeGetUserNotificationHandles(IntPtr[] rghNotifications, uint cHandles, ref uint pcHandlesNeeded); - //[DllImport("coredll.dll", EntryPoint = "CeGetUserNotification", SetLastError = true)] - //private static extern bool CeGetUserNotification(IntPtr hNotification, uint cBufferSize, ref uint pcBytesNeeded, IntPtr pBuffer); - - private const uint _maxHandles = 128; - private const uint _bufSize = 8192; - - private List _sList; - - string[][] _strArr; - public string[][] strArr - { - get { return _strArr; } - } - - public string[] sAppList - { - get { return _sList.ToArray(); } - } - - public CeUserNotificationsClass() - { - loadNotifications(); - fillDB(); - } - - public CeUserNotificationsClass(TreeView tv) - { - loadNotifications(); - loadNotifications(tv); - } - private int loadNotifications(TreeView tv) - { - int iCnt = 0; - tv.Nodes.Clear(); - TreeNode tnMain = tv.Nodes.Add("Notifications"); - - int[] iHandles = OpenNETCF.WindowsCE.Notification.Notify.GetUserNotificationHandles(); - _sList = new List(); - _sList.Clear(); - - _strArr = new string[iHandles.Length + 1][]; - - _strArr[0] = new string[7] { "App", "Args", "Event", "Start", "End", "Type", "handle" }; - - int i = 0; - - eventEntries = new EventEntry[iHandles.Length]; - - foreach (int iHandle in iHandles) - { - OpenNETCF.WindowsCE.Notification.UserNotificationInfoHeader infoHeader = OpenNETCF.WindowsCE.Notification.Notify.GetUserNotification(iHandle); - string[] strArray = new string[] { infoHeader.UserNotificationTrigger.Application, infoHeader.UserNotificationTrigger.Arguments }; - TreeNode tn = new TreeNode(infoHeader.UserNotificationTrigger.Application); - tnMain.Nodes.Add(tn); - tn.Nodes.Add("Args: " + infoHeader.UserNotificationTrigger.Arguments); - tn.Nodes.Add("Event: " + infoHeader.UserNotificationTrigger.Event.ToString()); - tn.Nodes.Add("Start: " + infoHeader.UserNotificationTrigger.StartTime.ToString("dd.MM.yyyy HH:mm")); - tn.Nodes.Add("End: " + infoHeader.UserNotificationTrigger.EndTime.ToString("dd.MM.yyyy HH:mm")); - tn.Nodes.Add("Type: " + infoHeader.UserNotificationTrigger.Type.ToString()); - tn.Nodes.Add("Handle: " + iHandles[i].ToString()); - - //eventEntries[i].sApp = infoHeader.UserNotificationTrigger.Application; - //eventEntries[i].sEvent = infoHeader.UserNotificationTrigger.Event.ToString(); - //eventEntries[i].sArg = infoHeader.UserNotificationTrigger.Arguments; - //eventEntries[i].sStartTime = infoHeader.UserNotificationTrigger.StartTime.ToString("dd.MM.yyyy HH:mm"); - //eventEntries[i].sEndTime = infoHeader.UserNotificationTrigger.EndTime.ToString("dd.MM.yyyy HH:mm"); - //eventEntries[i].sType = infoHeader.UserNotificationTrigger.Type.ToString(); - //eventEntries[i].sHandle = iHandles[i].ToString(); - - iCnt++; - } - tv.Refresh(); - return iCnt; - } - private void fillDB() - { - EventDB = new DataTable("Notifications"); - DataColumn[] dc = new DataColumn[7]; - string[] _fieldNames = new string[7] { "App", "Args", "Event", "Start", "End", "Type", "handle" }; - //build the table columns - for (int i = 0; i < 7; i++) - { - dc[i] = new DataColumn(); - dc[i].Caption = _fieldNames[i]; // "App"; - dc[i].ColumnName = _fieldNames[i]; // "App"; - dc[i].DataType = System.Type.GetType("System.String"); - dc[i].MaxLength = 256; - dc[i].Unique = false; - dc[i].AllowDBNull = false; - } - //add header - EventDB.Columns.AddRange(dc); - //add rows - for (int i = 0; i < eventEntries.Length; i++) - { - DataRow dr = EventDB.NewRow(); - object[] o = new object[7]{ eventEntries[i].sApp, eventEntries[i].sArg, eventEntries[i].sEvent, - eventEntries[i].sStartTime, eventEntries[i].sEndTime, eventEntries[i].sType, eventEntries[i].sHandle }; - dr.ItemArray = o; - EventDB.Rows.Add(dr); - } - } - private int loadNotifications() - { - int[] iHandles = OpenNETCF.WindowsCE.Notification.Notify.GetUserNotificationHandles(); - _sList= new List(); - _sList.Clear(); - - _strArr = new string[iHandles.Length + 1][]; - - _strArr[0] = new string[7] { "App", "Args", "Event", "Start", "End", "Type", "handle" }; - - int i = 0; - - eventEntries = new EventEntry[iHandles.Length]; - //eventEntries[0] = new EventEntry("App|Args|Event|Start|End|Type"); - - //############################### - - //############################### - - foreach (int iHandle in iHandles) - { - OpenNETCF.WindowsCE.Notification.UserNotificationInfoHeader infoHeader = OpenNETCF.WindowsCE.Notification.Notify.GetUserNotification(iHandle); - - _strArr[i]=new string[7]; - - string sApp = infoHeader.UserNotificationTrigger.Application; - _strArr[i][0]="'" + infoHeader.UserNotificationTrigger.Application + "'"; - - sApp += "|'" + infoHeader.UserNotificationTrigger.Arguments + "'"; - _strArr[i][1]=infoHeader.UserNotificationTrigger.Arguments; - - sApp += "|" + infoHeader.UserNotificationTrigger.Event.ToString(); - _strArr[i][2]=infoHeader.UserNotificationTrigger.Event.ToString(); - - sApp += "|" + infoHeader.UserNotificationTrigger.StartTime.ToString("ddMMyyyy HH:mm"); - _strArr[i][3] = infoHeader.UserNotificationTrigger.StartTime.ToString("ddMMyyyy HH:mm"); - - sApp += "|" + infoHeader.UserNotificationTrigger.EndTime.ToString("ddMMyyyy HH:mm"); - _strArr[i][4] = infoHeader.UserNotificationTrigger.EndTime.ToString("ddMMyyyy HH:mm"); - - sApp += "|" + infoHeader.UserNotificationTrigger.Type.ToString(); - _strArr[i][5] = infoHeader.UserNotificationTrigger.Type.ToString(); - - sApp += "|" + iHandles[i].ToString(); - _strArr[i][6] = iHandles[i].ToString(); - - eventEntries[i] = new EventEntry(sApp); - //eventEntries[i] = new EventEntry(_strArr[i]); - - i++; - _sList.Add(sApp); - } - - return _sList.Count; - } - - public void applyTableStyle(DataGrid dataGrid1) - { - // Creates two DataGridTableStyle objects, one for the Machine - // array, and one for the Parts ArrayList. - - DataGridTableStyle EventsTable = new DataGridTableStyle(); - // Sets the MappingName to the class name plus brackets. - EventsTable.MappingName = "EventEntry[]"; - - // Sets the AlternatingBackColor so you can see the difference. - //EventsTable.AlternatingBackColor = System.Drawing.Color.LightBlue; - - // Creates column styles. - DataGridTextBoxColumn eventApp = new DataGridTextBoxColumn(); - eventApp.MappingName = "sApp"; - eventApp.HeaderText = "sApp"; - eventApp.Width = dataGrid1.Width / 6 * 2; - - DataGridTextBoxColumn eventArg = new DataGridTextBoxColumn(); - eventArg.MappingName = "sArg"; - eventArg.HeaderText = "Arg"; - - DataGridTextBoxColumn eventEvent = new DataGridTextBoxColumn(); - eventEvent.MappingName = "sEvent"; - eventEvent.HeaderText = "Event"; - - DataGridTextBoxColumn eventStart = new DataGridTextBoxColumn(); - eventStart.MappingName = "sStartTime"; - eventStart.HeaderText = "Start"; - - DataGridTextBoxColumn eventEnd = new DataGridTextBoxColumn(); - eventEnd.MappingName = "sEndTime"; - eventEnd.HeaderText = "End"; - - DataGridTextBoxColumn eventType = new DataGridTextBoxColumn(); - eventType.MappingName = "sType"; - eventType.HeaderText = "Type"; - - DataGridTextBoxColumn eventHandle = new DataGridTextBoxColumn(); - eventHandle.MappingName = "sHandle"; - eventHandle.HeaderText = "handle"; - - // Adds the column styles to the grid table style. - EventsTable.GridColumnStyles.Add(eventApp); - EventsTable.GridColumnStyles.Add(eventArg); - EventsTable.GridColumnStyles.Add(eventEvent); - EventsTable.GridColumnStyles.Add(eventStart); - EventsTable.GridColumnStyles.Add(eventEnd); - EventsTable.GridColumnStyles.Add(eventType); - EventsTable.GridColumnStyles.Add(eventHandle); - - // Add the table style to the collection, but clear the - // collection first. - dataGrid1.TableStyles.Clear(); - dataGrid1.TableStyles.Add(EventsTable); - - } - } -} diff --git a/OpenNetCF_LargeTimer/LargeTimerTest.Designer.cs b/OpenNetCF_LargeTimer/LargeTimerTest.Designer.cs deleted file mode 100644 index e719b3b..0000000 --- a/OpenNetCF_LargeTimer/LargeTimerTest.Designer.cs +++ /dev/null @@ -1,92 +0,0 @@ -namespace OpenNetCF_LargeTimer -{ - partial class LargeTimerTest - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.btnStart = new System.Windows.Forms.Button(); - this.txtLog = new System.Windows.Forms.TextBox(); - this.btnStop = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // btnStart - // - this.btnStart.Location = new System.Drawing.Point(63, 3); - this.btnStart.Name = "btnStart"; - this.btnStart.Size = new System.Drawing.Size(116, 35); - this.btnStart.TabIndex = 0; - this.btnStart.Text = "start"; - this.btnStart.Click += new System.EventHandler(this.button1_Click); - // - // txtLog - // - this.txtLog.AcceptsReturn = true; - this.txtLog.AcceptsTab = true; - this.txtLog.Location = new System.Drawing.Point(2, 135); - this.txtLog.Multiline = true; - this.txtLog.Name = "txtLog"; - this.txtLog.ReadOnly = true; - this.txtLog.Size = new System.Drawing.Size(237, 130); - this.txtLog.TabIndex = 1; - this.txtLog.WordWrap = false; - // - // btnStop - // - this.btnStop.Location = new System.Drawing.Point(63, 44); - this.btnStop.Name = "btnStop"; - this.btnStop.Size = new System.Drawing.Size(116, 35); - this.btnStop.TabIndex = 0; - this.btnStop.Text = "stop"; - this.btnStop.Click += new System.EventHandler(this.btnStop_Click); - // - // LargeTimerTest - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.Controls.Add(this.txtLog); - this.Controls.Add(this.btnStop); - this.Controls.Add(this.btnStart); - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "LargeTimerTest"; - this.Text = "Form1"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Button btnStart; - private System.Windows.Forms.TextBox txtLog; - private System.Windows.Forms.Button btnStop; - } -} - diff --git a/OpenNetCF_LargeTimer/LargeTimerTest.cs b/OpenNetCF_LargeTimer/LargeTimerTest.cs deleted file mode 100644 index f9203a5..0000000 --- a/OpenNetCF_LargeTimer/LargeTimerTest.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using CEGETUSERNOTIFICATION; - -namespace OpenNetCF_LargeTimer -{ - public partial class LargeTimerTest : Form - { - OpenNETCF.WindowsCE.LargeIntervalTimer timer; - public LargeTimerTest() - { - InitializeComponent(); - myDict = new Dictionary(); - myDict2 = new Dictionary(); - } - - Dictionary myDict; - Dictionary myDict2; - private void button1_Click(object sender, EventArgs e) - { - addLog("START LargeIntervaleTimer"); - myDict.Clear(); myDict2.Clear(); - timer = new OpenNETCF.WindowsCE.LargeIntervalTimer(); - listUserNotifications(true); - timer.Interval = new TimeSpan(1, 0, 0); - timer.Tick += new EventHandler(timer_Tick); - timer.Enabled = true; - listUserNotifications(false); - } - - void listUserNotifications(bool bBeforeAfter) - { - System.Diagnostics.Debug.WriteLine("-------------------------------------------------"); - addLog("-----------------start list--------------------------------"); - CeUserNotificationsClass cls = new CeUserNotificationsClass(); - CeUserNotificationsClass.EventEntry[] myEvents = cls.eventEntries; - foreach (CeUserNotificationsClass.EventEntry entry in myEvents) - { - System.Diagnostics.Debug.WriteLine("Usernotification: " + entry.sHandle + ": '" + entry.sApp + "', '" + entry.sEvent + "', '" + entry.sStartTime + "'"); - addLog("Usernotification: " + entry.sHandle + ": '" + entry.sApp + "', '" + entry.sEvent + "', '" + entry.sStartTime + "'"); - if (bBeforeAfter) - myDict.Add(entry.sHandle, entry.sApp); - else - myDict2.Add(entry.sHandle, entry.sApp); - } - if (!bBeforeAfter) - { - for(int i=0; i sKeyPair = myDict2.ElementAt(i); - if (!myDict.ContainsKey(sKeyPair.Key)) - { - System.Diagnostics.Debug.WriteLine("New entry: " + sKeyPair); - addLog("++++++++++++++++++++\r\nNew entry: " + sKeyPair.Key + ", " + sKeyPair.Value + "\r\n++++++++++++++++++++"); - } - } - } - addLog("----------------end list---------------------------------"); - } - - void timer_Tick(object sender, EventArgs e) - { - - } - delegate void SetTextCallback(string text); - public void addLog(string text) - { - // InvokeRequired required compares the thread ID of the - // calling thread to the thread ID of the creating thread. - // If these threads are different, it returns true. - if (this.txtLog.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(addLog); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtLog.Text.Length > 2000) - txtLog.Text = ""; - txtLog.Text += text + "\r\n"; - txtLog.SelectionLength = 0; - txtLog.SelectionStart = txtLog.Text.Length - 1; - txtLog.ScrollToCaret(); - } - } - - private void btnStop_Click(object sender, EventArgs e) - { - addLog("STOP LargeIntervaleTimer"); - if (timer != null) - { - timer.Tick -= timer_Tick; - timer.Dispose(); - timer = null; - } - myDict2.Clear(); - listUserNotifications(false); - } - } -} \ No newline at end of file diff --git a/OpenNetCF_LargeTimer/LargeTimerTest.resx b/OpenNetCF_LargeTimer/LargeTimerTest.resx deleted file mode 100644 index 1e86201..0000000 --- a/OpenNetCF_LargeTimer/LargeTimerTest.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC_Phone - - - True - - \ No newline at end of file diff --git a/OpenNetCF_LargeTimer/OpenNetCF_LargeTimer.csproj b/OpenNetCF_LargeTimer/OpenNetCF_LargeTimer.csproj deleted file mode 100644 index fa38c5d..0000000 --- a/OpenNetCF_LargeTimer/OpenNetCF_LargeTimer.csproj +++ /dev/null @@ -1,107 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {3390D4A0-5ABC-482E-B924-0AF40E92F39C} - WinExe - Properties - OpenNetCF_LargeTimer - OpenNetCF_LargeTimer - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 2AC76CE7-3E8C-402d-85E7-AE9C98D7B6BA - 5.02 - OpenNetCF_LargeTimer - v3.5 - Windows Mobile 6.5.3 Professional DTK - - - Svn - Svn - Svn - SubversionScc - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - False - C:\Program Files\OpenNetCF23\OpenNETCF.WindowsCE.dll - - - - - - - - - - - - - - - Form - - - LargeTimerTest.cs - - - - - LargeTimerTest.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - - - \ No newline at end of file diff --git a/OpenNetCF_LargeTimer/Program.cs b/OpenNetCF_LargeTimer/Program.cs deleted file mode 100644 index 56038e4..0000000 --- a/OpenNetCF_LargeTimer/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using System.Windows.Forms; - -namespace OpenNetCF_LargeTimer -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new LargeTimerTest()); - } - } -} \ No newline at end of file diff --git a/OpenNetCF_LargeTimer/Properties/AssemblyInfo.cs b/OpenNetCF_LargeTimer/Properties/AssemblyInfo.cs deleted file mode 100644 index 4274684..0000000 --- a/OpenNetCF_LargeTimer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("OpenNetCF_LargeTimer")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("OpenNetCF_LargeTimer")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("a396ce5c-3596-4fdd-ae47-2acd7222daaf")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/OpenNetCF_LargeTimer/Properties/Resources.Designer.cs b/OpenNetCF_LargeTimer/Properties/Resources.Designer.cs deleted file mode 100644 index ed10902..0000000 --- a/OpenNetCF_LargeTimer/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5466 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace OpenNetCF_LargeTimer.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("OpenNetCF_LargeTimer.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/OpenNetCF_LargeTimer/Properties/Resources.resx b/OpenNetCF_LargeTimer/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/OpenNetCF_LargeTimer/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/OpenNetCF_LargeTimer/SystemTime.cs b/OpenNetCF_LargeTimer/SystemTime.cs deleted file mode 100644 index 6dad83b..0000000 --- a/OpenNetCF_LargeTimer/SystemTime.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; - -namespace CEGETUSERNOTIFICATION -{ - [StructLayout(LayoutKind.Sequential)] - public class SYSTEMTIME - { - public ushort wYear; - public ushort wMonth; - public ushort wDayOfWeek; - public ushort wDay; - public ushort wHour; - public ushort wMinute; - public ushort wSecond; - public ushort wMilliseconds; - - public SYSTEMTIME(DateTime dtDateTime) - { - this.wYear = (ushort)dtDateTime.Year; - this.wMonth = (ushort)dtDateTime.Month; - this.wDayOfWeek = (ushort)dtDateTime.DayOfWeek; - this.wDay = (ushort)dtDateTime.Day; - this.wHour = (ushort)dtDateTime.Hour; - this.wMinute = (ushort)dtDateTime.Minute; - this.wSecond = (ushort)dtDateTime.Second; - this.wMilliseconds = 0; - } - public SYSTEMTIME(byte[] buf, int idx) - { - wYear = BitConverter.ToUInt16(buf, idx); idx += 2; - wMonth = BitConverter.ToUInt16(buf, idx); idx += 2; - wDayOfWeek = BitConverter.ToUInt16(buf, idx); idx += 2; - wDay = BitConverter.ToUInt16(buf, idx); idx += 2; - wHour = BitConverter.ToUInt16(buf, idx); idx += 2; - wMinute = BitConverter.ToUInt16(buf, idx); idx += 2; - wSecond = BitConverter.ToUInt16(buf, idx); idx += 2; - wMilliseconds = BitConverter.ToUInt16(buf, idx); idx += 2; - } - public static DateTime GetAsDateTime(SYSTEMTIME st) - { - return new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); - } - - public static DateTime dtLocalDateTime - { - get{ - SYSTEMTIME sysTime = new SYSTEMTIME(DateTime.Now); - GetLocalTime(sysTime); - DateTime dtLocalTime = GetAsDateTime(sysTime); - return dtLocalDateTime; - } - } - [DllImport("coredll.dll")] - public static extern void GetLocalTime(SYSTEMTIME sysTime); - } - -} diff --git a/OpenNetCF_LargeTimer/WinCE.cs b/OpenNetCF_LargeTimer/WinCE.cs deleted file mode 100644 index 4841f52..0000000 --- a/OpenNetCF_LargeTimer/WinCE.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -namespace WinCE -{ - class WinCE - { - public static int findEndOfString(byte[] buf, int idx, int iSize) - { - int iRet = -1; - int iStart = idx; - int iEnd = iSize; - int iPos=idx; - //search for two zero bytes in sequence - do - { - if (buf[iPos] == 0 && buf[iPos + 1] == 0) - iRet = iPos+1; - iPos++; - } while (iPos < iSize-1 && iRet!=-1); - return iRet; - } - } -} diff --git a/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.Configuration.dll b/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.Configuration.dll deleted file mode 100644 index 51b7474..0000000 Binary files a/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.Configuration.dll and /dev/null differ diff --git a/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.WindowsCE.Messaging.dll b/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.WindowsCE.Messaging.dll deleted file mode 100644 index cf645fd..0000000 Binary files a/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.WindowsCE.Messaging.dll and /dev/null differ diff --git a/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.WindowsCE.dll b/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.WindowsCE.dll deleted file mode 100644 index ca9b9e9..0000000 Binary files a/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.WindowsCE.dll and /dev/null differ diff --git a/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.dll b/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.dll deleted file mode 100644 index bf77906..0000000 Binary files a/OpenNetCF_LargeTimer/bin/Debug/OpenNETCF.dll and /dev/null differ diff --git a/OpenNetCF_LargeTimer/bin/Debug/OpenNetCF_LargeTimer.exe b/OpenNetCF_LargeTimer/bin/Debug/OpenNetCF_LargeTimer.exe deleted file mode 100644 index fc24dd9..0000000 Binary files a/OpenNetCF_LargeTimer/bin/Debug/OpenNetCF_LargeTimer.exe and /dev/null differ diff --git a/PingAlert/Form1.Designer.cs b/PingAlert/Form1.Designer.cs deleted file mode 100644 index fe6c52a..0000000 --- a/PingAlert/Form1.Designer.cs +++ /dev/null @@ -1,219 +0,0 @@ -namespace PingAlert -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.mnuOptions = new System.Windows.Forms.MenuItem(); - this.listBox1 = new System.Windows.Forms.ListBox(); - this.txtLog = new System.Windows.Forms.TextBox(); - this.btnPingAll = new System.Windows.Forms.Button(); - this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); - this.btnSchedule = new System.Windows.Forms.Button(); - this.label1 = new System.Windows.Forms.Label(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.label2 = new System.Windows.Forms.Label(); - this.btnAdd = new System.Windows.Forms.Button(); - this.btnRemove = new System.Windows.Forms.Button(); - this.chkLog2File = new System.Windows.Forms.CheckBox(); - this.btnClearSchedule = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuExit); - this.mainMenu1.MenuItems.Add(this.mnuOptions); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // mnuOptions - // - this.mnuOptions.Text = "Options"; - // - // listBox1 - // - this.listBox1.Location = new System.Drawing.Point(3, 31); - this.listBox1.Name = "listBox1"; - this.listBox1.Size = new System.Drawing.Size(167, 72); - this.listBox1.TabIndex = 0; - // - // txtLog - // - this.txtLog.AcceptsReturn = true; - this.txtLog.AcceptsTab = true; - this.txtLog.Location = new System.Drawing.Point(3, 191); - this.txtLog.Multiline = true; - this.txtLog.Name = "txtLog"; - this.txtLog.ReadOnly = true; - this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtLog.Size = new System.Drawing.Size(231, 74); - this.txtLog.TabIndex = 1; - this.txtLog.WordWrap = false; - // - // btnPingAll - // - this.btnPingAll.Location = new System.Drawing.Point(5, 109); - this.btnPingAll.Name = "btnPingAll"; - this.btnPingAll.Size = new System.Drawing.Size(92, 21); - this.btnPingAll.TabIndex = 2; - this.btnPingAll.Text = "Ping all"; - this.btnPingAll.Click += new System.EventHandler(this.btnPingAll_Click); - // - // numericUpDown1 - // - this.numericUpDown1.Increment = new decimal(new int[] { - 15, - 0, - 0, - 0}); - this.numericUpDown1.Location = new System.Drawing.Point(86, 139); - this.numericUpDown1.Maximum = new decimal(new int[] { - 600, - 0, - 0, - 0}); - this.numericUpDown1.Name = "numericUpDown1"; - this.numericUpDown1.Size = new System.Drawing.Size(50, 22); - this.numericUpDown1.TabIndex = 3; - // - // btnSchedule - // - this.btnSchedule.Location = new System.Drawing.Point(142, 139); - this.btnSchedule.Name = "btnSchedule"; - this.btnSchedule.Size = new System.Drawing.Size(92, 21); - this.btnSchedule.TabIndex = 2; - this.btnSchedule.Text = "Schedule"; - this.btnSchedule.Click += new System.EventHandler(this.btnSchedule_Click); - // - // label1 - // - this.label1.Location = new System.Drawing.Point(5, 139); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(75, 16); - this.label1.Text = "Interval:"; - // - // textBox1 - // - this.textBox1.Location = new System.Drawing.Point(82, 4); - this.textBox1.Name = "textBox1"; - this.textBox1.Size = new System.Drawing.Size(152, 21); - this.textBox1.TabIndex = 5; - // - // label2 - // - this.label2.Location = new System.Drawing.Point(5, 4); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(71, 16); - this.label2.Text = "New Host:"; - // - // btnAdd - // - this.btnAdd.Location = new System.Drawing.Point(176, 31); - this.btnAdd.Name = "btnAdd"; - this.btnAdd.Size = new System.Drawing.Size(58, 23); - this.btnAdd.TabIndex = 7; - this.btnAdd.Text = "Add"; - this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); - // - // btnRemove - // - this.btnRemove.Location = new System.Drawing.Point(176, 60); - this.btnRemove.Name = "btnRemove"; - this.btnRemove.Size = new System.Drawing.Size(58, 23); - this.btnRemove.TabIndex = 7; - this.btnRemove.Text = "Remove"; - this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); - // - // chkLog2File - // - this.chkLog2File.Location = new System.Drawing.Point(141, 110); - this.chkLog2File.Name = "chkLog2File"; - this.chkLog2File.Size = new System.Drawing.Size(92, 19); - this.chkLog2File.TabIndex = 8; - this.chkLog2File.Text = "Log to File"; - // - // btnClearSchedule - // - this.btnClearSchedule.Location = new System.Drawing.Point(112, 164); - this.btnClearSchedule.Name = "btnClearSchedule"; - this.btnClearSchedule.Size = new System.Drawing.Size(121, 21); - this.btnClearSchedule.TabIndex = 2; - this.btnClearSchedule.Text = "Clear Schedules"; - this.btnClearSchedule.Click += new System.EventHandler(this.btnClearSchedule_Click); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.chkLog2File); - this.Controls.Add(this.btnRemove); - this.Controls.Add(this.btnAdd); - this.Controls.Add(this.textBox1); - this.Controls.Add(this.label2); - this.Controls.Add(this.label1); - this.Controls.Add(this.numericUpDown1); - this.Controls.Add(this.btnClearSchedule); - this.Controls.Add(this.btnSchedule); - this.Controls.Add(this.btnPingAll); - this.Controls.Add(this.txtLog); - this.Controls.Add(this.listBox1); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "Form1"; - this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.ListBox listBox1; - private System.Windows.Forms.TextBox txtLog; - private System.Windows.Forms.MenuItem mnuExit; - private System.Windows.Forms.MenuItem mnuOptions; - private System.Windows.Forms.Button btnPingAll; - private System.Windows.Forms.NumericUpDown numericUpDown1; - private System.Windows.Forms.Button btnSchedule; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Button btnAdd; - private System.Windows.Forms.Button btnRemove; - private System.Windows.Forms.CheckBox chkLog2File; - private System.Windows.Forms.Button btnClearSchedule; - } -} - diff --git a/PingAlert/Form1.cs b/PingAlert/Form1.cs deleted file mode 100644 index ac1c411..0000000 --- a/PingAlert/Form1.cs +++ /dev/null @@ -1,354 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.Collections; -using Microsoft.WindowsCE.Forms; -using System.Reflection; - -namespace PingAlert -{ - public partial class Form1 : Form - { - //using a public queue for comm - Queue theQueue = new Queue(); - bgThread2 theBGthread; - private int numberOfQueuedData=0; - StringBuilder sbHTML; - const string szHtmlFile = "\\Windows\\PingAlertReport.html"; - private bool bRunAndQuit = false; - private static bool bQuitIsOK = false; - - private System.Windows.Forms.Timer exitTimer1; - - private PingAlertSettings paSettings; - private const string _sLogFile = @"\PingAlert.Log.txt"; - - public Form1(String[] args) - { - InitializeComponent(); - - paSettings = new PingAlertSettings(); - readSettings(); - - //get cmdLine - String myArg=""; - if (args.Length == 1) - { - myArg = args[0]; - if (myArg.Equals("pingsweep", StringComparison.OrdinalIgnoreCase)) - bRunAndQuit = true; - } - - //prepare html string - startHTML(); - - theQueue=new Queue(); - //start the background thread - theBGthread = new bgThread2(theQueue); - theBGthread.bgThread2Event += new bgThread2.bgThread2EventHandler(theBGthread_bgThread2Event); -#if DEBUG - //addIp2Ping("127.0.0.1"); - //addIp2Ping("localhost"); - //addHost2Ping("google.com"); - //addHost2Ping("192.168.128.5"); - //addHost2Ping("smart"); - listBox1.Items.Clear(); - listBox1.Items.Add("google.com"); - listBox1.Items.Add("192.168.128.5"); - listBox1.Items.Add("smart"); -#endif - //timer needed to exit automatically? - if (bRunAndQuit) - { - exitTimer1 = new System.Windows.Forms.Timer(); - exitTimer1.Interval = 2000; - exitTimer1.Tick += new EventHandler(exitTimer1_Tick); - exitTimer1.Enabled = true; - int cnt = listBox1.Items.Count; - for (int i = 0; i < cnt; i++) - { - addHost2Ping(listBox1.Items[i].ToString()); - } - } - } - - private void readSettings() - { - string[] hostlist = paSettings.sHosts; - - if (hostlist!=null && hostlist.Length > 0) - { - listBox1.Items.Clear(); - for (int i = 0; i < hostlist.Length; i++) - { - listBox1.Items.Add(hostlist[i]); - } - } - int x = 0; - x = paSettings.iTimeInterval; - if (x > 0) - numericUpDown1.Value = x; - - x = paSettings.iLog2File; - if (x == 1) - chkLog2File.Checked = true; - else - chkLog2File.Checked = false; - } - private void saveSettings() - { - int cnt = listBox1.Items.Count; - if (cnt > 0) - { - string[] sList = new string[cnt]; - for (int i = 0; i < cnt; i++) - { - sList[i] = (string)listBox1.Items[i]; - } - paSettings.sHosts = sList; - } - int t = (int)numericUpDown1.Value; - if (t > 0) - paSettings.iTimeInterval = t; - - if (chkLog2File.Checked) - paSettings.iLog2File = 1; - else - paSettings.iLog2File = 0; - - //save to reg - paSettings.saveSettings(); - } - - private void exitTimer1_Tick(object sender, EventArgs e) - { - //is it OK to quit now - if(bQuitIsOK){ - exitTimer1.Enabled = false; - this.Close();//exit form - } - } - - private void startHTML() - { - sbHTML = new StringBuilder(); - sbHTML.Append("

PingAlert report

\r\n"); - sbHTML.Append("\r\n"); - } - private void closeHTML() - { - sbHTML.Append("
HostPing result
\r\n"); - } - - void theBGthread_bgThread2Event(object sender, bgThread2.BgThreadEventArgs bte) - { - dbgOut("Host:" + bte.qData.sHost); - try - { - //IP will be NULL if GetHost failed - dbgOut("IP:" + bte.qData.IP.ToString()); - } - catch (Exception) - { - dbgOut("IP:" + "null"); - } - dbgOut("Replies: " + bte.qData.iPingReplies); - dbgOut("Count: " + bte.qData.iPingCount); - dbgOut("ReplyTime: " + bte.qData.iPingReplyTime); - dbgOut("Timeout: " + bte.qData.iPingTimeout); - dbgOut("=================================="); - //n = new Nachricht(); - if (bte.qData.iPingCount != bte.qData.iPingReplies) - { - sbHTML.Append("" + bte.qData.sHost + "failed" + "\r\n"); - dbgOut("Ping for host '" + bte.qData.sHost + "' failed"); - } - else - { - sbHTML.Append("" + bte.qData.sHost + "OK" + "\r\n"); - dbgOut("Ping for host '" + bte.qData.sHost + "' OK"); - } - - //dbgOut("qDataCount=" + bte.qData._iCount.ToString() + " numberOfQueuedData: " + numberOfQueuedData.ToString()); - - if (bte.qData._iCount == numberOfQueuedData) - { - //end html - closeHTML(); - //write report file - //System.IO.TextWriter stringWriter = new System.IO.StringWriter(); - try - { - System.IO.TextWriter streamWriter = new System.IO.StreamWriter(szHtmlFile); - streamWriter.WriteLine(sbHTML); - streamWriter.Flush(); - streamWriter.Close(); - } - catch (Exception x) - { - addLog("Exception in write HTML: " + x.Message); - } - - //start notification - showNotification(); - bQuitIsOK = true; - } - } - - public void showNotification() - { - System.Diagnostics.ProcessStartInfo procInfo = new System.Diagnostics.ProcessStartInfo(@"\Windows\PingAlertToast.exe", ""); - System.Diagnostics.Process proc = new System.Diagnostics.Process(); - proc.StartInfo = procInfo; - if (proc.Start()) - addLog("PingAlertToast started"); - else - addLog("PingAlertToast start failed"); - proc.Close(); - - } - - public int addHost2Ping(string s) - { - int iRet = 0; - queueData theData = new queueData(); - theData.sHost = s; - //theData.sIP=s; - lock (theQueue.SyncRoot)// syncedCollection.SyncRoot) - { - theQueue.Enqueue(theData); - numberOfQueuedData++; - } - return iRet; - } - public void dbgOut(string s) - { - System.Diagnostics.Debug.WriteLine(s); - addLog(s); - } - - delegate void SetTextCallback(string text); - private void addLog(string text) - { - // InvokeRequired required compares the thread ID of the - // calling thread to the thread ID of the creating thread. - // If these threads are different, it returns true. - if (this.txtLog.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(addLog); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtLog.Text.Length > 2000) - txtLog.Text = ""; - txtLog.Text += text + "\r\n"; - txtLog.SelectionLength = text.Length; - txtLog.SelectionStart = txtLog.Text.Length - text.Length; - txtLog.ScrollToCaret(); - if(chkLog2File.Checked) - fileLog(text); - } - } - private void fileLog(string s){ - //cut log file size - System.IO.FileInfo fi = new System.IO.FileInfo(_sLogFile); - if (fi.Exists) - { - if (fi.Length > 1000000) - System.IO.File.Delete(_sLogFile); - } - - System.IO.StreamWriter sw = new System.IO.StreamWriter(_sLogFile, true); - sw.WriteLine(s); - sw.Flush(); - sw.Close(); - } - private void Form1_Closing(object sender, CancelEventArgs e) - { - if(theBGthread!=null) - theBGthread.Dispose(); - } - - private void mnuExit_Click(object sender, EventArgs e) - { - this.saveSettings(); - //first abort the thread!!!!! - if (theBGthread != null) - theBGthread.Dispose(); - System.Threading.Thread.Sleep(1000); - Application.Exit(); - } - - private void btnPingAll_Click(object sender, EventArgs e) - { - if (listBox1.Items.Count == 0) - return; -#if DEBUG - numberOfQueuedData = 0; - //addIp2Ping("127.0.0.1"); - //addIp2Ping("localhost"); - addHost2Ping("google.com"); - addHost2Ping("192.168.128.5"); - addHost2Ping("smart"); - -#endif - startHTML(); - for (int j = 0; j < listBox1.Items.Count; j++) - { - addHost2Ping(listBox1.Items[j].ToString()); - } - numberOfQueuedData = listBox1.Items.Count; - } - - private void btnSchedule_Click(object sender, EventArgs e) - { - //Save current Settings - paSettings.iTimeInterval = (int)numericUpDown1.Value; - paSettings.saveSettings(); - System.Diagnostics.ProcessStartInfo procInfo = new System.Diagnostics.ProcessStartInfo(@"\Windows\PingAlertScheduler.exe", ""); - System.Diagnostics.Process proc = new System.Diagnostics.Process(); - proc.StartInfo = procInfo; - if (proc.Start()) - addLog("PingAlertScheduler started"); - else - addLog("PingAlertScheduler start failed"); - proc.Close(); - } - - private void btnAdd_Click(object sender, EventArgs e) - { - if (textBox1.Text != "") - listBox1.Items.Add(textBox1.Text); - } - - private void btnRemove_Click(object sender, EventArgs e) - { - int d = listBox1.SelectedIndex; - if (d == -1) - return; - if (MessageBox.Show("Remove '" + listBox1.Items[d] + "' from list", "PingAlert Remove Host", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) - { - listBox1.Items.RemoveAt(d); - } - } - - private void btnClearSchedule_Click(object sender, EventArgs e) - { - System.Diagnostics.ProcessStartInfo procInfo = new System.Diagnostics.ProcessStartInfo(@"\Windows\PingAlertScheduler.exe", "clear"); - System.Diagnostics.Process proc = new System.Diagnostics.Process(); - proc.StartInfo = procInfo; - if (proc.Start()) - addLog("PingAlertScheduler start cleared"); - else - addLog("PingAlertScheduler clearing failed"); - proc.Close(); - - } - }//form class -}//namespace \ No newline at end of file diff --git a/PingAlert/Form1.resx b/PingAlert/Form1.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/PingAlert/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/PingAlert/PingAlert.csproj b/PingAlert/PingAlert.csproj deleted file mode 100644 index 21d42da..0000000 --- a/PingAlert/PingAlert.csproj +++ /dev/null @@ -1,108 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {22C42264-8C40-41AF-B512-C15FFF7E5C3E} - WinExe - Properties - PingAlert - PingAlert - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - b2c48bd2-963d-4549-9169-1fa021dce484 - 5.02 - - - v2.0 - Windows Mobile 6 Professional SDK - - - %25CSIDL_WINDOWS%25 - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - Component - - - Form - - - Form1.cs - - - - - - - - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/PingAlert/PingAlert.csproj.user b/PingAlert/PingAlert.csproj.user deleted file mode 100644 index 0622a74..0000000 --- a/PingAlert/PingAlert.csproj.user +++ /dev/null @@ -1,8 +0,0 @@ - - - b2c48bd2-963d-4549-9169-1fa021dce484d6518ffb-710f-11d3-99f2-00105a0df099 - - - pingsweep - - \ No newline at end of file diff --git a/PingAlert/PingAlert.sln b/PingAlert/PingAlert.sln deleted file mode 100644 index 0c5eefa..0000000 --- a/PingAlert/PingAlert.sln +++ /dev/null @@ -1,90 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PingAlert", "PingAlert.csproj", "{22C42264-8C40-41AF-B512-C15FFF7E5C3E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PingAlertToast", "PingAlertToast\PingAlertToast.vcproj", "{2782623A-1220-48BD-B37D-569AC84F4F4D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PingAlertScheduler", "PingAlertScheduler\PingAlertScheduler.vcproj", "{F0A396D5-AFC8-40EE-A375-C03B28EA38B8}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Debug|Windows Mobile 6 Professional SDK (ARMV4I) = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 6 Professional SDK (ARMV4I) = Release|Windows Mobile 6 Professional SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Mixed Platforms.Deploy.0 = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Any CPU.Build.0 = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Any CPU.Deploy.0 = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Mixed Platforms.Deploy.0 = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Any CPU - {22C42264-8C40-41AF-B512-C15FFF7E5C3E}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Any CPU - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Mixed Platforms.Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Mixed Platforms.Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Mixed Platforms.Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Mixed Platforms.Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {2782623A-1220-48BD-B37D-569AC84F4F4D}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Mixed Platforms.Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Mixed Platforms.Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Mixed Platforms.Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Mixed Platforms.Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {F0A396D5-AFC8-40EE-A375-C03B28EA38B8}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/PingAlert/PingAlert.suo b/PingAlert/PingAlert.suo deleted file mode 100644 index e8b23ab..0000000 Binary files a/PingAlert/PingAlert.suo and /dev/null differ diff --git a/PingAlert/PingAlertReport.html b/PingAlert/PingAlertReport.html deleted file mode 100644 index e5a3018..0000000 --- a/PingAlert/PingAlertReport.html +++ /dev/null @@ -1,5 +0,0 @@ - - -Test report. - - diff --git a/PingAlert/PingAlertScheduler/PingAlertScheduler.cpp b/PingAlert/PingAlertScheduler/PingAlertScheduler.cpp deleted file mode 100644 index 7a2a64c..0000000 --- a/PingAlert/PingAlertScheduler/PingAlertScheduler.cpp +++ /dev/null @@ -1,457 +0,0 @@ -// PingAlertScheduler.cpp : Defines the entry point for the console application. -// - -#include "stdafx.h" -#include "Notify.h" -#include "common\nclog.h" - -const __int64 nano100SecInDay=(__int64)10000000*60*60*24; -const __int64 nano10Minutes=(__int64)10000000*60*10; - -TCHAR str[MAX_PATH+1]; - -//name of the external executable to start -TCHAR szExtApp[] = L"\\Windows\\PingAlert.exe"; -TCHAR szExtArg[] = L"pingsweep"; -TCHAR szScheduleArg[] = L"PingAlert"; -int iScheduleInterval = 15; -TCHAR* szSubKey = L"Software\\PingAlert\\"; - -//////////// -//equivalent of DATEADD function from SQLServer -//Returns a new datetime value based on adding an interval -// to the specified date. -////////////*/ -SYSTEMTIME /*new datetime*/ -DT_AddDiff - ( const __int64 datepart, /*datepart with we want to manipulate, - {nano100SecInDay ...}*/ - const __int64 num, /*value used to increment/decrement datepart*/ - const SYSTEMTIME* pst /*valid datetime which we want change*/ - ) -{ - FILETIME ft; - SYSTEMTIME st; - __int64* pi; - - SystemTimeToFileTime (pst,&ft); - pi = (__int64*)&ft; - (*pi) += (__int64)num*datepart; - - /*convert FAILETIME to SYSTEMTIME*/ - FileTimeToSystemTime (&ft,&st); - - /*now, st contain new valid datetime, so return it*/ - return st; -} - -SYSTEMTIME AddDiff(SYSTEMTIME* pst, int minutes){ - FILETIME ft; - SYSTEMTIME st; - __int64* pi; - //LARGE_INTEGER li; - - /*convert SYSTEMTIME to FILETIME*/ - SystemTimeToFileTime (pst,&ft); - - SystemTimeToFileTime (pst,&ft); - - pi = (__int64*)&ft; - (*pi) += (__int64)minutes*(__int64)10000000*60; - - //li.LowPart = ft.dwLowDateTime; - //li.HighPart = ft.dwHighDateTime; - - /*convert FAILETIME to SYSTEMTIME*/ - FileTimeToSystemTime (&ft,&st); - - /*now, st contain new valid datetime, so return it*/ - return st; - -} - -static HRESULT ScheduleRunApp( - LPCTSTR szExeName, - LPCTSTR szArgs) -{ - //do not add a schedule if actual date is 21.3.2003 - SYSTEMTIME t; - memset(&t, 0, sizeof(SYSTEMTIME)); - GetLocalTime(&t); - //check if the system clock is at factory default, device specific! - if ( (t.wYear == 2003) && (t.wMonth == 3) && (t.wDay == 21) ) - { - nclog(L"PingAlertScheduler: # no next run schedule as date is 21.03.2003!\n"); - return NOERROR; - } - - - - HRESULT hr = S_OK; - HANDLE hNotify = NULL; - - // set a CE_NOTIFICATION_TRIGGER - CE_NOTIFICATION_TRIGGER notifTrigger; - memset(¬ifTrigger, 0, sizeof(CE_NOTIFICATION_TRIGGER)); - notifTrigger.dwSize = sizeof(CE_NOTIFICATION_TRIGGER); - - // calculate time - SYSTEMTIME st = {0}; - GetLocalTime(&st); - - /* - st = DT_AddDiff(nano100SecInDay, 1, &st); - st.wHour = 3; - st.wMinute=0; - st.wSecond=33; - */ - st = AddDiff(&st, iScheduleInterval); //wake in x minutes - wsprintf(str, L"Next run at: %02i.%02i.%02i %02i:%02i:%02i\n", - st.wDay, st.wMonth , st.wYear, - st.wHour , st.wMinute , st.wSecond ); - nclog(L"PingAlertScheduler: %s\n", str); - - notifTrigger.dwType = CNT_TIME; - notifTrigger.stStartTime = st; - - // timer: execute an exe at specified time - notifTrigger.lpszApplication = (LPTSTR)szExeName; - notifTrigger.lpszArguments = (LPTSTR)szArgs; - - hNotify = CeSetUserNotificationEx(0, ¬ifTrigger, NULL); - // NULL because we do not care the action - if (!hNotify) { - hr = E_FAIL; - nclog(L"PingAlertScheduler: CeSetUserNotificationEx FAILED...\n"); - } else { - // close the handle as we do not need to use it further - CloseHandle(hNotify); - nclog(L"PingAlertScheduler: CeSetUserNotificationEx succeeded...\n"); - } - return hr; -} - -//for debug use -static HRESULT ListNotiApps() -{ - HRESULT hr = S_OK; - - // hold a notification - PBYTE pBuff = (PBYTE)LocalAlloc(LPTR, 8192); - - if (!pBuff) { - return E_OUTOFMEMORY; - } - - // at most 256 notification handles - HANDLE hNotifHandlers[256]; - DWORD nNumHandlers, nNumClearedHandlers = 0; - DWORD i = 0; - int rc = CeGetUserNotificationHandles(hNotifHandlers, 255, &nNumHandlers); - if (!rc) { - ULONG uErr = GetLastError(); - hr = E_FAIL; - nclog(L"PingAlertScheduler: no more handles? in CeGetUserNotificationHandles()? GetLastError()=%u\n", uErr); - goto FuncExit; - } - - // iterate all notifications - // Notice: We do not care about the status of the notification. - // Just clear it even if it is not filed?? - nclog(L"PingAlertScheduler: ########## ListNotiApps() ############\n"); - for (; ipcent; - - - // Notice some events with NULL lpszApplication might be inserted! - if ( pNotifTrigger && pNotifTrigger->lpszApplication ) - { - nclog(L"PingAlertScheduler: %s\n", pNotifTrigger->lpszApplication); - if (pNotifTrigger->lpszApplication != NULL){ - nclog(L"PingAlertScheduler-ListNotiApps: %s\n", pNotifTrigger->lpszApplication); - } - else - { - nclog(L"PingAlertScheduler: NULL app\n"); - } - nclog(L"\n"); - } - } - - FuncExit: - nclog(L"PingAlertScheduler: ########## END of ListNotiApps()############\n"); - if (pBuff) { - LocalFree(pBuff); - } - - return hr; -} - -//Clear all schedules registered for szExeName -static HRESULT ClearRunApp(LPCTSTR szExeName) -{ - HRESULT hr = S_OK; - - // hold a notification - PBYTE pBuff = (PBYTE)LocalAlloc(LPTR, 8192); - - if (!pBuff) { - return E_OUTOFMEMORY; - } - - TCHAR mExeName[MAX_PATH]; - wsprintf(mExeName, L"%s", szExeName); - - // at most 256 notification handles - HANDLE hNotifHandlers[256]; - DWORD nNumHandlers, nNumClearedHandlers = 0; - DWORD i = 0; - int rc = CeGetUserNotificationHandles(hNotifHandlers, 255, &nNumHandlers); - if (!rc) { - ULONG uErr = GetLastError(); - hr = E_FAIL; - nclog(L"no more handles? in CeGetUserNotificationHandles()? GetLastError()=%u\n", uErr); - goto FuncExit; - } - - // iterate all notifications - // Notice: We do not care about the status of the notification. - // Just clear it even if it is not filed?? - nclog(L"PingAlertScheduler, ClearRunApp(): %s", L"######################\n"); - for (i=0; ipcent; - - //nclog(L"PingAlertScheduler, ClearRunApp(): %s\n", pNotifTrigger->lpszApplication); - - // Notice some events with NULL lpszApplication might be inserted! - if ( pNotifTrigger && pNotifTrigger->lpszApplication ){ - if(pNotifTrigger->lpszApplication != NULL){ - if (wcsicmp(pNotifTrigger->lpszApplication, mExeName)==0) { - nclog(L"PingAlertScheduler, ClearRunApp()-CeClearUserNotification for handle: 0x%0x\n", pnih->hNotification); - CeClearUserNotification(pnih->hNotification); - } - } - } - } - - FuncExit: - nclog(L"##### PingAlertScheduler, ClearRunApp():FuncExit ############\n"); - if (pBuff) { - LocalFree(pBuff); - } - - return hr; -} - -/* -void ClearRunAppAtTime(TCHAR FileName[MAX_PATH+1]) -{ - CeRunAppAtTime(FileName, 0); -} -*/ -int RunAppAtTime(TCHAR FileName[MAX_PATH+1]) -{ - //get actual time - SYSTEMTIME t; - memset(&t, 0, sizeof(SYSTEMTIME)); - GetLocalTime(&t); - - SYSTEMTIME newTime; - //add one day - newTime = DT_AddDiff(nano100SecInDay, 1, &t); - - newTime.wHour = 0; - newTime.wMinute = 59; - newTime.wSecond = 59; - - wsprintf(str, L"Next run at: %02i.%02i.%02i %02i:%02i:%02i", - newTime.wDay, newTime.wMonth , newTime.wYear, - newTime.wHour , newTime.wMinute , newTime.wSecond ); - nclog(L"PingAlertScheduler, RunAppAtTime(): %s", str); - - return CeRunAppAtTime(FileName, &t); - -} - -//read schedule interval from registry -int getTimeInterval(){ - HKEY hKey; - HRESULT hRes;// = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szSubKey, 0, 0, &hKey); - DWORD dwDisposition; // will get REG_CREATED_NEW_KEY if key is new - hRes = RegCreateKeyEx(HKEY_LOCAL_MACHINE, szSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, 0, NULL, &hKey, &dwDisposition); - if(hRes==ERROR_SUCCESS){ - DWORD dwType = REG_DWORD; - DWORD dwVal = 15; - DWORD dwSize = sizeof(DWORD); - if(dwDisposition==REG_CREATED_NEW_KEY){ - //if the key is new, create a new DWORD val fo TimeInterval - hRes = RegSetValueEx(hKey, L"TimeInterval", 0, dwType, (LPBYTE)&dwVal, dwSize); - } - else{ - hRes = RegQueryValueEx(hKey, L"TimeInterval", 0, &dwType, (LPBYTE) &dwVal, &dwSize); - } - if(hRes==ERROR_SUCCESS){ - RegCloseKey(hKey); - return dwVal; - } - RegCloseKey(hKey); - } - return -1; -} - -int _tmain(int argc, _TCHAR* argv[]) -{ - TCHAR lpCmdLine[1024]; //create a buffer large enough to hold cmd args - int x=0; - do{ - if(x>0) - wcscat(lpCmdLine, L" "); //insert blank between args - wcscat(lpCmdLine, argv[x]); - x++; - }while (x - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/PingAlert/PingAlertScheduler/ReadMe.txt b/PingAlert/PingAlertScheduler/ReadMe.txt deleted file mode 100644 index 41b4bc6..0000000 --- a/PingAlert/PingAlertScheduler/ReadMe.txt +++ /dev/null @@ -1,33 +0,0 @@ -======================================================================== - CONSOLE APPLICATION : PingAlertScheduler Project Overview -======================================================================== - -AppWizard has created this PingAlertScheduler application for you. - -This file contains a summary of what you will find in each of the files that -make up your PingAlertScheduler application. - - -PingAlertScheduler.vcproj - This is the main project file for VC++ projects generated using an Application Wizard. - It contains information about the version of Visual C++ that generated the file, and - information about the platforms, configurations, and project features selected with the - Application Wizard. - -PingAlertScheduler.cpp - This is the main application source file. - -///////////////////////////////////////////////////////////////////////////// -Other standard files: - -StdAfx.h, StdAfx.cpp - These files are used to build a precompiled header (PCH) file - named PingAlertScheduler.pch and a precompiled types file named StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Other notes: - -AppWizard uses "TODO:" comments to indicate parts of the source code you -should add to or customize. - -/////////////////////////////////////////////////////////////////////////////s \ No newline at end of file diff --git a/PingAlert/PingAlertScheduler/common/nclog.cpp b/PingAlert/PingAlertScheduler/common/nclog.cpp deleted file mode 100644 index 5d6a47b..0000000 --- a/PingAlert/PingAlertScheduler/common/nclog.cpp +++ /dev/null @@ -1,206 +0,0 @@ -// --- nclog.cpp --- - -//#include "winsock.h" -#include "winsock2.h" -#pragma comment (lib, "ws2.lib") - -#include -#include - -static SOCKET wsa_socket=INVALID_SOCKET; -#pragma comment(lib , "winsock") - -static unsigned short theLogPort; - -//file stuff -//global -static char logFileName[MAX_PATH]; -static TCHAR logFileNameW[MAX_PATH]; -static BOOL bFirstFileCall = true; - -// bind the log socket to a specific port. -static bool wsa_bind(unsigned short port) -{ - SOCKADDR_IN addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = htonl(INADDR_ANY); - int r=bind(wsa_socket,(sockaddr*)&addr,sizeof(addr)); - if (r==0) - theLogPort=port; - return (r==0); -} - -// initialize everything, if the socket isn't open. -static bool wsa_init() -{ - if (wsa_socket != INVALID_SOCKET) return true; - int r; - WSADATA wd; - BOOL bc=true; - - if (0 != WSAStartup(0x101, &wd)) - goto error; - wsa_socket=socket(PF_INET, SOCK_DGRAM, 0); - if (wsa_socket == INVALID_SOCKET) - goto error; - r=setsockopt(wsa_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bc, sizeof(bc)); - if (r!=0) - goto error; - if (wsa_bind(9998)) - return true; // bind to default port. - error: - if (wsa_socket != INVALID_SOCKET) - closesocket(wsa_socket); -#ifdef DEBUG - OutputDebugString(TEXT("nclog: TCP/IP Problem")); -#endif - return false; - -} - -// can be called externally to select a different port for operations -bool set_nclog_port(unsigned short x) { return wsa_bind(x); } - -static void wsa_send(const char *x) -{ - SOCKADDR_IN sa; - sa.sin_family = AF_INET; - sa.sin_port = htons(theLogPort); - sa.sin_addr.s_addr = htonl(INADDR_BROADCAST); - - if (SOCKET_ERROR == sendto(wsa_socket,x,strlen(x), 0, (sockaddr*) &sa, sizeof(sa))) - { -#ifdef DEBUG - //if (debug_mode) - DEBUGMSG(1, (L"nclog: Send Error")); -#endif - } -} - -//========================== start of file stuff ============================= -static int initFileNames() -{ - // Get name of executable - TCHAR lpFileName[MAX_PATH+1]; - GetModuleFileName(NULL, lpFileName, MAX_PATH); //lpFileName will contain the exe name of this running app! - //add txt extension - TCHAR txtFileName[MAX_PATH+1]; - wsprintf(txtFileName, L"%s.log.txt", lpFileName); - //store the filename to use in char and tchar - TCHAR logFileNameW[MAX_PATH]; - wsprintf(logFileNameW, txtFileName); - wcstombs(logFileName, logFileNameW, sizeof(logFileNameW)*sizeof(logFileNameW[0])); - - FILE *fp; - fp = fopen(logFileName, "a+"); - fclose(fp); - bFirstFileCall=false; - return 0; -} - -TCHAR* logDateTime(){ - static TCHAR str[64]; - TCHAR lpTimeStr[32]; - TCHAR lpDateStr[32]; - LONG res; - wsprintf(str,L""); - //Read the system time - res = GetTimeFormat(LOCALE_SYSTEM_DEFAULT, - TIME_FORCE24HOURFORMAT, - NULL, - L"hh:mm:ss", - lpTimeStr, - sizeof (lpTimeStr ) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpTimeStr, L"err"); - } - - //Read the system date - res = GetDateFormat( LOCALE_SYSTEM_DEFAULT, - NULL, - NULL, - L"dd.MM.yyyy", - lpDateStr, - sizeof (lpDateStr) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpDateStr, L"err"); - } - - wsprintf(str, L"Date and Time: %s %s", lpDateStr, lpTimeStr); - return str; -} - -static int writefile(TCHAR *filetext){ - /* File Write Function, written by professor chemicalX */ - FILE *fp; /* Declare FILE structure */ - TCHAR szTemp[255]; - char szTempA[255]; - - wsprintf(szTemp, L"%s", filetext); - wcstombs(szTempA, szTemp, sizeof(szTemp)/sizeof(TCHAR)); - - if (bFirstFileCall){ - // Get name of executable - initFileNames(); - } - - fp = fopen(logFileName, "a+"); - - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - /* First of we open the file supplied by the filename paremeter */ - - /* - * in the "a+" mode for appending, so if it doesnt exist its created. - * fp = fopen(filename,"w"); // Open using the "w" mode for writing. - */ - long fsize = strlen(szTempA); /* Declare the long fsize with the length of the filetext */ - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - /* paremeter witch stores the text or data to right to the file. */ - fwrite(szTempA, 1, fsize, fp); /* Write File */ - fclose(fp); /* Remember to close the file stream after calling file functions, */ - - /* otherwise the file wont be created. */ - return 0; -} -//========================== end of file stuff ============================= - -// format input, convert to 8-bit and send. -void nclog (const wchar_t *fmt, ...) -{ - va_list vl; - va_start(vl,fmt); - wchar_t buf[1024]; // to bad CE hasn't got wvnsprintf - wvsprintf(buf,fmt,vl); - wsa_init(); - char bufOut[512]; - WideCharToMultiByte(CP_ACP,0,buf,-1,bufOut,400, NULL, NULL); - wsa_send(bufOut); - - writefile(buf); -#ifdef DEBUG - DEBUGMSG(1, (buf)); -#else - RETAILMSG(1, (buf)); -#endif -} - -// finalize the socket on program termination. -struct _nclog_module -{ - ~_nclog_module() - { - if (wsa_socket!=INVALID_SOCKET) - { - nclog(L"nclog goes down\n"); - shutdown(wsa_socket,2); - closesocket(wsa_socket); - } - } - -}; - -static _nclog_module module; diff --git a/PingAlert/PingAlertScheduler/common/nclog.h b/PingAlert/PingAlertScheduler/common/nclog.h deleted file mode 100644 index a1d5f06..0000000 --- a/PingAlert/PingAlertScheduler/common/nclog.h +++ /dev/null @@ -1,23 +0,0 @@ -//nclog.h - - -extern void nclog (const wchar_t *fmt, ...); -//extern bool set_nclog_port(unsigned short x) { return wsa_bind(x); } -extern TCHAR* logDateTime(); - -/* -usage: - nclog(L"The Window Handle is: %x\n",hwnd); - -On your desktop, you need netcat to capture the output from your -program, i.e. you open a console and type: - -netcat -lup 9998 - -This will instruct netcat to show you everything that comes to your UDP -socket 9998 (which is the default for netcat). Since nclog opens the -socket in broadcast mode, you don't have to give an target adress. (Be -sure to select a port which does not interfer with the network you are -living in) - -*/ \ No newline at end of file diff --git a/PingAlert/PingAlertScheduler/log2file.h b/PingAlert/PingAlertScheduler/log2file.h deleted file mode 100644 index cf71e85..0000000 --- a/PingAlert/PingAlertScheduler/log2file.h +++ /dev/null @@ -1,175 +0,0 @@ -//log2file.h - -//use #define UseLogging to enable logging -#define UseLogging //to enable logging to file - -//global -char logFileName[MAX_PATH]; -TCHAR logFileNameW[MAX_PATH]; -//bool FirstStart = FALSE; - -void Add2Log(TCHAR); -void Add2Log(LPSTR); -void Add2Log(TCHAR *txt, BOOL bLogTime); -void Add2Log(char *txt, BOOL bLogTime); -void Add2Log (TCHAR *lpszFormat, ...); -void Add2LogWtime (TCHAR *lpszFormat, ...); - -int writefile(LPTSTR); -int newfile(LPSTR); -int newfile(TCHAR); -int appendfile(LPSTR); - -//================================================================================= -//implementation -//================================================================================= -//----------------------------------------------------------------------- -// Add2Log - Add string to the the file -// -void Add2Log (TCHAR *lpszFormat, ...) { - int nBuf;//, i; - TCHAR szBuffer[512]; - - va_list args; - va_start(args, lpszFormat); - - nBuf = vswprintf(szBuffer, lpszFormat, args); - Add2Log(szBuffer, false); - va_end(args); -} -//----------------------------------------------------------------------- -// Add2Log - Add string to the the file -// -void Add2LogWtime (TCHAR *lpszFormat, ...) { - int nBuf;//, i; - TCHAR szBuffer[512]; - - va_list args; - va_start(args, lpszFormat); - - nBuf = vswprintf(szBuffer, lpszFormat, args); - Add2Log(szBuffer, true); - va_end(args); -} -//----------------------------------------------------------------------- -// appendfile - set the global filename to append text -// -int appendfile(char *filename) -{ - //store the filename to use in char and tchar - sprintf(logFileName, filename); - mbstowcs(logFileNameW, logFileName, sizeof(logFileName)*sizeof(logFileName[0])); - - FILE *fp; - fp = fopen(logFileName, "a+"); - fclose(fp); - return 0; -} - -int newfile(char *filename) -{ - //store the filename to use in char and tchar - sprintf(logFileName, filename); - mbstowcs(logFileNameW, logFileName, sizeof(logFileName)*sizeof(logFileName[0])); - - FILE *fp; - fp = fopen(logFileName, "w+"); - fclose(fp); - return 0; -} - -int newfile(TCHAR *filename) -{ - //store the filename to use in char and tchar - TCHAR logFileNameW[MAX_PATH]; - wsprintf(logFileNameW, filename); - wcstombs(logFileName, logFileNameW, sizeof(logFileNameW)*sizeof(logFileNameW[0])); - - FILE *fp; - fp = fopen(logFileName, "w+"); - fclose(fp); - return 0; -} - -int writefile(TCHAR *filetext) -{ -#ifdef UseLogging - /* File Write Function, written by professor chemicalX */ - FILE *fp; /* Declare FILE structure */ - TCHAR szTemp[255]; - char szTempA[255]; - - wsprintf(szTemp, L"%s", filetext); - wcstombs(szTempA, szTemp, sizeof(szTemp)/sizeof(TCHAR)); - - fp = fopen(logFileName, "a+"); - - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - /* First of we open the file supplied by the filename paremeter */ - - /* - * in the "a+" mode for appending, so if it doesnt exist its created. - * fp = fopen(filename,"w"); // Open using the "w" mode for writing. - */ - long fsize = strlen(szTempA); /* Declare the long fsize with the length of the filetext */ - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - /* paremeter witch stores the text or data to right to the file. */ - fwrite(szTempA, 1, fsize, fp); /* Write File */ - fclose(fp); /* Remember to close the file stream after calling file functions, */ - - /* otherwise the file wont be created. */ -#endif - return 0; -} - -void Add2Log(TCHAR *txt, BOOL bLogTime = TRUE) -{ - TCHAR str[512]; - TCHAR lpTimeStr[128]; - TCHAR lpDateStr[128]; - LONG res; - wsprintf(str,L""); - //Read the system time - res = GetTimeFormat(LOCALE_SYSTEM_DEFAULT, - TIME_FORCE24HOURFORMAT, - NULL, - L"hh:mm:ss", - lpTimeStr, - sizeof (lpTimeStr ) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpTimeStr, L"err"); - } - - //Read the system date - res = GetDateFormat( LOCALE_SYSTEM_DEFAULT, - NULL, - NULL, - L"dd.MM.yyyy", - lpDateStr, - sizeof (lpDateStr) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpDateStr, L"err"); - } - - if (bLogTime == TRUE) - wsprintf(str, L"\t%s %s:\n%s", lpDateStr, lpTimeStr , txt); - else - wsprintf(str, L"%s", txt); - writefile(str); - -} - -void Add2Log(char *txt, BOOL bLogTime = TRUE) -{ - TCHAR szTemp[512]; - char szTempA[512]; - wsprintf(szTemp, L""); - sprintf(szTempA, ""); - sprintf(szTempA, "%s", txt); - mbstowcs(szTemp, szTempA, 512);//strlen(szTempA)*sizeof(szTempA[0])); - - Add2Log(szTemp, bLogTime); -} \ No newline at end of file diff --git a/PingAlert/PingAlertScheduler/stdafx.cpp b/PingAlert/PingAlertScheduler/stdafx.cpp deleted file mode 100644 index 45fd402..0000000 --- a/PingAlert/PingAlertScheduler/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// PingAlertScheduler.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/PingAlert/PingAlertScheduler/stdafx.h b/PingAlert/PingAlertScheduler/stdafx.h deleted file mode 100644 index 2c3dc08..0000000 --- a/PingAlert/PingAlertScheduler/stdafx.h +++ /dev/null @@ -1,56 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include - -#include -#pragma comment(lib, "aygshell.lib") - - - -#include -#include - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here diff --git a/PingAlert/PingAlertSettings.cs b/PingAlert/PingAlertSettings.cs deleted file mode 100644 index 18753fa..0000000 --- a/PingAlert/PingAlertSettings.cs +++ /dev/null @@ -1,241 +0,0 @@ -using System; -using Microsoft.Win32; - -using System.Collections.Generic; -using System.Text; -using System.Diagnostics; - -namespace PingAlert -{ - /// - /// settings class to persist settings in registry - /// - class PingAlertSettings:IDisposable - { - // Track whether Dispose has been called. - private bool disposed = false; - - private string[] _sHosts; - public string[] sHosts - { - get { - //_sHosts = regReadStrings(_regValueNameHosts); - return _sHosts; - } - set { - _sHosts = value; - //regWriteStrings(_regValueNameHosts, _sHosts); - } - } - private int _iTimeInterval=15; - public int iTimeInterval - { - get { return _iTimeInterval; } - set { _iTimeInterval = value; } - } - - private int _iLog2File = 0; - public int iLog2File - { - get { return _iLog2File; } - set { _iLog2File = value; } - } - - private const string _regSubKey = @"Software\PingAlert"; - private RegistryKey _regKey; - private const string _regValueNameHosts = "Hosts"; - private const string _regValueNameTimeInterval = "TimeInterval"; - private const string _regValueLog2File = "Log2File"; - - public PingAlertSettings(){ - //try to read settings from Reg - if (regOpenKey()) - { - regReadSettings(); - } - else - this.Dispose(); - } - - public void Dispose(){ - Dispose(true); - GC.SuppressFinalize(this); - } - private void Dispose(bool disposing) - { - // Check to see if Dispose has already been called. - if (!this.disposed) - { - // If disposing equals true, dispose all managed - // and unmanaged resources. - if (disposing) - { - // Dispose managed resources. - //save settings? - regWriteSettings(); - regCloseKey(); - //component.Dispose(); - } - - // Call the appropriate methods to clean up - // unmanaged resources here. - // If disposing is false, - // only the following code is executed. - //CloseHandle(handle); - //handle = IntPtr.Zero; - - // Note disposing has been done. - disposed = true; - - } - } - - private bool regReadSettings() - { - if (_regKey == null) - return false; - - //try to read host list - string[] s = regReadStrings(_regValueNameHosts); - if (s == null) - _sHosts = null; - else - _sHosts = s; - - int i=0; - i=regReadInt(_regValueNameTimeInterval); - if (i != -1) - { - _iTimeInterval = i; - } - else - _iTimeInterval = 15; - - i = regReadInt(_regValueLog2File); - if (i != -1) - { - _iLog2File = i; - } - else - _iLog2File = 0; - - return true; - } - - public int saveSettings() - { - this.regWriteSettings(); - if (_sHosts != null) - return _sHosts.Length; - else - return 0; - } - private bool regWriteSettings() - { - if (_sHosts != null) - { - if (_sHosts.Length > 0) - regWriteStrings(_regValueNameHosts, _sHosts); - } - if (_iTimeInterval > -1) - regWriteInt(_regValueNameTimeInterval, _iTimeInterval); - - if (_iLog2File == 1) - regWriteInt(_regValueLog2File, 1); - else - regWriteInt(_regValueLog2File, 0); - - return true; - } - - private int regReadInt(string sValuename) - { - if (_regKey == null) - return -1; - try - { - int i = (int)_regKey.GetValue(sValuename, -1); - return i; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadInt for '" + _regSubKey + "'/"+sValuename+". " + x.Message); - } - return -1; - } - private bool regWriteInt(string sValuename, int i) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, i); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteInt for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return false; - } - private string[] regReadStrings(string sValuename) - { - if (_regKey == null) - return null; - try - { - string[] s = (string[])_regKey.GetValue(sValuename, ""); - return s; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regReadStrings for '" + _regSubKey + "'/" + sValuename + ". " + x.Message); - } - return null; - } - - private bool regWriteStrings(string sValuename, string[] s) - { - if (_regKey == null) - return false; - try - { - _regKey.SetValue(sValuename, s); - _regKey.Flush(); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in regWriteStrings for '" + _regSubKey + "'. " + x.Message); - return false; - } - } - private bool regOpenKey() - { - try - { - _regKey = Registry.LocalMachine.CreateSubKey(_regSubKey); - return true; - } - catch (Exception x) - { - Debug.WriteLine("Exception in OpenSubKey/CreateSubKey for '" + _regSubKey + "'. " + x.Message); - } - return false; - } - private void regCloseKey() - { - if (_regKey != null) - { - try - { - Registry.LocalMachine.Close(); - } - catch (Exception x) - { - Debug.WriteLine("Exception in CloseKey for '" + _regSubKey + "'. " + x.Message); - } - } - } - } -} diff --git a/PingAlert/PingAlertToast/PingAlertToast.cpp b/PingAlert/PingAlertToast/PingAlertToast.cpp deleted file mode 100644 index af5a8b1..0000000 --- a/PingAlert/PingAlertToast/PingAlertToast.cpp +++ /dev/null @@ -1,429 +0,0 @@ -// PingAlertToast.cpp : Defines the entry point for the application. -// - -#include "stdafx.h" -#include "PingAlertToast.h" - - -#define MAX_LOADSTRING 100 - -// Global Variables: -HINSTANCE g_hInst; // current instance -HWND g_hWndMenuBar; // menu bar handle -SHNOTIFICATIONDATA g_shNotificationData = { 0 }; -HWND g_hWnd=NULL; -const int g_NotificationID=0x57D7; - -// GUID for the app {85EE47B2-57D7-EEFE-8E7A-36480443D062} -static const GUID guidNotifyApp = -{ 0x85ee47b2, 0x57d7, 0xEEFE, { 0x8e, 0x7a, 0x36, 0x48, 0x4, 0x43, 0xd0, 0x62 } }; -UINT g_uiNotifyIDCount = 12540; // id base for notify events -const DWORD g_dwNotificationCmdID1 = WM_USER + 100; -const DWORD g_dwNotificationCmdID2 = g_dwNotificationCmdID1 + 1; - -int showNotification(TCHAR* szText){ - LRESULT lRes=0; - // This code will add an SHNotification notificaion - SHNOTIFICATIONDATA sn = g_shNotificationData; - sn.cbStruct = sizeof(sn); - sn.dwID = g_NotificationID; - sn.npPriority = SHNP_INFORM; - sn.csDuration = -1; - sn.hicon = LoadIcon(g_hInst, MAKEINTRESOURCE(IDI_SAMPLEICON)); - sn.clsid = guidNotifyApp; - sn.grfFlags = 0; - sn.pszTitle = TEXT("PingAlert"); - sn.pszHTML = TEXT("There was at least one error. Please click PingAlert Report for more details."); - sn.rgskn[0].pszTitle = TEXT("Dismiss"); - sn.rgskn[0].skc.wpCmd = g_dwNotificationCmdID1; - sn.rgskn[0].skc.grfFlags = NOTIF_SOFTKEY_FLAGS_STAYOPEN; - sn.rgskn[1].pszTitle = TEXT("Hide"); - sn.rgskn[1].skc.wpCmd = g_dwNotificationCmdID2; - sn.rgskn[1].skc.grfFlags = NOTIF_SOFTKEY_FLAGS_HIDE; - sn.hwndSink=g_hWnd; - //Add the notification to the tray - lRes = SHNotificationAdd(&sn); - - //Put the data from an existing notification into a second SHNOTIFICATIONDATA struct -// SHNotificationUpdate(SHNUM_TITLE | SHNUM_HTML | SHNUM_ICON | SHNUM_SOFTKEYCMDS | SHNUM_SOFTKEYS, &sn2); - //Remove the notification from the tray -/* - SHNotificationRemove(&guidNotifyApp, 1); - //Add a new notification that utilizes the MRE functionality - sn.cbStruct = sizeof(sn); - sn.dwID = 1; - sn.npPriority = SHNP_INFORM; - sn.csDuration = 15; - sn.hicon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_SAMPLEICON)); - sn.clsid = CLSID_SHNAPI_Test; - sn.grfFlags = SHNF_STRAIGHTTOTRAY; - sn.pszTodaySK = TEXT("New Task"); - sn.pszTodayExec = TEXT("\\windows\\tasks.exe"); - //Add the notification to the tray - SHNotificationAdd(&sn); -*/ - return lRes; -} - -void FreeNotificationData(SHNOTIFICATIONDATA * pnd) -{ - //Remove the notification from the tray - LRESULT lRes = SHNotificationRemove(&guidNotifyApp, g_NotificationID); - if(lRes!=ERROR_SUCCESS){ - DEBUGMSG(1,(L"Error in SHNotificationRemove: lRes=%u\r\n", lRes)); - } - - if(pnd!=NULL){ - LocalFree((HLOCAL)pnd->pszHTML); - LocalFree((HLOCAL)pnd->pszTitle); - LocalFree((HLOCAL)pnd->pszTodaySK); - LocalFree((HLOCAL)pnd->pszTodayExec); - if (pnd->grfFlags & SHNF_HASMENU) - { - LocalFree((HLOCAL)pnd->skm.prgskc); - } - else - { - LocalFree((HLOCAL)pnd->rgskn[0].pszTitle); - LocalFree((HLOCAL)pnd->rgskn[1].pszTitle); - } - } -} - -void showHTML(TCHAR* szLink){ - SHELLEXECUTEINFO cShellExecuteInfo = {0}; - cShellExecuteInfo.cbSize = sizeof(SHELLEXECUTEINFO); - cShellExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS; - cShellExecuteInfo.hwnd = NULL; - cShellExecuteInfo.lpVerb = L"Open"; - cShellExecuteInfo.lpFile = szLink; - cShellExecuteInfo.nShow = SW_SHOWNORMAL; - //try to start - BOOL bRes = ShellExecuteEx(&cShellExecuteInfo); - if(!bRes){ - DEBUGMSG(1, (L"ShellExecuteEx failed for %s, %u\r\n", szLink, GetLastError())); - //try with createprocess - PROCESS_INFORMATION pi; - if(CreateProcess(L"\\windows\\iexplore.exe", szLink, NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi)==0){ - DEBUGMSG(1,(L"CreateProcess failed with %u\r\n", GetLastError())); - } - else{ - CloseHandle(pi.hThread); - CloseHandle(pi.hProcess); - } - } -} - -// Forward declarations of functions included in this code module: -ATOM MyRegisterClass(HINSTANCE, LPTSTR); -BOOL InitInstance(HINSTANCE, int); -LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); -INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); - -int WINAPI WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - MSG msg; - - // Perform application initialization: - if (!InitInstance(hInstance, nCmdShow)) - { - return FALSE; - } - - HACCEL hAccelTable; - hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PINGALERTTOAST)); - - // Main message loop: - while (GetMessage(&msg, NULL, 0, 0)) - { - if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - return (int) msg.wParam; -} - -// -// FUNCTION: MyRegisterClass() -// -// PURPOSE: Registers the window class. -// -// COMMENTS: -// -ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass) -{ - WNDCLASS wc; - - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = WndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = hInstance; - wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PINGALERTTOAST)); - wc.hCursor = 0; - wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; - wc.lpszClassName = szWindowClass; - - return RegisterClass(&wc); -} - -// -// FUNCTION: InitInstance(HINSTANCE, int) -// -// PURPOSE: Saves instance handle and creates main window -// -// COMMENTS: -// -// In this function, we save the instance handle in a global variable and -// create and display the main program window. -// -BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) -{ - HWND hWnd; - TCHAR szTitle[MAX_LOADSTRING]; // title bar text - TCHAR szWindowClass[MAX_LOADSTRING]; // main window class name - - g_hInst = hInstance; // Store instance handle in our global variable - - // SHInitExtraControls should be called once during your application's initialization to initialize any - // of the device specific controls such as CAPEDIT and SIPPREF. - SHInitExtraControls(); - - LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); - LoadString(hInstance, IDC_PINGALERTTOAST, szWindowClass, MAX_LOADSTRING); - - //If it is already running, then focus on the window, and exit - hWnd = FindWindow(szWindowClass, szTitle); - if (hWnd) - { - // set focus to foremost child window - // The "| 0x00000001" is used to bring any owned windows to the foreground and - // activate them. - SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001)); - return 0; - } - - if (!MyRegisterClass(hInstance, szWindowClass)) - { - return FALSE; - } - - hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); - - if (!hWnd) - { - return FALSE; - } - - // When the main window is created using CW_USEDEFAULT the height of the menubar (if one - // is created is not taken into account). So we resize the window after creating it - // if a menubar is present - if (g_hWndMenuBar) - { - RECT rc; - RECT rcMenuBar; - - GetWindowRect(hWnd, &rc); - GetWindowRect(g_hWndMenuBar, &rcMenuBar); - rc.bottom -= (rcMenuBar.bottom - rcMenuBar.top); - - MoveWindow(hWnd, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, FALSE); - } - - //ShowWindow(hWnd, nCmdShow); - ShowWindow(hWnd, SW_MINIMIZE); - UpdateWindow(hWnd); - - - return TRUE; -} - -// -// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) -// -// PURPOSE: Processes messages for the main window. -// -// WM_COMMAND - process the application menu -// WM_PAINT - Paint the main window -// WM_DESTROY - post a quit message and return -// -// -LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - int wmId, wmEvent; - PAINTSTRUCT ps; - HDC hdc; - TCHAR* szText = L"TEST PingAlert"; - static SHACTIVATEINFO s_sai; - g_hWnd=hWnd; -/* - typedef struct _NMSHN { - NMHDR hdr; - LPARAM lParam; - DWORD dwReturn; - Union { - LPCTSTR pszLink; - BOOL fTimeout; - POINT pt; - }; - } NMSHN; -*/ - NMSHN* notificationMsg; - NMHDR notificationHdr; - TCHAR szLink[MAX_PATH]; //var to hold link text - - switch (message) - { - case WM_NOTIFY: - DEBUGMSG(1, (L"WM_NOTIFY\r\n")); - if(wParam==g_NotificationID) - { - notificationMsg = (NMSHN*) lParam; - notificationHdr = notificationMsg->hdr; - if(notificationHdr.code == SHNN_LINKSEL){ - //MessageBox(hWnd, L"PingAlert Notification", L"PingAlert Notification", MB_OK); - wsprintf(szLink, L"%s", notificationMsg->pszLink); - showHTML(szLink); - } - //either use WM_COMMAND or SHNotify - /* - if(notificationHdr.code==SHNN_DISMISS) // && notificationMsg->fTimeout==FALSE) - { - PostQuitMessage(2); - } - */ - } - break; - case WM_COMMAND: - DEBUGMSG(1, (L"WM_COMMAND\r\n")); - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - if(wmId==g_dwNotificationCmdID1) - { - DEBUGMSG(1, (L"WM_COMMAND for notification menu Dismiss\r\n")); - FreeNotificationData(&g_shNotificationData); - PostQuitMessage(3); - } - else if(wmId==g_dwNotificationCmdID2) - { - DEBUGMSG(1, (L"WM_COMMAND for notification menu Hide\r\n")); - } - // Parse the menu selections: - switch (wmId) - { - case IDM_HELP_ABOUT: - DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About); - break; - case IDM_OK: - SendMessage (hWnd, WM_CLOSE, 0, 0); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - break; - case WM_CREATE: - DEBUGMSG(1, (L"WM_CREATE\r\n")); - SHMENUBARINFO mbi; - - memset(&mbi, 0, sizeof(SHMENUBARINFO)); - mbi.cbSize = sizeof(SHMENUBARINFO); - mbi.hwndParent = hWnd; - mbi.nToolBarId = IDR_MENU; - mbi.hInstRes = g_hInst; - - if (!SHCreateMenuBar(&mbi)) - { - g_hWndMenuBar = NULL; - } - else - { - g_hWndMenuBar = mbi.hwndMB; - } - - // Initialize the shell activate info structure - memset(&s_sai, 0, sizeof (s_sai)); - s_sai.cbSize = sizeof (s_sai); - - //remove old notification - SHNotificationRemove(&guidNotifyApp, g_NotificationID); - - //show actual notification - showNotification(szText); - - break; - case WM_PAINT: - DEBUGMSG(1, (L"WM_PAINT\r\n")); - hdc = BeginPaint(hWnd, &ps); - - // TODO: Add any drawing code here... - EndPaint(hWnd, &ps); - ShowWindow(hWnd, SW_MINIMIZE); // do not show window - break; - case WM_QUIT: - DEBUGMSG(1, (L"WM_QUIT\r\n")); - FreeNotificationData(&g_shNotificationData); - break; - case WM_DESTROY: - DEBUGMSG(1, (L"WM_DESTROY\r\n")); - CommandBar_Destroy(g_hWndMenuBar); - PostQuitMessage(0); - break; - - case WM_ACTIVATE: - DEBUGMSG(1, (L"WM_ACTIVATE\r\n")); - // Notify shell of our activate message - SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE); - break; - case WM_SETTINGCHANGE: - SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai); - break; - case WM_CLOSE: - DEBUGMSG(1, (L"WM_CLOSE\r\n")); - FreeNotificationData(&g_shNotificationData); - PostQuitMessage(1); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - return 0; -} - -// Message handler for about box. -INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - switch (message) - { - case WM_INITDIALOG: - { - // Create a Done button and size it. - SHINITDLGINFO shidi; - shidi.dwMask = SHIDIM_FLAGS; - shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN | SHIDIF_EMPTYMENU; - shidi.hDlg = hDlg; - SHInitDialog(&shidi); - } - return (INT_PTR)TRUE; - - case WM_COMMAND: - if (LOWORD(wParam) == IDOK) - { - EndDialog(hDlg, LOWORD(wParam)); - return TRUE; - } - break; - - case WM_CLOSE: - EndDialog(hDlg, message); - return TRUE; - - } - return (INT_PTR)FALSE; -} diff --git a/PingAlert/PingAlertToast/PingAlertToast.h b/PingAlert/PingAlertToast/PingAlertToast.h deleted file mode 100644 index d01e90b..0000000 --- a/PingAlert/PingAlertToast/PingAlertToast.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "resourceppc.h" diff --git a/PingAlert/PingAlertToast/PingAlertToast.ico b/PingAlert/PingAlertToast/PingAlertToast.ico deleted file mode 100644 index d551aa3..0000000 Binary files a/PingAlert/PingAlertToast/PingAlertToast.ico and /dev/null differ diff --git a/PingAlert/PingAlertToast/PingAlertToast.vcproj b/PingAlert/PingAlertToast/PingAlertToast.vcproj deleted file mode 100644 index b7aa39d..0000000 --- a/PingAlert/PingAlertToast/PingAlertToast.vcproj +++ /dev/null @@ -1,471 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/PingAlert/PingAlertToast/PingAlertToastppc.aps b/PingAlert/PingAlertToast/PingAlertToastppc.aps deleted file mode 100644 index cf38818..0000000 Binary files a/PingAlert/PingAlertToast/PingAlertToastppc.aps and /dev/null differ diff --git a/PingAlert/PingAlertToast/PingAlertToastppc.rc b/PingAlert/PingAlertToast/PingAlertToastppc.rc deleted file mode 100644 index 7e6bc51..0000000 --- a/PingAlert/PingAlertToast/PingAlertToastppc.rc +++ /dev/null @@ -1,208 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resourceppc.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#define APSTUDIO_HIDDEN_SYMBOLS -#include "windows.h" -#include "resdefce.h" -#undef APSTUDIO_HIDDEN_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// German (Germany) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -#ifdef _WIN32 -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_SAMPLEICON ICON "icon1.ico" -#endif // German (Germany) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_PINGALERTTOAST ICON "PingAlertToast.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDR_MENU MENU -BEGIN - POPUP "Help" - BEGIN - MENUITEM "About", IDM_HELP_ABOUT - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Accelerator -// - -IDC_PINGALERTTOAST ACCELERATORS -BEGIN - "A", IDM_HELP_ABOUT, VIRTKEY, CONTROL, NOINVERT - "Q", IDM_OK, VIRTKEY, CONTROL, NOINVERT -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_ABOUTBOX DIALOG 0, 0, 156, 129 -STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_CAPTION -EXSTYLE 0x80000000L -CAPTION "About PingAlertToast" -FONT 8, "MS Sans Serif" -BEGIN - ICON IDI_PINGALERTTOAST,IDC_STATIC_1,12,12,21,20,SS_REALSIZEIMAGE - LTEXT "PingAlertToast Version 1.0",IDC_STATIC_2,12,36,70,8,SS_NOPREFIX - LTEXT "Copyright (C) 2011",IDC_STATIC_3,12,48,66,8 -END - -IDD_ABOUTBOX_WIDE DIALOG 0, 0, 210, 129 -STYLE DS_SETFONT | WS_POPUP | WS_CAPTION -EXSTYLE 0x80000000L -CAPTION "About PingAlertToast" -FONT 8, "MS Sans Serif" -BEGIN - ICON IDI_PINGALERTTOAST,IDC_STATIC_1,12,12,21,20,SS_REALSIZEIMAGE - LTEXT "PingAlertToast Version 1.0",IDC_STATIC_2,48,12,66,8,SS_NOPREFIX - LTEXT "Copyright (C) 2011",IDC_STATIC_3,48,24,66,8 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_ABOUTBOX, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 149 - TOPMARGIN, 7 - BOTTOMMARGIN, 122 - END - - IDD_ABOUTBOX_WIDE, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 203 - TOPMARGIN, 7 - BOTTOMMARGIN, 122 - END -END -#endif // APSTUDIO_INVOKED - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resourceppc.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#define APSTUDIO_HIDDEN_SYMBOLS\r\n" - "#include ""windows.h""\r\n" - "#include ""resdefce.h""\r\n" - "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" - "LANGUAGE 9, 1\r\n" - "#pragma code_page(1252)\r\n" - "#include ""PingAlertToastppc.rc2"" // non-Microsoft Visual C++ edited resources\r\n" - "#endif\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE -BEGIN - IDS_APP_TITLE "PingAlertToast" - IDC_PINGALERTTOAST "PINGALERTTOAST" -END - -STRINGTABLE -BEGIN - IDS_OK "OK" - IDS_HELP "HELP" -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 -#pragma code_page(1252) -#include "PingAlertToastppc.rc2" // non-Microsoft Visual C++ edited resources -#endif - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/PingAlert/PingAlertToast/PingAlertToastppc.rc2 b/PingAlert/PingAlertToast/PingAlertToastppc.rc2 deleted file mode 100644 index 8a91b91..0000000 --- a/PingAlert/PingAlertToast/PingAlertToastppc.rc2 +++ /dev/null @@ -1,35 +0,0 @@ -// -// PingAlertToastPPC.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED -#error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... - -///////////////////////////////////////////////////////////////////////////// -HI_RES_AWARE CEUX {1} // turn off the emulation layer - // Remove this resource to enable pixel- - // doubling on platforms that support it -///////////////////////////////////////////////////////////////////////////// - -///////////////////////////////////////////////////////////////////////////// -// -// SHMENUBAR -// - -IDR_MENU SHMENUBAR DISCARDABLE -BEGIN - IDR_MENU, - 2, - - I_IMAGENONE, IDM_OK, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE, - IDS_OK, 0, NOMENU, - - I_IMAGENONE, IDM_HELP, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE, - IDS_HELP, 0, 0, -END - diff --git a/PingAlert/PingAlertToast/ReadMe.txt b/PingAlert/PingAlertToast/ReadMe.txt deleted file mode 100644 index 9ffa46d..0000000 --- a/PingAlert/PingAlertToast/ReadMe.txt +++ /dev/null @@ -1,63 +0,0 @@ -======================================================================== - WIN32 APPLICATION : PingAlertToast Project Overview -======================================================================== - -AppWizard has created this PingAlertToast application for you. - -This file contains a summary of what you will find in each of the files that -make up your PingAlertToast application. - - -PingAlertToast.vcproj - This is the main project file for VC++ projects generated using an Application Wizard. - It contains information about the version of Visual C++ that generated the file, and - information about the platforms, configurations, and project features selected with the - Application Wizard. - -PingAlertToast.cpp - This is the main application source file. - -///////////////////////////////////////////////////////////////////////////// -AppWizard has created the following resources: - - -PingAlertToastppc.rc - This is a listing of all of the Microsoft Windows resources that the - program uses when compiling for the Pocket PC 2003 platform, or a platform - that supports the same user interface model. It includes the icons, bitmaps, - and cursors that are stored in the RES subdirectory. This file can be - directly edited in Microsoft Visual C++. When the .rc file is persisted, - the defines in the data section are persisted as the hexadecimal version - of the numeric value they are defined to rather than the friendly name of - the define. - -PingAlertToastppc.rc2 - This file contains resources that are not edited by Microsoft - Visual C++. You should place all resources not editable by - the resource editor in this file. - -Resourceppc.h - This is the standard header file, which defines new resource IDs. - Microsoft Visual C++ reads and updates this file. - - - - -PingAlertToast.ico - This is an icon file, which is used as the application's icon (32x32). - This icon is included by the main resource file PingAlertToast.rc. - -///////////////////////////////////////////////////////////////////////////// -Other standard files: - -StdAfx.h, StdAfx.cpp - These files are used to build a precompiled header (PCH) file - named PingAlertToast.pch and a precompiled types file named StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Other notes: - -AppWizard uses "TODO:" comments to indicate parts of the source code you -should add to or customize. - -/////////////////////////////////////////////////////////////////////////////s \ No newline at end of file diff --git a/PingAlert/PingAlertToast/icon1.ico b/PingAlert/PingAlertToast/icon1.ico deleted file mode 100644 index 56ba259..0000000 Binary files a/PingAlert/PingAlertToast/icon1.ico and /dev/null differ diff --git a/PingAlert/PingAlertToast/resourceppc.h b/PingAlert/PingAlertToast/resourceppc.h deleted file mode 100644 index b7fbf0a..0000000 --- a/PingAlert/PingAlertToast/resourceppc.h +++ /dev/null @@ -1,33 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by PingAlertToastppc.rc -// -#define IDS_APP_TITLE 1 -#define IDC_PINGALERTTOAST 2 -#define IDI_PINGALERTTOAST 101 -#define IDR_MENU 102 -#define IDS_OK 103 -#define IDS_HELP 104 -#define IDD_ABOUTBOX 105 -#define IDD_ABOUTBOX_WIDE 106 -#define IDI_ICON1 129 -#define IDI_SAMPLEICON 129 -#define IDC_STATIC_1 201 -#define IDC_STATIC_2 202 -#define IDC_STATIC_3 203 -#define IDM_OK 40000 -#define IDM_HELP 40001 -#define IDM_HELP_ABOUT 40002 -#define IDC_STATIC -1 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 130 -#define _APS_NEXT_COMMAND_VALUE 32771 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 110 -#endif -#endif diff --git a/PingAlert/PingAlertToast/stdafx.cpp b/PingAlert/PingAlertToast/stdafx.cpp deleted file mode 100644 index f2f7031..0000000 --- a/PingAlert/PingAlertToast/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// PingAlertToast.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/PingAlert/PingAlertToast/stdafx.h b/PingAlert/PingAlertToast/stdafx.h deleted file mode 100644 index 65d8052..0000000 --- a/PingAlert/PingAlertToast/stdafx.h +++ /dev/null @@ -1,62 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include -#include - -#include -#pragma comment(lib, "aygshell.lib") - - -// Windows Header Files: -#include - -// C RunTime Header Files -#include -#include -#include -#include - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here diff --git a/PingAlert/Program.cs b/PingAlert/Program.cs deleted file mode 100644 index 0cd9d9d..0000000 --- a/PingAlert/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace PingAlert -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main(String[] args) - { - Application.Run(new Form1(args)); - } - } -} \ No newline at end of file diff --git a/PingAlert/Properties/AssemblyInfo.cs b/PingAlert/Properties/AssemblyInfo.cs deleted file mode 100644 index c228110..0000000 --- a/PingAlert/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("PingAlert")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("PingAlert")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("65bbd764-4c35-416b-99e8-f4230248f84a")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/PingAlert/Properties/Resources.Designer.cs b/PingAlert/Properties/Resources.Designer.cs deleted file mode 100644 index 5a7e498..0000000 --- a/PingAlert/Properties/Resources.Designer.cs +++ /dev/null @@ -1,67 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.3053 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace PingAlert.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PingAlert.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - internal static System.Drawing.Icon NotificationIcon { - get { - object obj = ResourceManager.GetObject("NotificationIcon", resourceCulture); - return ((System.Drawing.Icon)(obj)); - } - } - } -} diff --git a/PingAlert/Properties/Resources.resx b/PingAlert/Properties/Resources.resx deleted file mode 100644 index 1de51e6..0000000 --- a/PingAlert/Properties/Resources.resx +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - ..\Resources\NotificationIcon.ico;System.Drawing.Icon, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - \ No newline at end of file diff --git a/PingAlert/Resources/NotificationIcon.ico b/PingAlert/Resources/NotificationIcon.ico deleted file mode 100644 index 92c6b8e..0000000 Binary files a/PingAlert/Resources/NotificationIcon.ico and /dev/null differ diff --git a/PingAlert/Resources/notify.ico b/PingAlert/Resources/notify.ico deleted file mode 100644 index 85ac954..0000000 Binary files a/PingAlert/Resources/notify.ico and /dev/null differ diff --git a/PingAlert/UserNotifications.cs b/PingAlert/UserNotifications.cs deleted file mode 100644 index 2c2c47b..0000000 --- a/PingAlert/UserNotifications.cs +++ /dev/null @@ -1,420 +0,0 @@ -using System; -using System.ComponentModel; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Text; - -public class Nachricht:IDisposable -{ - //this.notification1 = new Microsoft.WindowsCE.Forms.Notification(); - - public Nachricht() - { - this.notification1 = new Microsoft.WindowsCE.Forms.Notification(); - } - private Microsoft.WindowsCE.Forms.Notification notification1; - public void Dispose(){ - notification1.Visible = false; - notification1 = null; - notification1.Dispose(); - Dispose(); - } - private void showNotification(string s) - { - StringBuilder HTMLString = new StringBuilder(); - //HTMLString.Append(s); - HTMLString.Append(""); - HTMLString.Append(s); - HTMLString.Append("

Dismiss Alert

"); - HTMLString.Append("
"); - HTMLString.Append(""); - HTMLString.Append(""); - HTMLString.Append(""); - - //Set the Text property to the HTML string. - notification1.Text = HTMLString.ToString(); - - //FileStream IconStream = new FileStream(".\\My Documents\\notify.ico", - // FileMode.Open, FileAccess.Read); - //notification1.Icon = new Icon(IconStream, 16, 16); - notification1.Caption = "PingAlert Notification"; - notification1.Critical = false; - - // Display icon up to 10 seconds. - notification1.InitialDuration = 5; - notification1.Visible = true; - notification1.ResponseSubmitted += new Microsoft.WindowsCE.Forms.ResponseSubmittedEventHandler(notification1_ResponseSubmitted); - } - - void notification1_ResponseSubmitted(object sender, Microsoft.WindowsCE.Forms.ResponseSubmittedEventArgs e) - { - notification1.Visible = false; - notification1 = null; - notification1.Dispose(); - - } - public void NewNotificationMethod(string str) - { - showNotification(str); - } -} - -namespace UserNotifications -{ - public sealed class UserNotifications - { - // Methods for memory allocation and marshalling. - private const uint LMEM_FIXED = 0; - private const uint LMEM_ZEROINIT = 0x0040; - private const uint LPTR = (LMEM_FIXED | LMEM_ZEROINIT); - - private static IntPtr AllocHLocal( int bytes ) - { - return( LocalAlloc(LPTR, (uint)bytes) ); - } - - private static void FreeHLocal( IntPtr hLocal ) - { - if( hLocal != IntPtr.Zero ) - { - if( IntPtr.Zero != LocalFree(hLocal) ) - { - throw new Win32Exception( Marshal.GetLastWin32Error() ); - } - hLocal = IntPtr.Zero; - } - } - - private static IntPtr StringToHLocal( string s ) - { - if( s == null ) - { - return( IntPtr.Zero ); - } - else - { - int nc = s.Length; - int len = 2*(1+nc); - IntPtr hLocal = AllocHLocal( len ); - if( hLocal == IntPtr.Zero ) - { - throw new OutOfMemoryException(); - } - else - { - Marshal.Copy( s.ToCharArray(), 0, hLocal, s.Length ); - return( hLocal ); - } - } - } - - - // Platform invoke declarations and calls - [DllImport("coredll.dll",SetLastError=true)] - private static extern IntPtr LocalAlloc( - uint uFlags, - uint uBytes - ); - - [DllImport("coredll.dll",SetLastError=true)] - private static extern IntPtr LocalFree( - IntPtr hMem - ); - - [DllImport("coredll.dll",SetLastError=true)] - private static extern IntPtr CeSetUserNotificationEx( - IntPtr h, - ref CE_NOTIFICATION_TRIGGER nt, - ref CE_USER_NOTIFICATION un - ); - - [DllImport("coredll.dll",SetLastError=true)] - private static extern IntPtr CeSetUserNotificationEx( - IntPtr h, - ref CE_NOTIFICATION_TRIGGER nt, - IntPtr un - ); - - - [DllImport("coredll.dll",SetLastError=true)] - private static extern void GetSystemTime( - out SYSTEMTIME lpSystemTime - ); - - [DllImport("coredll.dll",SetLastError=true)] - private static extern bool SystemTimeToFileTime( - ref SYSTEMTIME lpSystemTime, - out long lpFileTime - ); - - [DllImport("coredll.dll",SetLastError=true)] - private static extern bool FileTimeToLocalFileTime( - ref long lpFileTime, - out long lpLocalFileTime - ); - - [DllImport("coredll.dll",SetLastError=true)] - private static extern bool FileTimeToSystemTime( - ref long lpFileTime, - out SYSTEMTIME lpSystemTime - ); - - private static SYSTEMTIME DateTimeToSystemTime( DateTime dateTime ) - { - SYSTEMTIME systemTime; - long fileTime = dateTime.ToFileTime(); - FileTimeToLocalFileTime( ref fileTime, out fileTime ); - FileTimeToSystemTime( ref fileTime, out systemTime ); - return( systemTime ); - } - - // Structures. Note that all structures are LayoutKind.Sequential - // on the .NET Compact Framework and there is no need to - // plaform invoke [StructLayout(LayoutKind.Sequential)]. - - private struct SmartString: IDisposable - { - public IntPtr szString; - - public SmartString( string s ) - { - szString = StringToHLocal( s ); - } - - public void Dispose() - { - FreeHLocal( szString ); - } - } - - private struct CE_NOTIFICATION_TRIGGER: IDisposable - { - public uint dwSize; - public CNT_TYPE dwType; - public NOTIFICATION_EVENT dwEvent; - public SmartString lpszApplication; - public SmartString lpszArguments; - public SYSTEMTIME startTime; - public SYSTEMTIME endTime; - - public CE_NOTIFICATION_TRIGGER( string application, string arguments, - DateTime start ) - { - dwSize = (uint)Marshal.SizeOf( typeof(CE_NOTIFICATION_TRIGGER) ); - dwType = CNT_TYPE.CNT_TIME; - dwEvent = NOTIFICATION_EVENT.NONE; - - lpszApplication = new SmartString( application ); - lpszArguments = new SmartString( arguments ); - - startTime = DateTimeToSystemTime( start ); - endTime = new SYSTEMTIME(); - } - - public CE_NOTIFICATION_TRIGGER( DateTime start ) - { - dwSize = (uint)Marshal.SizeOf( typeof(CE_NOTIFICATION_TRIGGER) ); - dwType = CNT_TYPE.CNT_TIME; - dwEvent = NOTIFICATION_EVENT.NONE; - - lpszApplication = new SmartString( null ); - lpszArguments = new SmartString( null ); - - startTime = DateTimeToSystemTime( start ); - endTime = new SYSTEMTIME(); - } - - public CE_NOTIFICATION_TRIGGER( string application, string arguments, - NOTIFICATION_EVENT notificationEvent ) - { - dwSize = (uint)Marshal.SizeOf( typeof(CE_NOTIFICATION_TRIGGER) ); - dwType = CNT_TYPE.CNT_EVENT; - dwEvent = notificationEvent; - - lpszApplication = new SmartString(application); - lpszArguments = new SmartString(arguments); - - startTime = DateTimeToSystemTime( DateTime.Now ); - endTime = new SYSTEMTIME(); - } - - public CE_NOTIFICATION_TRIGGER( NOTIFICATION_EVENT notificationEvent ) - { - dwSize = (uint)Marshal.SizeOf( typeof(CE_NOTIFICATION_TRIGGER) ); - dwType = CNT_TYPE.CNT_EVENT; - dwEvent = notificationEvent; - - lpszApplication = new SmartString( null ); - lpszArguments = new SmartString( null ); - - startTime = DateTimeToSystemTime( DateTime.Now ); - endTime = DateTimeToSystemTime( DateTime.Now.AddDays(1) ); - } - - public void Dispose() - { - lpszApplication.Dispose(); - lpszArguments.Dispose(); - } - } - - public enum ActionFlags - { - PUN_LED = 1, - PUN_VIBRATE = 2, - PUN_DIALOG = 4, - PUN_SOUND = 8, - PUN_REPEAT = 16 - } - - private struct CE_USER_NOTIFICATION: IDisposable - { - public ActionFlags actionFlags; - public SmartString pwszDialogTitle; - public SmartString pwszDialogText; - public SmartString pwszSound; - public uint dwMaxSound; - public uint dwReserved; - - public CE_USER_NOTIFICATION( string title, string text ) - { - actionFlags = ActionFlags.PUN_DIALOG; - pwszDialogTitle = new SmartString( title ); - pwszDialogText = new SmartString( text ); - pwszSound = new SmartString( null ); - dwMaxSound = 0; - dwReserved = 0; - } - - public void Dispose() - { - pwszDialogTitle.Dispose(); - pwszDialogText.Dispose(); - pwszSound.Dispose(); - } - - } - - private enum CNT_TYPE: uint - { - CNT_EVENT = 1, - CNT_TIME = 2, - CNT_PERIOD = 3, - CNT_CLASSICTIME = 4 - } - - public enum NOTIFICATION_EVENT: uint - { - NONE = 0, - TIME_CHANGE = 1, - SYNC_END = 2, - ON_AC_POWER = 3, - OFF_AC_POWER = 4, - NET_CONNECT = 5, - NET_DISCONNECT = 6, - DEVICE_CHANGE = 7, - IR_DISCOVERED = 8, - RS232_DETECTED = 9, - RESTORE_END = 10, - WAKEUP = 11, - TZ_CHANGE = 12 - } - - private struct SYSTEMTIME - { - public ushort Year; - public ushort Month; - public ushort DayOfWeek; - public ushort Day; - public ushort Hour; - public ushort Minute; - public ushort Second ; - public ushort MilliSecond; - } - - - // Methods used by the application. - private static DateTime SystemTimeToDateTime( SYSTEMTIME dateTime ) - { - long lpFileTime; - SystemTimeToFileTime( ref dateTime, out lpFileTime ); - return( DateTime.FromFileTime( lpFileTime ) ); - } - - public static void RunApplication( string application, string arguments, - DateTime start ) - { - CE_NOTIFICATION_TRIGGER nt = - new CE_NOTIFICATION_TRIGGER( application, arguments, start ); - - using( nt ) - { - IntPtr hNotify = CeSetUserNotificationEx( IntPtr.Zero, ref nt, IntPtr.Zero ); - - if( hNotify == IntPtr.Zero ) - { - throw new Win32Exception( Marshal.GetLastWin32Error() ); - } - } - } - - public static void RunApplication( string application, string arguments, - NOTIFICATION_EVENT notificationEvent ) - { - CE_NOTIFICATION_TRIGGER nt = - new CE_NOTIFICATION_TRIGGER( application, arguments, notificationEvent ); - - using( nt ) - { - IntPtr hNotify = CeSetUserNotificationEx( IntPtr.Zero, ref nt, IntPtr.Zero ); - - if( hNotify == IntPtr.Zero ) - { - throw new Win32Exception( Marshal.GetLastWin32Error() ); - } - } - } - - public static void NotifyDialog( string title, string text, DateTime start ) - { - CE_NOTIFICATION_TRIGGER nt = - new CE_NOTIFICATION_TRIGGER( start ); - - CE_USER_NOTIFICATION un = new CE_USER_NOTIFICATION( title, text ); - - using( nt ) - using( un ) - { - IntPtr hNotify = CeSetUserNotificationEx( IntPtr.Zero, ref nt, ref un ); - - if( hNotify == IntPtr.Zero ) - { - throw new Win32Exception( Marshal.GetLastWin32Error() ); - } - } - } - - public static void NotifyDialog( string title, string text, - NOTIFICATION_EVENT notificationEvent ) - { - - CE_NOTIFICATION_TRIGGER nt = - new CE_NOTIFICATION_TRIGGER( notificationEvent ); - - CE_USER_NOTIFICATION un = new CE_USER_NOTIFICATION( title, text ); - - using( nt ) - using( un ) - { - IntPtr hNotify = CeSetUserNotificationEx( IntPtr.Zero, ref nt, ref un ); - - if( hNotify == IntPtr.Zero ) - { - throw new Win32Exception( Marshal.GetLastWin32Error() ); - } - } - } - - } -} - diff --git a/PingAlert/bgThread2.cs b/PingAlert/bgThread2.cs deleted file mode 100644 index 5f667e2..0000000 --- a/PingAlert/bgThread2.cs +++ /dev/null @@ -1,378 +0,0 @@ - -#pragma warning disable 0649 - -using System; -using System.Text; -using System.Windows.Forms; -using Microsoft.WindowsCE.Forms; -using System.ComponentModel; -using System.Threading; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; - - public class bgThread2 : Component - { - /// - /// the bgThread2EventHandler is the protoype of the eventhandler - /// - /// - /// - public delegate void bgThread2EventHandler(object sender, BgThreadEventArgs bte); - /// - /// this event function is the 'link' back to the subscriber of the event handler - /// and will be used to fire the event in the other thread - /// - public event bgThread2EventHandler bgThread2Event; - private Container components; - /// - /// we will run a background thread. this is the thread object we use - /// - private Thread myThread; - /// - /// a var to let the thread stop - /// in reality the thread will be mostly aborted by using thread.Abort() - /// - private bool bRunThread; - /// - /// we will store the derived window handle for communication - /// - internal bgThread2WndProc bgWnd; - - /// - /// we use a user window message ID, not any of the predefined WM_ constants - /// - internal const int msgID = 1025; - internal const int WM_COPYDATA = 0x004A; - #region WM_COPYDATA_code - internal struct COPYDATASTRUCT2 - { - public int dwData; - public int cbData; //size of following data struct - public IntPtr lpData; //pointer to UserData2 - } - - internal struct COPYDATASTRUCT - { - public int dwData; - public int cbData; //size of following string - public IntPtr lpData; //pointer to string - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct UserData - { - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)] - public string msg; - } - - //size=240 + 16 - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct UserData2 - { - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 240)] - public string sIP; - [MarshalAs(UnmanagedType.I4)] - public int iPingCount; - [MarshalAs(UnmanagedType.I4)] - public int iPingReplies; - [MarshalAs(UnmanagedType.I4)] - public int iPingTimeout; - [MarshalAs(UnmanagedType.I4)] - public int iPingReplyTime; - } - #endregion - #region Nested Class - - /// This is the message window we use to communicate back to the thread - /// where the bgThread2 object is created - /// so we avoid cross-threading updates problems especially with the GUI thread - /// - internal class bgThread2WndProc : MessageWindow - { - #region Fields - private bgThread2 _bgThread2; - public IntPtr hwndControl; - #endregion - #region Constructors - public bgThread2WndProc(bgThread2 Parent) - { - System.Diagnostics.Debug.WriteLine("Creating ThreadWnd..."); - this._bgThread2 = Parent; - hwndControl = Hwnd; - System.Diagnostics.Debug.WriteLine("bgThread2WndProc hWnd is 0x: "+hwndControl.ToInt32().ToString("x")); - } - #endregion - #region Methods - protected override void WndProc(ref Message m) - { - int iMsg = m.Msg; - System.Diagnostics.Debug.WriteLine("WndProc called..."); - switch (iMsg) - { - case WM_COPYDATA: - System.Diagnostics.Debug.WriteLine("WndProc sending notification ..."); - // extract the own data from the Windows Message m - //COPYDATASTRUCT data = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT)); - COPYDATASTRUCT2 data = (COPYDATASTRUCT2)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT2)); - //UserData userData = (UserData)Marshal.PtrToStructure(data.lpData, typeof(UserData)); - UserData2 userData = (UserData2)Marshal.PtrToStructure(data.lpData, typeof(UserData2)); - - //this._bgThread2.NotifyData(data.dwData, userData.msg); - this._bgThread2.NotifyData(userData); - m.Result = IntPtr.Zero; - break; - default: - base.WndProc(ref m); - break; - } - } - #endregion //Methods - - }//MsgWnd - #endregion - #region theClass - public bgThread2() - { - bgWnd = new bgThread2WndProc(this); - myThread = new Thread(myThreadStart); - bRunThread = true; - myThread.Start(); - } - private Queue _theQueue = new Queue(); - public bgThread2(Queue aQueue) - { - _theQueue = aQueue; - bgWnd = new bgThread2WndProc(this); - myThread = new Thread(myThreadStart); - bRunThread = true; - myThread.Start(); - } - #region TheTHREAD - private void myThreadStart() - { - queueData _qData = new queueData(); - System.Diagnostics.Debug.WriteLine("Entering thread proc"); - int iPreplies = 0; - int _i=0; - try - { - do - { - //The blocking function... - if (_theQueue.Count > 0) - { - //dequeue one IP to ping - lock (_theQueue.SyncRoot)// syncedCollection.SyncRoot) - { - _qData = (queueData)_theQueue.Dequeue();// get object from queue - } - - //System.Net.IPAddress ip; - try - { - _qData.IP = System.Net.Dns.Resolve(_qData.sHost).AddressList[0]; - iPreplies = myPing.PingQdata(ref _qData); - } - catch (Exception x) { - System.Diagnostics.Debug.WriteLine("bgThread2: Exception in GetHostEntry(): " + x.Message); - //invalid host, unable to get IP - iPreplies = 0; - } - - System.Diagnostics.Debug.WriteLine("Calling into UI thread..."); - //Microsoft.WindowsCE.Forms.Message msg = Message.Create(bgWnd.Hwnd, msgID, new IntPtr(_i), IntPtr.Zero); - int id = _i; //a simple counter - - //_qData.iPingReplies = iReply; - //SendData(bgWnd.Hwnd, id, "ping replies=" + iReply.ToString()); - - //SendData2(bgWnd.Hwnd, id, _qData); - - _i++; - _qData._iCount = _i; //need to know if this is the last queued data - this.NotifyData(_qData); - - System.Diagnostics.Debug.WriteLine("Thread sleeps..."); - } - Thread.Sleep(1000); - } while (bRunThread); - - } - catch (ThreadAbortException) - { - System.Diagnostics.Debug.WriteLine("Thread will abort"); - bRunThread = false; - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in ThreadStart: " + ex.Message); - } - System.Diagnostics.Debug.WriteLine("ThreadProc ended"); - } - #endregion - private void SendData(IntPtr hWnd, int id, string sMsg) - { - COPYDATASTRUCT data = new COPYDATASTRUCT(); - - data.dwData = id;// 3; // whatever value (have to match receiver end) - data.cbData = 512;// size of UserData struct (I have two 200 bytes long ANSI array) - - UserData userData = new UserData(); - if (sMsg.Length > 500) - userData.msg = sMsg.Substring(0, 500); - else - userData.msg = sMsg; - - //copy data to unmanaged pointers - data.lpData = Marshal.AllocCoTaskMem(data.cbData); - Marshal.StructureToPtr( userData, data.lpData, false); - - IntPtr lpData = Marshal.AllocCoTaskMem(Marshal.SizeOf(data)); - Marshal.StructureToPtr(data, lpData, false); - - Message msg1 = Message.Create(hWnd, WM_COPYDATA, lpData, lpData); - MessageWindow.SendMessage(ref msg1); - - Marshal.FreeCoTaskMem(data.lpData); - Marshal.FreeCoTaskMem(lpData); - } - private void SendData2(IntPtr hWnd, int id, queueData qData) - { - COPYDATASTRUCT2 data = new COPYDATASTRUCT2(); - - data.dwData = id;// 3; // whatever value (have to match receiver end) - data.cbData = 256; //System.Runtime.InteropServices.Marshal.SizeOf(UserData2);// size of UserData struct - - UserData2 userData = new UserData2(); - if (qData.sIP.Length > 240) - { - qData.sIP = qData.sIP.Substring(0, 240); - } - - userData.sIP = qData.sIP; - userData.iPingCount = qData.iPingCount; - userData.iPingReplies = qData.iPingReplies; - userData.iPingReplyTime = qData.iPingReplyTime; - userData.iPingTimeout = qData.iPingTimeout; - - //copy data to unmanaged pointers - data.lpData = Marshal.AllocCoTaskMem(data.cbData); - Marshal.StructureToPtr( userData, data.lpData, false); - - IntPtr lpData = Marshal.AllocCoTaskMem(Marshal.SizeOf(data)); - Marshal.StructureToPtr(data, lpData, false); - - Message msg1 = Message.Create(hWnd, WM_COPYDATA, lpData, lpData); - MessageWindow.SendMessage(ref msg1); - - Marshal.FreeCoTaskMem(data.lpData); - Marshal.FreeCoTaskMem(lpData); - } - protected override void Dispose (bool disposing) - { - if (disposing) - { - if (this.components != null) - { - this.components.Dispose (); - } - } - this.myThread.Abort(); - base.Dispose (disposing); - } - ~bgThread2() - { - myThread.Abort(); - this.Dispose (false); - } - #region theNotifyHandlers - - private void NotifyData(UserData2 u2Data) - { - BgThreadEventArgs _bgThread2EventArgs; - //is there any subscriber - if (this.bgThread2Event == null) - { - return; - } - try - { - queueData qData = new queueData(); - qData.sIP = u2Data.sIP; - qData.iPingCount = u2Data.iPingCount; - qData.iPingReplies = u2Data.iPingReplies; - qData.iPingReplyTime = u2Data.iPingReplyTime; - qData.iPingTimeout = u2Data.iPingTimeout; - _bgThread2EventArgs = new BgThreadEventArgs(qData); - this.bgThread2Event(this, _bgThread2EventArgs); - } - catch (MissingMethodException) - { - } - } - - private void NotifyData(queueData qData) - { - BgThreadEventArgs _bgThread2EventArgs; - //is there any subscriber - if (this.bgThread2Event == null) - { - return; - } - try - { - _bgThread2EventArgs = new BgThreadEventArgs(qData); - this.bgThread2Event(this, _bgThread2EventArgs); - } - catch (MissingMethodException) - { - } - } - private void NotifyData(int i1, string s) - { - BgThreadEventArgs _bgThread2EventArgs; - //is there any subscriber - if (this.bgThread2Event == null) - { - return; - } - try - { - _bgThread2EventArgs = new BgThreadEventArgs(i1, s); - this.bgThread2Event(this, _bgThread2EventArgs); - } - catch (MissingMethodException) - { - } - } - - #endregion - //============================================================================== - #region EventArgs - /// - /// the GUI eventhandler will get an instance of this EventArgs class - /// the instance is generated inside the bgThread2 class - /// - public class BgThreadEventArgs : EventArgs - { - #region Fields - public int iStatus; - public string sString; - public queueData qData; - #endregion - #region Constructors - public BgThreadEventArgs(int i1, string s) - { - this.iStatus = i1; - this.sString = s; - } - public BgThreadEventArgs(queueData data) - { - this.qData = data; - } - #endregion - } - #endregion - } - #endregion diff --git a/PingAlert/myQueueData.cs b/PingAlert/myQueueData.cs deleted file mode 100644 index 34660b5..0000000 --- a/PingAlert/myQueueData.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - - public class queueData - { - public int _iCount=0; - private string _sHost = ""; - public string sHost - { - get { return _sHost; } - set { _sHost = value; } - } - public System.Net.IPAddress IP;// = System.Net.IPAddress.Parse("127.0.0.1"); - - private string _sIP = "0.0.0.0"; - /// - /// server IP or host name for ping - /// - public string sIP - { - get { return _sIP; } - set { _sIP = value; } - } - private int _iPingCount = 4; - /// - /// how many pings to send - /// - public int iPingCount{ - get { return _iPingCount; } - set { _iPingCount = value; } - } - private int _iPingReplies = 0; - /// - /// number of good ping replies - /// - public int iPingReplies - { - get { return _iPingReplies; } - set { _iPingReplies = value; } - } - private int _iPingTimeout = 255; - /// - /// ICMP TTL, time to live for ping reply, default=255 - /// - public int iPingTimeout - { - get { return _iPingTimeout; } - set { _iPingTimeout = (byte)value; } - } - private int _iPingReplyTime=0; - /// - /// average ping reply time - /// - public int iPingReplyTime - { - get { return _iPingReplyTime; } - set { _iPingReplyTime = value; } - } - public queueData() - { - - } - } diff --git a/PingAlert/notify.ico b/PingAlert/notify.ico deleted file mode 100644 index 0e2ae4e..0000000 Binary files a/PingAlert/notify.ico and /dev/null differ diff --git a/PingAlert/ping.cs b/PingAlert/ping.cs deleted file mode 100644 index d44b9d5..0000000 --- a/PingAlert/ping.cs +++ /dev/null @@ -1,131 +0,0 @@ -//#define USES_EVENT_PUBLISHING -//use the above if you can fix the exception in Form1^, when setting the textbox1.text -//See project properties if there is already a conditional symbol USES_EVENT_PUBLISHING in the -//build settings -using System; -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; -using System.Net; -using System.Windows.Forms; -using System.ComponentModel; - - public static class myPing{ - #region ICMP helper stuff - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - private struct ICMP_OPTIONS - { - public Byte Ttl; - public Byte Tos; - public Byte Flags; - public Byte OptionsSize; - public IntPtr OptionsData; - }; - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - private struct ICMP_ECHO_REPLY - { - public int Address; - public int Status; - public int RoundTripTime; - public Int16 DataSize; - public Int16 Reserved; - public IntPtr DataPtr; - public ICMP_OPTIONS Options; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 250)] - public String Data; - } - - [DllImport("iphlpapi.dll", SetLastError = true)] - private static extern IntPtr IcmpCreateFile(); - [DllImport("iphlpapi.dll", SetLastError = true)] - private static extern bool IcmpCloseHandle(IntPtr handle); - [DllImport("iphlpapi.dll", SetLastError = true)] - private static extern Int32 IcmpSendEcho(IntPtr icmpHandle, Int32 destinationAddress, String requestData, Int32 requestSize, ref ICMP_OPTIONS requestOptions, ref ICMP_ECHO_REPLY replyBuffer, Int32 replySize, Int32 timeout); -#endregion - - public static int Ping(IPAddress IP) - { - IntPtr ICMPHandle; - Int32 iIP; - String sData; - ICMP_OPTIONS oICMPOptions = new ICMP_OPTIONS(); - ICMP_ECHO_REPLY ICMPReply = new ICMP_ECHO_REPLY(); - Int32 iReplies; - - ICMPHandle = IcmpCreateFile(); - iIP = BitConverter.ToInt32(IP.GetAddressBytes(), 0); - sData = "x"; - oICMPOptions.Ttl = 255; - - iReplies = IcmpSendEcho(ICMPHandle, iIP, - sData, sData.Length, ref oICMPOptions, ref ICMPReply, - Marshal.SizeOf(ICMPReply), 30); - - IcmpCloseHandle(ICMPHandle); - return iReplies; - } - public static int PingQdata(ref queueData qData) - { - - IntPtr ICMPHandle; - Int32 iIP; - String sData; - ICMP_OPTIONS oICMPOptions = new ICMP_OPTIONS(); - ICMP_ECHO_REPLY ICMPReply = new ICMP_ECHO_REPLY(); - Int32 iReplies; - - int[] roundTrips= new int[qData.iPingCount]; - - int averageRoundTrip=0; - - //reset ping reply count - qData.iPingReplies = 0; - /* - qData.iPingTimeout = (byte)qData.iPingTimeout; - qData.sIP = IP.ToString(); - qData.IP = IP; - */ - - ICMPHandle = IcmpCreateFile(); - iIP = BitConverter.ToInt32(qData.IP.GetAddressBytes(), 0); - sData = "x"; - - oICMPOptions.Ttl = (byte) qData.iPingTimeout; //time to live - - for(int i=0; i0) - averageRoundTrip = averageRoundTrip / counts; - else - averageRoundTrip = 0; - - qData.iPingReplyTime = averageRoundTrip; - - IcmpCloseHandle(ICMPHandle); - return qData.iPingReplies; - } - } diff --git a/PingAlert/setup/PingAlert.cab b/PingAlert/setup/PingAlert.cab deleted file mode 100644 index a88f88d..0000000 Binary files a/PingAlert/setup/PingAlert.cab and /dev/null differ diff --git a/PingNG/PingNG.sln b/PingNG/PingNG.sln deleted file mode 100644 index de67f14..0000000 --- a/PingNG/PingNG.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PingNG", "PingNG\PingNG.csproj", "{9C9E166F-37FA-451D-BBB2-5099D2EB240E}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9C9E166F-37FA-451D-BBB2-5099D2EB240E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9C9E166F-37FA-451D-BBB2-5099D2EB240E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9C9E166F-37FA-451D-BBB2-5099D2EB240E}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {9C9E166F-37FA-451D-BBB2-5099D2EB240E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9C9E166F-37FA-451D-BBB2-5099D2EB240E}.Release|Any CPU.Build.0 = Release|Any CPU - {9C9E166F-37FA-451D-BBB2-5099D2EB240E}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/PingNG/PingNG/Form1.Designer.cs b/PingNG/PingNG/Form1.Designer.cs deleted file mode 100644 index dd1952d..0000000 --- a/PingNG/PingNG/Form1.Designer.cs +++ /dev/null @@ -1,130 +0,0 @@ -namespace PingNG -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.txtLog = new System.Windows.Forms.TextBox(); - this.panel1 = new System.Windows.Forms.Panel(); - this.lblPingOptions = new System.Windows.Forms.Label(); - this.btnOptions = new System.Windows.Forms.Button(); - this.btnPing = new System.Windows.Forms.Button(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.panel1.SuspendLayout(); - this.SuspendLayout(); - // - // txtLog - // - this.txtLog.AcceptsReturn = true; - this.txtLog.AcceptsTab = true; - this.txtLog.BackColor = System.Drawing.Color.Black; - this.txtLog.Dock = System.Windows.Forms.DockStyle.Bottom; - this.txtLog.Font = new System.Drawing.Font("Courier New", 8F, System.Drawing.FontStyle.Regular); - this.txtLog.ForeColor = System.Drawing.Color.Lime; - this.txtLog.Location = new System.Drawing.Point(0, 95); - this.txtLog.Multiline = true; - this.txtLog.Name = "txtLog"; - this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtLog.Size = new System.Drawing.Size(238, 176); - this.txtLog.TabIndex = 0; - this.txtLog.WordWrap = false; - // - // panel1 - // - this.panel1.Controls.Add(this.lblPingOptions); - this.panel1.Controls.Add(this.btnOptions); - this.panel1.Controls.Add(this.btnPing); - this.panel1.Controls.Add(this.textBox1); - this.panel1.Dock = System.Windows.Forms.DockStyle.Top; - this.panel1.Location = new System.Drawing.Point(0, 0); - this.panel1.Name = "panel1"; - this.panel1.Size = new System.Drawing.Size(238, 84); - // - // lblPingOptions - // - this.lblPingOptions.Location = new System.Drawing.Point(5, 34); - this.lblPingOptions.Name = "lblPingOptions"; - this.lblPingOptions.Size = new System.Drawing.Size(130, 49); - this.lblPingOptions.Text = "label1"; - // - // btnOptions - // - this.btnOptions.Location = new System.Drawing.Point(147, 34); - this.btnOptions.Name = "btnOptions"; - this.btnOptions.Size = new System.Drawing.Size(74, 23); - this.btnOptions.TabIndex = 1; - this.btnOptions.Text = "options"; - this.btnOptions.Click += new System.EventHandler(this.btnOptions_Click); - // - // btnPing - // - this.btnPing.Location = new System.Drawing.Point(147, 5); - this.btnPing.Name = "btnPing"; - this.btnPing.Size = new System.Drawing.Size(74, 23); - this.btnPing.TabIndex = 1; - this.btnPing.Text = "ping"; - this.btnPing.Click += new System.EventHandler(this.btnPing_Click); - // - // textBox1 - // - this.textBox1.Location = new System.Drawing.Point(5, 5); - this.textBox1.Name = "textBox1"; - this.textBox1.Size = new System.Drawing.Size(136, 23); - this.textBox1.TabIndex = 0; - this.textBox1.Text = "google.de"; - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(238, 271); - this.Controls.Add(this.panel1); - this.Controls.Add(this.txtLog); - this.MaximizeBox = false; - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "Form1"; - this.Text = "pingNG"; - this.panel1.ResumeLayout(false); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.TextBox txtLog; - private System.Windows.Forms.Panel panel1; - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.Button btnOptions; - private System.Windows.Forms.Button btnPing; - private System.Windows.Forms.Label lblPingOptions; - } -} - diff --git a/PingNG/PingNG/Form1.cs b/PingNG/PingNG/Form1.cs deleted file mode 100644 index 8df008f..0000000 --- a/PingNG/PingNG/Form1.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using OpenNETCF.Net.NetworkInformation; -using System.Threading; - -namespace PingNG -{ - public partial class Form1 : Form - { - //global - myPing _myPing; - public Form1() - { - InitializeComponent(); - lblPingOptions.Text = myPingOptions.ToString(); - _myPing = new myPing(); - myPing.onReplyEvent += new myPing.ReplyEventHandler(_myPing_onReplyEvent); - //sample usage: _myPing.doPing("192.168.128.5", myPingOptions); - } - - void _myPing_onReplyEvent(object sender, myPing.PingReplyEventArgs args) - { - addLog(args.message); - if(args.replytype==myPing.PingReplyTypes.done) - enableButton(true); - } - - delegate void enableButtonCallback(bool bEnable); - public void enableButton(bool bEnable) - { - if (this.btnPing.InvokeRequired) - { - enableButtonCallback d = new enableButtonCallback(enableButton); - this.Invoke(d, new object[] { bEnable }); - } - else - this.btnPing.Enabled = bEnable; - } - delegate void SetTextCallback(string text); - public void addLog(string text) - { - // InvokeRequired required compares the thread ID of the - // calling thread to the thread ID of the creating thread. - // If these threads are different, it returns true. - if (this.txtLog.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(addLog); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtLog.Text.Length > 20000) - txtLog.Text = ""; - txtLog.Text += text + "\r\n"; - txtLog.SelectionLength = 0; - txtLog.SelectionStart = txtLog.Text.Length - 1; - txtLog.ScrollToCaret(); - } - } - - private void btnPing_Click(object sender, EventArgs e) - { - btnPing.Enabled = false; - _myPing.doPing(textBox1.Text, myPingOptions); - } - - PingOptions myPingOptions = new PingOptions(); - private void btnOptions_Click(object sender, EventArgs e) - { - frmOptions dlg = new frmOptions(ref myPingOptions); - if (dlg.ShowDialog() == DialogResult.OK) - lblPingOptions.Text= myPingOptions.ToString(); - } - } -} \ No newline at end of file diff --git a/PingNG/PingNG/Form1.resx b/PingNG/PingNG/Form1.resx deleted file mode 100644 index a68cf01..0000000 --- a/PingNG/PingNG/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - WEBPAD - - - False - - \ No newline at end of file diff --git a/PingNG/PingNG/IPOptions.cs b/PingNG/PingNG/IPOptions.cs deleted file mode 100644 index bfc5742..0000000 --- a/PingNG/PingNG/IPOptions.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; - -namespace OpenNETCF.Net.NetworkInformation -{ - /// - /// The ip_option_information structure describes the options to be - /// included in the header of an IP packet. The TTL, TOS, and Flags - /// values are carried in specific fields in the header. The OptionsData - /// bytes are carried in the options area following the standard IP header. - /// With the exception of source route options, this data must be in the - /// format to be transmitted on the wire as specified in RFC 791. A source - /// route option should contain the full route - first hop thru final - /// destination - in the route data. The first hop will be pulled out of the - /// data and the option will be reformatted accordingly. Otherwise, the route - /// option should be formatted as specified in RFC 791. - /// - internal struct IPOptions - { - internal IPOptions(PingOptions options) - { - ttl = 0x80; - tos = 0; - optionsSize = 0; - flags = 0; - optionsData = IntPtr.Zero; - - if (options != null) - { - this.ttl = (byte) options.Ttl; - if (options.DontFragment) - { - this.flags = DontFragmentFlag; - } - } - } - - /// - /// Time To Live. - /// - internal byte ttl; - /// - /// Type Of Service. - /// - internal byte tos; - /// - /// IP header flags. - /// - internal byte flags; - /// - /// Size in bytes of options data. - /// - internal byte optionsSize; - internal IntPtr optionsData; - - internal const int DontFragmentFlag = 2; - internal const int IPOptionsSize = 8; - } -} diff --git a/PingNG/PingNG/IPStatus.cs b/PingNG/PingNG/IPStatus.cs deleted file mode 100644 index b611e81..0000000 --- a/PingNG/PingNG/IPStatus.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; - -namespace OpenNETCF.Net.NetworkInformation -{ - /// - /// Reports the status of sending an Internet Control Message Protocol (ICMP) echo message to a computer. - /// - public enum IPStatus - { - BadDestination = 0x2b0a, - BadHeader = 0x2b22, - BadOption = 0x2aff, - BadRoute = 0x2b04, - DestinationHostUnreachable = 0x2afb, - DestinationNetworkUnreachable = 0x2afa, - DestinationPortUnreachable = 0x2afd, - DestinationProhibited = 0x2afc, - DestinationProtocolUnreachable = 0x2afc, - DestinationScopeMismatch = 0x2b25, - DestinationUnreachable = 11040, - HardwareError = 0x2b00, - IcmpError = 0x2b24, - NoResources = 0x2afe, - PacketTooBig = 0x2b01, - ParameterProblem = 0x2b07, - SourceQuench = 0x2b08, - Success = 0, - TimedOut = 11010, - TimeExceeded = 0x2b21, - TtlExpired = 0x2b05, - TtlReassemblyTimeExceeded = 0x2b06, - Unknown = -1, - UnrecognizedNextHeader = 0x2b23 - } -} diff --git a/PingNG/PingNG/IcmpEchoReply.cs b/PingNG/PingNG/IcmpEchoReply.cs deleted file mode 100644 index c9634d6..0000000 --- a/PingNG/PingNG/IcmpEchoReply.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace OpenNETCF.Net.NetworkInformation -{ - internal class IcmpEchoReply - { - internal uint address = 0; - internal uint status = 0; - internal uint roundTripTime = 0; - internal ushort dataSize = 0; - internal ushort reserved = 0; - internal IntPtr data = IntPtr.Zero; - /* IPOptions structure */ - internal byte ttl = 0; - internal byte tos = 0; - internal byte flags = 0; - internal byte optionsSize = 0; - internal IntPtr optionsData = IntPtr.Zero; - } -} diff --git a/PingNG/PingNG/Ping.cs b/PingNG/PingNG/Ping.cs deleted file mode 100644 index 4c8f05a..0000000 --- a/PingNG/PingNG/Ping.cs +++ /dev/null @@ -1,217 +0,0 @@ -using System; -using System.ComponentModel; -using System.Net; -using System.Runtime.InteropServices; -using OpenNETCF.Runtime.InteropServices; - -namespace OpenNETCF.Net.NetworkInformation -{ - /// - /// Allows an application to determine whether a remote computer is accessible over the network. - /// - public class Ping : Component, IDisposable - { - private const int DefaultSendBufferSize = 64; - private byte [] _defaultSendBuffer; - private IntPtr _handlePingV4 = IntPtr.Zero; - private IntPtr _replyBuffer; - private IntPtr _requestBuffer; - private bool _disposed; - - - /// - /// Initializes a new instance of the Ping class. - /// - public Ping() - { - } - - /// - /// Attempts to send an Internet Control Message Protocol (ICMP) echo message. - /// - public PingReply Send(string hostNameOrAddress) - { - return Send(hostNameOrAddress, SendBuffer, 5000, null); - } - - /// - /// Attempts to send an Internet Control Message Protocol (ICMP) echo message. - /// - /// - /// - /// - public PingReply Send(string hostNameOrAddress, int timeout) - { - return Send(hostNameOrAddress, SendBuffer, timeout, (PingOptions) null); - } - - /// - /// Attempts to send an Internet Control Message Protocol (ICMP) echo message. - /// - /// - /// - /// - /// - /// - public PingReply Send(string hostNameOrAddress, byte[] buffer, int timeout, PingOptions options) - { - if ("".CompareTo(hostNameOrAddress) >= 0) - { - throw new ArgumentNullException("hostNameOrAddress"); - } - - IPAddress address; - try - { - address = IPAddress.Parse(hostNameOrAddress); - } - catch - { - try - { - //IPHostEntry entry = Dns.Resolve(hostNameOrAddress); - IPHostEntry entry = Dns.GetHostEntry(hostNameOrAddress); - address = entry.AddressList[0]; - } - catch(Exception e) - { - throw new PingException("Impossible to resolve host or address.", e); - } - } - - return Send(address, buffer, timeout, options); - } - - /// - /// Attempts to send an Internet Control Message Protocol (ICMP) echo message. - /// - /// - /// - /// - /// - /// - public PingReply Send(IPAddress address, byte[] buffer, int timeout, PingOptions options) - { - PingReply reply; - if (buffer == null) - { - throw new ArgumentNullException("buffer"); - } - if (timeout < 0) - { - throw new ArgumentOutOfRangeException("timeout"); - } - if (address == null) - { - throw new ArgumentNullException("address"); - } - if (this._disposed) - { - throw new ObjectDisposedException(base.GetType().FullName); - } - - try - { - reply = InternalSend(address, buffer, timeout, options); - } - catch(Exception e) - { - throw new PingException("Impossible to send a packet.", e); - } - - return reply; - } - - private byte [] SendBuffer - { - get - { - if (_defaultSendBuffer == null) - { - _defaultSendBuffer = new byte[DefaultSendBufferSize]; - for(int i = 1; i < DefaultSendBufferSize; i++) - { - _defaultSendBuffer[i] = (byte)i; - } - } - - return _defaultSendBuffer; - } - } - - - private PingReply InternalSend(IPAddress address, byte [] buffer, int timeout, PingOptions options) - { - if (_handlePingV4 == IntPtr.Zero) _handlePingV4 = IcmpCreateFile(); - if (_replyBuffer == IntPtr.Zero) - { - _replyBuffer = MarshalEx.AllocHLocal(0xffff); - } - - IPOptions ipo = new IPOptions(options); - InitStructure(buffer); - IcmpSendEcho2(_handlePingV4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, (uint)address.Address, _requestBuffer, (ushort)buffer.Length, ref ipo, _replyBuffer, 0xffff, (uint)timeout); - FreeStructure(); - - IcmpEchoReply reply = (IcmpEchoReply)Marshal.PtrToStructure(this._replyBuffer, typeof(IcmpEchoReply)); - return new PingReply(reply); - } - - private void InitStructure(byte[] buffer) - { - _requestBuffer = MarshalEx.AllocHLocal(buffer.Length); - Marshal.Copy(buffer, 0, _requestBuffer, buffer.Length); - } - - private void FreeStructure() - { - if (_requestBuffer != IntPtr.Zero) - { - MarshalEx.FreeHLocal(_requestBuffer); - _requestBuffer = IntPtr.Zero; - } - } - - #region Disposing - protected override void Dispose(bool disposing) - { - if (this._disposed) - { - return; - } - this._disposed = true; - - if (this._replyBuffer != IntPtr.Zero) - { - MarshalEx.FreeHLocal(_replyBuffer); - _replyBuffer = IntPtr.Zero; - } - if (this._handlePingV4 != IntPtr.Zero) - { - IcmpCloseHandle(_handlePingV4); - _handlePingV4 = IntPtr.Zero; - } - } - - void System.IDisposable.Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - ~Ping() - { - Dispose(false); - } - #endregion - - [DllImport("iphlpapi.dll")] - internal static extern uint IcmpSendEcho2(IntPtr icmpHandle, IntPtr Event, IntPtr apcRoutine, IntPtr apcContext, uint ipAddress, IntPtr data, ushort dataSize, ref IPOptions options, IntPtr replyBuffer, uint replySize, uint timeout); - - [DllImport("iphlpapi.dll")] - internal static extern IntPtr IcmpCreateFile(); - - [DllImport("iphlpapi")] - internal static extern bool IcmpCloseHandle(IntPtr handle); - } -} diff --git a/PingNG/PingNG/PingException.cs b/PingNG/PingNG/PingException.cs deleted file mode 100644 index b9a56db..0000000 --- a/PingNG/PingNG/PingException.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; - -namespace OpenNETCF.Net.NetworkInformation -{ - /// - /// The exception that is thrown when a Send method calls a method that throws an exception. - /// - public class PingException : Exception - { - /// - /// Initializes a new instance of the PingException class using the specified message. - /// - /// A String that describes the error. - public PingException(string message) : base(message) - { - } - - /// - /// Initializes a new instance of the PingException class using the specified message and inner exception. - /// - /// A String that describes the error. - /// The exception that causes the current exception. - public PingException(string message, Exception innerException) : base(message, innerException) - { - } - } -} diff --git a/PingNG/PingNG/PingNG.csproj b/PingNG/PingNG/PingNG.csproj deleted file mode 100644 index a34396c..0000000 --- a/PingNG/PingNG/PingNG.csproj +++ /dev/null @@ -1,117 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {9C9E166F-37FA-451D-BBB2-5099D2EB240E} - WinExe - Properties - PingNG - PingNG - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - WindowsCE - E2BECB1F-8C8C-41ba-B736-9BE7D946A398 - 5.0 - PingNG - v2.0 - Windows CE - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - Form - - - Form1.cs - - - Form - - - frmOptions.cs - - - - - - - - Component - - - - - - - - Form1.cs - - - frmOptions.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/PingNG/PingNG/PingOptions.cs b/PingNG/PingNG/PingOptions.cs deleted file mode 100644 index 05da9ce..0000000 --- a/PingNG/PingNG/PingOptions.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; - -namespace OpenNETCF.Net.NetworkInformation -{ - /// - /// Used to control how Ping data packets are transmitted. - /// - public class PingOptions - { - int ttl = 128; - bool dontFragment; - - public int numOfPings = 4; - public int bufferSize = 32; - - int timeout = 1000; - public int TimeOut - { - get { return timeout; } - set { timeout = value; } - } - - /// - /// Gets or sets the number of routing nodes that can forward the Ping data before it is discarded. - /// - public int Ttl - { - set - { - ttl = value; - } - get - { - return ttl; - } - } - - /// - /// Gets or sets a Boolean value that controls fragmentation of the data sent to the remote host. - /// - public bool DontFragment - { - set - { - dontFragment = value; - } - get - { - return dontFragment; - } - } - - /// - /// Initializes a new instance of the PingOptions class. - /// - public PingOptions() - { - } - - internal PingOptions(IcmpEchoReply reply) - { - ttl = reply.ttl; - dontFragment = (reply.flags & IPOptions.DontFragmentFlag) > 0; - } - - /// - /// Initializes a new instance of the PingOptions class and sets the Time to Live and fragmentation values. - /// - /// Specifies the number of times the Ping data packets can be forwarded. - /// True to prevent data sent to the remote host from being fragmented; otherwise, false. - public PingOptions(int ttl, bool dontFragment) - { - if (ttl <= 0) - { - throw new ArgumentOutOfRangeException("ttl"); - } - - this.ttl = ttl; - this.dontFragment = dontFragment; - } - - public PingOptions(int ttl, bool dontFragment, int timeOut) - { - if (ttl <= 0) - { - throw new ArgumentOutOfRangeException("ttl"); - } - - this.ttl = ttl; - this.dontFragment = dontFragment; - this.timeout = timeOut; - } - - public override string ToString() - { - string s = string.Format("ttl={0}, DF={1}, buf={3}, #p={2}, timeout={4}", ttl, dontFragment, numOfPings, bufferSize, timeout); - return s; - } - } -} diff --git a/PingNG/PingNG/PingReply.cs b/PingNG/PingNG/PingReply.cs deleted file mode 100644 index 0c045c8..0000000 --- a/PingNG/PingNG/PingReply.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System.Net; -using System.Runtime.InteropServices; - -namespace OpenNETCF.Net.NetworkInformation -{ - /// - /// Provides information about the status and data resulting from a Send operation. - /// - public class PingReply - { - private IPAddress address; - private byte[] buffer; - private IPStatus ipStatus; - private long rtt; - private PingOptions options; - - /// - /// Gets the options used to transmit the reply to an Internet Control Message Protocol (ICMP) echo request. - /// - public PingOptions Options - { - get - { - return options; - } - } - - /// - /// Gets the address of the host that sends the Internet Control Message Protocol (ICMP) echo reply. - /// - public IPAddress Address - { - get - { - return this.address; - } - } - - /// - /// Gets the buffer of data received in an Internet Control Message Protocol (ICMP) echo reply message. - /// - public byte[] Buffer - { - get - { - return this.buffer; - } - } - - /// - /// Gets the number of milliseconds taken to send an Internet Control Message Protocol (ICMP) echo request and receive the corresponding ICMP echo reply message. - /// - public long RoundTripTime - { - get - { - return this.rtt; - } - } - - /// - /// Gets the status of an attempt to send an Internet Control Message Protocol (ICMP) echo request and receive the corresponding ICMP echo reply message. - /// - public IPStatus Status - { - get - { - return this.ipStatus; - } - set - { - this.ipStatus = value; - } - } - - public int DataSize - { - get; - set; - } - - internal PingReply(IcmpEchoReply reply) - { - address = new IPAddress((long) reply.address); - ipStatus = (IPStatus) reply.status; - options = new PingOptions(reply); - if (this.ipStatus == IPStatus.Success) - { - rtt = reply.roundTripTime; - buffer = new byte[reply.dataSize]; - this.DataSize = reply.dataSize; - Marshal.Copy(reply.data, this.buffer, 0, reply.dataSize); - } - else - { - buffer = new byte[0]; - } - } - } -} diff --git a/PingNG/PingNG/Program.cs b/PingNG/PingNG/Program.cs deleted file mode 100644 index 058bce6..0000000 --- a/PingNG/PingNG/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace PingNG -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/PingNG/PingNG/Properties/AssemblyInfo.cs b/PingNG/PingNG/Properties/AssemblyInfo.cs deleted file mode 100644 index 9013295..0000000 --- a/PingNG/PingNG/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("PingNG")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("PingNG")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("03bd0e70-de73-405b-a19f-292276cc25df")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/PingNG/PingNG/Properties/Resources.Designer.cs b/PingNG/PingNG/Properties/Resources.Designer.cs deleted file mode 100644 index d94d0f2..0000000 --- a/PingNG/PingNG/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5483 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace PingNG.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("PingNG.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/PingNG/PingNG/Properties/Resources.resx b/PingNG/PingNG/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/PingNG/PingNG/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/PingNG/PingNG/Runtime/InteropServices/AdvancedMarshaler.cs b/PingNG/PingNG/Runtime/InteropServices/AdvancedMarshaler.cs deleted file mode 100644 index fd8f0cf..0000000 --- a/PingNG/PingNG/Runtime/InteropServices/AdvancedMarshaler.cs +++ /dev/null @@ -1,571 +0,0 @@ -using System; -using System.IO; -using System.Collections; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Threading; - -namespace OpenNETCF.Runtime.InteropServices -{ - - /// - /// AdvancedMarshaler class implementation. - /// - public abstract class AdvancedMarshaler - { - #region Fields - // The internal buffer - protected byte[] data; - private MemoryStream stream; - private BinaryReader binReader; - private BinaryWriter binWriter; - private int size = 0; - - public int Size - { - get - { - return size; - } - } - - #endregion - - #region constructors - - public AdvancedMarshaler() - { - size = GetSize(); - data = new byte [size]; - } - - #endregion - - #region public methods - - /// - /// Copy bytes from a user array to the internal data array - /// and then call the internal Deserialize routine - /// - /// The byte array to be copied to the - /// internal array and then deserialized - public void DeserializeFromByteArray(byte[] b) - { - int ln = (b.Length < data.Length) ? b.Length : data.Length; - - Array.Copy(b, 0, data, 0, ln); - Deserialize(); - } - - public void Deserialize() - { - if (data != null) - { - if (binReader != null) - { - binReader.Close(); - stream.Close(); - } - // Create a stream from byte array - stream = new MemoryStream(data); - binReader = new BinaryReader(stream, System.Text.Encoding.Unicode); - ReadFromStream(binReader); - binReader.Close(); - } - - } - - public void Serialize() - { - if (data != null) - { - stream = new MemoryStream(data); - binWriter = new BinaryWriter(stream, System.Text.Encoding.Unicode); - WriteToStream(binWriter); - binWriter.Close(); - } - } - - public int GetSize() - { - int size = 0; - - FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance); - - foreach (FieldInfo field in fields ) - { - if (field.FieldType.IsArray) - { - size += GetFieldSize(field); - } - else if (field.FieldType == typeof(string)) - { - size += GetFieldSize(field)*2; - } - else if (field.FieldType.IsPrimitive) - { - size += Marshal.SizeOf(field.FieldType); - } - // This else condition added by JTF, 8/17/04 to handle sizing of structures within structures - else //process substructure - { - AdvancedMarshaler subStruct = (AdvancedMarshaler)Activator.CreateInstance(field.FieldType); - size += subStruct.GetSize(); - } - // End of Modifications - } - - return size; - } - - #endregion - - #region properties - - public byte[] ByteArray - { - get - { - return data; - } - } - - #endregion - - #region virtual and protected methods - - public virtual void ReadFromStream(BinaryReader reader) - { - object[] param = null; - - // Get all public fields - FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance); - - // Loop through the fields - foreach(FieldInfo field in fields) - { - // Retrieve the read method from ReadMethods hashtable - MethodInfo method = (MethodInfo)MarshallingMethods.ReadMethods[field.FieldType]; - - if (field.FieldType.IsArray) - { - Type element = field.FieldType.GetElementType(); - if (element.IsValueType && element.IsPrimitive) - { - if ((element == typeof(char)) || element == typeof(byte)) - { - param = new object[1]; - param[0] = GetFieldSize(field); - field.SetValue(this, method.Invoke(reader, param)); - } - else // any other value type array - { - param = new object[2]; - param[0] = reader; - - int fldSize = 1; - if (element == typeof(int)) - fldSize = 4; - - param[1] = GetFieldSize(field) / fldSize; - - field.SetValue(this, method.Invoke(null, param)); - } - } - else // array of sub structures - { - int size = GetFieldSize(field); - method = (MethodInfo)MarshallingMethods.ReadMethods[typeof(AdvancedMarshaler)]; - Array objArray = Array.CreateInstance(element, size); - for(int i=0;i - /// MarshallingMethods class implementation. - /// - public class MarshallingMethods - { - public static Hashtable ReadMethods = new Hashtable(); - public static Hashtable WriteMethods = new Hashtable(); - - #region constructors - - static MarshallingMethods() - { - // Read Methods - ReadMethods.Add(typeof(bool), typeof(BinaryReader).GetMethod("ReadBoolean")); - ReadMethods.Add(typeof(byte), typeof(BinaryReader).GetMethod("ReadByte")); - ReadMethods.Add(typeof(System.SByte), typeof(BinaryReader).GetMethod("ReadSByte")); - ReadMethods.Add(typeof(System.Single), typeof(BinaryReader).GetMethod("ReadSingle")); - ReadMethods.Add(typeof(byte[]), typeof(BinaryReader).GetMethod("ReadBytes")); - ReadMethods.Add(typeof(char[]), typeof(BinaryReader).GetMethod("ReadChars")); - ReadMethods.Add(typeof(System.Int16), typeof(BinaryReader).GetMethod("ReadInt16")); - ReadMethods.Add(typeof(System.Int32), typeof(BinaryReader).GetMethod("ReadInt32")); - ReadMethods.Add(typeof(System.UInt16), typeof(BinaryReader).GetMethod("ReadUInt16")); - ReadMethods.Add(typeof(System.UInt32), typeof(BinaryReader).GetMethod("ReadUInt32")); - ReadMethods.Add(typeof(System.String), typeof(MarshallingMethods).GetMethod("ReadString")); - ReadMethods.Add(typeof(System.DateTime), typeof(MarshallingMethods).GetMethod("ReadDateTime")); - ReadMethods.Add(typeof(System.Int16[]), typeof(MarshallingMethods).GetMethod("ReadInt16Array")); - ReadMethods.Add(typeof(System.Int32[]), typeof(MarshallingMethods).GetMethod("ReadInt32Array")); - ReadMethods.Add(typeof(System.UInt16[]), typeof(MarshallingMethods).GetMethod("ReadUInt16Array")); - ReadMethods.Add(typeof(System.UInt32[]), typeof(MarshallingMethods).GetMethod("ReadUInt32Array")); - ReadMethods.Add(typeof(AdvancedMarshaler), typeof(AdvancedMarshaler).GetMethod("ReadFromStream")); - //Write Methods - WriteMethods.Add(typeof(bool), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(bool)})); - WriteMethods.Add(typeof(byte), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(byte)})); - WriteMethods.Add(typeof(System.SByte), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.SByte)})); - WriteMethods.Add(typeof(System.Single), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.Single)})); - WriteMethods.Add(typeof(System.Int16), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.Int16)})); - WriteMethods.Add(typeof(System.Int32), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.Int32)})); - WriteMethods.Add(typeof(System.UInt16), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.UInt16)})); - WriteMethods.Add(typeof(System.UInt32), typeof(BinaryWriter).GetMethod("Write", new Type[]{typeof(System.UInt32)})); - WriteMethods.Add(typeof(System.String), typeof(MarshallingMethods).GetMethod("WriteString")); - WriteMethods.Add(typeof(AdvancedMarshaler), typeof(AdvancedMarshaler).GetMethod("WriteToStream")); - - WriteMethods.Add(typeof(System.Byte[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] {typeof(BinaryWriter), typeof(byte[]) })); - WriteMethods.Add(typeof(bool[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(bool[]) })); - // WriteMethods.Add(typeof(byte[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(byte[]) })); - WriteMethods.Add(typeof(char[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(char[]) })); - WriteMethods.Add(typeof(short[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(short[]) })); - WriteMethods.Add(typeof(ushort[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(ushort[]) })); - WriteMethods.Add(typeof(int[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(int[]) })); - WriteMethods.Add(typeof(uint[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(uint[]) })); - WriteMethods.Add(typeof(long[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(long[]) })); - WriteMethods.Add(typeof(ulong[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(ulong[]) })); - WriteMethods.Add(typeof(float[]), typeof(MarshallingMethods).GetMethod("WriteArray", new Type[] { typeof(BinaryWriter), typeof(float[]) })); - } - - #endregion - - #region static helper methods - - public static short[] ReadInt16Array(BinaryReader reader, int count) - { - short[] result = new short[count]; - - for(int i=0;i - /// CustomMarshalAsAttribute implementaion. - /// - public sealed class CustomMarshalAsAttribute : Attribute - { - public int SizeConst = 0; - public string SizeField = null; - public int ArraySize = 0; - } - - #endregion - -} diff --git a/PingNG/PingNG/Runtime/InteropServices/CriticalHandle.cs b/PingNG/PingNG/Runtime/InteropServices/CriticalHandle.cs deleted file mode 100644 index 695aa41..0000000 --- a/PingNG/PingNG/Runtime/InteropServices/CriticalHandle.cs +++ /dev/null @@ -1,135 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Runtime.InteropServices.CriticalHandle -// Copyright (c) 2005, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; - -namespace OpenNETCF.Runtime.InteropServices -{ - /// - /// Represents a wrapper class for handle resources. - /// New in v1.3 - /// - public abstract class CriticalHandle : IDisposable - { - private bool closed; - private bool invalid; - - /// - /// Initializes a new instance of the CriticalHandle class with the specified invalid handle value. - /// - /// The value of an invalid handle (usually 0 or -1). - protected CriticalHandle(IntPtr invalidHandleValue) - { - this.invalid = false; - handle = invalidHandleValue; - this.closed = false; - } - - /// - /// Specifies the handle to be wrapped. - /// - protected IntPtr handle; - - /// - /// Gets a value indicating whether the handle is closed. - /// - /// true if the handle is closed; otherwise, false. - public bool IsClosed - { - get - { - return closed; - } - } - - /// - /// When overridden in a derived class, gets a value indicating whether the handle value is invalid. - /// - /// true if the handle is valid; otherwise, false. - public abstract bool IsInvalid - { - get; - } - - /// - /// Marks the handle for releasing and freeing resources. - /// - public void Close() - { - Dispose(); - } - - /// - /// When overridden in a derived class, executes the code required to free the handle. - /// - /// - protected abstract bool ReleaseHandle(); - - /// - /// Sets the handle to the specified pre-existing handle. - /// - /// - protected void SetHandle(IntPtr handle) - { - this.handle = handle; - } - - /// - /// Marks a handle as invalid. - /// - public void SetHandleAsInvalid() - { - this.invalid = true; - GC.SuppressFinalize(this); - } - - #region IDisposable Members - - protected void Dispose(bool disposing) - { - if(!IsClosed && !IsInvalid) - { - ReleaseHandle(); - } - GC.SuppressFinalize(this); - } - - /// - /// Marks the handle for releasing and freeing resources. - /// - public void Dispose() - { - Dispose(true); - - } - - /// - /// Frees all resources associated with the handle. - /// - ~CriticalHandle() - { - Dispose(false); - } - #endregion - } -} diff --git a/PingNG/PingNG/Runtime/InteropServices/FILETIME.cs b/PingNG/PingNG/Runtime/InteropServices/FILETIME.cs deleted file mode 100644 index 9734495..0000000 --- a/PingNG/PingNG/Runtime/InteropServices/FILETIME.cs +++ /dev/null @@ -1,55 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Runtime.InteropServices.FILETIME -// Copyright (c) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; - -namespace OpenNETCF.Runtime.InteropServices -{ - /// - /// This structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601. - /// New in v1.1 - /// - public struct FILETIME - { - /// - /// Specifies the low 32 bits of the FILETIME. - /// - public int dwLowDateTime; - /// - /// Specifies the high 32 bits of the FILETIME. - /// - public int dwHighDateTime; - - #region ToDateTime - /// - /// Returns the equivalent of this FILETIME value. - /// - /// A which equates this value. - public DateTime ToDateTime() - { - return DateTime.FromFileTimeUtc(((int)dwHighDateTime) << 32 | (int)dwLowDateTime); - } - #endregion - - } -} diff --git a/PingNG/PingNG/Runtime/InteropServices/MarshalEx.cs b/PingNG/PingNG/Runtime/InteropServices/MarshalEx.cs deleted file mode 100644 index 4f0f7c5..0000000 --- a/PingNG/PingNG/Runtime/InteropServices/MarshalEx.cs +++ /dev/null @@ -1,1015 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Runtime.InteropServices.MarshalEx -// Copyright (c) 2003-2005, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Text; -using System.Runtime.InteropServices; - -namespace OpenNETCF.Runtime.InteropServices -{ - /// - /// Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks, and converting managed to unmanaged types, as well as other miscellaneous methods used when interacting with unmanaged code. - /// - public sealed class MarshalEx - { - //don't allow constructor to be called - all static methods - private MarshalEx(){} - - #region Fields - - private const int GMEM_FIXED = 0x0000; - private const int LMEM_MOVEABLE = 2; - private const int LMEM_ZEROINIT = 0x0040; - private const int LPTR = (GMEM_FIXED | LMEM_ZEROINIT); - private static readonly int HIWORDMASK = -65536;//new IntPtr((long)-65536); - - /// - /// Represents the default character size on the system; the default is 2 for Unicode systems and 1 for ANSI systems. This field is read-only. - /// - public static readonly int SystemDefaultCharSize = Marshal.SystemDefaultCharSize; - - #endregion - - #region Read functions - - #region IntPtr - /// - /// Reads an IntPtr from an unmanaged pointer. - /// - /// The address in unmanaged memory from which to read. - /// The offset from the ptr where the IntPtr is located. - /// The IntPtr read from the ptr parameter. - public static IntPtr ReadIntPtr(IntPtr ptr, int ofs) - { - int i = Marshal.ReadInt32(ptr,ofs); - return new IntPtr(i); - } - #endregion - - #region Int32 - /// - /// Reads an Int32 object from an unmanaged pointer. - /// - /// The address in unmanaged memory from which to read. - /// The offset from the ptr where the Int32 is located. - /// The Int32 read from the ptr parameter. - public static Int32 ReadInt32(IntPtr ptr, int ofs) - { - return Marshal.ReadInt32(ptr, ofs); - /*byte[] data = new byte[4]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, 4); - - return BitConverter.ToInt32(data,0);*/ - } - - /// - /// Reads a 32-bit unsigned integer from unmanaged memory. - /// - /// The base address in unmanaged memory from which to read. - /// An additional byte offset, added to the ptr parameter before reading. - /// The 32-bit unsigned integer read from the ptr parameter. - [CLSCompliant(false)] - public static UInt32 ReadUInt32(IntPtr ptr, int ofs) - { - byte[] data = new byte[4]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, 4); - - return BitConverter.ToUInt32(data,0); - } - #endregion - - #region Int16 - /// - /// Reads a Int16 from an unmanaged pointer. - /// - /// The address in unmanaged memory from which to read. - /// The offset from the ptr where the Int16 is located. - /// The Int16 read from the ptr parameter. - public static Int16 ReadInt16(IntPtr ptr, int ofs) - { - return Marshal.ReadInt16(ptr, ofs); - - /*byte[] data = new byte[2]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, 2); - - return BitConverter.ToInt16(data,0);*/ - } - - /// - /// - /// - /// - /// - /// - [CLSCompliant(false)] - public static UInt16 ReadUInt16(IntPtr ptr, int ofs) - { - byte[] data = new byte[2]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, 2); - - return BitConverter.ToUInt16(data,0); - } - #endregion - - #region String - /// - /// Reads a string from an unmanaged pointer. - /// - /// The address in unmanaged memory from which to read. - /// The offset from the ptr where the string is located. - /// Length in characters. - /// The string read from the ptr parameter. - public static string PtrToStringUni(IntPtr ptr, int ofs, int len) - { - int cb = len * Marshal.SystemDefaultCharSize; - byte[] data = new byte[cb]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, cb); - - string s = Encoding.Unicode.GetString(data, 0, len); - - int nullpos = s.IndexOf('\0'); - if(nullpos > -1) - s = s.Substring(0,nullpos); - - return s; - } - - /// - /// Allocates a managed System.String, copies a specified number of characters from an unmanaged ANSI string into it, and widens each ANSI character to Unicode. - /// - /// The address of the first character of the unmanaged string. - /// - /// The byte count of the input string to copy. - /// A managed System.String that holds a copy of the native ANSI string. - public static string PtrToStringAnsi(IntPtr ptr, int ofs, int len) - { - int cb = len; - byte[] data = new byte[cb]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, cb); - - string s = Encoding.ASCII.GetString(data, 0, len); - - int nullpos = s.IndexOf('\0'); - if(nullpos > -1) - s = s.Substring(0,nullpos); - - return s; - } - - /// - /// Copies all characters up to the first null from an unmanaged ANSI string to a managed System.String. Widens each ANSI character to Unicode. - /// New in v1.1 - /// - /// The address of the first character of the unmanaged string. - /// A managed object that holds a copy of the unmanaged ANSI string. - public static string PtrToStringAnsi(IntPtr ptr) - { - string returnval = ""; - byte thisbyte = 0; - int offset = 0; - - //while more chars to read - while(true) - { - //read current byte - thisbyte = Marshal.ReadByte(ptr, offset); - - //if not null - if(thisbyte == 0) - { - break; - } - - //add the character - returnval += ((char)thisbyte).ToString(); - - //move to next position - offset++; - } - - return returnval; - } - - /// - /// Allocates a managed System.String and copies all characters up to the first null character from an unmanaged Unicode string into it. - /// - /// The address of the first character of the unmanaged string. - /// A managed string holding a copy of the native string. - public static string PtrToStringUni(IntPtr ptr) - { - return Marshal.PtrToStringUni(ptr); - } - - /// - /// Allocates a managed and copies all characters up to the first null character from a string stored in unmanaged memory into it. - /// New in v1.1 - /// - /// The address of the first character. - /// A managed string that holds a copy of the unmanaged string. - public static string PtrToStringAuto(IntPtr ptr) - { - if(ptr==IntPtr.Zero) - { - return null; - } - else - { - //final string value - string returnval = ""; - - //read first byte - int firstbyte = Marshal.ReadByte(ptr, 0); - //read second byte - int secondbyte = Marshal.ReadByte(ptr, 1); - - //if first byte is non-zero continue - if(firstbyte!=0) - { - - //if second byte is zero we may have unicode or one byte string - if(secondbyte==0) - { - //read third byte - int thirdbyte = Marshal.ReadByte(ptr, 2); - - //if third byte is null this is a single byte string - if(thirdbyte==0) - { - //single ascii char - returnval = ((char)firstbyte).ToString(); - } - else - { - //read unicode - return Marshal.PtrToStringUni(ptr); - } - } - else - { - //else appears to be ASCII - return PtrToStringAnsi(ptr); - } - } - - return returnval; - } - } - #endregion - - #region Char - /// - /// Reads a single char from an unmanaged pointer. - /// - /// The address in unmanaged memory from which to read. - /// The offset from the ptr where the char is located. - /// The char read from the ptr parameter. - public static char ReadChar(IntPtr ptr, int ofs) - { - byte[] data = new byte[Marshal.SystemDefaultCharSize]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs),data, 0, data.Length); - - return BitConverter.ToChar(data,0); - } - #endregion - - #region Byte[] - /// - /// Reads a byte array from an unmanaged pointer. - /// - /// The address in unmanaged memory from which to read. - /// The offset from the ptr where the byte array is located. - /// The byte array read from the ptr parameter. - public static byte[] ReadByteArray(IntPtr ptr, int ofs, int len) - { - byte[] data = new byte[len]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, len); - - return data; - } - #endregion - - #region Int64 - /// - /// Reads an Int64 object from an unmanaged pointer. - /// - /// The address in unmanaged memory from which to read. - /// The offset from the ptr where the Int64 is located. - /// The Int64 read from the ptr parameter. - public static Int64 ReadInt64(IntPtr ptr, int ofs) - { - byte[] data = new byte[8]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, 8); - - return BitConverter.ToInt64(data,0); - } - - /// - /// - /// - /// - /// - /// - [CLSCompliant(false)] - public static UInt64 ReadUInt64(IntPtr ptr, int ofs) - { - byte[] data = new byte[8]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, 8); - - return BitConverter.ToUInt64(data,0); - } - #endregion - - #region Bool - - /// - /// Reads a bool from an unmanaged pointer. - /// - /// The address in unmanaged memory from which to read. - /// The offset from the ptr where the bool is located. - /// The bool read from the ptr parameter. - public static bool ReadBool(IntPtr ptr, int ofs) - { - bool b = false; - - byte[] data = new byte[4]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, 4); - - b = Convert.ToBoolean(data); - - return b; - } - - #endregion - - #region Byte - - /// - /// Reads a single byte from an unmanaged pointer. - /// - /// The address in unmanaged memory from which to read. - /// The offset from the ptr where the byte is located. - /// The byte read from the ptr parameter. - public static byte ReadByte(IntPtr ptr, int ofs) - { - return Marshal.ReadByte(ptr, ofs); - - /*byte b; - - byte[] data = new byte[1]; - Marshal.Copy(new IntPtr(ptr.ToInt32() + ofs), data, 0, 1); - - b = data[0]; - - return b;*/ - } - - #endregion - - #endregion - - #region Write functions - - #region IntPtr - - /// - /// Writes an IntPtr value to unmanaged memory. - /// - /// The address in unmanaged memory from which to write. - /// The offset of the IntPtr from the ptr. - /// The value to write. - public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val) - { - MarshalEx.WriteInt32(ptr, ofs, val.ToInt32()); - } - - #endregion - - #region Int32 - - /// - /// Writes an Int32 value to unmanaged memory. - /// - /// The base address in unmanaged memory from which to write. - /// An additional byte offset, added to the ptr parameter before writing. - /// The value to write. - public static void WriteInt32(IntPtr ptr, int ofs, int val) - { - Marshal.WriteInt32(ptr, ofs, val); - /*byte[] data = BitConverter.GetBytes(val); - Marshal.Copy(data, 0, new IntPtr(ptr.ToInt32() + ofs), data.Length);*/ - } - - /// - /// Writes a UInt32 value to unmanaged memory. - /// - /// The base address in unmanaged memory from which to write. - /// An additional byte offset, added to the ptr parameter before writing. - /// The value to write. - [CLSCompliant(false)] - public static void WriteUInt32(IntPtr ptr, int ofs, uint val) - { - byte[] data = BitConverter.GetBytes(val); - Marshal.Copy(data, 0, new IntPtr(ptr.ToInt32() + ofs), data.Length); - } - - #endregion - - #region Int16 - - /// - /// Writes an Int16 value to unmanaged memory. - /// - /// The address in unmanaged memory from which to write. - /// An additional byte offset, added to the ptr parameter before writing. - /// The value to write. - public static void WriteInt16(IntPtr ptr, int ofs, Int16 val) - { - Marshal.WriteInt16(ptr, ofs, val); - - /*byte[] data = BitConverter.GetBytes(val); - Marshal.Copy(data, 0, new IntPtr(ptr.ToInt32() + ofs), data.Length);*/ - } - - /// - /// Writes a 16-bit unsigned integer value to unmanaged memory. - /// - /// The base address in unmanaged memory from which to write. - /// An additional byte offset, added to the ptr parameter before writing. - /// The value to write. - [CLSCompliant(false)] - public static void WriteUInt16(IntPtr ptr, int ofs, UInt16 val) - { - byte[] data = BitConverter.GetBytes(val); - Marshal.Copy(data, 0, new IntPtr(ptr.ToInt32() + ofs), data.Length); - } - - #endregion - - #region String - - #region ANSI String - - /// - /// Copies the contents of a managed into unmanaged memory, converting into ANSI format as it copies. - /// - /// A managed string to be copied. - /// The address, in unmanaged memory, to where s was copied, or 0 if a null reference (Nothing in Visual Basic) string was supplied. - public static IntPtr StringToHGlobalAnsi(string s) - { - if(s == null) - return IntPtr.Zero; - - int i = s.Length + 1; - IntPtr ptr = LocalAlloc(LPTR, (uint)i); - - byte[] data = Encoding.ASCII.GetBytes(s); - Marshal.Copy(data, 0, ptr, data.Length); - - return ptr; - } - - #endregion - - #region Unicode String - /// - /// Copies the contents of a managed into unmanaged memory. - /// - /// A managed string to be copied. - /// The address, in unmanaged memory, to where s was copied, or 0 if a null reference (Nothing in Visual Basic) string was supplied. - public static IntPtr StringToHGlobalUni(string s) - { - if(s == null) - return IntPtr.Zero; - - int i = (s.Length + 1) * System.Text.UnicodeEncoding.CharSize; - - IntPtr ptr = LocalAlloc(LPTR,(uint)i); - - byte[] data = Encoding.Unicode.GetBytes(s); - Marshal.Copy(data, 0, ptr, data.Length); - - return ptr; - } - - #endregion - - #endregion - - #region Char - - /// - /// Writes a single char value to unmanaged memory. - /// - /// The address in unmanaged memory from which to write. - /// The offset of the char from the ptr. - /// The value to write. - public static void WriteChar(IntPtr ptr, int ofs, char val) - { - byte[] data = BitConverter.GetBytes(val); - Marshal.Copy(data, 0, new IntPtr(ptr.ToInt32() + ofs), data.Length); - } - - #endregion - - #region Byte[] - - /// - /// Writes a byte array to unmanaged memory. - /// - /// The address in unmanaged memory from which to write. - /// The offset of the byte array from the ptr. - /// The value to write. - public static void WriteByteArray(IntPtr ptr, int ofs, byte[] val) - { - Marshal.Copy(val, 0, new IntPtr(ptr.ToInt32() + ofs), val.Length); - } - - #endregion - - #region Int64 - - /// - /// Writes an Int64 value to unmanaged memory. - /// - /// The address in unmanaged memory from which to write. - /// An additional byte offset, added to the ptr parameter before writing. - /// The value to write. - public static void WriteInt64(IntPtr ptr, int ofs, Int64 val) - { - byte[] data = BitConverter.GetBytes(val); - Marshal.Copy(data, 0, new IntPtr(ptr.ToInt32() + ofs), data.Length); - } - - /// - /// Writes a 64-bit unsigned integer value to unmanaged memory. - /// - /// The address in unmanaged memory from which to write. - /// An additional byte offset, added to the ptr parameter before writing. - /// The value to write. - [CLSCompliant(false)] - public static void WriteUInt64(IntPtr ptr, int ofs, UInt64 val) - { - byte[] data = BitConverter.GetBytes(val); - Marshal.Copy(data, 0, new IntPtr(ptr.ToInt32() + ofs), data.Length); - } - - #endregion - - #region Bool - - /// - /// Writes a bool value to unmanaged memory. - /// - /// The address in unmanaged memory from which to write. - /// The offset of the bool from the ptr. - /// The value to write. - public static void WriteBool(IntPtr ptr, int ofs, bool val) - { - byte[] data = BitConverter.GetBytes(val); - Marshal.Copy(data, 0, new IntPtr(ptr.ToInt32() + ofs), data.Length); - } - - #endregion - - #region Byte - - /// - /// Writes a single byte value to unmanaged memory. - /// - /// The address in unmanaged memory from which to write. - /// The offset of the byte from the ptr. - /// The value to write. - public static void WriteByte(IntPtr ptr, int ofs, byte val) - { - Marshal.WriteByte(ptr, ofs, val); - - /*byte[] data = BitConverter.GetBytes(val); - Marshal.Copy(data, 0, new IntPtr(ptr.ToInt32() + ofs), data.Length);*/ - } - - #endregion - - #endregion - - #region Copy Functions - - /// - /// Copies data from an unmanaged memory pointer to a managed 8-bit unsigned integer array. - /// - /// The memory pointer to copy from. - /// The array to copy to. - /// The zero-based index into the array where Copy should start. - /// The number of array elements to copy. - public static void Copy(IntPtr source, byte[] destination, int startIndex, int length) - { - Marshal.Copy(source, destination, startIndex, length); - } - - /// - /// Copies data from an unmanaged memory pointer to a managed double-precision floating-point number array. - /// - /// The memory pointer to copy from. - /// The array to copy to. - /// The zero-based index into the array where Copy should start. - /// The number of array elements to copy. - public static void Copy(IntPtr source, double[] destination, int startIndex, int length) - { - Marshal.Copy(source, destination, startIndex, length); - } - - /// - /// Copies data from an unmanaged memory pointer to a managed single-precision floating-point number array. - /// - /// The memory pointer to copy from. - /// The array to copy to. - /// The zero-based index into the array where Copy should start. - /// The number of array elements to copy. - public static void Copy(IntPtr source, float[] destination, int startIndex, int length) - { - Marshal.Copy(source, destination, startIndex, length); - } - - /// - /// Copies data from an unmanaged memory pointer to a managed 64-bit signed integer array. - /// - /// The memory pointer to copy from. - /// The array to copy to. - /// The zero-based index into the array where Copy should start. - /// The number of array elements to copy. - public static void Copy(IntPtr source, long[] destination, int startIndex, int length) - { - Marshal.Copy(source, destination, startIndex, length); - } - - /// - /// Copies data from an unmanaged memory pointer to a managed 16-bit signed integer array. - /// - /// The memory pointer to copy from. - /// The array to copy to. - /// The zero-based index into the array where Copy should start. - /// The number of array elements to copy. - public static void Copy(IntPtr source, short[] destination, int startIndex, int length) - { - Marshal.Copy(source, destination, startIndex, length); - } - - /// - /// Copies data from an unmanaged memory pointer to a managed character array. - /// - /// The memory pointer to copy from. - /// The array to copy to. - /// The zero-based index into the array where Copy should start. - /// The number of array elements to copy. - public static void Copy(IntPtr source, char[] destination, int startIndex, int length) - { - Marshal.Copy(source, destination, startIndex, length); - } - - /// - /// Copies data from an unmanaged memory pointer to a managed 32-bit signed integer array. - /// - /// The memory pointer to copy from. - /// The array to copy to. - /// The zero-based index into the array where Copy should start. - /// The number of array elements to copy. - public static void Copy(IntPtr source, int[] destination, int startIndex, int length) - { - Marshal.Copy(source, destination, startIndex, length); - } - - /// - /// Copies data from a one-dimensional, managed 8-bit unsigned integer array to an unmanaged memory pointer. - /// - /// The one-dimensional array to copy from. - /// The zero-based index into the array where Copy should start. - /// The memory pointer to copy to. - /// The number of array elements to copy. - public static void Copy(byte[] source, int startIndex, IntPtr destination, int length) - { - Marshal.Copy(source, startIndex, destination, length); - } - - /// - /// Copies data from a one-dimensional, managed double-precision floating-point number array to an unmanaged memory pointer. - /// - /// The one-dimensional array to copy from. - /// The zero-based index into the array where Copy should start. - /// The memory pointer to copy to. - /// The number of array elements to copy. - public static void Copy(double[] source, int startIndex, IntPtr destination, int length) - { - Marshal.Copy(source, startIndex, destination, length); - } - - /// - /// Copies data from a one-dimensional, managed single-precision floating-point number array to an unmanaged memory pointer - /// - /// The one-dimensional array to copy from. - /// The zero-based index into the array where Copy should start. - /// The memory pointer to copy to. - /// The number of array elements to copy. - public static void Copy(float[] source, int startIndex, IntPtr destination, int length) - { - Marshal.Copy(source, startIndex, destination, length); - } - - /// - /// Copies data from a one-dimensional, managed 64-bit signed integer array to an unmanaged memory pointer. - /// - /// The one-dimensional array to copy from. - /// The zero-based index into the array where Copy should start. - /// The memory pointer to copy to. - /// The number of array elements to copy. - public static void Copy(long[] source, int startIndex, IntPtr destination, int length) - { - Marshal.Copy(source, startIndex, destination, length); - } - - /// - /// Copies data from a one-dimensional, managed 16-bit signed integer array to an unmanaged memory pointer. - /// - /// The one-dimensional array to copy from. - /// The zero-based index into the array where Copy should start. - /// The memory pointer to copy to. - /// The number of array elements to copy. - public static void Copy(short[] source, int startIndex, IntPtr destination, int length) - { - Marshal.Copy(source, startIndex, destination, length); - } - - /// - /// Copies data from a one-dimensional, managed character array to an unmanaged memory pointer. - /// - /// The one-dimensional array to copy from. - /// The zero-based index into the array where Copy should start. - /// The memory pointer to copy to. - /// The number of array elements to copy. - public static void Copy(char[] source, int startIndex, IntPtr destination, int length) - { - Marshal.Copy(source, startIndex, destination, length); - } - - /// - /// Copies data from a one-dimensional, managed 32-bit signed integer array to an unmanaged memory pointer. - /// - /// The one-dimensional array to copy from. - /// The zero-based index into the array where Copy should start. - /// The memory pointer to copy to. - /// The number of array elements to copy. - public static void Copy(int[] source, int startIndex, IntPtr destination, int length) - { - Marshal.Copy(source, startIndex, destination, length); - } - - #endregion - - #region Memory Functions - - private static bool IsNotWin32Atom(IntPtr ptr) - { - long b; - b = (long)ptr; - return (((long) 0) != (b & (long)MarshalEx.HIWORDMASK)); - } - - /// - /// Allocates unmanaged memory. - /// - /// The number of bytes in memory required. - /// An IntPtr to the newly allocated memory. This memory must be released using the Marshal.FreeHGlobal method. - public static IntPtr AllocHGlobal(int cb) - { - IntPtr ptr = LocalAlloc(LPTR, (uint)cb); - if (ptr == IntPtr.Zero) - { - throw new OutOfMemoryException(); - - } - return ptr; - } - - /// - /// Allocates unmanaged memory. - /// - /// The number of bytes in memory required. - /// An IntPtr to the newly allocated memory. This memory must be released using the Marshal.FreeHGlobal method. - public static IntPtr AllocHGlobal(IntPtr cb) - { - return MarshalEx.AllocHGlobal((int)cb); - } - - /// - /// Resizes a block of memory previously allocated with . - /// New in v1.2 - /// - /// A pointer to memory allocated with . - /// The new size of the allocated block. - /// An to the reallocated memory. - /// This memory must be released using . - /// There is insufficient memory to satisfy the request. - public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb) - { - IntPtr ptr = LocalReAllocCE(pv, (int)cb, LPTR); - - if(ptr == IntPtr.Zero) - { - throw new OutOfMemoryException(); - } - - return ptr; - } - - /// - /// Frees memory previously allocated from unmanaged memory. - /// - /// The handle returned by the original matching call to AllocHGlobal. - public static void FreeHGlobal(IntPtr hGlobal) - { - if(MarshalEx.IsNotWin32Atom(hGlobal)) - { - LocalFree(hGlobal); - } - else - { - throw new ArgumentException("hGlobal is not an unmanaged atom."); - } - } - - /// - /// Allocates unmanaged memory. - /// - /// The number of bytes in memory required. - /// An IntPtr to the newly allocated memory. This memory must be released using the method. - [CLSCompliant(false)] - public static IntPtr AllocHLocal(uint cb) - { - return LocalAlloc(LPTR, cb); - } - /// - /// Allocates unmanaged memory. - /// - /// The number of bytes in memory required. - /// An IntPtr to the newly allocated memory. This memory must be released using the method. - public static IntPtr AllocHLocal(int cb) - { - return LocalAlloc(LPTR, (uint)cb); - } - - /// - /// Frees memory previously allocated from unmanaged memory. - /// - /// The handle returned by the original matching call to AllocHGlobal. - public static void FreeHLocal(IntPtr hMem) - { - if(hMem != IntPtr.Zero) - LocalFree(hMem); - } - - /// - /// Converts a time_t value to a DateTime value. - /// - /// The time_t value to convert. - /// A DateTime value equivalent to the time_t suppled. - [CLSCompliant(false)] - public static DateTime Time_tToDateTime(uint time_t) - { - long win32FileTime = 10000000*(long)time_t + 116444736000000000; - return DateTime.FromFileTimeUtc(win32FileTime); - } - - /// - /// Returns the unmanaged size of an object in bytes. - /// - /// The object whose size is to be returned. - /// The size of the structure parameter in unmanaged code - public static int SizeOf(object structure) - { - return Marshal.SizeOf(structure); - } - - /// - /// Returns the size of an unmanaged type in bytes. - /// - /// The System.Type whose size is to be returned. - /// The size of the structure parameter in unmanaged code - public static int SizeOf(Type t) - { - return Marshal.SizeOf(t); - } - - /// - /// Marshals data from a managed object to an unmanaged block of memory. - /// - /// A managed object holding the data to be marshaled. This object must be an instance of a formatted class. - /// A pointer to an unmanaged block of memory, which must be allocated before this method is called. - /// true to have the System.Runtime.InteropServices.Marshal.DestroyStructure(System.IntPtr,System.Type) method called on the ptr parameter before this method executes. Note that passing false can lead to a memory leak. - public static void StructureToPtr(object structure, IntPtr ptr, bool fDeleteOld) - { - Marshal.StructureToPtr(structure, ptr, fDeleteOld); - } - - /// - /// Returns the length of the string at the pointer - /// - /// The pointer to the string to measure. - /// The length of the string at the pointer. - private static int lstrlenW(IntPtr ptr) - { - return String_wcslen(ptr); - } - - #endregion - - #region Miscellaneous Functions - - #region GetHINSTANCE - /// - /// Returns the instance handle (HINSTANCE) for the specified module. - /// New in v1.3 - /// - /// The whose HINSTANCE is desired. - /// The HINSTANCE for m; -1 if the module does not have an HINSTANCE. - public static IntPtr GetHINSTANCE(System.Reflection.Module m ) - { - IntPtr hinst = IntPtr.Zero; - - if(m.Assembly == System.Reflection.Assembly.GetCallingAssembly()) - { - hinst = GetModuleHandle(null); - } - else - { - hinst = GetModuleHandle(m.Assembly.GetName().CodeBase); - } - - if(hinst == IntPtr.Zero) - { - return new IntPtr(-1); - } - else - { - return hinst; - } - } - [DllImport("coredll.dll", EntryPoint="GetModuleHandleW", SetLastError=true)] - private static extern IntPtr GetModuleHandle(string lpszModule); - #endregion - - /// - /// Returns the error code returned by the last unmanaged function called using platform invoke that has the System.Runtime.InteropServices.DllImportAttribute.SetLastError flag set. - /// - /// The last error code set by a call to the Win32 SetLastError API method. - public static int GetLastWin32Error() - { - return Marshal.GetLastWin32Error(); - } - - /// - /// Indicates whether a specified object represents a COM object. - /// - /// The object to check. - /// true if the o parameter is a COM type; otherwise, false. - public static bool IsComObject(object o) - { - return Marshal.IsComObject(o); - } - - #endregion - - #region API Prototypes - - [DllImport("coredll.dll",EntryPoint="LocalAlloc",SetLastError=true)] - static extern IntPtr LocalAlloc(uint uFlags, uint Bytes); - - [DllImport("coredll.dll", EntryPoint="LocalReAlloc", SetLastError=true)] - static extern IntPtr LocalReAllocCE(IntPtr hMem, int uBytes, int fuFlags); - - [DllImport("coredll.dll",EntryPoint="LocalFree",SetLastError=true)] - static extern IntPtr LocalFree(IntPtr hMem); - - [DllImport("mscoree.dll",EntryPoint="#1",SetLastError=true)] - static extern int String_wcslen(IntPtr pws); - - #endregion - } -} diff --git a/PingNG/PingNG/Runtime/InteropServices/SafeHandle.cs b/PingNG/PingNG/Runtime/InteropServices/SafeHandle.cs deleted file mode 100644 index 53f63b7..0000000 --- a/PingNG/PingNG/Runtime/InteropServices/SafeHandle.cs +++ /dev/null @@ -1,156 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.Runtime.InteropServices.SafeHandle -// Copyright (c) 2005, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; - -namespace OpenNETCF.Runtime.InteropServices -{ - /// - /// Represents a wrapper class for operating system handles. - /// New in v1.3 - /// - public abstract class SafeHandle : IDisposable - { - private bool closed; - private bool dirty; - private bool ownsHandle; - private IntPtr invalid; - - /// - /// Initializes a new instance of the SafeHandle class with the specified invalid handle value. - /// - /// The value of an invalid handle (usually 0 or -1). - /// true to reliably let SafeHandle release the handle during the finalization phase; otherwise, false (not recommended). - protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle) - { - this.invalid = invalidHandleValue; - handle = invalidHandleValue; - this.closed = false; - this.ownsHandle = ownsHandle; - if(!ownsHandle) - { - GC.SuppressFinalize(this); - } - } - - /// - /// Specifies the handle to be wrapped. - /// - protected IntPtr handle; - - /// - /// Gets a value indicating whether the handle is closed. - /// - /// true if the handle is closed; otherwise, false. - public bool IsClosed - { - get - { - return closed; - } - } - - /// - /// When overridden in a derived class, gets a value indicating whether the handle value is invalid. - /// - /// true if the handle is valid; otherwise, false. - public abstract bool IsInvalid - { - get; - } - - /// - /// Marks the handle for releasing and freeing resources. - /// - public void Close() - { - Dispose(); - } - - /// - /// Returns the value of the field. - /// - /// - public IntPtr DangerousGetHandle() - { - return handle; - } - - /// - /// When overridden in a derived class, executes the code required to free the handle. - /// - /// - protected abstract bool ReleaseHandle(); - - /// - /// Sets the handle to the specified pre-existing handle. - /// - /// - protected void SetHandle(IntPtr handle) - { - this.handle = handle; - } - - /// - /// Marks a handle as invalid. - /// - public void SetHandleAsInvalid() - { - dirty = true; - GC.SuppressFinalize(this); - } - - #region IDisposable Members - - protected void Dispose(bool disposing) - { - if(ownsHandle && !IsClosed && !dirty && !IsInvalid) - { - ReleaseHandle(); - } - - if(disposing) - { - GC.SuppressFinalize(this); - } - } - - /// - /// Marks the handle for releasing and freeing resources. - /// - public void Dispose() - { - Dispose(true); - - } - - /// - /// Frees all resources associated with the handle. - /// - ~SafeHandle() - { - Dispose(false); - } - #endregion - } -} diff --git a/PingNG/PingNG/frmOptions.Designer.cs b/PingNG/PingNG/frmOptions.Designer.cs deleted file mode 100644 index 23fe1a6..0000000 --- a/PingNG/PingNG/frmOptions.Designer.cs +++ /dev/null @@ -1,263 +0,0 @@ -namespace PingNG -{ - partial class frmOptions - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuCancel = new System.Windows.Forms.MenuItem(); - this.mnuOK = new System.Windows.Forms.MenuItem(); - this.chkDoNotFragment = new System.Windows.Forms.CheckBox(); - this.label1 = new System.Windows.Forms.Label(); - this.numTTL = new System.Windows.Forms.NumericUpDown(); - this.label2 = new System.Windows.Forms.Label(); - this.numTimeout = new System.Windows.Forms.NumericUpDown(); - this.label3 = new System.Windows.Forms.Label(); - this.label4 = new System.Windows.Forms.Label(); - this.btnOK = new System.Windows.Forms.Button(); - this.btnCancel = new System.Windows.Forms.Button(); - this.label5 = new System.Windows.Forms.Label(); - this.numPings = new System.Windows.Forms.NumericUpDown(); - this.label6 = new System.Windows.Forms.Label(); - this.numBuffSize = new System.Windows.Forms.NumericUpDown(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuCancel); - this.mainMenu1.MenuItems.Add(this.mnuOK); - // - // mnuCancel - // - this.mnuCancel.Text = "Cancel"; - this.mnuCancel.Click += new System.EventHandler(this.btnCancel_Click); - // - // mnuOK - // - this.mnuOK.Text = "OK"; - this.mnuOK.Click += new System.EventHandler(this.btnOK_Click); - // - // chkDoNotFragment - // - this.chkDoNotFragment.Location = new System.Drawing.Point(9, 116); - this.chkDoNotFragment.Name = "chkDoNotFragment"; - this.chkDoNotFragment.Size = new System.Drawing.Size(181, 30); - this.chkDoNotFragment.TabIndex = 0; - this.chkDoNotFragment.Text = "do not fragment (DF)"; - // - // label1 - // - this.label1.Location = new System.Drawing.Point(9, 82); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(69, 18); - this.label1.Text = "TTL:"; - // - // numTTL - // - this.numTTL.Location = new System.Drawing.Point(84, 82); - this.numTTL.Maximum = new decimal(new int[] { - 256, - 0, - 0, - 0}); - this.numTTL.Minimum = new decimal(new int[] { - 1, - 0, - 0, - 0}); - this.numTTL.Name = "numTTL"; - this.numTTL.Size = new System.Drawing.Size(94, 24); - this.numTTL.TabIndex = 2; - this.numTTL.Value = new decimal(new int[] { - 128, - 0, - 0, - 0}); - // - // label2 - // - this.label2.Location = new System.Drawing.Point(9, 46); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(69, 18); - this.label2.Text = "Timeout:"; - // - // numTimeout - // - this.numTimeout.Location = new System.Drawing.Point(85, 46); - this.numTimeout.Maximum = new decimal(new int[] { - 10000, - 0, - 0, - 0}); - this.numTimeout.Minimum = new decimal(new int[] { - 1, - 0, - 0, - 0}); - this.numTimeout.Name = "numTimeout"; - this.numTimeout.Size = new System.Drawing.Size(93, 24); - this.numTimeout.TabIndex = 2; - this.numTimeout.Value = new decimal(new int[] { - 1000, - 0, - 0, - 0}); - // - // label3 - // - this.label3.Location = new System.Drawing.Point(184, 96); - this.label3.Name = "label3"; - this.label3.Size = new System.Drawing.Size(42, 21); - this.label3.Text = "hops"; - // - // label4 - // - this.label4.Location = new System.Drawing.Point(185, 49); - this.label4.Name = "label4"; - this.label4.Size = new System.Drawing.Size(42, 21); - this.label4.Text = "ms"; - // - // btnOK - // - this.btnOK.Location = new System.Drawing.Point(138, 228); - this.btnOK.Name = "btnOK"; - this.btnOK.Size = new System.Drawing.Size(87, 29); - this.btnOK.TabIndex = 6; - this.btnOK.Text = "OK"; - this.btnOK.Click += new System.EventHandler(this.btnOK_Click); - // - // btnCancel - // - this.btnCancel.Location = new System.Drawing.Point(8, 228); - this.btnCancel.Name = "btnCancel"; - this.btnCancel.Size = new System.Drawing.Size(87, 29); - this.btnCancel.TabIndex = 6; - this.btnCancel.Text = "cancel"; - this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); - // - // label5 - // - this.label5.Location = new System.Drawing.Point(8, 152); - this.label5.Name = "label5"; - this.label5.Size = new System.Drawing.Size(88, 18); - this.label5.Text = "Num pings:"; - // - // numPings - // - this.numPings.Location = new System.Drawing.Point(138, 152); - this.numPings.Maximum = new decimal(new int[] { - 1000, - 0, - 0, - 0}); - this.numPings.Name = "numPings"; - this.numPings.Size = new System.Drawing.Size(87, 24); - this.numPings.TabIndex = 2; - this.numPings.Value = new decimal(new int[] { - 4, - 0, - 0, - 0}); - // - // label6 - // - this.label6.Location = new System.Drawing.Point(9, 182); - this.label6.Name = "label6"; - this.label6.Size = new System.Drawing.Size(88, 18); - this.label6.Text = "Buffer Size:"; - // - // numBuffSize - // - this.numBuffSize.Location = new System.Drawing.Point(138, 182); - this.numBuffSize.Maximum = new decimal(new int[] { - 9000, - 0, - 0, - 0}); - this.numBuffSize.Minimum = new decimal(new int[] { - 20, - 0, - 0, - 0}); - this.numBuffSize.Name = "numBuffSize"; - this.numBuffSize.Size = new System.Drawing.Size(87, 24); - this.numBuffSize.TabIndex = 2; - this.numBuffSize.Value = new decimal(new int[] { - 32, - 0, - 0, - 0}); - // - // frmOptions - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(238, 295); - this.ControlBox = false; - this.Controls.Add(this.btnCancel); - this.Controls.Add(this.btnOK); - this.Controls.Add(this.label4); - this.Controls.Add(this.label3); - this.Controls.Add(this.numBuffSize); - this.Controls.Add(this.numPings); - this.Controls.Add(this.label6); - this.Controls.Add(this.numTimeout); - this.Controls.Add(this.label5); - this.Controls.Add(this.numTTL); - this.Controls.Add(this.label2); - this.Controls.Add(this.label1); - this.Controls.Add(this.chkDoNotFragment); - this.MaximizeBox = false; - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "frmOptions"; - this.Text = "Ping options"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuCancel; - private System.Windows.Forms.MenuItem mnuOK; - private System.Windows.Forms.CheckBox chkDoNotFragment; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.NumericUpDown numTTL; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.NumericUpDown numTimeout; - private System.Windows.Forms.Label label3; - private System.Windows.Forms.Label label4; - private System.Windows.Forms.Button btnOK; - private System.Windows.Forms.Button btnCancel; - private System.Windows.Forms.Label label5; - private System.Windows.Forms.NumericUpDown numPings; - private System.Windows.Forms.Label label6; - private System.Windows.Forms.NumericUpDown numBuffSize; - } -} \ No newline at end of file diff --git a/PingNG/PingNG/frmOptions.cs b/PingNG/PingNG/frmOptions.cs deleted file mode 100644 index 8280e62..0000000 --- a/PingNG/PingNG/frmOptions.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using OpenNETCF.Net.NetworkInformation; - -namespace PingNG -{ - public partial class frmOptions : Form - { - PingOptions _PO; - - public frmOptions(ref PingOptions po) - { - InitializeComponent(); - _PO = po; - read(); - } - void read() - { - chkDoNotFragment.Checked = _PO.DontFragment; - numTimeout.Value = _PO.TimeOut; - numTTL.Value = _PO.Ttl; - numPings.Value = _PO.numOfPings; - numBuffSize.Value = _PO.bufferSize; - } - private void btnOK_Click(object sender, EventArgs e) - { - _PO.Ttl = (int) numTTL.Value; - _PO.TimeOut = (int)numTimeout.Value; - _PO.DontFragment = chkDoNotFragment.Checked; - _PO.numOfPings = (int)numPings.Value; - _PO.bufferSize = (int)numBuffSize.Value; - this.DialogResult = DialogResult.OK; - this.Close(); - } - - private void btnCancel_Click(object sender, EventArgs e) - { - this.Close(); - } - } -} \ No newline at end of file diff --git a/PingNG/PingNG/frmOptions.resx b/PingNG/PingNG/frmOptions.resx deleted file mode 100644 index a68cf01..0000000 --- a/PingNG/PingNG/frmOptions.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - WEBPAD - - - False - - \ No newline at end of file diff --git a/PingNG/PingNG/myPing.cs b/PingNG/PingNG/myPing.cs deleted file mode 100644 index 968cab1..0000000 --- a/PingNG/PingNG/myPing.cs +++ /dev/null @@ -1,235 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; -using OpenNETCF.Net.NetworkInformation; -using System.Threading; -using System.Net; - -namespace PingNG -{ - class myPing:IDisposable - { - string _ipAddress="127.0.0.1"; - PingOptions _pingOptions = new PingOptions(); - - public void doPing(string ipAddress) - { - _ipAddress = ipAddress; - _pingOptions = new PingOptions(); - _ipAddress = ipAddress; - //Thread thread = new Thread(new ThreadStart(startPing)); - ThreadStart myThread = delegate { startPing(ipAddress, new PingOptions()); }; - thread = new Thread(myThread); - thread.Start(); - } - - Thread thread; - public void doPing(string ipAddress, PingOptions pingOptions) - { - string _ipAddress = ipAddress; - PingOptions _pingOptions = pingOptions; - - ThreadStart myThread = delegate { startPing(_ipAddress, _pingOptions); }; - thread = new Thread(myThread); - thread.Name="ping thread"; - thread.Start(); - } - - public void Dispose() - { - if (thread != null) - { - thread.Abort(); - thread = null; - } - } - - class HostParms - { - public string host; - public int retry; - public IPAddress ipAddress=null; - public bool isValid = false; - public HostParms(string sHost, int iRetry) - { - this.host = sHost; - this.retry = iRetry; - } - } - - bool checkHost(ref HostParms hostParms) - { - bool bRet = false; - IPHostEntry ipHost = new IPHostEntry(); - try - { - IPHostEntry entry = null; - int maxSeconds = hostParms.retry/* 10 */, counter = 0; - // see http://jianmingli.com/wp/?p=22 - // Start the asynchronous request for DNS information. - // This example does not use a delegate or user-supplied object - // so the last two arguments are null. - IAsyncResult result = Dns.BeginGetHostEntry(hostParms.host/* ipAddress */, null, null); - // Poll for completion information. - while (result.IsCompleted != true && counter < maxSeconds) - { - Thread.Sleep(1000); - counter++; - } - if (result.IsCompleted) //when we got here, the result is ready - entry = Dns.EndGetHostEntry(result); //blocks? - else - hostParms.isValid = false; // Thread.CurrentThread.Abort(); - - //IPHostEntry entry = Dns.Resolve(hostNameOrAddress); - //IPHostEntry entry = Dns.GetHostEntry(ipAddress); - hostParms.ipAddress = entry.AddressList[0]; - hostParms.isValid = true; - } - catch (ThreadAbortException e) - { - Thread.CurrentThread.Abort();// ("DNS failed within timeout", e); - } - catch (Exception e) - { - System.Diagnostics.Debug.WriteLine(string.Format( "Exception in checkHost({0}): {1}", hostParms.host, e.Message)); - //throw new PingUnknownHostException("Impossible to resolve host or address.", e); - } - - return hostParms.isValid; - } - //thread to do ping - public void startPing(string sHost, PingOptions pOptions) - { - System.Diagnostics.Debug.WriteLine("+++thread started"); - string ipAddress = sHost;//make a local copy - Ping myPing = new Ping(); - PingOptions myPingOptions = pOptions;//make a local copy - - int iTimeout = pOptions.TimeOut; - int _numberOfPings = pOptions.numOfPings; - bool doNotFragment = pOptions.DontFragment; - int bufferSize = pOptions.bufferSize; - byte[] buf = new byte[bufferSize]; - - //long sumRoundtripTime=0; - onReply(new PingReplyEventArgs("ping started...",PingReplyTypes.info)); - replyStats _replyStats = new replyStats(ipAddress); - PingReply reply = null; - try - { - onReply(new PingReplyEventArgs(pOptions.ToString(), PingReplyTypes.info)); - //check DNS first as this may block for long time - IPAddress address; - HostParms hostParms = new HostParms(ipAddress, 4); - try - { - //is IP address - address = IPAddress.Parse(ipAddress); - hostParms.isValid = true; - } - catch - { - if (checkHost(ref hostParms)) - ipAddress = hostParms.ipAddress.ToString(); - } - if (!hostParms.isValid) - throw new PingUnknownHostException("Unkown host: " + ipAddress); - - for (int ix = 0; ix < _numberOfPings; ix++) - { - reply = myPing.Send(ipAddress, buf, iTimeout, myPingOptions); - string sReply = ""; - if (reply.Status == IPStatus.Success) - { - //sumRoundtripTime += reply.RoundTripTime; - _replyStats.add(1, 1, reply.RoundTripTime); - sReply = myResources.getReply(reply, ipAddress); - } - else if (reply.Status == IPStatus.DestinationHostUnreachable) - { - _replyStats.add(1, 0, reply.RoundTripTime); - throw new PingUnknownHostException("Destination unreachable"); - } - else - { - _replyStats.add(1, 0, reply.RoundTripTime); - sReply = myResources.getReply(reply, ipAddress); - } - System.Diagnostics.Debug.WriteLine(sReply); - onReply(new PingReplyEventArgs(sReply)); - } - onReply(new PingReplyEventArgs(_replyStats.ToString(), PingReplyTypes.info)); - } - catch (PingUnknownHostException ex) - { - System.Diagnostics.Debug.WriteLine("PingUnknownHostException: " + ex.Message); - onReply(new PingReplyEventArgs("Unknown host: "+ ipAddress, PingReplyTypes.info)); - } - catch (PingException ex) - { - System.Diagnostics.Debug.WriteLine("PingException: " + ex.Message); - } - catch (ThreadAbortException ex) - { - onReply(new PingReplyEventArgs("ping failed", PingReplyTypes.info)); - Thread.CurrentThread.Abort(); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("PingException: " + ex.Message); - } - finally - { - onReply(new PingReplyEventArgs("done", PingReplyTypes.done)); - System.Diagnostics.Debug.WriteLine("---thread ended"); - } - } - - class PingUnknownHostException : Exception - { - public PingUnknownHostException(string message) - : base(message) - { - } - public PingUnknownHostException(string message, Exception innerException) - : base(message, innerException) - { - } - } - - public delegate void ReplyEventHandler(object sender, PingReplyEventArgs args); - public static event ReplyEventHandler onReplyEvent; - static void onReply(PingReplyEventArgs args) - { - System.Diagnostics.Debug.WriteLine("onReply: " + args.message); - ReplyEventHandler handler = onReplyEvent; - if (handler != null) - { - handler("pingReply", args); - } - } - public class PingReplyEventArgs : EventArgs - { - public string message; - public PingReplyTypes replytype; - public PingReplyEventArgs(string msg) - { - message = msg; - replytype = PingReplyTypes.info; - } - public PingReplyEventArgs(string msg, PingReplyTypes rtype) - { - message = msg; - replytype = rtype; - } - } - public enum PingReplyTypes - { - info, - reply, - done - } - } -} diff --git a/PingNG/PingNG/myResources.cs b/PingNG/PingNG/myResources.cs deleted file mode 100644 index 2ba0704..0000000 --- a/PingNG/PingNG/myResources.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using OpenNETCF.Net.NetworkInformation; - -namespace PingNG -{ - public class myResources - { - /* - Pinging google.de [74.125.224.183] with 32 bytes of data: - Reply from 74.125.224.183: bytes=32 time=215ms TTL=34 - Reply from 74.125.224.183: bytes=32 time=214ms TTL=34 - Reply from 74.125.224.183: bytes=32 time=215ms TTL=34 - Reply from 74.125.224.183: bytes=32 time=215ms TTL=34 - - Ping statistics for 74.125.224.183: - Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), - Approximate round trip times in milli-seconds: - Minimum = 214ms, Maximum = 215ms, Average = 214ms - */ - const string PingServerOK = "Reply from {0}: bytes={1} time={2}ms TTL={3}"; - const string BadDestinationName = "Ping request could not find host {0}. Please check the name and try again."; - const string BadOption = "Bad value for option: {0}"; - - public static string getReply(PingReply _pingReply, string ipAddress) - { - string s = ""; - switch (_pingReply.Status){ - case IPStatus.Success: - s = string.Format("Reply from {0}: bytes={1} time={2}ms TTL={3}", - _pingReply.Address.ToString(), - _pingReply.DataSize, - _pingReply.RoundTripTime, - _pingReply.Options.Ttl); - break; - case IPStatus.BadDestination: - s = string.Format(BadDestinationName, ipAddress); - break; - case IPStatus.BadOption: - s=string.Format(BadOption, getPingOptions(_pingReply.Options)); - break; - case IPStatus.TimedOut: - s = string.Format("ping timedout for {0}.", ipAddress); - break; - case IPStatus.DestinationHostUnreachable: - s = string.Format("Destination host {0} unreachable.", ipAddress); - break; - case IPStatus.BadRoute: - case IPStatus.DestinationNetworkUnreachable: - case IPStatus.DestinationPortUnreachable: - case IPStatus.DestinationProhibited: - case IPStatus.DestinationScopeMismatch: - case IPStatus.DestinationUnreachable: - case IPStatus.HardwareError: - case IPStatus.IcmpError: - case IPStatus.NoResources: - case IPStatus.PacketTooBig: - case IPStatus.ParameterProblem: - case IPStatus.SourceQuench: - case IPStatus.TimeExceeded: - case IPStatus.TtlExpired: - case IPStatus.TtlReassemblyTimeExceeded: - case IPStatus.Unknown: - case IPStatus.UnrecognizedNextHeader: - default: - s = "IPStatus." + _pingReply.Status.ToString(); - break; - } - return s; - } - - static string getPingOptions(PingOptions _pingOptions) - { - StringBuilder s = new StringBuilder(); - s.Append(string.Format("DF={0}, ", _pingOptions.DontFragment)); - s.Append(string.Format("TTL={0}", _pingOptions.Ttl)); - return s.ToString(); - } - public myResources(string sTarget, int iBytes, int iTime, int iTTL) - { - } - } - public class replyStats - { - public int sent=0; - public int rcvd=0; - public int percentLost - { - get - { - if (sent != 0) - return ((lost * 100) / sent); - else - return 100; - } - } - public long minTrip=0; - public long maxTrip=0; - public long avgTrip{ - get - { - if (sent == 0) - return 0; - if (tripValues.Count == 0) - return 0; - int sum = 0; - foreach (int v in tripValues) - sum += v; - int avg = sum / tripValues.Count; - return avg; - } - } - List tripValues=new List(); - string ipAddress = ""; - public int lost - { - get - { - return sent - rcvd; - } - } - public replyStats(string sIPaddress){ - ipAddress = sIPaddress; - minTrip = long.MaxValue; - maxTrip = 0; - } - public void add(int iSent, int iRcvd, long lTrip) - { - if (lTrip < minTrip) - minTrip = lTrip; - if (lTrip > maxTrip) - maxTrip = lTrip; - tripValues.Add(lTrip); - sent += iSent; - rcvd += iRcvd; - } - public override string ToString() - { - string s = string.Format(ReplyStats, ipAddress, - sent, rcvd, lost, percentLost, - minTrip, maxTrip, avgTrip); - return s; - } - const string ReplyStats = "Ping statistics for {0}:\r\n" + - " Packets: Sent = {1}, Received = {2}, Lost = {3} ({4}% loss),\r\n" + - "Approximate round trip times in milli-seconds:\r\n" + - " Minimum = {5}ms, Maximum = {6}ms, Average = {7}ms\r\n"; - } -} diff --git a/PingNG/doc/main.gif b/PingNG/doc/main.gif deleted file mode 100644 index e1c1df0..0000000 Binary files a/PingNG/doc/main.gif and /dev/null differ diff --git a/PingNG/doc/main2.gif b/PingNG/doc/main2.gif deleted file mode 100644 index 42d911d..0000000 Binary files a/PingNG/doc/main2.gif and /dev/null differ diff --git a/PingNG/doc/options_df.gif b/PingNG/doc/options_df.gif deleted file mode 100644 index 1ae5b17..0000000 Binary files a/PingNG/doc/options_df.gif and /dev/null differ diff --git a/PingNG/doc/ping192.txt b/PingNG/doc/ping192.txt deleted file mode 100644 index e6692e2..0000000 --- a/PingNG/doc/ping192.txt +++ /dev/null @@ -1,12 +0,0 @@ -ping started... -ttl=128, DF=False, buf=32, #p=4, timeout=1000 -Reply from 192.168.128.5: bytes=32 time=47ms TTL=128 -Reply from 192.168.128.5: bytes=32 time=4ms TTL=128 -Reply from 192.168.128.5: bytes=32 time=2ms TTL=128 -Reply from 192.168.128.5: bytes=32 time=4ms TTL=128 -Ping statistics for 192.168.128.5: - Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), -Approximate round trip times in milli-seconds: - Minimum = 2ms, Maximum = 47ms, Average = 14ms - -done diff --git a/PingNG/doc/ping_df_ok.txt b/PingNG/doc/ping_df_ok.txt deleted file mode 100644 index 4386708..0000000 --- a/PingNG/doc/ping_df_ok.txt +++ /dev/null @@ -1,12 +0,0 @@ -ping started... -ttl=128, DF=True, buf=1472, #p=4, timeout=1000 -Reply from 192.168.128.5: bytes=1472 time=8ms TTL=128 -Reply from 192.168.128.5: bytes=1472 time=5ms TTL=128 -Reply from 192.168.128.5: bytes=1472 time=4ms TTL=128 -Reply from 192.168.128.5: bytes=1472 time=6ms TTL=128 -Ping statistics for 192.168.128.5: - Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), -Approximate round trip times in milli-seconds: - Minimum = 4ms, Maximum = 8ms, Average = 5ms - -done \ No newline at end of file diff --git a/PingNG/doc/ping_df_too_big.txt b/PingNG/doc/ping_df_too_big.txt deleted file mode 100644 index b279e10..0000000 --- a/PingNG/doc/ping_df_too_big.txt +++ /dev/null @@ -1,12 +0,0 @@ -ping started... -ttl=128, DF=True, buf=1480, #p=4, timeout=1000 -IPStatus.PacketTooBig -IPStatus.PacketTooBig -IPStatus.PacketTooBig -IPStatus.PacketTooBig -Ping statistics for 192.168.128.5: - Packets: Sent = 4, Received = 0, Lost = 4 (100% loss), -Approximate round trip times in milli-seconds: - Minimum = 0ms, Maximum = 0ms, Average = 0ms - -done \ No newline at end of file diff --git a/ProjectHome.md b/ProjectHome.md new file mode 100644 index 0000000..668a4c6 --- /dev/null +++ b/ProjectHome.md @@ -0,0 +1 @@ +This googlecode is used for some of my windows mobile projects \ No newline at end of file diff --git a/RFIDwedge/Form1.Designer.cs b/RFIDwedge/Form1.Designer.cs deleted file mode 100644 index 6a8b765..0000000 --- a/RFIDwedge/Form1.Designer.cs +++ /dev/null @@ -1,111 +0,0 @@ -namespace RFID_Wedge -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.txtLog = new System.Windows.Forms.TextBox(); - this.txtTagData = new System.Windows.Forms.TextBox(); - this.txtTagID = new System.Windows.Forms.TextBox(); - this.btnConnect = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuExit); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // txtLog - // - this.txtLog.Location = new System.Drawing.Point(3, 143); - this.txtLog.Multiline = true; - this.txtLog.Name = "txtLog"; - this.txtLog.ReadOnly = true; - this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtLog.Size = new System.Drawing.Size(234, 122); - this.txtLog.TabIndex = 0; - this.txtLog.WordWrap = false; - // - // txtTagData - // - this.txtTagData.Location = new System.Drawing.Point(9, 60); - this.txtTagData.Name = "txtTagData"; - this.txtTagData.Size = new System.Drawing.Size(190, 21); - this.txtTagData.TabIndex = 1; - // - // txtTagID - // - this.txtTagID.Location = new System.Drawing.Point(9, 87); - this.txtTagID.Name = "txtTagID"; - this.txtTagID.Size = new System.Drawing.Size(190, 21); - this.txtTagID.TabIndex = 1; - // - // btnConnect - // - this.btnConnect.Location = new System.Drawing.Point(86, 14); - this.btnConnect.Name = "btnConnect"; - this.btnConnect.Size = new System.Drawing.Size(71, 26); - this.btnConnect.TabIndex = 2; - this.btnConnect.Text = "connect"; - this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.btnConnect); - this.Controls.Add(this.txtTagID); - this.Controls.Add(this.txtTagData); - this.Controls.Add(this.txtLog); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "Form1"; - this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.TextBox txtLog; - private System.Windows.Forms.TextBox txtTagData; - private System.Windows.Forms.TextBox txtTagID; - private System.Windows.Forms.Button btnConnect; - private System.Windows.Forms.MenuItem mnuExit; - } -} - diff --git a/RFIDwedge/Form1.cs b/RFIDwedge/Form1.cs deleted file mode 100644 index f7b6878..0000000 --- a/RFIDwedge/Form1.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using System.Runtime.InteropServices; - -namespace RFID_Wedge -{ - public partial class Form1 : Form - { - [DllImport("coredll.dll", EntryPoint = "keybd_event", SetLastError = true)] - private static extern void keybd_event(byte bVk, byte bScan, keyFlag dwFlags, int dwExtraInfo); - - [Flags] - enum keyFlag:int - { - KEYEVENTF_KEYDOWN = 0x0000, - KEYEVENTF_EXTENDEDKEY = 0x0001, //If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224). - KEYEVENTF_KEYUP = 0x0002 - } - - ThreadClass.myThread mThread; - - public Form1() - { - InitializeComponent(); - btnConnect_Click(this, new EventArgs()); - } - private void btnConnect_Click(object sender, EventArgs e) - { - if (mThread == null) - { - mThread = new ThreadClass.myThread(); - mThread.MyEvent += new EventHandler(mThread_MyEvent); - } - this.Hide(); - } - - public Object thisLock = new Object(); - - void mThread_MyEvent(object sender, ThreadClass.myThread.MyEventArgs e) - { - System.Diagnostics.Debug.WriteLine("Received event from thread: " + e.Message); - - lock (thisLock){ - //stringQueue.Enqueue(e.Message); - - //better do the following from a separate thread - byte[] bBuf = Encoding.ASCII.GetBytes(e.Message); - //only digits and letters are the same in Byte and VK_ values - - byte bVkey = 0x00; - bool bShift = false; - for (int i = 0; i < bBuf.Length; i++) - { - // System.Diagnostics.Debug.WriteLine("buffer: " + bBuf[i]); - //so start a translation - - bVkey = virtual_key_codes.vkTable[bBuf[i]].VKval; - bShift = virtual_key_codes.vkTable[bBuf[i]].bShift; - - if (bVkey != (byte)virtual_key_codes.V_KEY.VK_undef_0xff) - { - if (bShift) - { - keybd_event((byte)virtual_key_codes.V_KEY.VK_SHIFT, 0x00, keyFlag.KEYEVENTF_KEYDOWN, 0); - System.Threading.Thread.Sleep(2); - } - //send key - keybd_event(bVkey, 0x00, keyFlag.KEYEVENTF_KEYDOWN, 0); - System.Threading.Thread.Sleep(2); - keybd_event(bVkey, 0x00, keyFlag.KEYEVENTF_KEYUP, 0); - System.Threading.Thread.Sleep(2); - if (bShift) - { - keybd_event((byte)virtual_key_codes.V_KEY.VK_SHIFT, 0x00, keyFlag.KEYEVENTF_KEYUP, 0); - System.Threading.Thread.Sleep(2); - } - } - } - - } - } - - private void Form1_Closing(object sender, CancelEventArgs e) - { - System.Diagnostics.Debug.WriteLine("\n form closing..."); - if (mThread != null) - { - mThread.stopThread = true; - System.Threading.Thread.Sleep(1000); - } - mThread.Dispose(); - } - - private void mnuExit_Click(object sender, EventArgs e) - { - this.Close(); - } - } -} \ No newline at end of file diff --git a/RFIDwedge/Form1.resx b/RFIDwedge/Form1.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/RFIDwedge/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/RFIDwedge/Program.cs b/RFIDwedge/Program.cs deleted file mode 100644 index d5091b0..0000000 --- a/RFIDwedge/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace RFID_Wedge -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/RFIDwedge/Properties/AssemblyInfo.cs b/RFIDwedge/Properties/AssemblyInfo.cs deleted file mode 100644 index 04728ea..0000000 --- a/RFIDwedge/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("RFID_Wedge")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("RFID_Wedge")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("3561c7d0-9bc7-4c79-b513-510b6d6c9c50")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/RFIDwedge/Properties/Resources.Designer.cs b/RFIDwedge/Properties/Resources.Designer.cs deleted file mode 100644 index 2508e76..0000000 --- a/RFIDwedge/Properties/Resources.Designer.cs +++ /dev/null @@ -1,61 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.4952 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace RFID_Wedge.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RFID_Wedge.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - } -} diff --git a/RFIDwedge/Properties/Resources.resx b/RFIDwedge/Properties/Resources.resx deleted file mode 100644 index fdf135e..0000000 --- a/RFIDwedge/Properties/Resources.resx +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - - \ No newline at end of file diff --git a/RFIDwedge/RFID_Wedge.csproj b/RFIDwedge/RFID_Wedge.csproj deleted file mode 100644 index ea1e217..0000000 --- a/RFIDwedge/RFID_Wedge.csproj +++ /dev/null @@ -1,104 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {F00A4884-BC07-469D-940E-F35BBA40ED64} - WinExe - Properties - RFID_Wedge - RFID_Wedge - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - b2c48bd2-963d-4549-9169-1fa021dce484 - 5.2 - RFID_Wedge - v2.0 - Windows Mobile 6 Professional SDK - - - RFID_Wedge.Program - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - Form - - - Form1.cs - - - Component - - - - - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/RFIDwedge/RFID_Wedge.sln b/RFIDwedge/RFID_Wedge.sln deleted file mode 100644 index adbb27b..0000000 --- a/RFIDwedge/RFID_Wedge.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RFID_Wedge", "RFID_Wedge.csproj", "{F00A4884-BC07-469D-940E-F35BBA40ED64}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {F00A4884-BC07-469D-940E-F35BBA40ED64}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F00A4884-BC07-469D-940E-F35BBA40ED64}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F00A4884-BC07-469D-940E-F35BBA40ED64}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {F00A4884-BC07-469D-940E-F35BBA40ED64}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F00A4884-BC07-469D-940E-F35BBA40ED64}.Release|Any CPU.Build.0 = Release|Any CPU - {F00A4884-BC07-469D-940E-F35BBA40ED64}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/RFIDwedge/myThread.cs b/RFIDwedge/myThread.cs deleted file mode 100644 index d7139c4..0000000 --- a/RFIDwedge/myThread.cs +++ /dev/null @@ -1,756 +0,0 @@ -#define NORMALTAG -//change the above to read user TAG memory bank 3 -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Windows.Forms; - -using Intermec.DataCollection; -using Intermec.DataCollection.RFID; - -// USAGE: -//using ThreadClass; -//... -//ThreadClass.myThread mThread; -//private void button1_Click(object sender, EventArgs e) -//{ -// mThread = new myThread(); -// mThread.MyEvent += new EventHandler(onEvent); -//} -//public void onEvent(object o, ThreadClass.myThread.MyEventArgs s) -//{ -// System.Diagnostics.Debug.WriteLine("onEvent received: '" + s.Message + "'"); -// mThread.stopThread = true; -//} - -namespace ThreadClass -{ - public class myThread:Control,IDisposable - { - public class EventArgs : EventArgs - { - public EventArgs(T pValue) - { - m_value = pValue; - } - - private T m_value; - - public T Value - { - get { return m_value; } - } - } - public class MyEventArgs : EventArgs - { - private string msg; - - public MyEventArgs(string messageData) - { - msg = messageData; - } - public string Message - { - get { return msg; } - set { msg = value; } - } - } - - private EventHandler __MyEvent; - public event EventHandler MyEvent - { - add - { - lock (this) { __MyEvent += value; } - } - remove - { - lock (this) { __MyEvent -= value; } - } - } - - private EventHandler __pulseEvent; - public event EventHandler MyPulseEvent - { - add - { - lock (this) { __pulseEvent += value; } - } - remove - { - lock (this) { __pulseEvent -= value; } - } - } - private Thread m_Thread; - private bool m_stopThread = false; - public bool stopThread{ - get { return m_stopThread; } - set { m_stopThread = value; - if (m_stopThread) - m_Thread.Abort(); - } - } - private bool m_threadStopped = false; - public bool threadStopped - { - get { - lock (this) - { - return m_threadStopped; - } - } - } - - public myThread() - { - m_Thread = new Thread(new ThreadStart (this.threadWorker)); - m_Thread.Name = "my Worker Thread"; - m_Thread.Start(); - } - public void Dispose(){ - this.stopThread = true; - base.Dispose(); - } - private void threadWorker() - { - m_threadStopped = false; - System.Diagnostics.Debug.WriteLine("+++ Thread started"); - try - { - do - { - //DoSomething; - Thread.Sleep(1000); - doWork(); - //fire the event handlers - __MyEvent(this, new MyEventArgs("Hello from Thread")); - __pulseEvent(this, null); - } while (!m_stopThread); - } - catch (ThreadAbortException tx) - { - System.Diagnostics.Debug.WriteLine("ThreadAbortException: " + tx.Message + "\r\n ---Thread is aborted"); - } - finally - { - //switch off any LED - tools.SetLedStatus(3, tools.LedFlags.STATE_OFF); - } - m_threadStopped = true; - System.Diagnostics.Debug.WriteLine("\n---Thread stopped"); - } - - void doWork() - { - int iDelay = 0; bool bLEDoff = false; - logThis("Entering doWork()"); - while (!m_stopThread) - { - try - { - ConnectReader(); - while (m_Reader.IsConnected) - { - if (iDelay > 4) - { - tools.SetLedStatus(3, tools.LedFlags.STATE_ON); - bLEDoff = true; // need to turn off LED - iDelay = 0; - } - System.Threading.Thread.Sleep(200); - if (bLEDoff) - { - tools.SetLedStatus(3, tools.LedFlags.STATE_OFF); - bLEDoff = false; - } - iDelay++; - } - CloseReader(); - } - catch (BasicReaderException brx) - { - logThis("BasicReaderException in doWork(): " + brx.Message); - } - catch (BRIParserException bpx) - { - logThis("BRIParserException in doWork(): " + bpx.Message); - } - catch (Exception ex) - { - logThis("Exception in doWork(): " + ex.Message); - } - } - logThis("Leaving doWork()"); - } - - BasicBRIReader m_Reader = null; - bool m_bCenterEventProcessing = false; - public string sCurrentCMD; - Tag[] tags; - bool m_bEventLogging = true; - - private int OpenReader() - { - logThis("OpenReader..."); - BasicBRIReader.LoggerOptions LogOp = new BasicBRIReader.LoggerOptions(); - LogOp.LogFilePath = ".\\IDLClassDebugLog.txt"; - //LogOp.LogFilePath="\\Program Files\\IP4IDLAPP\\IDLClassDebugLog.txt"; - LogOp.ShowNonPrintableChars = true; - int res = 0; - try - { - if (m_Reader != null) - { - CloseReader(); - } - m_Reader = new BasicBRIReader(this, LogOp); - m_Reader.Open(); - AddEventHandlers(); - } - catch (BasicReaderException brx) - { - logThis("BasicReaderException in OpenReader(): " + brx.Message); - res = -1; - } - catch (SystemException sx) - { - logThis("SystemException in OpenReader(): " + sx.Message); - res = -2; - } - catch (Exception sx) - { - logThis("Exception in OpenReader(): " + sx.Message); - res = -2; - } - if (res != 0) - System.Threading.Thread.Sleep(5000); - return res; - } - /// - /// This function fires when the center trigger on the IP4 is pulled or released - /// - /// - /// - void brdr_EventHandlerCenterTrigger(object sender, BasicReaderEventArgs EvtArgs) - { - if (m_Reader.IsConnected == false) - { - //irda connection is still asleep after a 700 resume - return; - } - //avoid multiple processing -// if (m_bCenterEventProcessing) -// return; - m_bCenterEventProcessing = true; - /*CenterTriggerState*/ - /*EVT_CenterTrigger_EventArgs.STATE.PULLED*/ - if (EvtArgs.EventType.Equals(BasicReaderEventArgs.EventTypes.EVT_DCE) && // BasicReaderEventArgs.EventTypes.EVT_CENTER_TRIGGER) && - EvtArgs.EventData.Equals("BUTTON CENTER 1")) - { - #region Write Single TAG - #endregion -#if NORMALTAG - sCurrentCMD = "READ HEX(0,12)"; //TAGID -#else - sCurrentCMD = "READ HEX(3:0,12)"; //TAGID -#endif - // sCurrentCMD = "EPCID"; - if (ExecuteCMD(sCurrentCMD)) - { - logThis("OK READ HEX"); - } - else - { - logThis("failed"); - } - - } - m_bCenterEventProcessing = false; - } - - private int SetAttributes() - { - bool bStatus = false; - if (m_Reader.IsConnected == false) { return -1; } - sCurrentCMD = "ATTRIB TAGTYPE=EPCC1G2"; // comboBox1.Text; - bStatus = ExecuteCMD(sCurrentCMD); - if (bStatus == false) - { - logThis("SetAttrib failed, reader connected?"); - return -1; - } - else - { - logThis("RFID Connected"); - //This will set the Option IntermecSettings-RFID-Reader 1-Enable Reader - //Configuring the DCE Transport Programmatically Using BRI - Intermec.DataCollection.RFID.BasicBRIReader DCEConfig = new BasicBRIReader(null); - try - { - DCEConfig.Open("TCP://127.0.0.1:2189"); - // BRI device command. - DCEConfig.Execute("device 1 attrib adminstatus=on"); - DCEConfig.Close(); - return 0; - } - catch (BasicReaderException bex) - { - logThis("SetAttrib() DCEConfig could not connect to DCE: " + bex.Message); - return -2; - } - catch (Exception ex) - { - logThis("SetAttrib() DCEConfig exception " + ex.Message); - return -3; - } - } - } - - private bool ExecuteCMD(string tCMD) - { - if (m_Reader == null) - return false; - byte[] aFieldSeparator = { (byte)' ' }; - byte[] aRespBuf; - string tMsg = null; - logThis("Sending->" + tCMD); - try - { - if (m_Reader.IsConnected) - tMsg = m_Reader.Execute(tCMD); - else - { - logThis("Reader disconnected, please Connect"); - return false; - } - } - catch (BasicReaderException eBRI) - { - logThis("BasicReaderException: " + eBRI.ToString()); - return false; - } - catch (System.NullReferenceException nr) - { - logThis("Null Ref Exception: " + nr.Message); - logThis("stack: " + nr.StackTrace); - return false; - } - - // if tags were successfully read - if (tMsg.IndexOf("BRI ERR") >= 0) - System.Diagnostics.Debugger.Break(); - //"H112233445566778899001122 HE2001040\r\nOK>" - // System.Diagnostics.Debug.WriteLine("Msg: "+tMsg); - //Show TAG ID - #region READ EPCID/TAGID - if (sCurrentCMD.StartsWith("READ ")) //TAGID - { - if (tMsg.IndexOf("RDERR") >= 0) - { - //ChangeStatus(eStatus.TagReadError); - return false; - } - aRespBuf = tools.StrToByteArray(tMsg); - tags = BRIParser.GetTags(aRespBuf, aFieldSeparator); - System.Diagnostics.Debug.WriteLine("tags.Length: " + tags.Length); - - if (tags == null) - { - return false; - } - System.Diagnostics.Debug.WriteLine("Msg: " + tMsg); -#if !NORMALTAG - #region ReadUserMemory - // remove newline and carriage returns - tMsg = tMsg.Replace('\n', ' '); - tMsg = tMsg.Replace("\r",""); - string[] ids = tMsg.Split(' '); - // get the even arguments only - System.Diagnostics.Debug.WriteLine("id num " + ids.Length); - if (ids.Length > 1) - { - for (int j = 1; j < ids.Length; j+=2) - { - // System.Diagnostics.Debug.WriteLine("tag " +j+" "+ tags[j].ToString()); - string s = ids[j]; - System.Diagnostics.Debug.WriteLine(j + " Read id: " + s); - s = s.Substring(1,s.Length-1); - - for (int i = 0; i < s.Length; i++) - { - // remove first part of byte '3' - if (s.Substring(i, 1) == "3") s = s.Remove(i, 1); - else - { - // chop off ending zeroes - s = s.Substring(0, i); - break; - } - //System.Diagnostics.Debug.WriteLine(i+" length: "+start.Length+" newString " + start); - } - // make multiple tags comma delimited - string sOut = ""; - if (s.Length > 1) - { - //if (j != ids.Length - 2) s = s + ","; - for ( int i = 0; i < tags.Length; i++ ) - { - sOut += s[i]; - if (i != s.Length - 1) - sOut += ","; - } - s = sOut; - } - __MyEvent(this, new MyEventArgs(s)); - } - } - #endregion -#else -#region ReadNormalTagMemory - // make multiple tags comma delimited - string sOut = ""; - if (tags.Length > 1) - { - //if (j != ids.Length - 2) s = s + ","; - for ( int i = 0; i < tags.Length; i++ ) - { - sOut += tags[i]; - if (i != tags.Length - 1) - sOut += ","; - } - } - else{ - sOut = tags[0].ToString(); - } - __MyEvent(this, new MyEventArgs(sOut)); -#endregion -#endif - /* - #region READ single TAG - if (tags.Length == 1) - { - //read data from the tag - System.Diagnostics.Debug.WriteLine("READ TAGID tag data: " + tags[0].ToString()); - } - #endregion - * / - - //read tag data (aka EPCID) - /* - if (tMsg.StartsWith("H")) - { - string s; - s = tMsg.Substring(1, 24); - System.Diagnostics.Debug.WriteLine("Read data: " + s); - string[] args = tMsg.Split(' '); - if (args.Length > 1) - { - System.Diagnostics.Debug.WriteLine("Arg 2: " + args[1]); - string start = args[1].Substring(1,args[1].Length-1); - - for (int i = 0; i < start.Length; i++) - { - start = start.Remove(i, 1); - //System.Diagnostics.Debug.WriteLine(i+" length: "+start.Length+" newString " + start); - } - System.Diagnostics.Debug.WriteLine("final ver " + start); - - __MyEvent(this, new MyEventArgs(start)); - } - //txtTagID.Text = s; - } - */ - } - #endregion - #region ATTRIB - if (sCurrentCMD.Equals("ATTRIB TAGTYPE=EPCC1G2") == true) - { - if (tMsg.IndexOf("OK") >= 0) - return true; - else - return false; - } - if ((tMsg.IndexOf("ERR") >= 0) & (sCurrentCMD.Equals("ATTRIB SCHEDOPT=1") == false)) - { - //MessageBox.Show("Warning, BRI ERR occured for: " + tCMD + "\r\n" + tMsg); - logThis("BRI ERR for: " + tCMD + "\r\n" + tMsg); - return false; - } - #endregion - return true; - } - - private int ParseResponseMessage(string tMsg) - { - int x = 0; - string tString = ""; - char tChar = '0'; - - //just to make parsing code uniform - tMsg += "\r\n"; - - char[] tMyCharList = tMsg.ToCharArray(); - - //clear response list - int RspCount = 0; - - string[] RspMsgList = new string[1000]; - RspMsgList.Initialize(); - - //parse the response message - for (x = 0; x < tMyCharList.Length; x++) - { - tChar = tMyCharList[x]; - if (tChar.Equals('\n') == false & tChar.Equals('\r') == false) - { - tString += tChar; - } - else if (tChar.Equals('\r') == true) - { - RspCount++; - RspMsgList[RspCount] = tString; - tString = ""; - } - } - - //process the response messages - for (x = 1; x <= RspCount; x++) - { - if (RspMsgList[x].IndexOf("H") == 0 & RspMsgList[x].IndexOf("HOP") < 0) - { - //Tag Data - if (sCurrentCMD.Equals("R")) - { - //skip this data, its part of a bug work around regarding cont read modes - } - else - { - logThis(RspMsgList[x]); - } - } - else if (RspMsgList[x].IndexOf("OK>") == 0) - { - //end of reader response - if (sCurrentCMD.StartsWith("R") == false & sCurrentCMD.StartsWith("W") == false) - { - logThis(RspMsgList[x]); - } - break; - } - else if (sCurrentCMD.IndexOf("ATTRIB") == 0) - { - logThis(RspMsgList[x]); - } - else if (sCurrentCMD.IndexOf("UTIL") == 0) - { - logThis(RspMsgList[x]); - } - }//END for (x = 1; x <= RspCount; x++) - - return 0; - } - private void ConnectReader() - { - Cursor.Current = Cursors.WaitCursor; - System.Diagnostics.Debug.WriteLine("Opening Reader..."); - if (OpenReader() == 0) - { - System.Diagnostics.Debug.WriteLine("... Reader opened. Trying to set Attributes ..."); - //try first command - int res = SetAttributes(); - if (res != 0) - { - System.Diagnostics.Debug.WriteLine("... SetAttributes failed! Closing Reader"); - m_Reader.Close(); - m_Reader = null; - } - } - - if (m_Reader != null) - { - if (m_Reader.IsConnected) - { - System.Diagnostics.Debug.WriteLine("Reader connected. ChangeStatus(ReadBarcode)"); - } - else - { - System.Diagnostics.Debug.WriteLine("Reader connected. ChangeStatus(ReadBarcode)"); - } - } - - Cursor.Current = Cursors.Default; - } - private void CloseReader() - { - if (m_Reader != null) - try - { - if (m_Reader != null) - m_Reader.Close(); - RemoveEventHandlers(); - } - catch (BasicReaderException brx) - { - logThis("CloseReader(): " + brx.Message); - } - catch (SystemException sx) - { - logThis("CloseReader(): " + sx.Message); - } - finally - { - //ChangeStatus(eStatus.Offline); - } - } - /// - /// Add the event handler to handle the tag events and trigger pulls. - /// Not all of these are used but added as samples of what are available. - /// - /// - private int AddEventHandlers() - { - try - { - //this.m_Reader.EventHandlerRadio += new Radio_EventHandler(brdr_EventHandlerRadio); - //this.m_Reader.EventHandlerTag += new Tag_EventHandler(brdr_EventHandlerTag); - - //deprecated from v2.1: this.m_Reader.EventHandlerCenterTrigger += new CenterTrigger_EventHandler(brdr_EventHandlerCenterTrigger); - //deprecated from v2.1: this.m_Reader.EventHandlerDCE += new DCE_EventHandler(brdr_EventHandlerDCE); - - this.m_Reader.ReaderEvent += new BasicEvent(brdr_ReaderEventHandler); - - //this.m_Reader.EventHandlerOverflow += new Overflow_EventHandler(brdr_EventHandlerOverflow); - } - catch - { - MessageBox.Show("Exception trying to create event handlers"); - return -1; - } - return 0; - } - - public static void logThis(string s) - { - // System.Diagnostics.Debug.WriteLine("LOG: " + s); - try - { - System.IO.TextWriter tw = new System.IO.StreamWriter("\\RFIDWegdeLog.txt", true); - string dt = DateTime.Now.ToShortTimeString(); - tw.WriteLine(dt + ": " + s); - tw.Flush(); - tw.Close(); - - } - catch (Exception x) - { - System.Diagnostics.Debug.WriteLine("Exception: " + x.Message); - } - - } - private int RemoveEventHandlers() - { - try - { - //this.m_Reader.EventHandlerRadio -= brdr_EventHandlerRadio; - //this.m_Reader.EventHandlerTag -= brdr_EventHandlerTag; - - //deprecated from v2.1: this.m_Reader.EventHandlerCenterTrigger -= brdr_EventHandlerCenterTrigger; - //deprecated from v2.1: this.m_Reader.EventHandlerDCE -= brdr_EventHandlerDCE; - - this.m_Reader.ReaderEvent -= brdr_ReaderEventHandler; - - //this.m_Reader.EventHandlerOverflow -= brdr_EventHandlerOverflow; - } - catch - { - MessageBox.Show("Exception trying to create event handlers"); - return -1; - } - return 0; - } - void brdr_ReaderEventHandler(object sender, BasicReaderEventArgs EvtArgs) - { - System.Diagnostics.Debug.WriteLine("ReaderEvent: Type=" + EvtArgs.EventType.ToString() + - "\n\tEventData='" + EvtArgs.EventData + "'"); - switch ((int)EvtArgs.EventType) - { - /* - OLD: UNKNOWN = 1, - SHUTDOWN = 2, - BUTTON = 3, - DEVICE = 4, - EventTypes.EVT_BATTERY - EventTypes.EVT_CENTER_TRIGGER - EventTypes.EVT_DCE -Battery pulled - * ReaderEvent: Type=EVT_DCE - EventData='DEVICE 1 DISCONNECTED' - ReaderEvent: Type=EVT_DCE - EventData='DEVICE 1 CONNECTING' - The thread 0xc66b4f1a has exited with code 0 (0x0). - ReaderEvent: Type=EVT_DCE - EventData='DEVICE 1 CONNECTED' -Center Trigger - * ReaderEvent: Type=EVT_TRIGGER - EventData='TRIGPULL GPIO 0' - ReaderEvent: Type=EVT_DCE - EventData='BUTTON CENTER 1' - ReaderEvent: Type=EVT_TRIGGER - EventData='TRIGRELEASE GPIO 1' - ReaderEvent: Type=EVT_DCE - EventData='BUTTON CENTER 0' - - EventTypes.EVT_RADIO - EventTypes.EVT_READER_RECONNECTED - EventTypes.EVT_RESET - EventTypes.EVT_TAG - EventTypes.EVT_THERMAL - EventTypes.EVT_TRIGGER - EventTypes.EVT_TRIGGERACTION - */ - case (int)BasicReaderEventArgs.EventTypes.EVT_RADIO: - brdr_EventHandlerRadio(sender, EvtArgs); - break; - case (int)BasicReaderEventArgs.EventTypes.EVT_DCE: // EVT_CENTER_TRIGGER: - if (m_bEventLogging) - logThis("brdr_ReaderEvent() BUTTON:" + EvtArgs.EventData); - brdr_EventHandlerCenterTrigger(sender, EvtArgs); - break; - case (int)BasicReaderEventArgs.EventTypes.EVT_BATTERY: - case (int)BasicReaderEventArgs.EventTypes.EVT_CENTER_TRIGGER: - case (int)BasicReaderEventArgs.EventTypes.EVT_READER_RECONNECTED: - case (int)BasicReaderEventArgs.EventTypes.EVT_RESET: - case (int)BasicReaderEventArgs.EventTypes.EVT_TAG: - case (int)BasicReaderEventArgs.EventTypes.EVT_THERMAL: - case (int)BasicReaderEventArgs.EventTypes.EVT_TRIGGER: - case (int)BasicReaderEventArgs.EventTypes.EVT_TRIGGERACTION: - case (int)BasicReaderEventArgs.EventTypes.EVT_UNKNOWN: - if (m_bEventLogging) - { - logThis("brdr_ReaderEvent() type: " + Convert.ToString((Int16)EvtArgs.EventType) + "=" + EvtArgs.EventType.ToString()); - logThis("brdr_ReaderEvent() data: '" + EvtArgs.EventData + "'"); - } - break; - default: - // The DCE has encountered an undefined condition... - if (m_bEventLogging) - logThis("brdr_ReaderEvent(): Unknown Type " + Convert.ToString((Int16)EvtArgs.EventType) + " - Data: '" + EvtArgs.EventData + "'"); - //CloseReader(); - break; - } - } - void brdr_EventHandlerRadio(object sender, BasicReaderEventArgs EvtArgs) - { - int iTimeLeft = Convert.ToInt32(EvtArgs.EventData); - //pause a little bit to avoid duty cycle failures - logThis("duty time left=" + iTimeLeft.ToString() + "Sleeping 500ms..."); - System.Threading.Thread.Sleep(500); - logThis("...OK"); - //MessageBox.Show("brdr_EventHandlerRadio():\r\n" + iTimeLeft.ToString()); - if (m_bEventLogging) - logThis("brdr_EventHandlerRadio() TimeLeft: " + iTimeLeft.ToString()); - } - - } -} diff --git a/RFIDwedge/tools.cs b/RFIDwedge/tools.cs deleted file mode 100644 index 27ddcb3..0000000 --- a/RFIDwedge/tools.cs +++ /dev/null @@ -1,361 +0,0 @@ -using System; -using System.IO; -using System.Collections; -using System.Collections.Generic; -using System.Windows.Forms; - -using System.Runtime.InteropServices; - - public class tools - { - public static string ReverseString(string s) - { - int i = 0; - string str=""; - for (i = s.Length-1; i >= 0; i--) - { - str = str + s.Substring(i, 1); - } - return str; - } - - /// - /// Copy a string until a \r appears - /// - /// input string - /// string cutdown to \r - public static string CopyToR(string s) - { - int i = 0; - string t = ""; - while (s.Substring(i, 1) != "\r") - { - t += s.Substring(i, 1); - i++; - } - return t; - } - /// - /// C# to convert a string to a byte array. - /// - /// - /// sbyte[] - public static sbyte[] StrToSByteArray(string str) - { - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - byte[] src = new byte[str.Length]; - sbyte[] dest = new sbyte[src.Length]; - src = encoding.GetBytes(str); - System.Buffer.BlockCopy(src, 0, dest, 0, src.Length); - return dest; - } - public static byte[] StrToByteArray(string str) - { - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - byte[] src = new byte[str.Length]; - src = encoding.GetBytes(str); - return src; - } - - #region NLED - // see also http://community.opennetcf.com/forums/t/80.aspx - /// - /// LED manipulation - /// - /// Normal use: - /// First, get the count of LED's by calling GetLedCount() - /// Second, if the number of LED's is greater than zero, set the state of each desired LED - /// by calling SetLedStatus(led #, flag) where the first LED is zero and the flag is defined - /// by one of the LedFlags enumerations - /// - - [Flags] - public enum LedFlags : int - { - STATE_OFF = 0x0000, /* dark LED */ - STATE_ON = 0x0001, /* light LED */ - STATE_BLINK = 0x0002, /* flashing LED */ - } - - public const Int32 NLED_COUNT_INFO_ID = 0; - public const Int32 NLED_SUPPORTS_INFO_ID = 1; - public const Int32 NLED_SETTINGS_INFO_ID = 2; - - public class NLED_COUNT_INFO - { - public UInt32 cLeds; - } - - public class NLED_SUPPORTS_INFO - { - public UInt32 Lednum; - public Int32 lCycleAdjust; - public bool fAdjustTotalCycleTime; - public bool fAdjustOnTime; - public bool fAdjustOffTime; - public bool fMetaCycleOn; - public bool fMetaCycleOff; - }; - - public class NLED_SETTINGS_INFO - { - public UInt32 LedNum; - public LedFlags OnOffBlink; - public Int32 TotalCycleTime; - public Int32 OnTime; - public Int32 OffTime; - public Int32 MetaCycleOn; - public Int32 MetaCycleoff; - }; - - [DllImport("CoreDll")] - private extern static bool NLedGetDeviceInfo(Int32 nID, NLED_COUNT_INFO nci); - - [DllImport("CoreDll")] - private extern static bool NLedGetDeviceInfo(Int32 nID, NLED_SUPPORTS_INFO nsi); - - [DllImport("CoreDll")] - private extern static bool NLedGetDeviceInfo(Int32 nID, NLED_SETTINGS_INFO nsi); - - [DllImport("CoreDll")] - private extern static bool NLedSetDevice(Int32 nID, NLED_SETTINGS_INFO nsi); - - public static uint GetLedCount() - { - NLED_COUNT_INFO nci = new NLED_COUNT_INFO(); - - uint LedCount = 0; - - if (NLedGetDeviceInfo(NLED_COUNT_INFO_ID, nci)) - LedCount = nci.cLeds; - - return LedCount; - } - - public static bool SetLedStatus(uint nLed, LedFlags fState) - { - NLED_SETTINGS_INFO nsi = new NLED_SETTINGS_INFO(); - - nsi.LedNum = nLed; - nsi.OnOffBlink = fState; - - return NLedSetDevice(NLED_SETTINGS_INFO_ID, nsi); - } - #endregion - - #region NewStuff - //=============================================================================================== - // New stuff - //=============================================================================================== - - /// - /// takes a string of 0s and 1s and returns a uint - /// - /// a 'binary' string of 0s and 1s - /// - public static UInt32 BinStr2Uint(string s) - { - int maxbits = s.Length; - int i; - UInt32 u=0; - //s[s.lenghth] = Bit[0] - //start at end of string, highest bit - for (i = 0; i < maxbits ; i++) - { - if (s.Substring( i, 1).Equals("1")) - { - u += (uint)Math.Pow(2, i); - } - } - return u; - } - - /// - /// convert an uint to a BinStr - /// - /// - /// a BinStr of 0s and 1s, lowest bit left - public static string Uint2BinStr(UInt32 u) - { - int maxbits = 32; - UInt32 u32 = u; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (u32 >= Math.Pow(2, i-1)) - { - s = "1" + s; - u32 -= (UInt32)Math.Pow(2, i-1); - } - else - s = "0" + s; - } - s.PadRight(32, '0'); - return s; - } - - /// - /// get binary string in reverse order - /// - /// - /// - /// - public static string Uint2BinStr(UInt32 u, int bitcount) - { - //49977473 -> //10111110101001100010000001 - //123456789 -> 00000111010110111100110100010101 - // "00000111 01011011 11001101 00010101 - // " - string s = Uint2BinStr(u); - if (s.Length > bitcount) - { - s = s.Substring(0, bitcount); - } - else if (s.Length < bitcount) - s = s.PadRight(bitcount, '0'); - return s; - } - - /// - /// Convert a BinStr ie '01010011' to a hex string '53'hex - /// - /// - /// a hex str - public static string BinStr2HexStr(string BinStr) - { - //convert byte by byte - string sHex2=""; - string sBin8=""; - string sHex=""; - string sBin = BinStr; - byte b = 0; - //ensure a binstr dividable by 8 - if (sBin.Length % 8 > 0) //is there any rest? - { - int l = sBin.Length; - int c = l / 8; - c++; - c = c * 8; - l = c - l; - for (int i = 0; i < l; i++) - sBin = sBin + "0"; - } - //start at lowest bit - while (sBin.Length > 0) - { - sBin8 = sBin.Substring(0, 8); //01010011 - b = (byte)BinStr2Uint(sBin); - sHex2 = Convert.ToString(b, 16); //0x53 - sHex = sHex2.PadLeft(2,'0') + sHex ; - sBin = sBin.Substring(8); - } - return sHex; - } - /// - /// convert a BinStr to a Hex string - /// - /// - /// the Byte width, ie 12 means you get a string with 24 letters - /// each byte is translated to a two-letter hex str - /// - public static string BinStr2HexStr(string BinStr, int ByteWidth) - { - string HexStr = BinStr2HexStr(BinStr); - if (HexStr.Length < ByteWidth) //pad left with '0' - HexStr = HexStr.PadLeft(ByteWidth*2, '0'); - else if (HexStr.Length > ByteWidth) //return right part, cut left - HexStr = HexStr.Substring(HexStr.Length - (ByteWidth * 2), ByteWidth * 2); - return HexStr; - } - - public static char[] HexStr2CharAr(string sHex) - { - char[] c; - string sBin = ""; - sBin = HexStr2BinStr(sHex); - c=BinStr2CharAr(sBin); - return c; - } - - public static string CharAr2HexStr(char[] c) - { - string s = ""; - string sBin = ""; - sBin = CharAr2BinStr(c); - s = BinStr2HexStr(sBin); - return s; - } - - public static string HexStr2BinStr(string hex) - { - byte b; - string BinStr = ""; - string sBin8 = ""; - string hex2 = ""; - if (hex.Length == 24) - { - //from left to right //34 ....... - for (int i = 0; i < 12; i++) - { //0-1-2-3-4- 5- 6- 7- 8- 9-10-11 - hex2 = hex.Substring(i*2, 2);//start at right, 0-2-4-6-8-10-12-14-16-18-20-22 - b = Convert.ToByte(hex2, 16); - sBin8 = Uint2BinStr(b).Substring(0,8); - BinStr = sBin8 + BinStr ; - } - } - if (!BinStr2HexStr(BinStr).Equals(hex.ToLower())) - System.Diagnostics.Debugger.Break(); - return BinStr; - } - - /// - /// convert a BinStr to a char[] array - /// - /// - /// - public static char[] BinStr2CharAr(string BinStr) - { - int bitcount = BinStr.Length; - if (BinStr.Length > 96) - BinStr = BinStr.Substring(0,96);//limit bitcount to 96 - else if (BinStr.Length < 96) - BinStr = BinStr.PadRight(96, '0'); - - char[] c = new char[96]; - for (int i = 0; i < 96; i++) - { - if (BinStr.Substring(i, 1).Equals("1")) - c[i] = '1'; - else - c[i] = '0'; - } - return c; - } - /// - /// convert a char[] to BinStr (substr(0,1)=char[0] - /// BinStr highest Bit at RIGHT! - /// - /// - /// - public static string CharAr2BinStr(char[] c) - { - int bitcount = c.Length; - string s = ""; - for (int i = 0; i < bitcount; i++) - { - if (c[i] == '1') - s = s + "1"; - else - s = s + "0"; - } - if (s.Length < 96) - s.PadRight(96, '0'); - else if (s.Length > 96) - s = s.Substring(0, 96); - return s; - } -#endregion - } diff --git a/RFIDwedge/virtual_key_codes.cs b/RFIDwedge/virtual_key_codes.cs deleted file mode 100644 index d96728c..0000000 --- a/RFIDwedge/virtual_key_codes.cs +++ /dev/null @@ -1,564 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -namespace RFID_Wedge -{ - static class virtual_key_codes - { - /// - /// a list of known VKEY values as enumeration - /// - public enum V_KEY : byte - { - VK_NULL, - VK_LBUTTON, - VK_RBUTTON, - VK_CANCEL, - VK_MBUTTON, - undef_0x05, - undef_0x06, - undef_0x07, - VK_BACK, - VK_TAB, - undef_0x0A, - undef_0x0B, - VK_CLEAR, - VK_RETURN, - undef_0x0E, - undef_0x0F, - VK_SHIFT, - VK_CONTROL, - VK_MENU, - VK_PAUSE, - VK_CAPITAL, - VK_HANGUL, - undef_0x16, - VK_JUNJA, - VK_FINAL, - VK_KANJI, - undef_0x1A, - VK_ESCAPE, - VK_CONVERT, - VK_NOCONVERT, - undef_0x1E, - undef_0x1F, - VK_SPACE, - VK_PRIOR, - VK_NEXT, - VK_END, - VK_HOME, - VK_LEFT, - VK_UP, - VK_RIGHT, - VK_DOWN, - VK_SELECT, - VK_PRINT, - VK_EXECUTE, - VK_SNAPSHOT, - VK_INSERT, - VK_DELETE, - VK_HELP, - VK_0, - VK_1, - VK_2, - VK_3, - VK_4, - VK_5, - VK_6, - VK_7, - VK_8, - VK_9, - undef_0x3A, - undef_0x3B, - undef_0x3C, - undef_0x3D, - undef_0x3E, - undef_0x3F, - undef_0x40, - VK_A, - VK_B, - VK_C, - VK_D, - VK_E, - VK_F, - VK_G, - VK_H, - VK_I, - VK_J, - VK_K, - VK_L, - VK_M, - VK_N, - VK_O, - VK_P, - VK_Q, - VK_R, - VK_S, - VK_T, - VK_U, - VK_V, - VK_W, - VK_X, - VK_Y, - VK_Z, - VK_LWIN, - VK_RWIN, - VK_APPS, - undef_0x5E, - VK_SLEEP, - VK_NUMPAD0, - VK_NUMPAD1, - VK_NUMPAD2, - VK_NUMPAD3, - VK_NUMPAD4, - VK_NUMPAD5, - VK_NUMPAD6, - VK_NUMPAD7, - VK_NUMPAD8, - VK_NUMPAD9, - VK_MULTIPLY, - VK_ADD, - VK_SEPARATOR, - VK_SUBTRACT, - VK_DECIMAL, - VK_DIVIDE, - VK_F1, - VK_F2, - VK_F3, - VK_F4, - VK_F5, - VK_F6, - VK_F7, - VK_F8, - VK_F9, - VK_F10, - VK_F11, - VK_F12, - VK_F13, - VK_F14, - VK_F15, - VK_F16, - VK_F17, - VK_F18, - VK_F19, - VK_F20, - VK_F21, - VK_F22, - VK_F23, - VK_F24, - undef_0x88, - undef_0x89, - undef_0x8A, - undef_0x8B, - undef_0x8C, - undef_0x8D, - undef_0x8E, - undef_0x8F, - VK_NUMLOCK, - VK_SCROLL, - undef_0x92, - undef_0x93, - undef_0x94, - undef_0x95, - undef_0x96, - undef_0x97, - undef_0x98, - undef_0x99, - undef_0x9A, - undef_0x9B, - undef_0x9C_light, //0x9c controls screen backlight on CN50 - undef_0x9D, - undef_0x9E, - undef_0x9F, - VK_LSHIFT, - VK_RSHIFT, - VK_LCONTROL, - VK_RCONTROL, - VK_LMENU, - VK_RMENU, - VK_BROWSER_BACK, - VK_BROWSER_FORWARD, - VK_BROWSER_REFRESH, - VK_BROWSER_STOP, - VK_BROWSER_SEARCH, - VK_BROWSER_FAVORITES, - VK_BROWSER_HOME, - VK_VOLUME_MUTE, - VK_VOLUME_DOWN, - VK_VOLUME_UP, - VK_MEDIA_NEXT_TRACK, - VK_MEDIA_PREV_TRACK, - VK_MEDIA_STOP, - VK_MEDIA_PLAY_PAUSE, - VK_LAUNCH_MAIL, - VK_LAUNCH_MEDIA_SELECT, - VK_LAUNCH_APP1, - VK_LAUNCH_APP2, - undef_0xB8, - undef_0xB9, - VK_SEMICOLON, - VK_EQUAL, - VK_COMMA, - VK_HYPHEN, - VK_PERIOD, - VK_SLASH, - VK_BACKQUOTE, - VK_APP1, - VK_APP2, - VK_APP3, - VK_APP4, - VK_APP5, - VK_APP6, - undef_0xC7, - undef_0xC8, - undef_0xC9, - undef_0xCA, - undef_0xCB, - undef_0xCC, - undef_0xCD, - undef_0xCE, - undef_0xCF, - undef_0xD0, - undef_0xD1, - undef_0xD2, - undef_0xD3, - undef_0xD4, - undef_0xD5, - undef_0xD6, - undef_0xD7, - undef_0xD8, - undef_0xD9, - undef_0xDA, - VK_LBRACKET, - VK_BACKSLASH, - VK_RBRACKET, - VK_APOSTROPHE, - VK_OFF, - undef_0xE0, - undef_0xE1_SCAN, - VK_EXTEND_BSLASH, - undef_0xE3, - undef_0xE4, - VK_PROCESSKEY, - undef_0xE6, - undef_0xE7, - undef_0xE8, - undef_0xE9, - undef_0xEA, - undef_0xEB, - undef_0xEC, - undef_0xED, - undef_0xEE, - undef_0xEF, - undef_0xF0, - undef_0xF1, - undef_0xF2, - undef_0xF3, - undef_0xF4, - undef_0xF5, - VK_ATTN, - VK_CRSEL, - VK_EXSEL, - VK_EREOF, - VK_PLAY, - VK_ZOOM, - VK_NONAME, - VK_PA1, - VK_OEM_CLEAR, - VK_undef_0xff - } - - // the struct used to save a ASCII <-> VK_ table - public class KTABLE{ - byte kByte; // key byte - string txt; // description - byte kVKval; //the VK value to send for kByte - public byte VKval - { - get { return kVKval; } - } - bool kShift; - public bool bShift - { - get { return kShift; } - } - public KTABLE(byte b, string s, byte val, bool bShift){ - kByte=b; - txt=s; - kVKval = val; - kShift = bShift; - } - public KTABLE(byte b, string s, V_KEY val, bool bShift) - { - kByte = b; - txt = s; - kVKval = (byte)val; - kShift = bShift; - } - }; - - // the translation tabel for ASCII to VK_ values - // first val is byte code to translate and third val is VK_ value to be used with keybd_event and other VK_ functions - public static KTABLE[] vkTable = { - new KTABLE (0x00, "NUL", V_KEY.VK_NULL, false), - new KTABLE (0x01, "SOH", V_KEY.VK_undef_0xff, false), - new KTABLE (0x02, "STX", V_KEY.VK_undef_0xff, false), - new KTABLE (0x03, "ETX", V_KEY.VK_undef_0xff, false), - new KTABLE (0x04, "EOT", V_KEY.VK_undef_0xff, false), - new KTABLE (0x05, "ENQ", V_KEY.VK_undef_0xff, false), - new KTABLE (0x06, "ACK", V_KEY.VK_undef_0xff, false), - new KTABLE (0x07, "BEL", V_KEY.VK_undef_0xff, false), - new KTABLE (0x08, "BS", V_KEY.VK_BACK, false), - new KTABLE (0x09, "HT", V_KEY.VK_TAB, false), - new KTABLE (0x0A, "LF", V_KEY.VK_RETURN, false), - new KTABLE (0x0B, "VT", V_KEY.VK_TAB, false), - new KTABLE (0x0C, "FF", V_KEY.VK_undef_0xff, false), - new KTABLE (0x0D, "CR", V_KEY.VK_RETURN, false), - new KTABLE (0x0E, "SO", V_KEY.VK_undef_0xff, false), - new KTABLE (0x0F, "SI", V_KEY.VK_undef_0xff, false), - new KTABLE (0x10, "DLE", V_KEY.VK_undef_0xff, false), - new KTABLE (0x11, "DC1", V_KEY.VK_undef_0xff, false), - new KTABLE (0x12, "DC2", V_KEY.VK_undef_0xff, false), - new KTABLE (0x13, "DC3", V_KEY.VK_undef_0xff, false), - new KTABLE (0x14, "DC4", V_KEY.VK_undef_0xff, false), - new KTABLE (0x15, "NAK", V_KEY.VK_undef_0xff, false), - new KTABLE (0x16, "SYN", V_KEY.VK_undef_0xff, false), - new KTABLE (0x17, "ETB", V_KEY.VK_undef_0xff, false), - new KTABLE (0x18, "CAN", V_KEY.VK_undef_0xff, false), - new KTABLE (0x19, "EM", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1A, "SUB", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1B, "ESC", V_KEY.VK_ESCAPE, false), - new KTABLE (0x1C, "FS", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1D, "GS", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1E, "RS", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1F, "US", V_KEY.VK_undef_0xff, false), - new KTABLE (0x20, " ", V_KEY.VK_SPACE, false), - new KTABLE (0x21, "!", V_KEY.VK_1, true), - new KTABLE (0x22, "\"", V_KEY.VK_APOSTROPHE, true), - new KTABLE (0x23, "#", V_KEY.VK_3, true), - new KTABLE (0x24, "$", V_KEY.VK_4, true), - new KTABLE (0x25, "%", V_KEY.VK_5, true), - new KTABLE (0x26, "&", V_KEY.VK_7, true), - new KTABLE (0x27, "'", V_KEY.VK_APOSTROPHE, false), - new KTABLE (0x28, "(", V_KEY.VK_9, true), - new KTABLE (0x29, ")", V_KEY.VK_0, true), - new KTABLE (0x2A, "*", V_KEY.VK_8, true), - new KTABLE (0x2B, "+", V_KEY.VK_EQUAL, true), - new KTABLE (0x2C, ",", V_KEY.VK_COMMA, false), - new KTABLE (0x2D, "-", V_KEY.VK_HYPHEN, false), - new KTABLE (0x2E, ".", V_KEY.VK_PERIOD, false), - new KTABLE (0x2F, "/", V_KEY.VK_SLASH, false), - new KTABLE (0x30, "0", V_KEY.VK_0, false), - new KTABLE (0x31, "1", V_KEY.VK_1, false), - new KTABLE (0x32, "2", V_KEY.VK_2, false), - new KTABLE (0x33, "3", V_KEY.VK_3, false), - new KTABLE (0x34, "4", V_KEY.VK_4, false), - new KTABLE (0x35, "5", V_KEY.VK_5, false), - new KTABLE (0x36, "6", V_KEY.VK_6, false), - new KTABLE (0x37, "7", V_KEY.VK_7, false), - new KTABLE (0x38, "8", V_KEY.VK_8, false), - new KTABLE (0x39, "9", V_KEY.VK_9, false), - new KTABLE (0x3A, ":", V_KEY.VK_SEMICOLON, true), - new KTABLE (0x3B, ";", V_KEY.VK_SEMICOLON, false), - new KTABLE (0x3C, "<", V_KEY.VK_COMMA, true), - new KTABLE (0x3D, "=", V_KEY.VK_EQUAL, false), - new KTABLE (0x3E, ">", V_KEY.VK_PERIOD, true), - new KTABLE (0x3F, "?", V_KEY.VK_SLASH, true), - new KTABLE (0x40, "@", V_KEY.VK_2, true), - new KTABLE (0x41, "A", V_KEY.VK_A, true), - new KTABLE (0x42, "B", V_KEY.VK_B, true), - new KTABLE (0x43, "C", V_KEY.VK_C, true), - new KTABLE (0x44, "D", V_KEY.VK_D, true), - new KTABLE (0x45, "E", V_KEY.VK_E, true), - new KTABLE (0x46, "F", V_KEY.VK_F, true), - new KTABLE (0x47, "G", V_KEY.VK_G, true), - new KTABLE (0x48, "H", V_KEY.VK_H, true), - new KTABLE (0x49, "I", V_KEY.VK_I, true), - new KTABLE (0x4A, "J", V_KEY.VK_J, true), - new KTABLE (0x4B, "K", V_KEY.VK_K, true), - new KTABLE (0x4C, "L", V_KEY.VK_L, true), - new KTABLE (0x4D, "M", V_KEY.VK_M, true), - new KTABLE (0x4E, "N", V_KEY.VK_N, true), - new KTABLE (0x4F, "O", V_KEY.VK_O, true), - new KTABLE (0x50, "P", V_KEY.VK_P, true), - new KTABLE (0x51, "Q", V_KEY.VK_Q, true), - new KTABLE (0x52, "R", V_KEY.VK_R, true), - new KTABLE (0x53, "S", V_KEY.VK_S, true), - new KTABLE (0x54, "T", V_KEY.VK_T, true), - new KTABLE (0x55, "U", V_KEY.VK_U, true), - new KTABLE (0x56, "V", V_KEY.VK_V, true), - new KTABLE (0x57, "W", V_KEY.VK_W, true), - new KTABLE (0x58, "X", V_KEY.VK_X, true), - new KTABLE (0x59, "Y", V_KEY.VK_Y, true), - new KTABLE (0x5A, "Z", V_KEY.VK_Z, true), - new KTABLE (0x5B, "[", V_KEY.VK_LBRACKET, false), - new KTABLE (0x5C, "\\", V_KEY.VK_BACKSLASH, false), - new KTABLE (0x5D, "]", V_KEY.VK_RBRACKET, false), - new KTABLE (0x5E, "^", V_KEY.VK_6, true), - new KTABLE (0x5F, "_", V_KEY.VK_HYPHEN, true), - new KTABLE (0x60, "`", V_KEY.VK_BACKQUOTE, false), - new KTABLE (0x61, "a", V_KEY.VK_A, false), - new KTABLE (0x62, "b", V_KEY.VK_B, false), - new KTABLE (0x63, "c", V_KEY.VK_C, false), - new KTABLE (0x64, "d", V_KEY.VK_D, false), - new KTABLE (0x65, "e", V_KEY.VK_E, false), - new KTABLE (0x66, "f", V_KEY.VK_F, false), - new KTABLE (0x67, "g", V_KEY.VK_G, false), - new KTABLE (0x68, "h", V_KEY.VK_H, false), - new KTABLE (0x69, "i", V_KEY.VK_I, false), - new KTABLE (0x6A, "j", V_KEY.VK_J, false), - new KTABLE (0x6B, "k", V_KEY.VK_K, false), - new KTABLE (0x6C, "l", V_KEY.VK_L, false), - new KTABLE (0x6D, "m", V_KEY.VK_M, false), - new KTABLE (0x6E, "n", V_KEY.VK_N, false), - new KTABLE (0x6F, "o", V_KEY.VK_O, false), - new KTABLE (0x70, "p", V_KEY.VK_P, false), - new KTABLE (0x71, "q", V_KEY.VK_Q, false), - new KTABLE (0x72, "r", V_KEY.VK_R, false), - new KTABLE (0x73, "s", V_KEY.VK_S, false), - new KTABLE (0x74, "t", V_KEY.VK_T, false), - new KTABLE (0x75, "u", V_KEY.VK_U, false), - new KTABLE (0x76, "v", V_KEY.VK_V, false), - new KTABLE (0x77, "w", V_KEY.VK_W, false), - new KTABLE (0x78, "x", V_KEY.VK_X, false), - new KTABLE (0x79, "y", V_KEY.VK_Y, false), - new KTABLE (0x7A, "z", V_KEY.VK_Z, false), - new KTABLE (0x7B, "{", V_KEY.VK_LBRACKET, true), - new KTABLE (0x7C, "|", V_KEY.VK_BACKSLASH, true), - new KTABLE (0x7D, "}", V_KEY.VK_RBRACKET, true), - new KTABLE (0x7E, "~", V_KEY.VK_BACKQUOTE, true), - new KTABLE (0x7F, "DEL", V_KEY.VK_DELETE, false), - //this will not come from ASCII barcode readers - new KTABLE (0x80, "\x80", 0x80, true), - new KTABLE (0x81, "\x81", 0x81, true), - new KTABLE (0x82, "\x82", 0x82, true), - new KTABLE (0x83, "\x83", 0x83, true), - new KTABLE (0x84, "\x84", 0x84, true), - new KTABLE (0x85, "\x85", 0x85, true), - new KTABLE (0x86, "\x86", 0x86, true), - new KTABLE (0x87, "\x87", 0x87, true), - new KTABLE (0x88, "\x88", 0x88, true), - new KTABLE (0x89, "\x89", 0x89, true), - new KTABLE (0x8A, "\x8A", 0x8A, true), - new KTABLE (0x8B, "\x8B", 0x8B, true), - new KTABLE (0x8C, "\x8C", 0x8C, true), - new KTABLE (0x8D, "\x8D", 0x8D, true), - new KTABLE (0x8E, "\x8E", 0x8E, true), - new KTABLE (0x8F, "\x8F", 0x8F, true), - new KTABLE (0x90, "\x90", 0x90, true), - new KTABLE (0x91, "\x91", 0x91, true), - new KTABLE (0x92, "\x92", 0x92, true), - new KTABLE (0x93, "\x93", 0x93, true), - new KTABLE (0x94, "\x94", 0x94, true), - new KTABLE (0x95, "\x95", 0x95, true), - new KTABLE (0x96, "\x96", 0x96, true), - new KTABLE (0x97, "\x97", 0x97, true), - new KTABLE (0x98, "\x98", 0x98, true), - new KTABLE (0x99, "\x99", 0x99, true), - new KTABLE (0x9A, "\x9A", 0x9A, true), - new KTABLE (0x9B, "\x9B", 0x9B, true), - new KTABLE (0x9C, "\x9C", 0x9C, true), - new KTABLE (0x9D, "\x9D", 0x9D, true), - new KTABLE (0x9E, "\x9E", 0x9E, true), - new KTABLE (0x9F, "\x9F", 0x9F, true), - new KTABLE (0xA0, "\xA0", 0xA0, true), - new KTABLE (0xA1, "¡", 0xA1, true), - new KTABLE (0xA2, "¢", 0xA2, true), - new KTABLE (0xA3, "£", 0xA3, true), - new KTABLE (0xA4, "¤", 0xA4, true), - new KTABLE (0xA5, "¥", 0xA5, true), - new KTABLE (0xA6, "¦", 0xA6, true), - new KTABLE (0xA7, "§", 0xA7, true), - new KTABLE (0xA8, "¨", 0xA8, true), - new KTABLE (0xA9, "©", 0xA9, true), - new KTABLE (0xAA, "ª", 0xAA, true), - new KTABLE (0xAB, "«", 0xAB, true), - new KTABLE (0xAC, "¬", 0xAC, true), - new KTABLE (0xAD, "­", 0xAD, true), - new KTABLE (0xAE, "®", 0xAE, true), - new KTABLE (0xAF, "¯", 0xAF, true), - new KTABLE (0xB0, "°", 0xB0, true), - new KTABLE (0xB1, "±", 0xB1, true), - new KTABLE (0xB2, "²", 0xB2, true), - new KTABLE (0xB3, "³", 0xB3, true), - new KTABLE (0xB4, "´", 0xB4, true), - new KTABLE (0xB5, "µ", 0xB5, true), - new KTABLE (0xB6, "¶", 0xB6, true), - new KTABLE (0xB7, "·", 0xB7, true), - new KTABLE (0xB8, "¸", 0xB8, true), - new KTABLE (0xB9, "¹", 0xB9, true), - new KTABLE (0xBA, "º", 0xBA, true), - new KTABLE (0xBB, "»", 0xBB, true), - new KTABLE (0xBC, "¼", 0xBC, true), - new KTABLE (0xBD, "½", 0xBD, true), - new KTABLE (0xBE, "¾", 0xBE, true), - new KTABLE (0xBF, "¿", 0xBF, true), - new KTABLE (0xC0, "À", 0xC0, true), - new KTABLE (0xC1, "Á", 0xC1, true), - new KTABLE (0xC2, "Â", 0xC2, true), - new KTABLE (0xC3, "Ã", 0xC3, true), - new KTABLE (0xC4, "Ä", 0xC4, true), - new KTABLE (0xC5, "Å", 0xC5, true), - new KTABLE (0xC6, "Æ", 0xC6, true), - new KTABLE (0xC7, "Ç", 0xC7, true), - new KTABLE (0xC8, "È", 0xC8, true), - new KTABLE (0xC9, "É", 0xC9, true), - new KTABLE (0xCA, "Ê", 0xCA, true), - new KTABLE (0xCB, "Ë", 0xCB, true), - new KTABLE (0xCC, "Ì", 0xCC, true), - new KTABLE (0xCD, "Í", 0xCD, true), - new KTABLE (0xCE, "Î", 0xCE, true), - new KTABLE (0xCF, "Ï", 0xCF, true), - new KTABLE (0xD0, "Ð", 0xD0, true), - new KTABLE (0xD1, "Ñ", 0xD1, true), - new KTABLE (0xD2, "Ò", 0xD2, true), - new KTABLE (0xD3, "Ó", 0xD3, true), - new KTABLE (0xD4, "Ô", 0xD4, true), - new KTABLE (0xD5, "Õ", 0xD5, true), - new KTABLE (0xD6, "Ö", 0xD6, true), - new KTABLE (0xD7, "×", 0xD7, true), - new KTABLE (0xD8, "Ø", 0xD8, true), - new KTABLE (0xD9, "Ù", 0xD9, true), - new KTABLE (0xDA, "Ú", 0xDA, true), - new KTABLE (0xDB, "Û", 0xDB, true), - new KTABLE (0xDC, "Ü", 0xDC, true), - new KTABLE (0xDD, "Ý", 0xDD, true), - new KTABLE (0xDE, "Þ", 0xDE, true), - new KTABLE (0xDF, "ß", 0xDF, true), - new KTABLE (0xE0, "à", 0xE0, true), - new KTABLE (0xE1, "á", 0xE1, true), - new KTABLE (0xE2, "â", 0xE2, true), - new KTABLE (0xE3, "ã", 0xE3, true), - new KTABLE (0xE4, "ä", 0xE4, true), - new KTABLE (0xE5, "å", 0xE5, true), - new KTABLE (0xE6, "æ", 0xE6, true), - new KTABLE (0xE7, "ç", 0xE7, true), - new KTABLE (0xE8, "è", 0xE8, true), - new KTABLE (0xE9, "é", 0xE9, true), - new KTABLE (0xEA, "ê", 0xEA, true), - new KTABLE (0xEB, "ë", 0xEB, true), - new KTABLE (0xEC, "ì", 0xEC, true), - new KTABLE (0xED, "í", 0xED, true), - new KTABLE (0xEE, "î", 0xEE, true), - new KTABLE (0xEF, "ï", 0xEF, true), - new KTABLE (0xF0, "ð", 0xF0, true), - new KTABLE (0xF1, "ñ", 0xF1, true), - new KTABLE (0xF2, "ò", 0xF2, true), - new KTABLE (0xF3, "ó", 0xF3, true), - new KTABLE (0xF4, "ô", 0xF4, true), - new KTABLE (0xF5, "õ", 0xF5, true), - new KTABLE (0xF6, "ö", 0xF6, true), - new KTABLE (0xF7, "÷", 0xF7, true), - new KTABLE (0xF8, "ø", 0xF8, true), - new KTABLE (0xF9, "ù", 0xF9, true), - new KTABLE (0xFA, "ú", 0xFA, true), - new KTABLE (0xFB, "û", 0xFB, true), - new KTABLE (0xFC, "ü", 0xFC, true), - new KTABLE (0xFD, "ý", 0xFD, true), - new KTABLE (0xFE, "þ", 0xFE, true), - new KTABLE (0xFF, "ÿ", 0xFF, true) - }; - } -} diff --git a/RFIDwedge2/Form1.Designer.cs b/RFIDwedge2/Form1.Designer.cs deleted file mode 100644 index 29c30af..0000000 --- a/RFIDwedge2/Form1.Designer.cs +++ /dev/null @@ -1,90 +0,0 @@ -namespace RFIDwedge2 -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.btnConnect = new System.Windows.Forms.Button(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuExit); - // - // btnConnect - // - this.btnConnect.Location = new System.Drawing.Point(81, 220); - this.btnConnect.Name = "btnConnect"; - this.btnConnect.Size = new System.Drawing.Size(74, 22); - this.btnConnect.TabIndex = 0; - this.btnConnect.Text = "Connect"; - this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // textBox1 - // - this.textBox1.AcceptsReturn = true; - this.textBox1.AcceptsTab = true; - this.textBox1.Location = new System.Drawing.Point(22, 17); - this.textBox1.Multiline = true; - this.textBox1.Name = "textBox1"; - this.textBox1.Size = new System.Drawing.Size(198, 186); - this.textBox1.TabIndex = 1; - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.textBox1); - this.Controls.Add(this.btnConnect); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "RFIDwedge2"; - this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Button btnConnect; - private System.Windows.Forms.MenuItem mnuExit; - private System.Windows.Forms.TextBox textBox1; - } -} - diff --git a/RFIDwedge2/Form1.cs b/RFIDwedge2/Form1.cs deleted file mode 100644 index 6028e31..0000000 --- a/RFIDwedge2/Form1.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using System.Runtime.InteropServices; -using VKEYS; - -namespace RFIDwedge2 -{ - public partial class Form1 : Form - { - [DllImport("coredll.dll", EntryPoint = "keybd_event", SetLastError = true)] - private static extern void keybd_event(byte bVk, byte bScan, keyFlag dwFlags, int dwExtraInfo); - - [Flags] - enum keyFlag : int - { - KEYEVENTF_KEYDOWN = 0x0000, - KEYEVENTF_EXTENDEDKEY = 0x0001, //If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224). - KEYEVENTF_KEYUP = 0x0002 - } - - ThreadClass.myThread mThread; - public Object thisLock = new Object(); - - public Form1() - { - InitializeComponent(); - btnConnect_Click(this, new EventArgs()); - textBox1.Focus(); - } - - private void btnConnect_Click(object sender, EventArgs e) - { - if (mThread == null) - { - mThread = new ThreadClass.myThread(); - mThread.MyEvent += new EventHandler(mThread_MyEvent); - } - - } - void mThread_MyEvent(object sender, ThreadClass.myThread.MyEventArgs e) - { - System.Diagnostics.Debug.WriteLine("Received event from thread: " + e.Message); - - lock (thisLock) - { - //stringQueue.Enqueue(e.Message); - - //better do the following from a separate thread - byte[] bBuf = Encoding.ASCII.GetBytes(e.Message); - //only digits and letters are the same in Byte and VK_ values - - byte bVkey = 0x00; - bool bShift = false; - for (int i = 0; i < bBuf.Length; i++) - { - // System.Diagnostics.Debug.WriteLine("buffer: " + bBuf[i]); - //so start a translation - - bVkey = virtual_key_codes.vkTable[bBuf[i]].VKval; - bShift = virtual_key_codes.vkTable[bBuf[i]].bShift; - - if (bVkey != (byte)virtual_key_codes.V_KEY.VK_undef_0xff) - { - if (bShift) - { - keybd_event((byte)virtual_key_codes.V_KEY.VK_SHIFT, 0x00, keyFlag.KEYEVENTF_KEYDOWN, 0); - System.Threading.Thread.Sleep(2); - } - //send key - keybd_event(bVkey, 0x00, keyFlag.KEYEVENTF_KEYDOWN, 0); - System.Threading.Thread.Sleep(2); - keybd_event(bVkey, 0x00, keyFlag.KEYEVENTF_KEYUP, 0); - System.Threading.Thread.Sleep(2); - if (bShift) - { - keybd_event((byte)virtual_key_codes.V_KEY.VK_SHIFT, 0x00, keyFlag.KEYEVENTF_KEYUP, 0); - System.Threading.Thread.Sleep(2); - } - } - } - - } - } - - private void Form1_Closing(object sender, CancelEventArgs e) - { - System.Diagnostics.Debug.WriteLine("\n form closing..."); - if (mThread != null) - { - mThread.stopThread = true; - System.Threading.Thread.Sleep(1000); - } - mThread.Dispose(); - - } - - private void mnuExit_Click(object sender, EventArgs e) - { - this.Close(); - } - } -} \ No newline at end of file diff --git a/RFIDwedge2/Form1.resx b/RFIDwedge2/Form1.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/RFIDwedge2/Form1.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/RFIDwedge2/HexEncoding.cs b/RFIDwedge2/HexEncoding.cs deleted file mode 100644 index b051eea..0000000 --- a/RFIDwedge2/HexEncoding.cs +++ /dev/null @@ -1,184 +0,0 @@ -using System; -using System.Text; -using System.Globalization; - -namespace Utility -{ - /// - /// Summary description for HexEncoding. - /// - public class HexEncoding - { - public HexEncoding() - { - // - // TODO: Add constructor logic here - // - } - public static int GetByteCount(string hexString) - { - int numHexChars = 0; - char c; - // remove all none A-F, 0-9, characters - for (int i=0; i - /// Creates a byte array from the hexadecimal string. Each two characters are combined - /// to create one byte. First two hexadecimal characters become first byte in returned array. - /// Non-hexadecimal characters are ignored. - /// - /// string to convert to byte array - /// number of characters in string ignored - /// byte array, in the same left-to-right order as the hexString - public static byte[] GetBytes(string hexString, out int discarded) - { - discarded = 0; - string newString = ""; - char c; - // remove all none A-F, 0-9, characters - for (int i=0; i=0){ - string s = val.Substring(iPos, 4); - byte b = byte.Parse(val.Substring(iPos+2,2), NumberStyles.HexNumber); - //string c = Convert.ToString(b,16); - char ch = (char)b; - //test - //byte[] bTest = Encoding.ASCII.GetBytes(ch.ToString()); - //System.Diagnostics.Debug.WriteLine(string.Format("Encoded {0:x} as '{1}'", bTest,ch)); - string o = val.Substring(0, iPos) + ch + val.Substring(iPos + 4); - val = o; - iPos = val.IndexOf("\\x"); - } - byte[] valAsByteArray = Encoding.ASCII.GetBytes(val); - return valAsByteArray; - } - public static string ToMixedString(string s) - { - byte[] bytes = Encoding.ASCII.GetBytes(s); - string sReturn = ToMixedString(bytes); - return sReturn; - } - public static string ToMixedString(byte[] bytes) - { - string hexString = ""; - for (int i = 0; i < bytes.Length; i++) - { - if (bytes[i] >= 0x20) - { - //hexString += bytes[i].ToString(); - hexString += ASCIIEncoding.ASCII.GetString(bytes, i, 1); - } - else - { - hexString += "\\x"; // "<" - hexString += bytes[i].ToString("X2"); - //if (i <= bytes.Length - 1) hexString += "-"; - //hexString += ">"; - } - } - return hexString; - } - - /// - /// Determines if given string is in proper hexadecimal string format - /// - /// - /// - public static bool InHexFormat(string hexString) - { - bool hexFormat = true; - - foreach (char digit in hexString) - { - if (!IsHexDigit(digit)) - { - hexFormat = false; - break; - } - } - return hexFormat; - } - - /// - /// Returns true is c is a hexadecimal digit (A-F, a-f, 0-9) - /// - /// Character to test - /// true if hex digit, false if not - public static bool IsHexDigit(Char c) - { - int numChar; - int numA = Convert.ToInt32('A'); - int num1 = Convert.ToInt32('0'); - c = Char.ToUpper(c); - numChar = Convert.ToInt32(c); - if (numChar >= numA && numChar < (numA + 6)) - return true; - if (numChar >= num1 && numChar < (num1 + 10)) - return true; - return false; - } - /// - /// Converts 1 or 2 character string into equivalant byte value - /// - /// 1 or 2 character string - /// byte - private static byte HexToByte(string hex) - { - if (hex.Length > 2 || hex.Length <= 0) - throw new ArgumentException("hex must be 1 or 2 characters in length"); - byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber); - return newByte; - } - } -} diff --git a/RFIDwedge2/Program.cs b/RFIDwedge2/Program.cs deleted file mode 100644 index b6e32dc..0000000 --- a/RFIDwedge2/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace RFIDwedge2 -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/RFIDwedge2/Properties/AssemblyInfo.cs b/RFIDwedge2/Properties/AssemblyInfo.cs deleted file mode 100644 index b1d1805..0000000 --- a/RFIDwedge2/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("RFIDwedge2")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("RFIDwedge2")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("8bc01859-abde-4815-ad11-11638a31da9b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/RFIDwedge2/Properties/Resources.Designer.cs b/RFIDwedge2/Properties/Resources.Designer.cs deleted file mode 100644 index 0322d4d..0000000 --- a/RFIDwedge2/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.4959 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace RFIDwedge2.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("RFIDwedge2.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/RFIDwedge2/Properties/Resources.resx b/RFIDwedge2/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/RFIDwedge2/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/RFIDwedge2/RFIDwedge2.csproj b/RFIDwedge2/RFIDwedge2.csproj deleted file mode 100644 index 257d510..0000000 --- a/RFIDwedge2/RFIDwedge2.csproj +++ /dev/null @@ -1,100 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {2D96FD5C-061E-4948-804D-DA2089AF6534} - WinExe - Properties - RFIDwedge2 - RFIDwedge2 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - b2c48bd2-963d-4549-9169-1fa021dce484 - 5.2 - RFIDwedge2 - v2.0 - Windows Mobile 6 Professional SDK - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - Form - - - Form1.cs - - - - Component - - - - - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - - - \ No newline at end of file diff --git a/RFIDwedge2/RFIDwedge2.csproj.user b/RFIDwedge2/RFIDwedge2.csproj.user deleted file mode 100644 index a35f3ee..0000000 --- a/RFIDwedge2/RFIDwedge2.csproj.user +++ /dev/null @@ -1,5 +0,0 @@ - - - b2c48bd2-963d-4549-9169-1fa021dce484d6518ffb-710f-11d3-99f2-00105a0df099 - - \ No newline at end of file diff --git a/RFIDwedge2/RFIDwedge2.sln b/RFIDwedge2/RFIDwedge2.sln deleted file mode 100644 index 24c1eac..0000000 --- a/RFIDwedge2/RFIDwedge2.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RFIDwedge2", "RFIDwedge2.csproj", "{2D96FD5C-061E-4948-804D-DA2089AF6534}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2D96FD5C-061E-4948-804D-DA2089AF6534}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2D96FD5C-061E-4948-804D-DA2089AF6534}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2D96FD5C-061E-4948-804D-DA2089AF6534}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {2D96FD5C-061E-4948-804D-DA2089AF6534}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2D96FD5C-061E-4948-804D-DA2089AF6534}.Release|Any CPU.Build.0 = Release|Any CPU - {2D96FD5C-061E-4948-804D-DA2089AF6534}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/RFIDwedge2/RFIDwedge2.suo b/RFIDwedge2/RFIDwedge2.suo deleted file mode 100644 index f866361..0000000 Binary files a/RFIDwedge2/RFIDwedge2.suo and /dev/null differ diff --git a/RFIDwedge2/myThread.cs b/RFIDwedge2/myThread.cs deleted file mode 100644 index 8e9a9ec..0000000 --- a/RFIDwedge2/myThread.cs +++ /dev/null @@ -1,819 +0,0 @@ -//#define NORMALTAG -//change the above to read user TAG memory bank 3 -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Windows.Forms; - -using Intermec.DataCollection; -using Intermec.DataCollection.RFID; - -// USAGE: -//using ThreadClass; -//... -//ThreadClass.myThread mThread; -//private void button1_Click(object sender, EventArgs e) -//{ -// mThread = new myThread(); -// mThread.MyEvent += new EventHandler(onEvent); -//} -//public void onEvent(object o, ThreadClass.myThread.MyEventArgs s) -//{ -// System.Diagnostics.Debug.WriteLine("onEvent received: '" + s.Message + "'"); -// mThread.stopThread = true; -//} - -namespace ThreadClass -{ - public class myThread:Control,IDisposable - { - public class EventArgs : EventArgs - { - public EventArgs(T pValue) - { - m_value = pValue; - } - - private T m_value; - - public T Value - { - get { return m_value; } - } - } - public class MyEventArgs : EventArgs - { - private string msg; - - public MyEventArgs(string messageData) - { - msg = messageData; - } - public string Message - { - get { return msg; } - set { msg = value; } - } - } - - private EventHandler __MyEvent; - public event EventHandler MyEvent - { - add - { - lock (this) { __MyEvent += value; } - } - remove - { - lock (this) { __MyEvent -= value; } - } - } - - private EventHandler __pulseEvent; - public event EventHandler MyPulseEvent - { - add - { - lock (this) { __pulseEvent += value; } - } - remove - { - lock (this) { __pulseEvent -= value; } - } - } - private Thread m_Thread; - private bool m_stopThread = false; - public bool stopThread{ - get { return m_stopThread; } - set { m_stopThread = value; - if (m_stopThread) - m_Thread.Abort(); - } - } - private bool m_threadStopped = false; - public bool threadStopped - { - get { - lock (this) - { - return m_threadStopped; - } - } - } - - public myThread() - { - m_Thread = new Thread(new ThreadStart (this.threadWorker)); - m_Thread.Name = "my Worker Thread"; - m_Thread.Start(); - } - public void Dispose(){ - this.stopThread = true; - base.Dispose(); - } - private void threadWorker() - { - m_threadStopped = false; - System.Diagnostics.Debug.WriteLine("+++ Thread started"); - try - { - do - { - //DoSomething; - Thread.Sleep(1000); - doWork(); - //fire the event handlers - __MyEvent(this, new MyEventArgs("Hello from Thread")); - __pulseEvent(this, null); - } while (!m_stopThread); - } - catch (ThreadAbortException tx) - { - System.Diagnostics.Debug.WriteLine("ThreadAbortException: " + tx.Message + "\r\n ---Thread is aborted"); - } - finally - { - //switch off any LED - tools.SetLedStatus(3, tools.LedFlags.STATE_OFF); - } - m_threadStopped = true; - System.Diagnostics.Debug.WriteLine("\n---Thread stopped"); - } - - void doWork() - { - int iDelay = 0; bool bLEDoff = false; - logThis("Entering doWork()"); - while (!m_stopThread) - { - try - { - ConnectReader(); - while (m_Reader.IsConnected) - { - if (iDelay > 4) - { - tools.SetLedStatus(3, tools.LedFlags.STATE_ON); - bLEDoff = true; // need to turn off LED - iDelay = 0; - } - System.Threading.Thread.Sleep(200); - if (bLEDoff) - { - tools.SetLedStatus(3, tools.LedFlags.STATE_OFF); - bLEDoff = false; - } - iDelay++; - } - CloseReader(); - } - catch (BasicReaderException brx) - { - logThis("BasicReaderException in doWork(): " + brx.Message); - } - catch (BRIParserException bpx) - { - logThis("BRIParserException in doWork(): " + bpx.Message); - } - catch (Exception ex) - { - logThis("Exception in doWork(): " + ex.Message); - } - } - logThis("Leaving doWork()"); - } - - BasicBRIReader m_Reader = null; - bool m_bCenterEventProcessing = false; - public string sCurrentCMD; - Tag[] tags; - bool m_bEventLogging = true; - - private int OpenReader() - { - logThis("OpenReader..."); - BasicBRIReader.LoggerOptions LogOp = new BasicBRIReader.LoggerOptions(); - LogOp.LogFilePath = ".\\IDLClassDebugLog.txt"; - //LogOp.LogFilePath="\\Program Files\\IP4IDLAPP\\IDLClassDebugLog.txt"; - LogOp.ShowNonPrintableChars = true; - int res = 0; - try - { - if (m_Reader != null) - { - CloseReader(); - } - m_Reader = new BasicBRIReader(this, LogOp); - m_Reader.Open(); - AddEventHandlers(); - } - catch (BasicReaderException brx) - { - logThis("BasicReaderException in OpenReader(): " + brx.Message); - res = -1; - } - catch (SystemException sx) - { - logThis("SystemException in OpenReader(): " + sx.Message); - res = -2; - } - catch (Exception sx) - { - logThis("Exception in OpenReader(): " + sx.Message); - res = -2; - } - if (res != 0) - System.Threading.Thread.Sleep(5000); - return res; - } - /// - /// This function fires when the center trigger on the IP4 is pulled or released - /// - /// - /// - void brdr_EventHandlerCenterTrigger(object sender, BasicReaderEventArgs EvtArgs) - { - if (m_Reader.IsConnected == false) - { - //irda connection is still asleep after a 700 resume - return; - } - //avoid multiple processing -// if (m_bCenterEventProcessing) -// return; - m_bCenterEventProcessing = true; - /*CenterTriggerState*/ - /*EVT_CenterTrigger_EventArgs.STATE.PULLED*/ - if (EvtArgs.EventType.Equals(BasicReaderEventArgs.EventTypes.EVT_DCE) && // BasicReaderEventArgs.EventTypes.EVT_CENTER_TRIGGER) && - EvtArgs.EventData.Equals("BUTTON CENTER 1")) - { - #region Write Single TAG - #endregion -#if NORMALTAG - sCurrentCMD = "READ HEX(0,12)"; //TAGID -#else - sCurrentCMD = "READ HEX(3:0,12) REPORT=EVENTALL"; //TAGID -#endif - // sCurrentCMD = "EPCID"; - if (ExecuteCMD(sCurrentCMD)) - { - logThis("OK READ HEX"); - } - else - { - logThis("failed"); - } - - } - m_bCenterEventProcessing = false; - } - - private int SetAttributes() - { - bool bStatus = false; - if (m_Reader.IsConnected == false) { return -1; } - sCurrentCMD = "ATTRIB TAGTYPE=EPCC1G2"; // comboBox1.Text; - bStatus = ExecuteCMD(sCurrentCMD); - if (bStatus == false) - { - logThis("SetAttrib failed, reader connected?"); - return -1; - } - else - { - logThis("RFID Connected"); - //This will set the Option IntermecSettings-RFID-Reader 1-Enable Reader - //Configuring the DCE Transport Programmatically Using BRI - Intermec.DataCollection.RFID.BasicBRIReader DCEConfig = new BasicBRIReader(null); - try - { - DCEConfig.Open("TCP://127.0.0.1:2189"); - // BRI device command. - DCEConfig.Execute("device 1 attrib adminstatus=on"); - DCEConfig.Close(); - return 0; - } - catch (BasicReaderException bex) - { - logThis("SetAttrib() DCEConfig could not connect to DCE: " + bex.Message); - return -2; - } - catch (Exception ex) - { - logThis("SetAttrib() DCEConfig exception " + ex.Message); - return -3; - } - } - } - - private bool ExecuteCMD(string tCMD) - { - if (m_Reader == null) - return false; - byte[] aFieldSeparator = { (byte)' ' }; - byte[] aRespBuf; - string tMsg = null; - logThis("Sending->" + tCMD); - try - { - if (m_Reader.IsConnected) - tMsg = m_Reader.Execute(tCMD); - else - { - logThis("Reader disconnected, please Connect"); - return false; - } - } - catch (BasicReaderException eBRI) - { - logThis("BasicReaderException: " + eBRI.ToString()); - return false; - } - catch (System.NullReferenceException nr) - { - logThis("Null Ref Exception: " + nr.Message); - logThis("stack: " + nr.StackTrace); - return false; - } - - // if tags were successfully read - if (tMsg.IndexOf("BRI ERR") >= 0) - System.Diagnostics.Debugger.Break(); - //"H112233445566778899001122 HE2001040\r\nOK>" - // System.Diagnostics.Debug.WriteLine("Msg: "+tMsg); - //Show TAG ID - #region READ EPCID/TAGID - if (sCurrentCMD.StartsWith("READ ")) //TAGID - { - if (tMsg.IndexOf("RDERR") >= 0) - { - //ChangeStatus(eStatus.TagReadError); - return false; - } - aRespBuf = tools.StrToByteArray(tMsg); - tags = BRIParser.GetTags(aRespBuf, aFieldSeparator); - System.Diagnostics.Debug.WriteLine("tags.Length: " + tags.Length); - - if (tags == null) - { - return false; - } - System.Diagnostics.Debug.WriteLine("Msg: " + tMsg); -#if !NORMALTAG - #region ReadUserMemory - // remove newline and carriage returns - tMsg = tMsg.Replace('\n', ' '); - tMsg = tMsg.Replace("\r",""); - string[] ids = tMsg.Split(' '); - // get the even arguments only - System.Diagnostics.Debug.WriteLine("id num " + ids.Length); - if (ids.Length > 1) - { - for (int j = 1; j < ids.Length; j+=2) - { - // System.Diagnostics.Debug.WriteLine("tag " +j+" "+ tags[j].ToString()); - string s = ids[j]; - System.Diagnostics.Debug.WriteLine(j + " Read id: " + s); - s = s.Substring(1,s.Length-1); - - for (int i = 0; i < s.Length; i++) - { - // remove first part of byte '3' - if (s.Substring(i, 1) == "3") s = s.Remove(i, 1); - else - { - // chop off ending zeroes - s = s.Substring(0, i); - break; - } - //System.Diagnostics.Debug.WriteLine(i+" length: "+start.Length+" newString " + start); - } - // make multiple tags comma delimited - string sOut = ""; - if (s.Length > 1) - { - //if (j != ids.Length - 2) s = s + ","; - for ( int i = 0; i < tags.Length; i++ ) - { - sOut += s[i]; - if (i != s.Length - 1) - sOut += ","; - } - s = sOut; - } - __MyEvent(this, new MyEventArgs(s)); - } - } - #endregion -#else -#region ReadNormalTagMemory - // make multiple tags comma delimited - string sOut = ""; - if (tags.Length > 1) - { - //if (j != ids.Length - 2) s = s + ","; - for ( int i = 0; i < tags.Length; i++ ) - { - sOut += tags[i]; - if (i != tags.Length - 1) - sOut += ","; - } - } - else{ - sOut = tags[0].ToString(); - } - __MyEvent(this, new MyEventArgs(sOut)); -#endregion -#endif - /* - #region READ single TAG - if (tags.Length == 1) - { - //read data from the tag - System.Diagnostics.Debug.WriteLine("READ TAGID tag data: " + tags[0].ToString()); - } - #endregion - * / - - //read tag data (aka EPCID) - /* - if (tMsg.StartsWith("H")) - { - string s; - s = tMsg.Substring(1, 24); - System.Diagnostics.Debug.WriteLine("Read data: " + s); - string[] args = tMsg.Split(' '); - if (args.Length > 1) - { - System.Diagnostics.Debug.WriteLine("Arg 2: " + args[1]); - string start = args[1].Substring(1,args[1].Length-1); - - for (int i = 0; i < start.Length; i++) - { - start = start.Remove(i, 1); - //System.Diagnostics.Debug.WriteLine(i+" length: "+start.Length+" newString " + start); - } - System.Diagnostics.Debug.WriteLine("final ver " + start); - - __MyEvent(this, new MyEventArgs(start)); - } - //txtTagID.Text = s; - } - */ - } - #endregion - #region ATTRIB - if (sCurrentCMD.Equals("ATTRIB TAGTYPE=EPCC1G2") == true) - { - if (tMsg.IndexOf("OK") >= 0) - return true; - else - return false; - } - if ((tMsg.IndexOf("ERR") >= 0) & (sCurrentCMD.Equals("ATTRIB SCHEDOPT=1") == false)) - { - //MessageBox.Show("Warning, BRI ERR occured for: " + tCMD + "\r\n" + tMsg); - logThis("BRI ERR for: " + tCMD + "\r\n" + tMsg); - return false; - } - #endregion - return true; - } - - private void reportTAGS(string sTAGs) - { - /* - Received event from thread: - ReaderEvent: Type=EVT_TAG - EventData='H300833B2DDD9014035050000 MEMOVRN' - id num 2 - 1 Read id: MEMOVRN - Received event from thread: - ReaderEvent: Type=EVT_TAG - EventData='H3005FB63AC1F3681EC880468 H313233343536373839303132' - id num 2 - 1 Read id: H313233343536373839303132 - * the above is the hex of the string 123456789012 - */ - - #region ReadUserMemory - // remove newline and carriage returns - sTAGs = sTAGs.Replace('\n', ' '); - sTAGs = sTAGs.Replace("\r", ""); - string[] ids = sTAGs.Split(' '); - // get the even arguments only - System.Diagnostics.Debug.WriteLine("id num " + ids.Length); - if (ids.Length > 1) - { - for (int j = 1; j < ids.Length; j += 2) - { - // System.Diagnostics.Debug.WriteLine("tag " +j+" "+ tags[j].ToString()); - string s = ids[j]; - System.Diagnostics.Debug.WriteLine(j + " Read id: " + s); - if(!s.StartsWith("H")) //is this a valid Hex string or possibly an error - return; - - s = s.Substring(1, s.Length - 1); //cut the H at the beginning - - //convert hex back to string - int iErrCnt = 0; - byte[] b = Utility.HexEncoding.GetBytes(s, out iErrCnt); - s = System.Text.Encoding.Default.GetString(b, 0, b.Length); //this replaces the strange converter below - - ////for (int i = 0; i < s.Length; i++) - ////{ - //// // remove first part of byte '3' - //// if (s.Substring(i, 1) == "3") s = s.Remove(i, 1); - //// else - //// { - //// // chop off ending zeroes - //// s = s.Substring(0, i); - //// break; - //// } - //// //System.Diagnostics.Debug.WriteLine(i+" length: "+start.Length+" newString " + start); - ////} - - //in continous mode REPORT=EVENT or EVENTALL we always get a separate event for each TAG reported - //so there will never be multiple TAGs in one event - __MyEvent(this, new MyEventArgs(s)); - } - } - #endregion - } - - private int ParseResponseMessage(string tMsg) - { - int x = 0; - string tString = ""; - char tChar = '0'; - - //just to make parsing code uniform - tMsg += "\r\n"; - - char[] tMyCharList = tMsg.ToCharArray(); - - //clear response list - int RspCount = 0; - - string[] RspMsgList = new string[1000]; - RspMsgList.Initialize(); - - //parse the response message - for (x = 0; x < tMyCharList.Length; x++) - { - tChar = tMyCharList[x]; - if (tChar.Equals('\n') == false & tChar.Equals('\r') == false) - { - tString += tChar; - } - else if (tChar.Equals('\r') == true) - { - RspCount++; - RspMsgList[RspCount] = tString; - tString = ""; - } - } - - //process the response messages - for (x = 1; x <= RspCount; x++) - { - if (RspMsgList[x].IndexOf("H") == 0 & RspMsgList[x].IndexOf("HOP") < 0) - { - //Tag Data - if (sCurrentCMD.Equals("R")) - { - //skip this data, its part of a bug work around regarding cont read modes - } - else - { - logThis(RspMsgList[x]); - } - } - else if (RspMsgList[x].IndexOf("OK>") == 0) - { - //end of reader response - if (sCurrentCMD.StartsWith("R") == false & sCurrentCMD.StartsWith("W") == false) - { - logThis(RspMsgList[x]); - } - break; - } - else if (sCurrentCMD.IndexOf("ATTRIB") == 0) - { - logThis(RspMsgList[x]); - } - else if (sCurrentCMD.IndexOf("UTIL") == 0) - { - logThis(RspMsgList[x]); - } - }//END for (x = 1; x <= RspCount; x++) - - return 0; - } - private void ConnectReader() - { - Cursor.Current = Cursors.WaitCursor; - System.Diagnostics.Debug.WriteLine("Opening Reader..."); - if (OpenReader() == 0) - { - System.Diagnostics.Debug.WriteLine("... Reader opened. Trying to set Attributes ..."); - //try first command - int res = SetAttributes(); - if (res != 0) - { - System.Diagnostics.Debug.WriteLine("... SetAttributes failed! Closing Reader"); - m_Reader.Close(); - m_Reader = null; - } - } - - if (m_Reader != null) - { - if (m_Reader.IsConnected) - { - System.Diagnostics.Debug.WriteLine("Reader connected. ChangeStatus(ReadBarcode)"); - } - else - { - System.Diagnostics.Debug.WriteLine("Reader connected. ChangeStatus(ReadBarcode)"); - } - } - - Cursor.Current = Cursors.Default; - } - private void CloseReader() - { - if (m_Reader != null) - try - { - if (m_Reader != null) - m_Reader.Close(); - RemoveEventHandlers(); - } - catch (BasicReaderException brx) - { - logThis("CloseReader(): " + brx.Message); - } - catch (SystemException sx) - { - logThis("CloseReader(): " + sx.Message); - } - finally - { - //ChangeStatus(eStatus.Offline); - } - } - /// - /// Add the event handler to handle the tag events and trigger pulls. - /// Not all of these are used but added as samples of what are available. - /// - /// - private int AddEventHandlers() - { - try - { - //this.m_Reader.EventHandlerRadio += new Radio_EventHandler(brdr_EventHandlerRadio); - //this.m_Reader.EventHandlerTag += new Tag_EventHandler(brdr_EventHandlerTag); - - //deprecated from v2.1: this.m_Reader.EventHandlerCenterTrigger += new CenterTrigger_EventHandler(brdr_EventHandlerCenterTrigger); - //deprecated from v2.1: this.m_Reader.EventHandlerDCE += new DCE_EventHandler(brdr_EventHandlerDCE); - - this.m_Reader.ReaderEvent += new BasicEvent(brdr_ReaderEventHandler); - - //this.m_Reader.EventHandlerOverflow += new Overflow_EventHandler(brdr_EventHandlerOverflow); - } - catch - { - MessageBox.Show("Exception trying to create event handlers"); - return -1; - } - return 0; - } - - public static void logThis(string s) - { - // System.Diagnostics.Debug.WriteLine("LOG: " + s); - try - { - System.IO.TextWriter tw = new System.IO.StreamWriter("\\RFIDWegdeLog.txt", true); - string dt = DateTime.Now.ToShortTimeString(); - tw.WriteLine(dt + ": " + s); - tw.Flush(); - tw.Close(); - - } - catch (Exception x) - { - System.Diagnostics.Debug.WriteLine("Exception: " + x.Message); - } - - } - private int RemoveEventHandlers() - { - try - { - //this.m_Reader.EventHandlerRadio -= brdr_EventHandlerRadio; - //this.m_Reader.EventHandlerTag -= brdr_EventHandlerTag; - - //deprecated from v2.1: this.m_Reader.EventHandlerCenterTrigger -= brdr_EventHandlerCenterTrigger; - //deprecated from v2.1: this.m_Reader.EventHandlerDCE -= brdr_EventHandlerDCE; - - this.m_Reader.ReaderEvent -= brdr_ReaderEventHandler; - - //this.m_Reader.EventHandlerOverflow -= brdr_EventHandlerOverflow; - } - catch - { - MessageBox.Show("Exception trying to create event handlers"); - return -1; - } - return 0; - } - void brdr_ReaderEventHandler(object sender, BasicReaderEventArgs EvtArgs) - { - System.Diagnostics.Debug.WriteLine("ReaderEvent: Type=" + EvtArgs.EventType.ToString() + - "\n\tEventData='" + EvtArgs.EventData + "'"); - switch ((int)EvtArgs.EventType) - { - /* - OLD: UNKNOWN = 1, - SHUTDOWN = 2, - BUTTON = 3, - DEVICE = 4, - EventTypes.EVT_BATTERY - EventTypes.EVT_CENTER_TRIGGER - EventTypes.EVT_DCE -Battery pulled - * ReaderEvent: Type=EVT_DCE - EventData='DEVICE 1 DISCONNECTED' - ReaderEvent: Type=EVT_DCE - EventData='DEVICE 1 CONNECTING' - The thread 0xc66b4f1a has exited with code 0 (0x0). - ReaderEvent: Type=EVT_DCE - EventData='DEVICE 1 CONNECTED' -Center Trigger - * ReaderEvent: Type=EVT_TRIGGER - EventData='TRIGPULL GPIO 0' - ReaderEvent: Type=EVT_DCE - EventData='BUTTON CENTER 1' - ReaderEvent: Type=EVT_TRIGGER - EventData='TRIGRELEASE GPIO 1' - ReaderEvent: Type=EVT_DCE - EventData='BUTTON CENTER 0' - - EventTypes.EVT_RADIO - EventTypes.EVT_READER_RECONNECTED - EventTypes.EVT_RESET - EventTypes.EVT_TAG - EventTypes.EVT_THERMAL - EventTypes.EVT_TRIGGER - EventTypes.EVT_TRIGGERACTION - */ - case (int)BasicReaderEventArgs.EventTypes.EVT_RADIO: - brdr_EventHandlerRadio(sender, EvtArgs); - break; - case (int)BasicReaderEventArgs.EventTypes.EVT_DCE: // EVT_CENTER_TRIGGER: - if (m_bEventLogging) - logThis("brdr_ReaderEvent() BUTTON:" + EvtArgs.EventData); - brdr_EventHandlerCenterTrigger(sender, EvtArgs); - break; - case (int)BasicReaderEventArgs.EventTypes.EVT_TAG: - reportTAGS(EvtArgs.EventData); - break; - case (int)BasicReaderEventArgs.EventTypes.EVT_BATTERY: - case (int)BasicReaderEventArgs.EventTypes.EVT_CENTER_TRIGGER: - case (int)BasicReaderEventArgs.EventTypes.EVT_READER_RECONNECTED: - case (int)BasicReaderEventArgs.EventTypes.EVT_RESET: - case (int)BasicReaderEventArgs.EventTypes.EVT_THERMAL: - case (int)BasicReaderEventArgs.EventTypes.EVT_TRIGGER: - case (int)BasicReaderEventArgs.EventTypes.EVT_TRIGGERACTION: - case (int)BasicReaderEventArgs.EventTypes.EVT_UNKNOWN: - if (m_bEventLogging) - { - logThis("brdr_ReaderEvent() type: " + Convert.ToString((Int16)EvtArgs.EventType) + "=" + EvtArgs.EventType.ToString()); - logThis("brdr_ReaderEvent() data: '" + EvtArgs.EventData + "'"); - } - break; - default: - // The DCE has encountered an undefined condition... - if (m_bEventLogging) - logThis("brdr_ReaderEvent(): Unknown Type " + Convert.ToString((Int16)EvtArgs.EventType) + " - Data: '" + EvtArgs.EventData + "'"); - //CloseReader(); - break; - } - } - void brdr_EventHandlerRadio(object sender, BasicReaderEventArgs EvtArgs) - { - int iTimeLeft = Convert.ToInt32(EvtArgs.EventData); - //pause a little bit to avoid duty cycle failures - logThis("duty time left=" + iTimeLeft.ToString() + "Sleeping 500ms..."); - System.Threading.Thread.Sleep(500); - logThis("...OK"); - //MessageBox.Show("brdr_EventHandlerRadio():\r\n" + iTimeLeft.ToString()); - if (m_bEventLogging) - logThis("brdr_EventHandlerRadio() TimeLeft: " + iTimeLeft.ToString()); - } - - } -} diff --git a/RFIDwedge2/tools.cs b/RFIDwedge2/tools.cs deleted file mode 100644 index 27ddcb3..0000000 --- a/RFIDwedge2/tools.cs +++ /dev/null @@ -1,361 +0,0 @@ -using System; -using System.IO; -using System.Collections; -using System.Collections.Generic; -using System.Windows.Forms; - -using System.Runtime.InteropServices; - - public class tools - { - public static string ReverseString(string s) - { - int i = 0; - string str=""; - for (i = s.Length-1; i >= 0; i--) - { - str = str + s.Substring(i, 1); - } - return str; - } - - /// - /// Copy a string until a \r appears - /// - /// input string - /// string cutdown to \r - public static string CopyToR(string s) - { - int i = 0; - string t = ""; - while (s.Substring(i, 1) != "\r") - { - t += s.Substring(i, 1); - i++; - } - return t; - } - /// - /// C# to convert a string to a byte array. - /// - /// - /// sbyte[] - public static sbyte[] StrToSByteArray(string str) - { - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - byte[] src = new byte[str.Length]; - sbyte[] dest = new sbyte[src.Length]; - src = encoding.GetBytes(str); - System.Buffer.BlockCopy(src, 0, dest, 0, src.Length); - return dest; - } - public static byte[] StrToByteArray(string str) - { - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - byte[] src = new byte[str.Length]; - src = encoding.GetBytes(str); - return src; - } - - #region NLED - // see also http://community.opennetcf.com/forums/t/80.aspx - /// - /// LED manipulation - /// - /// Normal use: - /// First, get the count of LED's by calling GetLedCount() - /// Second, if the number of LED's is greater than zero, set the state of each desired LED - /// by calling SetLedStatus(led #, flag) where the first LED is zero and the flag is defined - /// by one of the LedFlags enumerations - /// - - [Flags] - public enum LedFlags : int - { - STATE_OFF = 0x0000, /* dark LED */ - STATE_ON = 0x0001, /* light LED */ - STATE_BLINK = 0x0002, /* flashing LED */ - } - - public const Int32 NLED_COUNT_INFO_ID = 0; - public const Int32 NLED_SUPPORTS_INFO_ID = 1; - public const Int32 NLED_SETTINGS_INFO_ID = 2; - - public class NLED_COUNT_INFO - { - public UInt32 cLeds; - } - - public class NLED_SUPPORTS_INFO - { - public UInt32 Lednum; - public Int32 lCycleAdjust; - public bool fAdjustTotalCycleTime; - public bool fAdjustOnTime; - public bool fAdjustOffTime; - public bool fMetaCycleOn; - public bool fMetaCycleOff; - }; - - public class NLED_SETTINGS_INFO - { - public UInt32 LedNum; - public LedFlags OnOffBlink; - public Int32 TotalCycleTime; - public Int32 OnTime; - public Int32 OffTime; - public Int32 MetaCycleOn; - public Int32 MetaCycleoff; - }; - - [DllImport("CoreDll")] - private extern static bool NLedGetDeviceInfo(Int32 nID, NLED_COUNT_INFO nci); - - [DllImport("CoreDll")] - private extern static bool NLedGetDeviceInfo(Int32 nID, NLED_SUPPORTS_INFO nsi); - - [DllImport("CoreDll")] - private extern static bool NLedGetDeviceInfo(Int32 nID, NLED_SETTINGS_INFO nsi); - - [DllImport("CoreDll")] - private extern static bool NLedSetDevice(Int32 nID, NLED_SETTINGS_INFO nsi); - - public static uint GetLedCount() - { - NLED_COUNT_INFO nci = new NLED_COUNT_INFO(); - - uint LedCount = 0; - - if (NLedGetDeviceInfo(NLED_COUNT_INFO_ID, nci)) - LedCount = nci.cLeds; - - return LedCount; - } - - public static bool SetLedStatus(uint nLed, LedFlags fState) - { - NLED_SETTINGS_INFO nsi = new NLED_SETTINGS_INFO(); - - nsi.LedNum = nLed; - nsi.OnOffBlink = fState; - - return NLedSetDevice(NLED_SETTINGS_INFO_ID, nsi); - } - #endregion - - #region NewStuff - //=============================================================================================== - // New stuff - //=============================================================================================== - - /// - /// takes a string of 0s and 1s and returns a uint - /// - /// a 'binary' string of 0s and 1s - /// - public static UInt32 BinStr2Uint(string s) - { - int maxbits = s.Length; - int i; - UInt32 u=0; - //s[s.lenghth] = Bit[0] - //start at end of string, highest bit - for (i = 0; i < maxbits ; i++) - { - if (s.Substring( i, 1).Equals("1")) - { - u += (uint)Math.Pow(2, i); - } - } - return u; - } - - /// - /// convert an uint to a BinStr - /// - /// - /// a BinStr of 0s and 1s, lowest bit left - public static string Uint2BinStr(UInt32 u) - { - int maxbits = 32; - UInt32 u32 = u; - int i; - string s=""; - //s[0] = bit[0] - //start at highest value and test - for (i = maxbits; i > 0; i--) - { - if (u32 >= Math.Pow(2, i-1)) - { - s = "1" + s; - u32 -= (UInt32)Math.Pow(2, i-1); - } - else - s = "0" + s; - } - s.PadRight(32, '0'); - return s; - } - - /// - /// get binary string in reverse order - /// - /// - /// - /// - public static string Uint2BinStr(UInt32 u, int bitcount) - { - //49977473 -> //10111110101001100010000001 - //123456789 -> 00000111010110111100110100010101 - // "00000111 01011011 11001101 00010101 - // " - string s = Uint2BinStr(u); - if (s.Length > bitcount) - { - s = s.Substring(0, bitcount); - } - else if (s.Length < bitcount) - s = s.PadRight(bitcount, '0'); - return s; - } - - /// - /// Convert a BinStr ie '01010011' to a hex string '53'hex - /// - /// - /// a hex str - public static string BinStr2HexStr(string BinStr) - { - //convert byte by byte - string sHex2=""; - string sBin8=""; - string sHex=""; - string sBin = BinStr; - byte b = 0; - //ensure a binstr dividable by 8 - if (sBin.Length % 8 > 0) //is there any rest? - { - int l = sBin.Length; - int c = l / 8; - c++; - c = c * 8; - l = c - l; - for (int i = 0; i < l; i++) - sBin = sBin + "0"; - } - //start at lowest bit - while (sBin.Length > 0) - { - sBin8 = sBin.Substring(0, 8); //01010011 - b = (byte)BinStr2Uint(sBin); - sHex2 = Convert.ToString(b, 16); //0x53 - sHex = sHex2.PadLeft(2,'0') + sHex ; - sBin = sBin.Substring(8); - } - return sHex; - } - /// - /// convert a BinStr to a Hex string - /// - /// - /// the Byte width, ie 12 means you get a string with 24 letters - /// each byte is translated to a two-letter hex str - /// - public static string BinStr2HexStr(string BinStr, int ByteWidth) - { - string HexStr = BinStr2HexStr(BinStr); - if (HexStr.Length < ByteWidth) //pad left with '0' - HexStr = HexStr.PadLeft(ByteWidth*2, '0'); - else if (HexStr.Length > ByteWidth) //return right part, cut left - HexStr = HexStr.Substring(HexStr.Length - (ByteWidth * 2), ByteWidth * 2); - return HexStr; - } - - public static char[] HexStr2CharAr(string sHex) - { - char[] c; - string sBin = ""; - sBin = HexStr2BinStr(sHex); - c=BinStr2CharAr(sBin); - return c; - } - - public static string CharAr2HexStr(char[] c) - { - string s = ""; - string sBin = ""; - sBin = CharAr2BinStr(c); - s = BinStr2HexStr(sBin); - return s; - } - - public static string HexStr2BinStr(string hex) - { - byte b; - string BinStr = ""; - string sBin8 = ""; - string hex2 = ""; - if (hex.Length == 24) - { - //from left to right //34 ....... - for (int i = 0; i < 12; i++) - { //0-1-2-3-4- 5- 6- 7- 8- 9-10-11 - hex2 = hex.Substring(i*2, 2);//start at right, 0-2-4-6-8-10-12-14-16-18-20-22 - b = Convert.ToByte(hex2, 16); - sBin8 = Uint2BinStr(b).Substring(0,8); - BinStr = sBin8 + BinStr ; - } - } - if (!BinStr2HexStr(BinStr).Equals(hex.ToLower())) - System.Diagnostics.Debugger.Break(); - return BinStr; - } - - /// - /// convert a BinStr to a char[] array - /// - /// - /// - public static char[] BinStr2CharAr(string BinStr) - { - int bitcount = BinStr.Length; - if (BinStr.Length > 96) - BinStr = BinStr.Substring(0,96);//limit bitcount to 96 - else if (BinStr.Length < 96) - BinStr = BinStr.PadRight(96, '0'); - - char[] c = new char[96]; - for (int i = 0; i < 96; i++) - { - if (BinStr.Substring(i, 1).Equals("1")) - c[i] = '1'; - else - c[i] = '0'; - } - return c; - } - /// - /// convert a char[] to BinStr (substr(0,1)=char[0] - /// BinStr highest Bit at RIGHT! - /// - /// - /// - public static string CharAr2BinStr(char[] c) - { - int bitcount = c.Length; - string s = ""; - for (int i = 0; i < bitcount; i++) - { - if (c[i] == '1') - s = s + "1"; - else - s = s + "0"; - } - if (s.Length < 96) - s.PadRight(96, '0'); - else if (s.Length > 96) - s = s.Substring(0, 96); - return s; - } -#endregion - } diff --git a/RFIDwedge2/virtual_key_codes.cs b/RFIDwedge2/virtual_key_codes.cs deleted file mode 100644 index ac1c9c9..0000000 --- a/RFIDwedge2/virtual_key_codes.cs +++ /dev/null @@ -1,564 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -namespace VKEYS -{ - static class virtual_key_codes - { - /// - /// a list of known VKEY values as enumeration - /// - public enum V_KEY : byte - { - VK_NULL, - VK_LBUTTON, - VK_RBUTTON, - VK_CANCEL, - VK_MBUTTON, - undef_0x05, - undef_0x06, - undef_0x07, - VK_BACK, - VK_TAB, - undef_0x0A, - undef_0x0B, - VK_CLEAR, - VK_RETURN, - undef_0x0E, - undef_0x0F, - VK_SHIFT, - VK_CONTROL, - VK_MENU, - VK_PAUSE, - VK_CAPITAL, - VK_HANGUL, - undef_0x16, - VK_JUNJA, - VK_FINAL, - VK_KANJI, - undef_0x1A, - VK_ESCAPE, - VK_CONVERT, - VK_NOCONVERT, - undef_0x1E, - undef_0x1F, - VK_SPACE, - VK_PRIOR, - VK_NEXT, - VK_END, - VK_HOME, - VK_LEFT, - VK_UP, - VK_RIGHT, - VK_DOWN, - VK_SELECT, - VK_PRINT, - VK_EXECUTE, - VK_SNAPSHOT, - VK_INSERT, - VK_DELETE, - VK_HELP, - VK_0, - VK_1, - VK_2, - VK_3, - VK_4, - VK_5, - VK_6, - VK_7, - VK_8, - VK_9, - undef_0x3A, - undef_0x3B, - undef_0x3C, - undef_0x3D, - undef_0x3E, - undef_0x3F, - undef_0x40, - VK_A, - VK_B, - VK_C, - VK_D, - VK_E, - VK_F, - VK_G, - VK_H, - VK_I, - VK_J, - VK_K, - VK_L, - VK_M, - VK_N, - VK_O, - VK_P, - VK_Q, - VK_R, - VK_S, - VK_T, - VK_U, - VK_V, - VK_W, - VK_X, - VK_Y, - VK_Z, - VK_LWIN, - VK_RWIN, - VK_APPS, - undef_0x5E, - VK_SLEEP, - VK_NUMPAD0, - VK_NUMPAD1, - VK_NUMPAD2, - VK_NUMPAD3, - VK_NUMPAD4, - VK_NUMPAD5, - VK_NUMPAD6, - VK_NUMPAD7, - VK_NUMPAD8, - VK_NUMPAD9, - VK_MULTIPLY, - VK_ADD, - VK_SEPARATOR, - VK_SUBTRACT, - VK_DECIMAL, - VK_DIVIDE, - VK_F1, - VK_F2, - VK_F3, - VK_F4, - VK_F5, - VK_F6, - VK_F7, - VK_F8, - VK_F9, - VK_F10, - VK_F11, - VK_F12, - VK_F13, - VK_F14, - VK_F15, - VK_F16, - VK_F17, - VK_F18, - VK_F19, - VK_F20, - VK_F21, - VK_F22, - VK_F23, - VK_F24, - undef_0x88, - undef_0x89, - undef_0x8A, - undef_0x8B, - undef_0x8C, - undef_0x8D, - undef_0x8E, - undef_0x8F, - VK_NUMLOCK, - VK_SCROLL, - undef_0x92, - undef_0x93, - undef_0x94, - undef_0x95, - undef_0x96, - undef_0x97, - undef_0x98, - undef_0x99, - undef_0x9A, - undef_0x9B, - undef_0x9C_light, //0x9c controls screen backlight on CN50 - undef_0x9D, - undef_0x9E, - undef_0x9F, - VK_LSHIFT, - VK_RSHIFT, - VK_LCONTROL, - VK_RCONTROL, - VK_LMENU, - VK_RMENU, - VK_BROWSER_BACK, - VK_BROWSER_FORWARD, - VK_BROWSER_REFRESH, - VK_BROWSER_STOP, - VK_BROWSER_SEARCH, - VK_BROWSER_FAVORITES, - VK_BROWSER_HOME, - VK_VOLUME_MUTE, - VK_VOLUME_DOWN, - VK_VOLUME_UP, - VK_MEDIA_NEXT_TRACK, - VK_MEDIA_PREV_TRACK, - VK_MEDIA_STOP, - VK_MEDIA_PLAY_PAUSE, - VK_LAUNCH_MAIL, - VK_LAUNCH_MEDIA_SELECT, - VK_LAUNCH_APP1, - VK_LAUNCH_APP2, - undef_0xB8, - undef_0xB9, - VK_SEMICOLON, - VK_EQUAL, - VK_COMMA, - VK_HYPHEN, - VK_PERIOD, - VK_SLASH, - VK_BACKQUOTE, - VK_APP1, - VK_APP2, - VK_APP3, - VK_APP4, - VK_APP5, - VK_APP6, - undef_0xC7, - undef_0xC8, - undef_0xC9, - undef_0xCA, - undef_0xCB, - undef_0xCC, - undef_0xCD, - undef_0xCE, - undef_0xCF, - undef_0xD0, - undef_0xD1, - undef_0xD2, - undef_0xD3, - undef_0xD4, - undef_0xD5, - undef_0xD6, - undef_0xD7, - undef_0xD8, - undef_0xD9, - undef_0xDA, - VK_LBRACKET, - VK_BACKSLASH, - VK_RBRACKET, - VK_APOSTROPHE, - VK_OFF, - undef_0xE0, - undef_0xE1_SCAN, - VK_EXTEND_BSLASH, - undef_0xE3, - undef_0xE4, - VK_PROCESSKEY, - undef_0xE6, - undef_0xE7, - undef_0xE8, - undef_0xE9, - undef_0xEA, - undef_0xEB, - undef_0xEC, - undef_0xED, - undef_0xEE, - undef_0xEF, - undef_0xF0, - undef_0xF1, - undef_0xF2, - undef_0xF3, - undef_0xF4, - undef_0xF5, - VK_ATTN, - VK_CRSEL, - VK_EXSEL, - VK_EREOF, - VK_PLAY, - VK_ZOOM, - VK_NONAME, - VK_PA1, - VK_OEM_CLEAR, - VK_undef_0xff - } - - // the struct used to save a ASCII <-> VK_ table - public class KTABLE{ - byte kByte; // key byte - string txt; // description - byte kVKval; //the VK value to send for kByte - public byte VKval - { - get { return kVKval; } - } - bool kShift; - public bool bShift - { - get { return kShift; } - } - public KTABLE(byte b, string s, byte val, bool bShift){ - kByte=b; - txt=s; - kVKval = val; - kShift = bShift; - } - public KTABLE(byte b, string s, V_KEY val, bool bShift) - { - kByte = b; - txt = s; - kVKval = (byte)val; - kShift = bShift; - } - }; - - // the translation tabel for ASCII to VK_ values - // first val is byte code to translate and third val is VK_ value to be used with keybd_event and other VK_ functions - public static KTABLE[] vkTable = { - new KTABLE (0x00, "NUL", V_KEY.VK_NULL, false), - new KTABLE (0x01, "SOH", V_KEY.VK_undef_0xff, false), - new KTABLE (0x02, "STX", V_KEY.VK_undef_0xff, false), - new KTABLE (0x03, "ETX", V_KEY.VK_undef_0xff, false), - new KTABLE (0x04, "EOT", V_KEY.VK_undef_0xff, false), - new KTABLE (0x05, "ENQ", V_KEY.VK_undef_0xff, false), - new KTABLE (0x06, "ACK", V_KEY.VK_undef_0xff, false), - new KTABLE (0x07, "BEL", V_KEY.VK_undef_0xff, false), - new KTABLE (0x08, "BS", V_KEY.VK_BACK, false), - new KTABLE (0x09, "HT", V_KEY.VK_TAB, false), - new KTABLE (0x0A, "LF", V_KEY.VK_RETURN, false), - new KTABLE (0x0B, "VT", V_KEY.VK_TAB, false), - new KTABLE (0x0C, "FF", V_KEY.VK_undef_0xff, false), - new KTABLE (0x0D, "CR", V_KEY.VK_RETURN, false), - new KTABLE (0x0E, "SO", V_KEY.VK_undef_0xff, false), - new KTABLE (0x0F, "SI", V_KEY.VK_undef_0xff, false), - new KTABLE (0x10, "DLE", V_KEY.VK_undef_0xff, false), - new KTABLE (0x11, "DC1", V_KEY.VK_undef_0xff, false), - new KTABLE (0x12, "DC2", V_KEY.VK_undef_0xff, false), - new KTABLE (0x13, "DC3", V_KEY.VK_undef_0xff, false), - new KTABLE (0x14, "DC4", V_KEY.VK_undef_0xff, false), - new KTABLE (0x15, "NAK", V_KEY.VK_undef_0xff, false), - new KTABLE (0x16, "SYN", V_KEY.VK_undef_0xff, false), - new KTABLE (0x17, "ETB", V_KEY.VK_undef_0xff, false), - new KTABLE (0x18, "CAN", V_KEY.VK_undef_0xff, false), - new KTABLE (0x19, "EM", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1A, "SUB", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1B, "ESC", V_KEY.VK_ESCAPE, false), - new KTABLE (0x1C, "FS", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1D, "GS", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1E, "RS", V_KEY.VK_undef_0xff, false), - new KTABLE (0x1F, "US", V_KEY.VK_undef_0xff, false), - new KTABLE (0x20, " ", V_KEY.VK_SPACE, false), - new KTABLE (0x21, "!", V_KEY.VK_1, true), - new KTABLE (0x22, "\"", V_KEY.VK_APOSTROPHE, true), - new KTABLE (0x23, "#", V_KEY.VK_3, true), - new KTABLE (0x24, "$", V_KEY.VK_4, true), - new KTABLE (0x25, "%", V_KEY.VK_5, true), - new KTABLE (0x26, "&", V_KEY.VK_7, true), - new KTABLE (0x27, "'", V_KEY.VK_APOSTROPHE, false), - new KTABLE (0x28, "(", V_KEY.VK_9, true), - new KTABLE (0x29, ")", V_KEY.VK_0, true), - new KTABLE (0x2A, "*", V_KEY.VK_8, true), - new KTABLE (0x2B, "+", V_KEY.VK_EQUAL, true), - new KTABLE (0x2C, ",", V_KEY.VK_COMMA, false), - new KTABLE (0x2D, "-", V_KEY.VK_HYPHEN, false), - new KTABLE (0x2E, ".", V_KEY.VK_PERIOD, false), - new KTABLE (0x2F, "/", V_KEY.VK_SLASH, false), - new KTABLE (0x30, "0", V_KEY.VK_0, false), - new KTABLE (0x31, "1", V_KEY.VK_1, false), - new KTABLE (0x32, "2", V_KEY.VK_2, false), - new KTABLE (0x33, "3", V_KEY.VK_3, false), - new KTABLE (0x34, "4", V_KEY.VK_4, false), - new KTABLE (0x35, "5", V_KEY.VK_5, false), - new KTABLE (0x36, "6", V_KEY.VK_6, false), - new KTABLE (0x37, "7", V_KEY.VK_7, false), - new KTABLE (0x38, "8", V_KEY.VK_8, false), - new KTABLE (0x39, "9", V_KEY.VK_9, false), - new KTABLE (0x3A, ":", V_KEY.VK_SEMICOLON, true), - new KTABLE (0x3B, ";", V_KEY.VK_SEMICOLON, false), - new KTABLE (0x3C, "<", V_KEY.VK_COMMA, true), - new KTABLE (0x3D, "=", V_KEY.VK_EQUAL, false), - new KTABLE (0x3E, ">", V_KEY.VK_PERIOD, true), - new KTABLE (0x3F, "?", V_KEY.VK_SLASH, true), - new KTABLE (0x40, "@", V_KEY.VK_2, true), - new KTABLE (0x41, "A", V_KEY.VK_A, true), - new KTABLE (0x42, "B", V_KEY.VK_B, true), - new KTABLE (0x43, "C", V_KEY.VK_C, true), - new KTABLE (0x44, "D", V_KEY.VK_D, true), - new KTABLE (0x45, "E", V_KEY.VK_E, true), - new KTABLE (0x46, "F", V_KEY.VK_F, true), - new KTABLE (0x47, "G", V_KEY.VK_G, true), - new KTABLE (0x48, "H", V_KEY.VK_H, true), - new KTABLE (0x49, "I", V_KEY.VK_I, true), - new KTABLE (0x4A, "J", V_KEY.VK_J, true), - new KTABLE (0x4B, "K", V_KEY.VK_K, true), - new KTABLE (0x4C, "L", V_KEY.VK_L, true), - new KTABLE (0x4D, "M", V_KEY.VK_M, true), - new KTABLE (0x4E, "N", V_KEY.VK_N, true), - new KTABLE (0x4F, "O", V_KEY.VK_O, true), - new KTABLE (0x50, "P", V_KEY.VK_P, true), - new KTABLE (0x51, "Q", V_KEY.VK_Q, true), - new KTABLE (0x52, "R", V_KEY.VK_R, true), - new KTABLE (0x53, "S", V_KEY.VK_S, true), - new KTABLE (0x54, "T", V_KEY.VK_T, true), - new KTABLE (0x55, "U", V_KEY.VK_U, true), - new KTABLE (0x56, "V", V_KEY.VK_V, true), - new KTABLE (0x57, "W", V_KEY.VK_W, true), - new KTABLE (0x58, "X", V_KEY.VK_X, true), - new KTABLE (0x59, "Y", V_KEY.VK_Y, true), - new KTABLE (0x5A, "Z", V_KEY.VK_Z, true), - new KTABLE (0x5B, "[", V_KEY.VK_LBRACKET, false), - new KTABLE (0x5C, "\\", V_KEY.VK_BACKSLASH, false), - new KTABLE (0x5D, "]", V_KEY.VK_RBRACKET, false), - new KTABLE (0x5E, "^", V_KEY.VK_6, true), - new KTABLE (0x5F, "_", V_KEY.VK_HYPHEN, true), - new KTABLE (0x60, "`", V_KEY.VK_BACKQUOTE, false), - new KTABLE (0x61, "a", V_KEY.VK_A, false), - new KTABLE (0x62, "b", V_KEY.VK_B, false), - new KTABLE (0x63, "c", V_KEY.VK_C, false), - new KTABLE (0x64, "d", V_KEY.VK_D, false), - new KTABLE (0x65, "e", V_KEY.VK_E, false), - new KTABLE (0x66, "f", V_KEY.VK_F, false), - new KTABLE (0x67, "g", V_KEY.VK_G, false), - new KTABLE (0x68, "h", V_KEY.VK_H, false), - new KTABLE (0x69, "i", V_KEY.VK_I, false), - new KTABLE (0x6A, "j", V_KEY.VK_J, false), - new KTABLE (0x6B, "k", V_KEY.VK_K, false), - new KTABLE (0x6C, "l", V_KEY.VK_L, false), - new KTABLE (0x6D, "m", V_KEY.VK_M, false), - new KTABLE (0x6E, "n", V_KEY.VK_N, false), - new KTABLE (0x6F, "o", V_KEY.VK_O, false), - new KTABLE (0x70, "p", V_KEY.VK_P, false), - new KTABLE (0x71, "q", V_KEY.VK_Q, false), - new KTABLE (0x72, "r", V_KEY.VK_R, false), - new KTABLE (0x73, "s", V_KEY.VK_S, false), - new KTABLE (0x74, "t", V_KEY.VK_T, false), - new KTABLE (0x75, "u", V_KEY.VK_U, false), - new KTABLE (0x76, "v", V_KEY.VK_V, false), - new KTABLE (0x77, "w", V_KEY.VK_W, false), - new KTABLE (0x78, "x", V_KEY.VK_X, false), - new KTABLE (0x79, "y", V_KEY.VK_Y, false), - new KTABLE (0x7A, "z", V_KEY.VK_Z, false), - new KTABLE (0x7B, "{", V_KEY.VK_LBRACKET, true), - new KTABLE (0x7C, "|", V_KEY.VK_BACKSLASH, true), - new KTABLE (0x7D, "}", V_KEY.VK_RBRACKET, true), - new KTABLE (0x7E, "~", V_KEY.VK_BACKQUOTE, true), - new KTABLE (0x7F, "DEL", V_KEY.VK_DELETE, false), - //this will not come from ASCII barcode readers - new KTABLE (0x80, "\x80", 0x80, true), - new KTABLE (0x81, "\x81", 0x81, true), - new KTABLE (0x82, "\x82", 0x82, true), - new KTABLE (0x83, "\x83", 0x83, true), - new KTABLE (0x84, "\x84", 0x84, true), - new KTABLE (0x85, "\x85", 0x85, true), - new KTABLE (0x86, "\x86", 0x86, true), - new KTABLE (0x87, "\x87", 0x87, true), - new KTABLE (0x88, "\x88", 0x88, true), - new KTABLE (0x89, "\x89", 0x89, true), - new KTABLE (0x8A, "\x8A", 0x8A, true), - new KTABLE (0x8B, "\x8B", 0x8B, true), - new KTABLE (0x8C, "\x8C", 0x8C, true), - new KTABLE (0x8D, "\x8D", 0x8D, true), - new KTABLE (0x8E, "\x8E", 0x8E, true), - new KTABLE (0x8F, "\x8F", 0x8F, true), - new KTABLE (0x90, "\x90", 0x90, true), - new KTABLE (0x91, "\x91", 0x91, true), - new KTABLE (0x92, "\x92", 0x92, true), - new KTABLE (0x93, "\x93", 0x93, true), - new KTABLE (0x94, "\x94", 0x94, true), - new KTABLE (0x95, "\x95", 0x95, true), - new KTABLE (0x96, "\x96", 0x96, true), - new KTABLE (0x97, "\x97", 0x97, true), - new KTABLE (0x98, "\x98", 0x98, true), - new KTABLE (0x99, "\x99", 0x99, true), - new KTABLE (0x9A, "\x9A", 0x9A, true), - new KTABLE (0x9B, "\x9B", 0x9B, true), - new KTABLE (0x9C, "\x9C", 0x9C, true), - new KTABLE (0x9D, "\x9D", 0x9D, true), - new KTABLE (0x9E, "\x9E", 0x9E, true), - new KTABLE (0x9F, "\x9F", 0x9F, true), - new KTABLE (0xA0, "\xA0", 0xA0, true), - new KTABLE (0xA1, "¡", 0xA1, true), - new KTABLE (0xA2, "¢", 0xA2, true), - new KTABLE (0xA3, "£", 0xA3, true), - new KTABLE (0xA4, "¤", 0xA4, true), - new KTABLE (0xA5, "¥", 0xA5, true), - new KTABLE (0xA6, "¦", 0xA6, true), - new KTABLE (0xA7, "§", 0xA7, true), - new KTABLE (0xA8, "¨", 0xA8, true), - new KTABLE (0xA9, "©", 0xA9, true), - new KTABLE (0xAA, "ª", 0xAA, true), - new KTABLE (0xAB, "«", 0xAB, true), - new KTABLE (0xAC, "¬", 0xAC, true), - new KTABLE (0xAD, "­", 0xAD, true), - new KTABLE (0xAE, "®", 0xAE, true), - new KTABLE (0xAF, "¯", 0xAF, true), - new KTABLE (0xB0, "°", 0xB0, true), - new KTABLE (0xB1, "±", 0xB1, true), - new KTABLE (0xB2, "²", 0xB2, true), - new KTABLE (0xB3, "³", 0xB3, true), - new KTABLE (0xB4, "´", 0xB4, true), - new KTABLE (0xB5, "µ", 0xB5, true), - new KTABLE (0xB6, "¶", 0xB6, true), - new KTABLE (0xB7, "·", 0xB7, true), - new KTABLE (0xB8, "¸", 0xB8, true), - new KTABLE (0xB9, "¹", 0xB9, true), - new KTABLE (0xBA, "º", 0xBA, true), - new KTABLE (0xBB, "»", 0xBB, true), - new KTABLE (0xBC, "¼", 0xBC, true), - new KTABLE (0xBD, "½", 0xBD, true), - new KTABLE (0xBE, "¾", 0xBE, true), - new KTABLE (0xBF, "¿", 0xBF, true), - new KTABLE (0xC0, "À", 0xC0, true), - new KTABLE (0xC1, "Á", 0xC1, true), - new KTABLE (0xC2, "Â", 0xC2, true), - new KTABLE (0xC3, "Ã", 0xC3, true), - new KTABLE (0xC4, "Ä", 0xC4, true), - new KTABLE (0xC5, "Å", 0xC5, true), - new KTABLE (0xC6, "Æ", 0xC6, true), - new KTABLE (0xC7, "Ç", 0xC7, true), - new KTABLE (0xC8, "È", 0xC8, true), - new KTABLE (0xC9, "É", 0xC9, true), - new KTABLE (0xCA, "Ê", 0xCA, true), - new KTABLE (0xCB, "Ë", 0xCB, true), - new KTABLE (0xCC, "Ì", 0xCC, true), - new KTABLE (0xCD, "Í", 0xCD, true), - new KTABLE (0xCE, "Î", 0xCE, true), - new KTABLE (0xCF, "Ï", 0xCF, true), - new KTABLE (0xD0, "Ð", 0xD0, true), - new KTABLE (0xD1, "Ñ", 0xD1, true), - new KTABLE (0xD2, "Ò", 0xD2, true), - new KTABLE (0xD3, "Ó", 0xD3, true), - new KTABLE (0xD4, "Ô", 0xD4, true), - new KTABLE (0xD5, "Õ", 0xD5, true), - new KTABLE (0xD6, "Ö", 0xD6, true), - new KTABLE (0xD7, "×", 0xD7, true), - new KTABLE (0xD8, "Ø", 0xD8, true), - new KTABLE (0xD9, "Ù", 0xD9, true), - new KTABLE (0xDA, "Ú", 0xDA, true), - new KTABLE (0xDB, "Û", 0xDB, true), - new KTABLE (0xDC, "Ü", 0xDC, true), - new KTABLE (0xDD, "Ý", 0xDD, true), - new KTABLE (0xDE, "Þ", 0xDE, true), - new KTABLE (0xDF, "ß", 0xDF, true), - new KTABLE (0xE0, "à", 0xE0, true), - new KTABLE (0xE1, "á", 0xE1, true), - new KTABLE (0xE2, "â", 0xE2, true), - new KTABLE (0xE3, "ã", 0xE3, true), - new KTABLE (0xE4, "ä", 0xE4, true), - new KTABLE (0xE5, "å", 0xE5, true), - new KTABLE (0xE6, "æ", 0xE6, true), - new KTABLE (0xE7, "ç", 0xE7, true), - new KTABLE (0xE8, "è", 0xE8, true), - new KTABLE (0xE9, "é", 0xE9, true), - new KTABLE (0xEA, "ê", 0xEA, true), - new KTABLE (0xEB, "ë", 0xEB, true), - new KTABLE (0xEC, "ì", 0xEC, true), - new KTABLE (0xED, "í", 0xED, true), - new KTABLE (0xEE, "î", 0xEE, true), - new KTABLE (0xEF, "ï", 0xEF, true), - new KTABLE (0xF0, "ð", 0xF0, true), - new KTABLE (0xF1, "ñ", 0xF1, true), - new KTABLE (0xF2, "ò", 0xF2, true), - new KTABLE (0xF3, "ó", 0xF3, true), - new KTABLE (0xF4, "ô", 0xF4, true), - new KTABLE (0xF5, "õ", 0xF5, true), - new KTABLE (0xF6, "ö", 0xF6, true), - new KTABLE (0xF7, "÷", 0xF7, true), - new KTABLE (0xF8, "ø", 0xF8, true), - new KTABLE (0xF9, "ù", 0xF9, true), - new KTABLE (0xFA, "ú", 0xFA, true), - new KTABLE (0xFB, "û", 0xFB, true), - new KTABLE (0xFC, "ü", 0xFC, true), - new KTABLE (0xFD, "ý", 0xFD, true), - new KTABLE (0xFE, "þ", 0xFE, true), - new KTABLE (0xFF, "ÿ", 0xFF, true) - }; - } -} diff --git a/SensorScan5.md b/SensorScan5.md new file mode 100644 index 0000000..712acbd --- /dev/null +++ b/SensorScan5.md @@ -0,0 +1,18 @@ +#Description of SensorScan5 solution + +# SensorScan5 # + +An experimental code to detect shakes/movements using a G-sensor (accelerometer). + +For details see: +[Blog article](http://www.hjgode.de/wp/2011/02/13/mobile-development-shake-that-thing/) + +# Details # + +This code is written for Intermec Sensor library. Needs to be adopted for other sensor devices like HTC Windows Mobile. + +--- + + * Needs Intermec device and libs if compiled with USE\_SCANNER + * Visual Studio 2008 SmartDevice C# solution + * uses a modified perfChart class, original published at codeproject: [PerfChart Class](http://www.codeproject.com/KB/miscctrl/SimplePerfChart.aspx) \ No newline at end of file diff --git a/SensorScan5/EventAction.cs b/SensorScan5/EventAction.cs deleted file mode 100644 index 3f07699..0000000 --- a/SensorScan5/EventAction.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -namespace NativeSync -{ - enum EventAction : int - { - Pulse = 1, - Reset = 2, - Set = 3 - } -} diff --git a/SensorScan5/Form1.Designer.cs b/SensorScan5/Form1.Designer.cs deleted file mode 100644 index 489e28b..0000000 --- a/SensorScan5/Form1.Designer.cs +++ /dev/null @@ -1,828 +0,0 @@ -namespace SensorScan5 -{ - partial class mainFrm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - SpPerfChart.PerfChartStyle perfChartStyle1 = new SpPerfChart.PerfChartStyle(); - SpPerfChart.ChartPen chartPen1 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen2 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen3 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen4 = new SpPerfChart.ChartPen(); - SpPerfChart.PerfChartStyle perfChartStyle2 = new SpPerfChart.PerfChartStyle(); - SpPerfChart.ChartPen chartPen5 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen6 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen7 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen8 = new SpPerfChart.ChartPen(); - SpPerfChart.PerfChartStyle perfChartStyle3 = new SpPerfChart.PerfChartStyle(); - SpPerfChart.ChartPen chartPen9 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen10 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen11 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen12 = new SpPerfChart.ChartPen(); - SpPerfChart.PerfChartStyle perfChartStyle4 = new SpPerfChart.PerfChartStyle(); - SpPerfChart.ChartPen chartPen13 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen14 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen15 = new SpPerfChart.ChartPen(); - SpPerfChart.ChartPen chartPen16 = new SpPerfChart.ChartPen(); - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.menuItem1 = new System.Windows.Forms.MenuItem(); - this.tabControl1 = new System.Windows.Forms.TabControl(); - this.tabPage1 = new System.Windows.Forms.TabPage(); - this.cbSensity = new System.Windows.Forms.ComboBox(); - this.label16 = new System.Windows.Forms.Label(); - this.label8 = new System.Windows.Forms.Label(); - this.label7 = new System.Windows.Forms.Label(); - this.label6 = new System.Windows.Forms.Label(); - this.label5 = new System.Windows.Forms.Label(); - this.label4 = new System.Windows.Forms.Label(); - this.label3 = new System.Windows.Forms.Label(); - this.label10 = new System.Windows.Forms.Label(); - this.label1 = new System.Windows.Forms.Label(); - this.label2 = new System.Windows.Forms.Label(); - this.lblAcceleration = new System.Windows.Forms.Label(); - this.lblRoll = new System.Windows.Forms.Label(); - this.lblPitch = new System.Windows.Forms.Label(); - this.lblTilt = new System.Windows.Forms.Label(); - this.lblDirection = new System.Windows.Forms.Label(); - this.lblOrientation = new System.Windows.Forms.Label(); - this.labelGFZ = new System.Windows.Forms.Label(); - this.labelGFY = new System.Windows.Forms.Label(); - this.labelGFX = new System.Windows.Forms.Label(); - this.tabPage2 = new System.Windows.Forms.TabPage(); - this.txtLog = new System.Windows.Forms.TextBox(); - this.tabPage3 = new System.Windows.Forms.TabPage(); - this.perfChart4 = new SpPerfChart.PerfChart(); - this.perfChart3 = new SpPerfChart.PerfChart(); - this.perfChart2 = new SpPerfChart.PerfChart(); - this.perfChart1 = new SpPerfChart.PerfChart(); - this.tabPage4 = new System.Windows.Forms.TabPage(); - this.txtShake5Treshold = new System.Windows.Forms.TextBox(); - this.trackBar5 = new System.Windows.Forms.TrackBar(); - this.txtShake4Treshold = new System.Windows.Forms.TextBox(); - this.trackBar4 = new System.Windows.Forms.TrackBar(); - this.txtShake3Treshold = new System.Windows.Forms.TextBox(); - this.trackBar2 = new System.Windows.Forms.TrackBar(); - this.txt6Treshold = new System.Windows.Forms.TextBox(); - this.trackBar6 = new System.Windows.Forms.TrackBar(); - this.txtShake2Treshold = new System.Windows.Forms.TextBox(); - this.trackBar1 = new System.Windows.Forms.TrackBar(); - this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); - this.lblShake9 = new System.Windows.Forms.Label(); - this.lblShake8 = new System.Windows.Forms.Label(); - this.lblShake7 = new System.Windows.Forms.Label(); - this.lblShake6 = new System.Windows.Forms.Label(); - this.lblShake5 = new System.Windows.Forms.Label(); - this.lblShake4 = new System.Windows.Forms.Label(); - this.lblShake3 = new System.Windows.Forms.Label(); - this.lbShake2 = new System.Windows.Forms.Label(); - this.lblShake1 = new System.Windows.Forms.Label(); - this.btnTEST = new System.Windows.Forms.Button(); - this.tabControl1.SuspendLayout(); - this.tabPage1.SuspendLayout(); - this.tabPage2.SuspendLayout(); - this.tabPage3.SuspendLayout(); - this.tabPage4.SuspendLayout(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.menuItem1); - // - // menuItem1 - // - this.menuItem1.Text = "Exit"; - this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click); - // - // tabControl1 - // - this.tabControl1.Controls.Add(this.tabPage1); - this.tabControl1.Controls.Add(this.tabPage2); - this.tabControl1.Controls.Add(this.tabPage3); - this.tabControl1.Controls.Add(this.tabPage4); - this.tabControl1.Dock = System.Windows.Forms.DockStyle.Bottom; - this.tabControl1.Location = new System.Drawing.Point(0, 3); - this.tabControl1.Name = "tabControl1"; - this.tabControl1.SelectedIndex = 0; - this.tabControl1.Size = new System.Drawing.Size(240, 265); - this.tabControl1.TabIndex = 0; - // - // tabPage1 - // - this.tabPage1.Controls.Add(this.cbSensity); - this.tabPage1.Controls.Add(this.label16); - this.tabPage1.Controls.Add(this.label8); - this.tabPage1.Controls.Add(this.label7); - this.tabPage1.Controls.Add(this.label6); - this.tabPage1.Controls.Add(this.label5); - this.tabPage1.Controls.Add(this.label4); - this.tabPage1.Controls.Add(this.label3); - this.tabPage1.Controls.Add(this.label10); - this.tabPage1.Controls.Add(this.label1); - this.tabPage1.Controls.Add(this.label2); - this.tabPage1.Controls.Add(this.lblAcceleration); - this.tabPage1.Controls.Add(this.lblRoll); - this.tabPage1.Controls.Add(this.lblPitch); - this.tabPage1.Controls.Add(this.lblTilt); - this.tabPage1.Controls.Add(this.lblDirection); - this.tabPage1.Controls.Add(this.lblOrientation); - this.tabPage1.Controls.Add(this.labelGFZ); - this.tabPage1.Controls.Add(this.labelGFY); - this.tabPage1.Controls.Add(this.labelGFX); - this.tabPage1.Location = new System.Drawing.Point(0, 0); - this.tabPage1.Name = "tabPage1"; - this.tabPage1.Size = new System.Drawing.Size(240, 242); - this.tabPage1.Text = "data"; - // - // cbSensity - // - this.cbSensity.BackColor = System.Drawing.Color.MistyRose; - this.cbSensity.Items.Add("0.0"); - this.cbSensity.Items.Add("1.0"); - this.cbSensity.Items.Add("0.1"); - this.cbSensity.Items.Add("0.01"); - this.cbSensity.Items.Add("0.001"); - this.cbSensity.Location = new System.Drawing.Point(146, 174); - this.cbSensity.Name = "cbSensity"; - this.cbSensity.Size = new System.Drawing.Size(75, 22); - this.cbSensity.TabIndex = 53; - this.cbSensity.SelectedIndexChanged += new System.EventHandler(this.cbSensity_SelectedIndexChanged_1); - // - // label16 - // - this.label16.BackColor = System.Drawing.Color.MistyRose; - this.label16.Location = new System.Drawing.Point(7, 174); - this.label16.Name = "label16"; - this.label16.Size = new System.Drawing.Size(66, 19); - this.label16.Text = "Sensity:"; - // - // label8 - // - this.label8.Location = new System.Drawing.Point(109, 25); - this.label8.Name = "label8"; - this.label8.Size = new System.Drawing.Size(29, 14); - this.label8.Text = "Z:"; - this.label8.TextAlign = System.Drawing.ContentAlignment.TopRight; - // - // label7 - // - this.label7.Location = new System.Drawing.Point(109, 42); - this.label7.Name = "label7"; - this.label7.Size = new System.Drawing.Size(29, 14); - this.label7.Text = "Y:"; - this.label7.TextAlign = System.Drawing.ContentAlignment.TopRight; - // - // label6 - // - this.label6.Location = new System.Drawing.Point(109, 9); - this.label6.Name = "label6"; - this.label6.Size = new System.Drawing.Size(29, 14); - this.label6.Text = "X:"; - this.label6.TextAlign = System.Drawing.ContentAlignment.TopRight; - // - // label5 - // - this.label5.Location = new System.Drawing.Point(89, 86); - this.label5.Name = "label5"; - this.label5.Size = new System.Drawing.Size(35, 14); - this.label5.Text = "Roll:"; - // - // label4 - // - this.label4.Location = new System.Drawing.Point(48, 85); - this.label4.Name = "label4"; - this.label4.Size = new System.Drawing.Size(35, 14); - this.label4.Text = "Pitch:"; - // - // label3 - // - this.label3.Location = new System.Drawing.Point(7, 85); - this.label3.Name = "label3"; - this.label3.Size = new System.Drawing.Size(35, 14); - this.label3.Text = "Tilt:"; - // - // label10 - // - this.label10.Location = new System.Drawing.Point(7, 129); - this.label10.Name = "label10"; - this.label10.Size = new System.Drawing.Size(76, 14); - this.label10.Text = "Acceleration:"; - // - // label1 - // - this.label1.Location = new System.Drawing.Point(7, 71); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(76, 14); - this.label1.Text = "Orientation:"; - // - // label2 - // - this.label2.Location = new System.Drawing.Point(7, 9); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(76, 14); - this.label2.Text = "Acceleration:"; - // - // lblAcceleration - // - this.lblAcceleration.Location = new System.Drawing.Point(144, 129); - this.lblAcceleration.Name = "lblAcceleration"; - this.lblAcceleration.Size = new System.Drawing.Size(77, 14); - this.lblAcceleration.Text = "-"; - this.lblAcceleration.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblRoll - // - this.lblRoll.Location = new System.Drawing.Point(89, 99); - this.lblRoll.Name = "lblRoll"; - this.lblRoll.Size = new System.Drawing.Size(35, 14); - this.lblRoll.Text = "-"; - this.lblRoll.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblPitch - // - this.lblPitch.Location = new System.Drawing.Point(48, 99); - this.lblPitch.Name = "lblPitch"; - this.lblPitch.Size = new System.Drawing.Size(35, 14); - this.lblPitch.Text = "-"; - this.lblPitch.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblTilt - // - this.lblTilt.Location = new System.Drawing.Point(7, 99); - this.lblTilt.Name = "lblTilt"; - this.lblTilt.Size = new System.Drawing.Size(35, 14); - this.lblTilt.Text = "-"; - this.lblTilt.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblDirection - // - this.lblDirection.Location = new System.Drawing.Point(144, 85); - this.lblDirection.Name = "lblDirection"; - this.lblDirection.Size = new System.Drawing.Size(77, 14); - this.lblDirection.Text = "-"; - this.lblDirection.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblOrientation - // - this.lblOrientation.Location = new System.Drawing.Point(144, 71); - this.lblOrientation.Name = "lblOrientation"; - this.lblOrientation.Size = new System.Drawing.Size(77, 14); - this.lblOrientation.Text = "-"; - this.lblOrientation.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // labelGFZ - // - this.labelGFZ.Location = new System.Drawing.Point(144, 25); - this.labelGFZ.Name = "labelGFZ"; - this.labelGFZ.Size = new System.Drawing.Size(77, 14); - this.labelGFZ.Text = "-"; - this.labelGFZ.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // labelGFY - // - this.labelGFY.Location = new System.Drawing.Point(144, 40); - this.labelGFY.Name = "labelGFY"; - this.labelGFY.Size = new System.Drawing.Size(77, 16); - this.labelGFY.Text = "-"; - this.labelGFY.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // labelGFX - // - this.labelGFX.Location = new System.Drawing.Point(144, 9); - this.labelGFX.Name = "labelGFX"; - this.labelGFX.Size = new System.Drawing.Size(77, 14); - this.labelGFX.Text = "-"; - this.labelGFX.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // tabPage2 - // - this.tabPage2.Controls.Add(this.txtLog); - this.tabPage2.Location = new System.Drawing.Point(0, 0); - this.tabPage2.Name = "tabPage2"; - this.tabPage2.Size = new System.Drawing.Size(232, 239); - this.tabPage2.Text = "log"; - // - // txtLog - // - this.txtLog.AcceptsReturn = true; - this.txtLog.AcceptsTab = true; - this.txtLog.BackColor = System.Drawing.SystemColors.Control; - this.txtLog.Location = new System.Drawing.Point(3, 3); - this.txtLog.Multiline = true; - this.txtLog.Name = "txtLog"; - this.txtLog.ReadOnly = true; - this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtLog.Size = new System.Drawing.Size(226, 206); - this.txtLog.TabIndex = 1; - this.txtLog.Text = "log"; - this.txtLog.WordWrap = false; - // - // tabPage3 - // - this.tabPage3.Controls.Add(this.perfChart4); - this.tabPage3.Controls.Add(this.perfChart3); - this.tabPage3.Controls.Add(this.perfChart2); - this.tabPage3.Controls.Add(this.perfChart1); - this.tabPage3.Location = new System.Drawing.Point(0, 0); - this.tabPage3.Name = "tabPage3"; - this.tabPage3.Size = new System.Drawing.Size(232, 239); - this.tabPage3.Text = "graph"; - // - // perfChart4 - // - this.perfChart4._maxDecimal = new decimal(new int[] { - 100, - 0, - 0, - 0}); - perfChartStyle1.AntiAliasing = true; - chartPen1.Color = System.Drawing.Color.Black; - chartPen1.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen1.Width = 1F; - perfChartStyle1.AvgLinePen = chartPen1; - perfChartStyle1.BackgroundColorBottom = System.Drawing.Color.DarkGreen; - perfChartStyle1.BackgroundColorTop = System.Drawing.Color.DarkGreen; - chartPen2.Color = System.Drawing.Color.Black; - chartPen2.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen2.Width = 1F; - perfChartStyle1.ChartLinePen = chartPen2; - chartPen3.Color = System.Drawing.Color.Black; - chartPen3.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen3.Width = 1F; - perfChartStyle1.HorizontalGridPen = chartPen3; - perfChartStyle1.ShowAverageLine = true; - perfChartStyle1.ShowHorizontalGridLines = true; - perfChartStyle1.ShowVerticalGridLines = true; - chartPen4.Color = System.Drawing.Color.Black; - chartPen4.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen4.Width = 1F; - perfChartStyle1.VerticalGridPen = chartPen4; - this.perfChart4._PerfChartStyle = perfChartStyle1; - this.perfChart4._ScaleMode = SpPerfChart.ScaleMode.Absolute; - this.perfChart4._SymmetricDisplay = true; - this.perfChart4._TimerInterval = 100; - this.perfChart4._TimerMode = SpPerfChart.TimerMode.Disabled; - this.perfChart4.Location = new System.Drawing.Point(4, 160); - this.perfChart4.Name = "perfChart4"; - this.perfChart4.Size = new System.Drawing.Size(227, 47); - this.perfChart4.TabIndex = 0; - // - // perfChart3 - // - this.perfChart3._maxDecimal = new decimal(new int[] { - 100, - 0, - 0, - 0}); - perfChartStyle2.AntiAliasing = true; - chartPen5.Color = System.Drawing.Color.Black; - chartPen5.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen5.Width = 1F; - perfChartStyle2.AvgLinePen = chartPen5; - perfChartStyle2.BackgroundColorBottom = System.Drawing.Color.DarkGreen; - perfChartStyle2.BackgroundColorTop = System.Drawing.Color.DarkGreen; - chartPen6.Color = System.Drawing.Color.Black; - chartPen6.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen6.Width = 1F; - perfChartStyle2.ChartLinePen = chartPen6; - chartPen7.Color = System.Drawing.Color.Black; - chartPen7.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen7.Width = 1F; - perfChartStyle2.HorizontalGridPen = chartPen7; - perfChartStyle2.ShowAverageLine = true; - perfChartStyle2.ShowHorizontalGridLines = true; - perfChartStyle2.ShowVerticalGridLines = true; - chartPen8.Color = System.Drawing.Color.Black; - chartPen8.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen8.Width = 1F; - perfChartStyle2.VerticalGridPen = chartPen8; - this.perfChart3._PerfChartStyle = perfChartStyle2; - this.perfChart3._ScaleMode = SpPerfChart.ScaleMode.Absolute; - this.perfChart3._SymmetricDisplay = true; - this.perfChart3._TimerInterval = 100; - this.perfChart3._TimerMode = SpPerfChart.TimerMode.Disabled; - this.perfChart3.Location = new System.Drawing.Point(4, 102); - this.perfChart3.Name = "perfChart3"; - this.perfChart3.Size = new System.Drawing.Size(227, 47); - this.perfChart3.TabIndex = 0; - // - // perfChart2 - // - this.perfChart2._maxDecimal = new decimal(new int[] { - 100, - 0, - 0, - 0}); - perfChartStyle3.AntiAliasing = true; - chartPen9.Color = System.Drawing.Color.Black; - chartPen9.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen9.Width = 1F; - perfChartStyle3.AvgLinePen = chartPen9; - perfChartStyle3.BackgroundColorBottom = System.Drawing.Color.DarkGreen; - perfChartStyle3.BackgroundColorTop = System.Drawing.Color.DarkGreen; - chartPen10.Color = System.Drawing.Color.Black; - chartPen10.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen10.Width = 1F; - perfChartStyle3.ChartLinePen = chartPen10; - chartPen11.Color = System.Drawing.Color.Black; - chartPen11.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen11.Width = 1F; - perfChartStyle3.HorizontalGridPen = chartPen11; - perfChartStyle3.ShowAverageLine = true; - perfChartStyle3.ShowHorizontalGridLines = true; - perfChartStyle3.ShowVerticalGridLines = true; - chartPen12.Color = System.Drawing.Color.Black; - chartPen12.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen12.Width = 1F; - perfChartStyle3.VerticalGridPen = chartPen12; - this.perfChart2._PerfChartStyle = perfChartStyle3; - this.perfChart2._ScaleMode = SpPerfChart.ScaleMode.Absolute; - this.perfChart2._SymmetricDisplay = true; - this.perfChart2._TimerInterval = 100; - this.perfChart2._TimerMode = SpPerfChart.TimerMode.Disabled; - this.perfChart2.Location = new System.Drawing.Point(4, 52); - this.perfChart2.Name = "perfChart2"; - this.perfChart2.Size = new System.Drawing.Size(227, 47); - this.perfChart2.TabIndex = 0; - // - // perfChart1 - // - this.perfChart1._maxDecimal = new decimal(new int[] { - 100, - 0, - 0, - 0}); - perfChartStyle4.AntiAliasing = true; - chartPen13.Color = System.Drawing.Color.Black; - chartPen13.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen13.Width = 1F; - perfChartStyle4.AvgLinePen = chartPen13; - perfChartStyle4.BackgroundColorBottom = System.Drawing.Color.DarkGreen; - perfChartStyle4.BackgroundColorTop = System.Drawing.Color.DarkGreen; - chartPen14.Color = System.Drawing.Color.Black; - chartPen14.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen14.Width = 1F; - perfChartStyle4.ChartLinePen = chartPen14; - chartPen15.Color = System.Drawing.Color.Black; - chartPen15.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen15.Width = 1F; - perfChartStyle4.HorizontalGridPen = chartPen15; - perfChartStyle4.ShowAverageLine = true; - perfChartStyle4.ShowHorizontalGridLines = true; - perfChartStyle4.ShowVerticalGridLines = true; - chartPen16.Color = System.Drawing.Color.Black; - chartPen16.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; - chartPen16.Width = 1F; - perfChartStyle4.VerticalGridPen = chartPen16; - this.perfChart1._PerfChartStyle = perfChartStyle4; - this.perfChart1._ScaleMode = SpPerfChart.ScaleMode.Absolute; - this.perfChart1._SymmetricDisplay = true; - this.perfChart1._TimerInterval = 100; - this.perfChart1._TimerMode = SpPerfChart.TimerMode.Disabled; - this.perfChart1.Location = new System.Drawing.Point(4, 2); - this.perfChart1.Name = "perfChart1"; - this.perfChart1.Size = new System.Drawing.Size(227, 47); - this.perfChart1.TabIndex = 0; - // - // tabPage4 - // - this.tabPage4.Controls.Add(this.btnTEST); - this.tabPage4.Controls.Add(this.txtShake5Treshold); - this.tabPage4.Controls.Add(this.trackBar5); - this.tabPage4.Controls.Add(this.txtShake4Treshold); - this.tabPage4.Controls.Add(this.trackBar4); - this.tabPage4.Controls.Add(this.txtShake3Treshold); - this.tabPage4.Controls.Add(this.trackBar2); - this.tabPage4.Controls.Add(this.txt6Treshold); - this.tabPage4.Controls.Add(this.trackBar6); - this.tabPage4.Controls.Add(this.txtShake2Treshold); - this.tabPage4.Controls.Add(this.trackBar1); - this.tabPage4.Controls.Add(this.numericUpDown1); - this.tabPage4.Controls.Add(this.lblShake9); - this.tabPage4.Controls.Add(this.lblShake8); - this.tabPage4.Controls.Add(this.lblShake7); - this.tabPage4.Controls.Add(this.lblShake6); - this.tabPage4.Controls.Add(this.lblShake5); - this.tabPage4.Controls.Add(this.lblShake4); - this.tabPage4.Controls.Add(this.lblShake3); - this.tabPage4.Controls.Add(this.lbShake2); - this.tabPage4.Controls.Add(this.lblShake1); - this.tabPage4.Location = new System.Drawing.Point(0, 0); - this.tabPage4.Name = "tabPage4"; - this.tabPage4.Size = new System.Drawing.Size(240, 242); - this.tabPage4.Text = "Shaker"; - // - // txtShake5Treshold - // - this.txtShake5Treshold.Location = new System.Drawing.Point(103, 104); - this.txtShake5Treshold.Name = "txtShake5Treshold"; - this.txtShake5Treshold.Size = new System.Drawing.Size(56, 21); - this.txtShake5Treshold.TabIndex = 9; - this.txtShake5Treshold.Text = "8"; - // - // trackBar5 - // - this.trackBar5.LargeChange = 2; - this.trackBar5.Location = new System.Drawing.Point(7, 105); - this.trackBar5.Maximum = 18; - this.trackBar5.Minimum = 1; - this.trackBar5.Name = "trackBar5"; - this.trackBar5.Size = new System.Drawing.Size(90, 21); - this.trackBar5.TabIndex = 8; - this.trackBar5.TickFrequency = 10; - this.trackBar5.Value = 8; - this.trackBar5.ValueChanged += new System.EventHandler(this.trackBar5_ValueChanged); - // - // txtShake4Treshold - // - this.txtShake4Treshold.Location = new System.Drawing.Point(103, 79); - this.txtShake4Treshold.Name = "txtShake4Treshold"; - this.txtShake4Treshold.Size = new System.Drawing.Size(56, 21); - this.txtShake4Treshold.TabIndex = 9; - this.txtShake4Treshold.Text = "120"; - // - // trackBar4 - // - this.trackBar4.LargeChange = 50; - this.trackBar4.Location = new System.Drawing.Point(7, 80); - this.trackBar4.Maximum = 180; - this.trackBar4.Minimum = 10; - this.trackBar4.Name = "trackBar4"; - this.trackBar4.Size = new System.Drawing.Size(90, 21); - this.trackBar4.SmallChange = 10; - this.trackBar4.TabIndex = 8; - this.trackBar4.TickFrequency = 10; - this.trackBar4.Value = 120; - this.trackBar4.ValueChanged += new System.EventHandler(this.trackBar4_ValueChanged); - // - // txtShake3Treshold - // - this.txtShake3Treshold.Location = new System.Drawing.Point(103, 54); - this.txtShake3Treshold.Name = "txtShake3Treshold"; - this.txtShake3Treshold.Size = new System.Drawing.Size(56, 21); - this.txtShake3Treshold.TabIndex = 9; - this.txtShake3Treshold.Text = "120"; - // - // trackBar2 - // - this.trackBar2.LargeChange = 50; - this.trackBar2.Location = new System.Drawing.Point(7, 55); - this.trackBar2.Maximum = 180; - this.trackBar2.Minimum = 10; - this.trackBar2.Name = "trackBar2"; - this.trackBar2.Size = new System.Drawing.Size(90, 21); - this.trackBar2.SmallChange = 10; - this.trackBar2.TabIndex = 8; - this.trackBar2.TickFrequency = 10; - this.trackBar2.Value = 120; - this.trackBar2.ValueChanged += new System.EventHandler(this.trackBar2_ValueChanged); - // - // txt6Treshold - // - this.txt6Treshold.Location = new System.Drawing.Point(103, 133); - this.txt6Treshold.Name = "txt6Treshold"; - this.txt6Treshold.Size = new System.Drawing.Size(56, 21); - this.txt6Treshold.TabIndex = 9; - this.txt6Treshold.Text = "120"; - // - // trackBar6 - // - this.trackBar6.LargeChange = 50; - this.trackBar6.Location = new System.Drawing.Point(7, 134); - this.trackBar6.Maximum = 180; - this.trackBar6.Minimum = 10; - this.trackBar6.Name = "trackBar6"; - this.trackBar6.Size = new System.Drawing.Size(90, 21); - this.trackBar6.SmallChange = 10; - this.trackBar6.TabIndex = 8; - this.trackBar6.TickFrequency = 10; - this.trackBar6.Value = 120; - this.trackBar6.ValueChanged += new System.EventHandler(this.trackBar6_ValueChanged); - // - // txtShake2Treshold - // - this.txtShake2Treshold.Location = new System.Drawing.Point(103, 28); - this.txtShake2Treshold.Name = "txtShake2Treshold"; - this.txtShake2Treshold.Size = new System.Drawing.Size(56, 21); - this.txtShake2Treshold.TabIndex = 9; - this.txtShake2Treshold.Text = "120"; - // - // trackBar1 - // - this.trackBar1.LargeChange = 50; - this.trackBar1.Location = new System.Drawing.Point(7, 29); - this.trackBar1.Maximum = 180; - this.trackBar1.Minimum = 10; - this.trackBar1.Name = "trackBar1"; - this.trackBar1.Size = new System.Drawing.Size(90, 21); - this.trackBar1.SmallChange = 10; - this.trackBar1.TabIndex = 8; - this.trackBar1.TickFrequency = 10; - this.trackBar1.Value = 120; - this.trackBar1.ValueChanged += new System.EventHandler(this.trackBar1_ValueChanged); - // - // numericUpDown1 - // - this.numericUpDown1.Location = new System.Drawing.Point(118, 4); - this.numericUpDown1.Maximum = new decimal(new int[] { - 10, - 0, - 0, - 0}); - this.numericUpDown1.Minimum = new decimal(new int[] { - 1, - 0, - 0, - 0}); - this.numericUpDown1.Name = "numericUpDown1"; - this.numericUpDown1.Size = new System.Drawing.Size(42, 22); - this.numericUpDown1.TabIndex = 7; - this.numericUpDown1.Value = new decimal(new int[] { - 8, - 0, - 0, - 0}); - this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged); - // - // lblShake9 - // - this.lblShake9.Location = new System.Drawing.Point(166, 192); - this.lblShake9.Name = "lblShake9"; - this.lblShake9.Size = new System.Drawing.Size(67, 19); - this.lblShake9.Text = "Move1"; - this.lblShake9.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblShake8 - // - this.lblShake8.Location = new System.Drawing.Point(166, 173); - this.lblShake8.Name = "lblShake8"; - this.lblShake8.Size = new System.Drawing.Size(67, 19); - this.lblShake8.Text = "Shake8"; - this.lblShake8.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblShake7 - // - this.lblShake7.Location = new System.Drawing.Point(166, 154); - this.lblShake7.Name = "lblShake7"; - this.lblShake7.Size = new System.Drawing.Size(67, 19); - this.lblShake7.Text = "Shake7"; - this.lblShake7.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblShake6 - // - this.lblShake6.Location = new System.Drawing.Point(166, 129); - this.lblShake6.Name = "lblShake6"; - this.lblShake6.Size = new System.Drawing.Size(67, 25); - this.lblShake6.Text = "Shake6"; - this.lblShake6.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblShake5 - // - this.lblShake5.Location = new System.Drawing.Point(166, 104); - this.lblShake5.Name = "lblShake5"; - this.lblShake5.Size = new System.Drawing.Size(67, 25); - this.lblShake5.Text = "Shake5"; - this.lblShake5.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblShake4 - // - this.lblShake4.Location = new System.Drawing.Point(166, 79); - this.lblShake4.Name = "lblShake4"; - this.lblShake4.Size = new System.Drawing.Size(67, 25); - this.lblShake4.Text = "Shake4"; - this.lblShake4.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblShake3 - // - this.lblShake3.Location = new System.Drawing.Point(166, 54); - this.lblShake3.Name = "lblShake3"; - this.lblShake3.Size = new System.Drawing.Size(67, 25); - this.lblShake3.Text = "Shake3"; - this.lblShake3.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lbShake2 - // - this.lbShake2.Location = new System.Drawing.Point(166, 29); - this.lbShake2.Name = "lbShake2"; - this.lbShake2.Size = new System.Drawing.Size(67, 22); - this.lbShake2.Text = "Shake2"; - this.lbShake2.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // lblShake1 - // - this.lblShake1.Location = new System.Drawing.Point(166, 4); - this.lblShake1.Name = "lblShake1"; - this.lblShake1.Size = new System.Drawing.Size(67, 22); - this.lblShake1.Text = "Shake1"; - this.lblShake1.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // btnTEST - // - this.btnTEST.Location = new System.Drawing.Point(84, 173); - this.btnTEST.Name = "btnTEST"; - this.btnTEST.Size = new System.Drawing.Size(74, 37); - this.btnTEST.TabIndex = 19; - this.btnTEST.Text = "TEST"; - this.btnTEST.Click += new System.EventHandler(this.btnTEST_Click); - // - // mainFrm - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.tabControl1); - this.Menu = this.mainMenu1; - this.Name = "mainFrm"; - this.Text = "SensorScan5"; - this.tabControl1.ResumeLayout(false); - this.tabPage1.ResumeLayout(false); - this.tabPage2.ResumeLayout(false); - this.tabPage3.ResumeLayout(false); - this.tabPage4.ResumeLayout(false); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.TabControl tabControl1; - private System.Windows.Forms.TabPage tabPage1; - private System.Windows.Forms.TabPage tabPage2; - private System.Windows.Forms.Label label8; - private System.Windows.Forms.Label label7; - private System.Windows.Forms.Label label6; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Label labelGFZ; - private System.Windows.Forms.Label labelGFY; - private System.Windows.Forms.Label labelGFX; - private System.Windows.Forms.TabPage tabPage3; - private System.Windows.Forms.MenuItem menuItem1; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label lblOrientation; - private System.Windows.Forms.TextBox txtLog; - private System.Windows.Forms.ComboBox cbSensity; - private System.Windows.Forms.Label label16; - private System.Windows.Forms.TabPage tabPage4; - private System.Windows.Forms.Label lblShake1; - private System.Windows.Forms.Label lblShake7; - private System.Windows.Forms.Label lblShake6; - private System.Windows.Forms.Label lblShake5; - private System.Windows.Forms.Label lblShake4; - private System.Windows.Forms.Label lblShake3; - private System.Windows.Forms.Label lbShake2; - private System.Windows.Forms.NumericUpDown numericUpDown1; - private System.Windows.Forms.TextBox txtShake2Treshold; - private System.Windows.Forms.TrackBar trackBar1; - private System.Windows.Forms.TextBox txtShake3Treshold; - private System.Windows.Forms.TrackBar trackBar2; - private System.Windows.Forms.TextBox txtShake4Treshold; - private System.Windows.Forms.TrackBar trackBar4; - private System.Windows.Forms.TextBox txtShake5Treshold; - private System.Windows.Forms.TrackBar trackBar5; - private System.Windows.Forms.TextBox txt6Treshold; - private System.Windows.Forms.TrackBar trackBar6; - private System.Windows.Forms.Label lblDirection; - private System.Windows.Forms.Label lblTilt; - private System.Windows.Forms.Label lblRoll; - private System.Windows.Forms.Label lblPitch; - private System.Windows.Forms.Label lblShake8; - private System.Windows.Forms.Label label5; - private System.Windows.Forms.Label label4; - private System.Windows.Forms.Label label3; - private System.Windows.Forms.Label lblAcceleration; - private System.Windows.Forms.Label label10; - private System.Windows.Forms.Label lblShake9; - private SpPerfChart.PerfChart perfChart3; - private SpPerfChart.PerfChart perfChart2; - private SpPerfChart.PerfChart perfChart1; - private SpPerfChart.PerfChart perfChart4; - private System.Windows.Forms.Button btnTEST; - } -} - diff --git a/SensorScan5/Form1.cs b/SensorScan5/Form1.cs deleted file mode 100644 index 5ed8a26..0000000 --- a/SensorScan5/Form1.cs +++ /dev/null @@ -1,449 +0,0 @@ -#define ASYNCHRONOUS -#define USE_SCANNER -/* - * define USE_SCANNER to use barcode scanner code - * define ASYNCHRONOUS to use the sensor in async mode -*/ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using Intermec.Device; -#if USE_SCANNER -using Intermec.DataCollection; -#endif - -using NativeSync; // scanner control events - -namespace SensorScan5 -{ - public partial class mainFrm : Form - { - private Sensor mySensor; - //private Timer myTimer; //a windows forms timer, inaccurate -#if !ASYNCHRONOUS - bgThread myThread; -#endif - ShakeDetection.ShakeClass1 shaker1; - ShakeDetection.ShakeClass2 shaker2; - ShakeDetection.ShakeClass3 shaker3; - ShakeDetection.ShakeClass4 shaker4; - ShakeDetection.ShakeClass5 shaker5; - ShakeDetection.ShakeClass6 shaker6; - ShakeDetection.ShakeClass7 shaker7; - ShakeDetection.ShakeClass8 shaker8; - ShakeDetection.ShakeClass9 shaker9; - - Movedetection.MovementClass1 move1; - -#if USE_SCANNER - //scan event control - ScanEvents scanEvents; - BarcodeReader bcr; - Timer scanTimer; - int scanTimeout = 20; //switch scanner off after xx seconds -#endif - private bool starting = true; - public mainFrm() - { - InitializeComponent(); -#if ASYNCHRONOUS - try - { - mySensor = new Sensor(this, Sensor.SensorsEnabled.AccelerometerEnabled, true); - } - catch (Exception) - { - MessageBox.Show("No sensor available. Did you install SensorCab runtime? Exit"); - Application.Exit(); - } - //call mySensor_AccelerationEvent for Acceleration events from sensor - mySensor.AccelerationMinimumNotifyDelta = 0; - mySensor.SensorDataUpdateInterval = 10; - mySensor.AccelerationEvent += new AccelerationEventHandler(mySensor_AccelerationEvent); -#else - //mySensor = new Sensor(this, Sensor.SensorsEnabled.AccelerometerEnabled, false); -#endif - cbSensity.SelectedIndex = 3; //default is 0.01, 0 means all events - trackBar1.Value = 100; - - //mySensor.SensorDataUpdateInterval = 50; - - // - shaker1 = new ShakeDetection.ShakeClass1("shake1"); - shaker1.shakeTreshold = 8.0; - //shaker1.logEnabled = true; - //better implementation - shaker1.ShakeDetected += new ShakeDetection.ShakeClass.ShakeDetectedEventHandler(shaker1_ShakeDetected); - // - shaker2 = new ShakeDetection.ShakeClass2("shake2"); - //shaker2.logEnabled = true; - shaker2.ShakeDetected += new ShakeDetection.ShakeClass.ShakeDetectedEventHandler(shaker2_ShakeDetected); - - // - shaker3 = new ShakeDetection.ShakeClass3("shake3"); - //shaker3.logEnabled = true; - shaker3.ShakeDetected += new ShakeDetection.ShakeClass.ShakeDetectedEventHandler(shaker3_ShakeDetected); - - // - shaker4 = new ShakeDetection.ShakeClass4("shake4"); - //shaker4.logEnabled = true; - shaker4.ShakeDetected += new ShakeDetection.ShakeClass.ShakeDetectedEventHandler(shaker4_ShakeDetected); - - // - shaker5 = new ShakeDetection.ShakeClass5("shake5"); - trackBar5.Value = 8; trackBar1_ValueChanged(this, null); - //shaker5.logEnabled = true; - shaker5.ShakeDetected += new ShakeDetection.ShakeClass.ShakeDetectedEventHandler(shaker5_ShakeDetected); - - // - shaker6 = new ShakeDetection.ShakeClass6("shake6"); - //shaker6.logEnabled = true; - shaker6.ShakeDetected += new ShakeDetection.ShakeClass.ShakeDetectedEventHandler(shaker6_ShakeDetected); - trackBar6.Value = 120; - - // - shaker7 = new ShakeDetection.ShakeClass7("shake7"); - //shaker7.logEnabled = true; - shaker7.ShakeDetected += new ShakeDetection.ShakeClass.ShakeDetectedEventHandler(shaker7_ShakeDetected); - - // - shaker8 = new ShakeDetection.ShakeClass8("shake8"); - //shaker8.logEnabled = true; - shaker8.ShakeDetected += new ShakeDetection.ShakeClass.ShakeDetectedEventHandler(shaker8_ShakeDetected); - - // - shaker9 = new ShakeDetection.ShakeClass9("shake9"); - //shaker8.logEnabled = true; - shaker9.ShakeDetected += new ShakeDetection.ShakeClass.ShakeDetectedEventHandler(shaker9_ShakeDetected); - - // - move1 = new Movedetection.MovementClass1("move1"); - move1.logEnabled = true; - move1.MoveDetected += new Movedetection.MovementClass.MoveDetectedEventHandler(move1_MoveDetected); - move1.IdleDetected += new Movedetection.MovementClass.IdleDetectedEventHandler(move1_IdleDetected); - -#if !ASYNCHRONOUS - //myTimer.Interval = 50; //approx 20 events per second - //myTimer.Tick += new EventHandler(myTimer_Tick); - //myTimer.Enabled = true; //do not enable timer before assigning the shaker/move classes - //myTimer.Enabled = true; - myThread = new bgThread(); - myThread.bgThreadEvent += new bgThread.bgThreadEventHandler(myThread_bgThreadEvent); -#endif - //perfChart1.maxDecimal = 1500; - perfChart1._SymmetricDisplay= true; - perfChart1._ScaleMode = SpPerfChart.ScaleMode.Relative; - //perfChart2.maxDecimal = 1500; - perfChart2._SymmetricDisplay = true; - perfChart2._ScaleMode = SpPerfChart.ScaleMode.Relative; - //perfChart3.maxDecimal = 1500; - perfChart3._SymmetricDisplay = true; - perfChart3._ScaleMode = SpPerfChart.ScaleMode.Relative; - - perfChart4._SymmetricDisplay = true; - perfChart4._ScaleMode = SpPerfChart.ScaleMode.Relative; - - starting = false; - -#if USE_SCANNER - scanEvents = new ScanEvents(); - try - { - bcr = new BarcodeReader(); - bcr.ContinuesScan = true; - scanTimer = new Timer(); - scanTimer.Interval = 1000; //fire every second - scanTimer.Tick += new EventHandler(scanTimer_Tick); - scanTimer.Enabled = true; - } - catch (Exception) - { - //scanner not available - } -#endif - } -#if USE_SCANNER - private int scanTimeCounter = 0; - private bool bScannerIsOn = false; - /// - /// light the scanner for xx seconds - /// restart 'timer' if a scan was detected - /// - /// - /// - void scanTimer_Tick(object sender, EventArgs e) - { - scanTimeCounter++; - if (scanTimeCounter > scanTimeout) - { - bcr.ScannerOn = false; - bScannerIsOn = false; - scanTimeout = 0; - } - } -#endif - void myThread_bgThreadEvent(object sender, ShakeDetection.ShakeEventArgs bte) - { - processData(bte._gvector); - } - - void shaker9_ShakeDetected(object sender, ShakeDetection.ShakeEventArgs bre) - { - shakeLabel(lblShake9); - } - - void move1_IdleDetected(object sender, Movedetection.MovementEventArgs bre) - { - //System.Diagnostics.Debug.WriteLine("Idle event fired"); - //get actual delta average - double d = move1._Avg_deltaG_rms; - perfChart4._AddValue((decimal)d); - } - - void move1_MoveDetected(object sender, Movedetection.MovementEventArgs bre) - { - //System.Diagnostics.Debug.WriteLine("Move event fired"); - shakeLabel(lblShake9); - } - - void shaker8_ShakeDetected(object sender, ShakeDetection.ShakeEventArgs bre) - { - shakeLabel(lblShake8); - } - - void shaker7_ShakeDetected(object sender, ShakeDetection.ShakeEventArgs bre) - { - shakeLabel(lblShake7); - } - - void shaker6_ShakeDetected(object sender, ShakeDetection.ShakeEventArgs bre) - { - shakeLabel(lblShake6); - } - - void shaker5_ShakeDetected(object sender, ShakeDetection.ShakeEventArgs bre) - { - shakeLabel(lblShake5); - } - - void shaker4_ShakeDetected(object sender, ShakeDetection.ShakeEventArgs bre) - { - shakeLabel(lblShake4); - } - - void shaker3_ShakeDetected(object sender, ShakeDetection.ShakeEventArgs bre) - { - shakeLabel(lblShake3); -#if USE_SCANNER - if (!bScannerIsOn) - { - //scanEvents.doScanButton(); //use for remote control - bcr.ScannerOn = true; - bScannerIsOn = true; - } - scanTimeout = 0; //reset scanner timeout -#endif - } - - void shaker2_ShakeDetected(object sender, ShakeDetection.ShakeEventArgs e) - { - shakeLabel(lbShake2); - } - - void shaker1_ShakeDetected(object sender, ShakeDetection.ShakeEventArgs bre) - { - shakeLabel(lblShake1); - } - - - void mySensor_AccelerationEvent(object sender, Sensor.AccelerationArgs AccelerationArgs) - { - ShakeDetection.GVector gv = new ShakeDetection.GVector(AccelerationArgs.GForceX, - AccelerationArgs.GForceY, - AccelerationArgs.GForceZ); - - processData(gv); - } - - void formatChart(ref SpPerfChart.PerfChart pc) - { - pc._SymmetricDisplay = true; - pc._ScaleMode = SpPerfChart.ScaleMode.Relative; - } - - void myTimer_Tick(object sender, EventArgs e) - { - ShakeDetection.GVector gv = new ShakeDetection.GVector(mySensor.Acceleration.GForceX, - mySensor.Acceleration.GForceY, - mySensor.Acceleration.GForceZ); - processData(gv); - } - - private void processData(ShakeDetection.GVector gv) - { - if (starting) - return; - labelGFX.Text = gv.X.ToString("0.00000"); - labelGFY.Text = gv.Y.ToString("0.00000"); - labelGFZ.Text = gv.Z.ToString("0.00000"); - - lblOrientation.Text = gv.ToScreenOrientation().ToString(); - lblDirection.Text = gv.direction.ToString(); - - lblTilt.Text = gv.Tilt.ToString("0"); - lblRoll.Text = gv.Roll.ToString("0"); - lblPitch.Text = gv.Pitch.ToString("0"); - - lblAcceleration.Text = gv.Length.ToString("0.0"); - - addLog(gv.ToString()); - - shaker1.addValues(gv); - - shaker2.addValues(gv); - - shaker3.addValues(gv); - - shaker4.addValues(gv); - - shaker5.addValues(gv); - - shaker6.addValues(gv); - - shaker7.addValues(gv); - - shaker8.addValues(gv); - - shaker9.addValues(gv); - - Movedetection.GMVector gmv = new Movedetection.GMVector(gv.X, gv.Y, gv.Z); - move1.addValues(gmv); - - perfChart1._AddValue((decimal)gv.X); - perfChart2._AddValue((decimal)gv.Y); - perfChart3._AddValue((decimal)gv.Z); - } - - private void menuItem1_Click(object sender, EventArgs e) - { - //myTimer.Enabled = false; - if (MessageBox.Show("Exit?", "SensorScan", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) - { -#if !ASYNCHRONOUS - if (myThread != null) - myThread.Dispose(); -#endif - Application.Exit(); - } - } - - delegate void SetTextCallback(string text); - private void addLog(string text) - { - // InvokeRequired required compares the thread ID of the - // calling thread to the thread ID of the creating thread. - // If these threads are different, it returns true. - if (this.txtLog.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(addLog); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtLog.Text.Length > 2000) - txtLog.Text = ""; - txtLog.Text += text + "\r\n"; - txtLog.SelectionLength = text.Length; - txtLog.SelectionStart = txtLog.Text.Length - text.Length; - txtLog.ScrollToCaret(); - } - } - delegate void SetShakeLabelCallback(Label lb); - void shakeLabel(Label lb) - { - if (lb.InvokeRequired) - { - SetShakeLabelCallback d = new SetShakeLabelCallback(shakeLabel); - this.Invoke(d, new object[] { lb }); - } - else - { - lb.BackColor = Color.Red; - Application.DoEvents(); - System.Threading.Thread.Sleep(50); - lb.BackColor = Color.White; - Application.DoEvents(); - } - } - - private void cbSensity_SelectedIndexChanged_1(object sender, EventArgs e) - { - if (starting) - return; - mySensor.AccelerationMinimumNotifyDelta = float.Parse(cbSensity.SelectedItem.ToString()); - } - - private void numericUpDown1_ValueChanged(object sender, EventArgs e) - { - shaker1.shakeTreshold = (double) numericUpDown1.Value; - } - - private void trackBar1_ValueChanged(object sender, EventArgs e) - { - float d = trackBar1.Value / 100f; - txtShake2Treshold.Text = d.ToString("0.00"); - Application.DoEvents(); - if(shaker2!=null) - shaker2.shakeTreshold = (double)d; - } - - private void trackBar2_ValueChanged(object sender, EventArgs e) - { - float d = trackBar2.Value / 100f; - txtShake3Treshold.Text = d.ToString("0.00"); - Application.DoEvents(); - if(shaker3!=null) - shaker3.shakeTreshold = (double)d; - } - - private void trackBar4_ValueChanged(object sender, EventArgs e) - { - float d = trackBar4.Value / 100f; - txtShake4Treshold.Text = d.ToString("0.00"); - Application.DoEvents(); - if (shaker4 != null) - shaker4.shakeTreshold = (double)d; - - } - - private void trackBar5_ValueChanged(object sender, EventArgs e) - { - //need treshold around 800 - double d = trackBar5.Value * 100; - txtShake5Treshold.Text = d.ToString(); - Application.DoEvents(); - if (shaker5 != null) - shaker5.shakeTreshold = d; - } - - private void trackBar6_ValueChanged(object sender, EventArgs e) - { - float d = trackBar6.Value / 100f; - txt6Treshold.Text = d.ToString("0.00"); - Application.DoEvents(); - if (shaker6 != null) - shaker6.shakeTreshold = (double)d; - } - - private void btnTEST_Click(object sender, EventArgs e) - { - //scanEvents.doScanButton(); - shaker3_ShakeDetected(this, new ShakeDetection.ShakeEventArgs(new ShakeDetection.GVector(0, 0, -.8))); - } - - } -} \ No newline at end of file diff --git a/SensorScan5/Form1.resx b/SensorScan5/Form1.resx deleted file mode 100644 index 2114884..0000000 --- a/SensorScan5/Form1.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 17, 17 - - - Pocket_PC - - - True - - - 38 - - text/microsoft-resx2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 diff --git a/SensorScan5/MovementClass/GMVector.cs b/SensorScan5/MovementClass/GMVector.cs deleted file mode 100644 index c82e5bd..0000000 --- a/SensorScan5/MovementClass/GMVector.cs +++ /dev/null @@ -1,329 +0,0 @@ -using System; -#region CN50 XYZ vectors -/* - (N) - +Y - | -Z - | / - | / - | .' - +-----------+/ - | +-------+ | - | | | | - | | | | - | | | | -(E)''''''| | / | |'''''' (W) -+X | |.' | | -X - | /-------+ | - |/ | - .' | - / +-----------+ - .' | - / | - +Z | - -Y - (S) - - //calc the acceleration or the longest vector - double accel = Math.Sqrt(x * x + y * y + z * z); - //calc the X angle, should be about 180 if device is upright - double degrees = Math.Acos(x / b) * 360.0 / Math.PI; - - * when device is faceup on table: x=0 y=0 z=1 - * when device is faceup on table: x=0 y=0 z=-1 - * when device is upright scan to roof: x=0 y=-1 z=0 - * when device is upright scanner to down: x=0 y=1 z=0 - * when scanner lays on left side: x=-1 y=0 z=0 - * when scanner lays on right side: x=1 y=0 z=0 -*/ - -#endregion -namespace Movedetection -{ - public struct GMVector - { - public GMVector(double x, double y, double z) - { - myX = x; - myY = y; - myZ = z; -#if MAGNETIC_SENSOR - myHeading = 0; - myStrength = 0; -#endif - myTicks = (ulong)(DateTime.Now.Ticks / 10000); //there are 10000 ticks in a millisecond - //http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx - - myDirection = GetDirection(myX, myY, myZ); - myScreenOrientation = GetScreenorientation(myX, myY, myZ); - moveState = MoveState.idle; - } - //private static GMVector lastGMVector=new GMVector(); - public enum MoveState : int - { - idle=0, - move=1 - } - MoveState moveState; - public MoveState _moveState - { - get { return moveState; } - set { moveState = value; } - } - - ScreenOrientation myScreenOrientation; - public ScreenOrientation _ScreenOrientation{ - get { return myScreenOrientation; } - } - - Direction myDirection; - public Direction _Direction - { - get { return myDirection; } - } - - ulong myTicks; - /// - /// changed to have milliseconds instead of 100ns - /// - public ulong Ticks - { - get { return myTicks; } - } - double myX; - public double X - { - get { return myX; } - //set { myX = value; } - } - double myY; - public double Y - { - get { return myY; } - //set { myY = value; } - } - double myZ; - public double Z - { - get { return myZ; } - //set { myZ = value; } - } - - #region Magnetic Sensor -#if MAGNETIC_SENSOR - double myHeading; - /// - /// Compass heading in degrees, for use with magnetic sensors - /// - public double Heading - { - get { return myHeading; } - set { myHeading = value; } - } - double myStrength; - /// - /// the magnetic strength, for use with magnetic sensors - /// - public double Strength - { - get { return myStrength; } - set { myStrength = value; } - } -#endif - #endregion - public GMVector Normalize() - { - return Scale(1 / Length); - } - - public GMVector Scale(double scale) - { - GMVector ret = this; - ret.myX *= scale; - ret.myY *= scale; - ret.myZ *= scale; - return ret; - } - /// - /// Convert a radian to degree - /// - /// - /// - /// - /// - private double RadianToDegree(double d){ - double dRes; - dRes= d*180/Math.PI; - return dRes; - } - /* - pitch = arctan(Ax/sqrt(Ay^2+Az^2)) - roll = arctan(Ay/sqrt(Ax^2+Az^2)) - theta = arctan(sqrt(Ax^2+Az^2)/Az) - * //http://cache.freescale.com/files/sensors/doc/app_note/AN3461.pdf - * Pitch (phi) is defined as the angle of the X-axis relative to ground. - * pitch = arctan(x/sqrt(y*y+z*z)) - * Roll (rho) is defined as the angle of the Y-axis relative to the ground. - * roll = arctan(Y/sqrt(x*x+z*z)) - * Tilt (theta) is the angle of the Z axis relative to gravity. - * theta = sqrt(x*x + y*y)/z - */ - public double Pitch{ - get{ - GMVector gv1=this; - double p = Math.Atan(gv1.X / Math.Sqrt(Math.Pow(gv1.Y,2) / Math.Pow(gv1.Z,2))); - return this.RadianToDegree(p); - } - } - public double Roll{ - get{ - GMVector gv1=this; - //double p = Math.Atan(gv1.Z / gv1.X); - double p=Math.Atan(gv1.Y / Math.Sqrt(Math.Pow(gv1.X,2) + Math.Pow(gv1.Z,2))); - return this.RadianToDegree(p); - } - } - public double Tilt{ //was called theta - get{ - GMVector gv1 = this; - double p = Math.Sqrt(Math.Pow(gv1.X, 2) + Math.Pow(gv1.Y, 2)) / gv1.Z; - return this.RadianToDegree(p); - } - } - #region segmented direction - /* - http://en.wikipedia.org/wiki/Boxing_the_compass - attention: this here is based on +Y/+X (-1/0) equal 0 degree equal North - */ - public enum Direction:int{ - None=-1, - W=0, - WSW, - SW, - SSW, - S, - SSE, - SE, - ESE, - E, - ENE, - NE, - NNE, - N, - NNW, - NW, - WNW, - } - public Direction direction - { //http://stackoverflow.com/questions/1437790/how-to-snap-a-directional-2d-vector-to-a-compass-n-ne-e-se-s-sw-w-nw - get{ - GMVector gv=this; - int segmentCount=16; - int compassSegment = (((int) Math.Round(Math.Atan2(gv.Y, gv.X) / (2 * Math.PI / segmentCount))) + segmentCount) % segmentCount; - return (Direction)compassSegment; - } - } - private static Direction GetDirection(double x, double y, double z) - { //http://stackoverflow.com/questions/1437790/how-to-snap-a-directional-2d-vector-to-a-compass-n-ne-e-se-s-sw-w-nw - int segmentCount=16; - int compassSegment = (((int) Math.Round(Math.Atan2(y, x) / (2 * Math.PI / segmentCount))) + segmentCount) % segmentCount; - return (Direction)compassSegment; - } - - #endregion - /// - /// the X angle of the vector - /// - public int angleX - { - get - { - return (int)(Math.Acos(myX / Length) * 360.0 / Math.PI); - } - } - /// - /// the Y angle of the vector - /// - public int angleY - { - get - { - return (int)(Math.Acos(myY / Length) * 360.0 / Math.PI); - } - } - /// - /// the Z angle of the vector - /// - public int angleZ - { - get - { - return (int)(Math.Acos(myZ / Length) * 360.0 / Math.PI); - } - } - - /// - /// although this is called length it is the max. acceleration force - /// - public double Length - { - get - { - return Math.Sqrt(myX * myX + myY * myY + myZ * myZ); - } - } - - /// - /// calc the distance between the end of two vectors - /// - /// the vector to compare to - /// - public double EuclideanDistance(GMVector gvOld) - { - return Math.Sqrt(Math.Pow(this.X - gvOld.X, 2) + Math.Pow(this.Y - gvOld.Y, 2) + Math.Pow(this.Z - gvOld.Z, 2)); - } - public ulong TicksDiff(GMVector gvNew) - { - GMVector gvOld=this; - ulong diff = gvNew.Ticks - gvOld.Ticks; - //one tick is 100 nano seconds, scaled with 10000 to milliseconds - return diff; - } - public override string ToString() - { - return string.Format("X={0} Y={1} Z={2} Accel={3} angleX={4} angleX={5} angleX={6} orientation={7} direction={8} ticks={9} moving={10}", - Math.Round(myX, 4), Math.Round(myY, 4), Math.Round(myZ, 4), - Length, - angleX, angleY,angleZ, - GetScreenorientation(myX, myY, myZ), - GetDirection(myX, myY, myZ), - Ticks, - moveState); - } - - //changed to match CN50 XYZ directions - private static ScreenOrientation GetScreenorientation(double X, double Y, double Z) - { - if (Math.Abs(X) > Math.Abs(Y)) - { - if (Math.Abs(X) > Math.Abs(Z)) - { - if (X > 0) - return ScreenOrientation.ReverseLandscape; //changed from Landscape - return ScreenOrientation.Landscape; //changed from ReverseLandscape - } - } - else if (Math.Abs(Y) > Math.Abs(Z)) - { - if (Y > 0) - return ScreenOrientation.ReversePortrait; //changed from Portrait - return ScreenOrientation.Portrait; // changed from ReversePortrait - } - - if (Z > 0) - return ScreenOrientation.FaceUp; //this is different to HTC - return ScreenOrientation.FaceDown; //this is different to HTC - } - } -} - diff --git a/SensorScan5/MovementClass/MovementClass.cs b/SensorScan5/MovementClass/MovementClass.cs deleted file mode 100644 index 6e3557e..0000000 --- a/SensorScan5/MovementClass/MovementClass.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -namespace Movedetection -{ - /// - /// Main abstract class to implement various Shake detector classes - /// - public abstract class MovementClass:IMovement,IDisposable - { - #region Properties - private string _name = "MovementClass"; - /// - /// used to identify multiple classes that inherited this class - /// - public string name{ - get{return _name;} - set { _name = value; } - } - /// - /// generic constructor - /// - /// - public MovementClass (String s) - { - this._name=s; - } - public MovementClass() - { - this._name = "MovementClass"; - } - private bool _logEnabled = false; - public bool logEnabled - { - get { return _logEnabled; } - set { _logEnabled = value; } - } - private bool _logToFile = false; - /// - /// enable logging to file - /// - public bool logToFile - { - get { return _logToFile; } - set { _logToFile = value; } - } - #endregion - /// - /// implemented for completeness - /// - public void Dispose(){ - } - - #region Events - /// - /// the move detected event handler - /// - public event MoveDetectedEventHandler MoveDetected; - /// - /// the shake detected delegate - /// - /// - /// - public delegate void MoveDetectedEventHandler(object sender, MovementEventArgs bre); - private void MoveDetectedEvent(object mySender, MovementEventArgs myArgs) - { - if (this.MoveDetected == null) - return; - this.MoveDetected(this, myArgs);// this.movementEventArgs); - } - /// - /// this eventhandler should be fired by the derived classes to signal a shake detection - /// - /// - public void OnMoveDetected(GMVector gv) - { - MoveDetectedEvent(this, new MovementEventArgs(gv)); - } - //======================================================================================== - /// - /// the shake detected event handler - /// - public event IdleDetectedEventHandler IdleDetected; - /// - /// the shake detected delegate - /// - /// - /// - public delegate void IdleDetectedEventHandler(object sender, MovementEventArgs bre); - private void IdleDetectedEvent(object mySender, MovementEventArgs myArgs) - { - if (this.IdleDetected==null) - return; - this.IdleDetected(this, myArgs ); //this.idleEventArgs); - } - /// - /// this eventhandler should be fired by the derived classes to signal a shake detection - /// - /// - public void OnIdleDetected(GMVector gv) - { - IdleDetectedEvent(this, new MovementEventArgs(gv)); - } - #endregion - #region Methods - /// - /// implement this with the actual vector and use OnShakeEvent to signal a 'Shake' - /// - /// - public abstract void addValues(GMVector gv); - public abstract void setTreshold(double high, double low); - #endregion - #region Logging - public void Logger(string s) - { - if (!_logEnabled) - return; - System.Diagnostics.Debug.WriteLine(_name + ": " + s); - if (_logToFile) - { - string sFileName = @"\" + _name + ".log.txt"; - System.IO.TextWriter tw = new System.IO.StreamWriter(sFileName, true); - //tw.WriteLine(X.ToString() + "," + Y.ToString() + "," + Z.ToString() + "," + AngleX.ToString() + "," + AngleY.ToString()); - tw.WriteLine(_name + ": " + s); - tw.Close(); - } - } - #endregion - - } -} - diff --git a/SensorScan5/MovementClass/MovementClass1.cs b/SensorScan5/MovementClass/MovementClass1.cs deleted file mode 100644 index 49a115a..0000000 --- a/SensorScan5/MovementClass/MovementClass1.cs +++ /dev/null @@ -1,338 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Movedetection -{ - /// - /// chalenge: recognize a gesture pattern - /// Detect movement (Accelerometer_WBSN.pdf http://www.google.co.uk/url?sa=t&source=web&cd=6&ved=0CDwQFjAF&url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.120.296%26rep%3Drep1%26type%3Dpdf&ei=wTMHTf_NL8e3hQf-oZXtBw&usg=AFQjCNGgZnlYRvBzKg4uJRveSwVHhxIa-g&sig2=URThwmeDoZF2JdCMj2Babg) - /// 1. calc the actual acceleration: Length=sqrt(x*x+y*y+z*z) - /// 2. get the diff to the previous DeltaAcceleration: LengthNow - LengthPrevious - /// 3. get the average of deltas for about 1 sec (should be 20 measurements): SUM(DeltaAccelerations)/sps; //sps=samples per second - /// - class MovementClass1:MovementClass - { - - public MovementClass1(string s) - { - base.name = s; - this.setTreshold(.2d, 0.5d); - myQueue = new LimitedQueue(_queueLength); - - myAverages = new LimitedQueue(_queueLength); - - //need at least 3 seconds recording size, but only record crossing values - myCrossUPs = new LimitedQueue(_queueLength); - myCrossDOWNs = new LimitedQueue(_queueLength); - - myGmin = 0.2d; //was 0.9d but we get a deltaAverage of about around 0.14 - myTmin = 10; // 15 is equal to 0.75 seconds if samples per seconds is 20 - - _treshCountRMS = 2000; //should be 3000 for 60 samples in 3 seconds at 20 samples/second, - //BUT we only see ~2 samples per second - - basicLogger("Movement1 Class\r\nx\ty\tz\ttick\tdeltaG"); - } - - public override void setTreshold(double high, double low) - { - myGmin = high; - myRMSmin = low; - } - - public override void addValues(GMVector gv) - { - GMVector gvOld; - if (myQueue.Count>0)// !_firstCall) - { - //_samplesPerSecond= - //calc samples per second - if (!_samplesPerSecondsCalulated) - { - if (myQueue.Count > 10) - { - GMVector[] myQueueArray = myQueue.ToArray(); - ulong iSamplesCount = 0; - ulong iTickSum = 0; - ulong tickDiff = 0; - for (int c = myQueueArray.Length - 1; c > 1; c--) - { - iSamplesCount++; - tickDiff = myQueueArray[c].Ticks - myQueueArray[c - 1].Ticks; - iTickSum += tickDiff; - } - _samplesPerSecond = (uint)(1000 / (iTickSum / iSamplesCount)); // number of samples per second, ticks stored as milliseconds - _samplesPerSecondsCalulated = true; - } - } - //get and store delta - gvOld = myQueue.Peek(); - //calculate deltaG for current and last sample - double deltaG = Math.Abs(gv.Length-gvOld.Length); - - //save for later use - gRMSAverage currentRMS=new gRMSAverage(deltaG, gv.Ticks); - myAverages.Enqueue(currentRMS); - - basicLogger(string.Format("{0}\t{1}\t{2}\t{3}\t{4}", - gv.X, gv.Y, gv.Z, - gv.Ticks, - deltaG)); - - /* Theory: - * RSD: Rapid Shake Detection - * acceleration change is the sum of the delta G between consecutive samples divided - * by the number of samples per second - * Drastic Movement - * average acceleration change exceeds about 0.9G per sample (50ms period) - * calculated over the last .75 seconds - * Sustained Movement - * more fequently exceed an acceleration of about 0.5G (0.5G acceleration change per sample) - * exceed 0.5G value within time frame for non-consecutive samples (cross counter) - * time frame is set to reset after 60 non-consecutive (about 3 seconds at 50ms per sample) samples below 0.5G - */ - - //test for condition1 - bool bCondition1=false; - if (myAverages.Count > 1) - { - bCondition1 = condition1(currentRMS); - } - - //test for condition2 - bool bCondition2=false; - if (myAverages.Count > 1) - { - gRMSAverage lastRMS = myAverages.Peek(); - bCondition2 = condition2(currentRMS, lastRMS); - } - - //=============================================================================================== - //start when queue is filled - if (myQueue.Count >= 20) - { - //rapid shake detection (RSD) - //Condition1: have at least an average of 0.9G for at least .75 second - if(bCondition1 & bCondition2) - OnMoveDetected(gv); - }//start with filled queue - } - //else - // _firstCall = false; - - myQueue.Enqueue(gv); - - gvOld = gv; - } - - /* Theory: - * RSD: Rapid Shake Detection - * acceleration change is the sum of the delta G between consecutive samples divided - * by the number of samples per second - * Drastic Movement (condition1) - * average acceleration change exceeds about 0.9G per sample (50ms period) - * calculated over the last .75 seconds - */ - /// - /// deltaG above 0.9G for at least .75 seconds - /// - /// - private bool condition1(gRMSAverage currentRMS) - { - if (!_samplesPerSecondsCalulated) - return false; - - bool bRet1 = false; - //get average of values of last .75 seconds, tick diff is about 10ms between samples - double sum = 0; - int iSamples = 0; - - foreach (gRMSAverage gRMS in myAverages) - { - if (currentRMS.tick - gRMS.tick < 75 * 1000) //the ticks saved are milliseconds, .75seconds=75000 milliseconds - { - sum += gRMS.deltaG; - iSamples++; - } - } - //sum of deltas divided by samples per second - double DeltaAverage = sum / _samplesPerSecond;// (iSamples * 4 / 3); - - Avg_deltaG_rms = DeltaAverage; - - //call back for information, the caller reads _Avg_deltaG_rms - OnIdleDetected(new GMVector(0, 0, 0)); - - //how many samples exceed the Gmin treshold - int iCountG = 0; - foreach (GMVector g in myQueue) - { - if (g.Length > DeltaAverage) - iCountG++; - } - //Condition1: have at least an average of 0.9G for at least .75 second - if (DeltaAverage > myGmin){ - if (iCountG > myTmin) - { - //delete all entries, RESET - myQueue.Clear(); - //_firstCall = true; - - //OnMoveDetected(gv); - bRet1 = true; - } - } - return bRet1; - } - - /// - /// deltaG above .5G for more than 3 seconds and - /// without deltaG below .5G within last 3 seconds - /// - /// - /// - private bool condition2(gRMSAverage currentRMS, gRMSAverage lastRMS){ - - if (!_samplesPerSecondsCalulated) - return false; - - bool bRet = false; - crossDirection crossDir = crossDirection.unknown; - if (currentRMS.deltaG > myRMSmin && lastRMS.deltaG < myRMSmin) - { - //crossUp - crossDir = crossDirection.crossUP; - } - else if (currentRMS.deltaG < myRMSmin && lastRMS.deltaG > myRMSmin) - { - //crossDown - crossDir = crossDirection.crossDown; - } - - if (myCrossDOWNs.Count > 0) - { - gRMSAverage lastRMSup = myCrossDOWNs.Peek(); - if (crossDir == crossDirection.crossUP && (currentRMS.tick - lastRMSup.tick) >= _treshCountRMS) - { - if (myCrossUPs.Count > 0) - { - gRMSAverage lastRMSdown = myCrossDOWNs.Peek(); - if ((currentRMS.tick - lastRMSdown.tick) > _treshCountRMS) - bRet = true; - } - } - } - //enqueue current values - if (crossDir == crossDirection.crossUP) - myCrossUPs.Enqueue(currentRMS); - if (crossDir == crossDirection.crossDown) - myCrossDOWNs.Enqueue(currentRMS); - return bRet; - } -#region fields - private uint _samplesPerSecond = 20; - private bool _samplesPerSecondsCalulated = false; - - private enum crossDirection : int - { - unknown = 0, - crossUP = 1, - crossDown = -1, - } - - private class gRMSAverage - { - private double _deltaG; - public double deltaG - { - get { return _deltaG; } - } - private ulong _tick; - public ulong tick - { - get { return _tick; } - } - public gRMSAverage(double delta, ulong tick) - { - _deltaG = delta; - _tick = tick; - } - } - - //private static bool _firstCall = true; - - /// - /// store a list of acceleration data - /// - private LimitedQueue myQueue; - - /// - /// store a list of relevant delta acceleration data and ticks - /// - private LimitedQueue myAverages; - - /// - /// queue to record deltaG averages crossing from deltaG from <.5G to >.5G - /// - private LimitedQueue myCrossUPs; - - /// - /// queue to record deltaG averages crossing from deltaG from >.5G to <.5G - /// - private LimitedQueue myCrossDOWNs; - - private int _queueLength = 20; //20 samples per second will be great - - /// - /// how long should the 0.5 treshold be met - /// - private uint _treshCountRMS = 3000; //should be normally 3 seconds - public uint treshCountRMS - { - get { return _treshCountRMS; } - } - - /// - /// minimum G to exceed for shake detection - /// - private double myGmin=0.9; - public double _Gmin - { - set { myGmin = value; } - } - - /// - /// minimum G to exceed for sustained movement detection - /// - private double myRMSmin = 0.5; - public double _RMSmin - { - get { return myRMSmin; } - set { myRMSmin = value; } - } - - private double myTmin; - public double _Tmin - { - set { myTmin = value; } - } - - private double Avg_deltaG_rms; - public double _Avg_deltaG_rms - { - get { return Avg_deltaG_rms; } - } -#endregion - public static void basicLogger(string s) - { - string sFileName = @"\basicxyz.log.txt"; - System.IO.TextWriter tw = new System.IO.StreamWriter(sFileName, true); - //tw.WriteLine(X.ToString() + "," + Y.ToString() + "," + Z.ToString() + "," + AngleX.ToString() + "," + AngleY.ToString()); - tw.WriteLine(s); - tw.Flush(); - tw.Close(); - } - - } -} diff --git a/SensorScan5/MovementClass/MovementEventArgs.cs b/SensorScan5/MovementClass/MovementEventArgs.cs deleted file mode 100644 index 0f715bd..0000000 --- a/SensorScan5/MovementClass/MovementEventArgs.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -namespace Movedetection -{ - public class MovementEventArgs : EventArgs - { - /* HACK: fields are typically private, but making this internal so it - * can be accessed from other classes. In practice should use properties. - */ - internal GMVector _gmvector; - public MovementEventArgs() - { - } - public MovementEventArgs(GMVector gmvector) - : base() - { - this._gmvector = gmvector; - } - } -} - diff --git a/SensorScan5/MovementClass/ScreenOrientation.cs b/SensorScan5/MovementClass/ScreenOrientation.cs deleted file mode 100644 index 0673fa7..0000000 --- a/SensorScan5/MovementClass/ScreenOrientation.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -namespace Movedetection -{ - public enum ScreenOrientation - { - Landscape = 0, - ReverseLandscape = 1, - Portrait = 2, - ReversePortrait = 3, // upside down - FaceDown = 4, - FaceUp = 5 - } -} - diff --git a/SensorScan5/MovementClass/iMovement.cs b/SensorScan5/MovementClass/iMovement.cs deleted file mode 100644 index ecb6579..0000000 --- a/SensorScan5/MovementClass/iMovement.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Movedetection -{ - public interface IMovement - { - // event EventHandler ShakeEventHandler; - void OnIdleDetected(GMVector gv); - void OnMoveDetected(GMVector gv); - void addValues(GMVector gv); - } - -} \ No newline at end of file diff --git a/SensorScan5/NativeEvents/CoreDLL.cs b/SensorScan5/NativeEvents/CoreDLL.cs deleted file mode 100644 index a61bad8..0000000 --- a/SensorScan5/NativeEvents/CoreDLL.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; - -namespace NativeSync -{ - internal class CoreDLL - { - - [DllImport("CoreDLL", SetLastError=true)] - public static extern IntPtr CreateEvent( - IntPtr AlwaysNull0, - [In, MarshalAs(UnmanagedType.Bool)] bool ManualReset, - [In, MarshalAs(UnmanagedType.Bool)] bool bInitialState, - [In, MarshalAs(UnmanagedType.BStr)] string Name); - - [DllImport("CoreDLL", SetLastError = true)] - public static extern IntPtr CreateSemaphore( - int alwaysZero, - int lInitialCount, - int lMaximumCount, - string lpName - ); - - - [DllImport("CoreDLL",SetLastError=true)] - public static extern int ReleaseSemaphore( - IntPtr hSemaphore, - int lReleaseCount, - out int lpPreviousCount - ); - - [DllImport("CoreDLL",SetLastError=true)] - public static extern IntPtr CreateMutex( - int alwaysZero , - [In, MarshalAs(UnmanagedType.Bool)] bool bInitialOwner, - [In, MarshalAs(UnmanagedType.BStr)] string lpName - ); - - [DllImport("CoreDLL", SetLastError = true)] - public static extern int ReleaseMutex( - IntPtr hMutex - ); - - - [DllImport("coredll.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool CloseHandle(IntPtr hObject); - - [DllImport("CoreDLL",SetLastError=true)] - [return: MarshalAs(UnmanagedType.I4)] - public static extern int WaitForMultipleObjects(int objectCount, IntPtr[] eventList, bool waitAll, int timeOut); - - [DllImport("CoreDLL", SetLastError = true)] - public static extern int SetEventData(IntPtr hEvent, [In, MarshalAs(UnmanagedType.U4)] int dwData); - - [DllImport("CoreDLL", SetLastError = true)] - public static extern int GetEventData(IntPtr hEvent); - - [DllImport("CoreDLL", SetLastError = true)] - public extern static int WaitForSingleObject(IntPtr hEvent, int timeout); - - [DllImport("coredll.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool EventModify(IntPtr hEvent, [In, MarshalAs(UnmanagedType.U4)] int dEvent); - - } -} diff --git a/SensorScan5/NativeEvents/ScanEvents.cs b/SensorScan5/NativeEvents/ScanEvents.cs deleted file mode 100644 index 09c5dba..0000000 --- a/SensorScan5/NativeEvents/ScanEvents.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace NativeSync -{ - class ScanEvents - { - private static class Logging - { - public static bool logEnabled = false; - public static void doLog(string s) - { - if(logEnabled) - System.Diagnostics.Debug.WriteLine(s); - } - } - /// - /// defines the time the scan button is pressed down - /// - public int scanHoldTime = 100; - private SystemEvent scanEvent;// = new SystemEvent("StateLeftScan", false, false); - private SystemEvent scanEventDelta;// = new SystemEvent("DeltaLeftScan", false, false); - - public ScanEvents() - { - scanEvent = new SystemEvent("StateLeftScan", false, false); - scanEventDelta = new SystemEvent("DeltaLeftScan", false, false); - } - public void doScanButton() - { - //Set StateLeftScan, Set DeltaLeftScan, wait a bit, - //Unset StateLeftScan, Set DeltaLeftScan - - if (scanEvent.SetEvent()) - Logging.doLog("set StateLeftScan event OK"); - else - Logging.doLog("set StateLeftScan event failed!"); - - if (scanEventDelta.SetEvent()) - Logging.doLog("set scanEventDelta event OK"); - else - Logging.doLog("set scanEventDelta event failed!"); - - System.Threading.Thread.Sleep(scanHoldTime); - - if (scanEvent.ResetEvent()) - Logging.doLog("reset StateLeftScan event OK"); - else - Logging.doLog("reset StateLeftScan event failed!"); - - if (scanEventDelta.SetEvent()) - Logging.doLog("set scanEventDelta2 event OK"); - else - Logging.doLog("set scanEventDelta2 event failed!"); - } - } -} diff --git a/SensorScan5/NativeEvents/SyncObject.cs b/SensorScan5/NativeEvents/SyncObject.cs deleted file mode 100644 index cecb5df..0000000 --- a/SensorScan5/NativeEvents/SyncObject.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -namespace NativeSync -{ - public abstract class SyncBase:IDisposable - { - protected IntPtr _hSyncHandle; - protected bool _firstInstance; - const int INFINITE = -1; - - public bool FirstInstance - { - get { return _firstInstance; } - } - - public IntPtr SyncHandle - { - get - { - return _hSyncHandle; - } - } - - public static SyncBase WaitForMultipleObjects(int timeout, params SyncBase[] syncObjectList) - { - IntPtr[] handleList = new IntPtr[syncObjectList.Length]; - for (int i = 0; i < syncObjectList.Length; ++i) - { - handleList[i] = syncObjectList[i].SyncHandle; - } - int retIndex = NativeSync.CoreDLL.WaitForMultipleObjects(syncObjectList.Length, handleList, false, timeout); - if (retIndex < syncObjectList.Length) - return syncObjectList[retIndex]; - return null; - } - - public bool SetEvent() - { - return CoreDLL.EventModify(_hSyncHandle, (int)EventAction.Set); - } - - - public static SyncBase WaitForMultipleObjects(params SyncBase[] syncObjectList) - { - return WaitForMultipleObjects(INFINITE, syncObjectList); - } - - public WaitObjectReturnValue Wait(int timeout) - { - return (WaitObjectReturnValue)CoreDLL.WaitForSingleObject(_hSyncHandle, timeout); - } - - public WaitObjectReturnValue Wait() - { - return (WaitObjectReturnValue)CoreDLL.WaitForSingleObject(_hSyncHandle, -1); - } - - - #region IDisposable Members - - public virtual void Dispose() - { - CoreDLL.CloseHandle(_hSyncHandle); - } - - #endregion - } -} diff --git a/SensorScan5/NativeEvents/SystemEvent.cs b/SensorScan5/NativeEvents/SystemEvent.cs deleted file mode 100644 index 6de9e9d..0000000 --- a/SensorScan5/NativeEvents/SystemEvent.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; - -namespace NativeSync -{ - - public class SystemEvent : SyncBase - { - bool _manualReset; - - public SystemEvent(string name, bool manualReset, bool initialState) - { - _manualReset = manualReset; - _hSyncHandle = CoreDLL.CreateEvent(IntPtr.Zero, manualReset, initialState, name); - this._firstInstance= (0 == Marshal.GetLastWin32Error()); - } - - public bool ManualReset - { - get { return _manualReset; } - } - - public bool PulseEvent() - { - return CoreDLL.EventModify(_hSyncHandle, (int)EventAction.Pulse); - } - - public bool ResetEvent() - { - return CoreDLL.EventModify(_hSyncHandle, (int)EventAction.Reset); - } - - public void SetEventData(int data) - { - CoreDLL.SetEventData(_hSyncHandle, data); - } - - public int GetEventData() - { - return CoreDLL.GetEventData(_hSyncHandle); - } - - } -} diff --git a/SensorScan5/NativeEvents/WaitObjectReturnValue.cs b/SensorScan5/NativeEvents/WaitObjectReturnValue.cs deleted file mode 100644 index c41eb08..0000000 --- a/SensorScan5/NativeEvents/WaitObjectReturnValue.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -namespace NativeSync -{ - public enum WaitObjectReturnValue: long - { - WAIT_OBJECT_0 = 0x00000000L, - WAIT_TIMEOUT = 0x000000102L, - WAIT_ABANDONED = 0x00000080L, - WAIT_FAILED = 0xffffffffL - } -} diff --git a/SensorScan5/Program.cs b/SensorScan5/Program.cs deleted file mode 100644 index 958af4d..0000000 --- a/SensorScan5/Program.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; - -namespace SensorScan5 -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new mainFrm()); - } - } -} \ No newline at end of file diff --git a/SensorScan5/Properties/AssemblyInfo.cs b/SensorScan5/Properties/AssemblyInfo.cs deleted file mode 100644 index 74618e3..0000000 --- a/SensorScan5/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SensorScan5")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec")] -[assembly: AssemblyProduct("SensorScan5")] -[assembly: AssemblyCopyright("Copyright © Intermec 2010")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("93570bb4-84fc-4de6-9b19-9769e0509a6b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - diff --git a/SensorScan5/Properties/Resources.Designer.cs b/SensorScan5/Properties/Resources.Designer.cs deleted file mode 100644 index a794f93..0000000 --- a/SensorScan5/Properties/Resources.Designer.cs +++ /dev/null @@ -1,64 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -<<<<<<< .mine -// Runtime Version:2.0.50727.5466 -======= -// Runtime Version:2.0.50727.3634 ->>>>>>> .r143 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace SensorScan5.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SensorScan5.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/SensorScan5/Properties/Resources.resx b/SensorScan5/Properties/Resources.resx deleted file mode 100644 index 451318b..0000000 --- a/SensorScan5/Properties/Resources.resx +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 diff --git a/SensorScan5/SensorScan5.csproj b/SensorScan5/SensorScan5.csproj deleted file mode 100644 index 22bb496..0000000 --- a/SensorScan5/SensorScan5.csproj +++ /dev/null @@ -1,158 +0,0 @@ - - - Debug - AnyCPU -<<<<<<< .mine - 9.0.30729 -======= - 9.0.21022 ->>>>>>> .r143 - 2.0 - {5A36EAD3-115B-4707-8FDE-704B16E08CA9} - WinExe - Properties - SensorScan5 - SensorScan5 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - b2c48bd2-963d-4549-9169-1fa021dce484 - 5.02 - SensorScan5 - v2.0 - - -<<<<<<< .mine - - - - - 2.0 - Windows Mobile 6 Professional SDK - %25CSIDL_PROGRAM_FILES%25 -======= - - - - - 2.0 - Windows Mobile 6 Professional SDK ->>>>>>> .r143 - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - -<<<<<<< .mine - -======= - ->>>>>>> .r143 - - - - - - - - - - - - Component - - - - - Form - - - Form1.cs - - - - - - - - - - - - - - - - Designer - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - - - - - - - - - - - - - - - - - {31045968-12E1-457C-AD26-F540F4F1822B} - perfChartClass - - - - - - - - - - - - - - \ No newline at end of file diff --git a/SensorScan5/SensorScan5.csproj.user b/SensorScan5/SensorScan5.csproj.user deleted file mode 100644 index d57a6ce..0000000 --- a/SensorScan5/SensorScan5.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - b2c48bd2-963d-4549-9169-1fa021dce484d6518ffb-710f-11d3-99f2-00105a0df099 - false - - \ No newline at end of file diff --git a/SensorScan5/SensorScan5.sln b/SensorScan5/SensorScan5.sln deleted file mode 100644 index 585773f..0000000 --- a/SensorScan5/SensorScan5.sln +++ /dev/null @@ -1,29 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SensorScan5", "SensorScan5.csproj", "{5A36EAD3-115B-4707-8FDE-704B16E08CA9}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "perfChartClass", "perfChartClass\perfChartClass.csproj", "{31045968-12E1-457C-AD26-F540F4F1822B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5A36EAD3-115B-4707-8FDE-704B16E08CA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5A36EAD3-115B-4707-8FDE-704B16E08CA9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5A36EAD3-115B-4707-8FDE-704B16E08CA9}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {5A36EAD3-115B-4707-8FDE-704B16E08CA9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5A36EAD3-115B-4707-8FDE-704B16E08CA9}.Release|Any CPU.Build.0 = Release|Any CPU - {5A36EAD3-115B-4707-8FDE-704B16E08CA9}.Release|Any CPU.Deploy.0 = Release|Any CPU - {31045968-12E1-457C-AD26-F540F4F1822B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {31045968-12E1-457C-AD26-F540F4F1822B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {31045968-12E1-457C-AD26-F540F4F1822B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {31045968-12E1-457C-AD26-F540F4F1822B}.Release|Any CPU.Build.0 = Release|Any CPU - {31045968-12E1-457C-AD26-F540F4F1822B}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/SensorScan5/SensorScan5.suo b/SensorScan5/SensorScan5.suo deleted file mode 100644 index 6664846..0000000 Binary files a/SensorScan5/SensorScan5.suo and /dev/null differ diff --git a/SensorScan5/ShakeClass/FifoQueue.cs b/SensorScan5/ShakeClass/FifoQueue.cs deleted file mode 100644 index 43054d7..0000000 --- a/SensorScan5/ShakeClass/FifoQueue.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -public class LimitedQueue : Queue -{ - private int limit = -1; - - public int Limit - { - get { return limit; } - set { limit = value; } - } - - public LimitedQueue(int limit) - : base(limit) - { - this.Limit = limit; - } - - public new void Enqueue(T item) - { - if (this.Count >= this.Limit) - { - this.Dequeue(); - } - base.Enqueue(item); - } -} diff --git a/SensorScan5/ShakeClass/GVector.cs b/SensorScan5/ShakeClass/GVector.cs deleted file mode 100644 index 52f7950..0000000 --- a/SensorScan5/ShakeClass/GVector.cs +++ /dev/null @@ -1,298 +0,0 @@ -using System; -#region CN50 XYZ vectors -/* - (N) - +Y - | -Z - | / - | / - | .' - +-----------+/ - | +-------+ | - | | | | - | | | | - | | | | -(E)''''''| | / | |'''''' (W) -+X | |.' | | -X - | /-------+ | - |/ | - .' | - / +-----------+ - .' | - / | - +Z | - -Y - (S) - - //calc the acceleration or the longest vector - double accel = Math.Sqrt(x * x + y * y + z * z); - //calc the X angle, should be about 180 if device is upright - double degrees = Math.Acos(x / b) * 360.0 / Math.PI; - - * when device is faceup on table: x=0 y=0 z=1 - * when device is faceup on table: x=0 y=0 z=-1 - * when device is upright scan to roof: x=0 y=-1 z=0 - * when device is upright scanner to down: x=0 y=1 z=0 - * when scanner lays on left side: x=-1 y=0 z=0 - * when scanner lays on right side: x=1 y=0 z=0 -*/ - -#endregion -namespace ShakeDetection -{ - public struct GVector - { - public GVector(double x, double y, double z) - { - myX = x; - myY = y; - myZ = z; - myHeading = 0; - myStrength = 0; - myTicks=DateTime.Now.Ticks; - } - long myTicks; - public long Ticks - { - get { return myTicks; } - } - double myX; - public double X - { - get { return myX; } - set { myX = value; } - } - double myY; - public double Y - { - get { return myY; } - set { myY = value; } - } - double myZ; - public double Z - { - get { return myZ; } - set { myZ = value; } - } - - double myHeading; - /// - /// Compass heading in degrees, for use with magnetic sensors - /// - public double Heading - { - get { return myHeading; } - set { myHeading = value; } - } - double myStrength; - /// - /// the magnetic strength, for use with magnetic sensors - /// - public double Strength - { - get { return myStrength; } - set { myStrength = value; } - } - - public GVector Normalize() - { - return Scale(1 / Length); - } - - public GVector Scale(double scale) - { - GVector ret = this; - ret.myX *= scale; - ret.myY *= scale; - ret.myZ *= scale; - return ret; - } - /// - /// Convert a radian to degree - /// - /// - /// - /// - /// - private double RadianToDegree(double d){ - double dRes; - dRes= d*180/Math.PI; - return dRes; - } - /* - pitch = arctan(Ax/sqrt(Ay^2+Az^2)) - roll = arctan(Ay/sqrt(Ax^2+Az^2)) - theta = arctan(sqrt(Ax^2+Az^2)/Az) - * //http://cache.freescale.com/files/sensors/doc/app_note/AN3461.pdf - * Pitch (phi) is defined as the angle of the X-axis relative to ground. - * pitch = arctan(x/sqrt(y*y+z*z)) - * Roll (rho) is defined as the angle of the Y-axis relative to the ground. - * roll = arctan(Y/sqrt(x*x+z*z)) - * Tilt (theta) is the angle of the Z axis relative to gravity. - * theta = sqrt(x*x + y*y)/z - */ - public double Pitch{ - get{ - GVector gv1=this; - double p = Math.Atan(gv1.X / Math.Sqrt(Math.Pow(gv1.Y,2) / Math.Pow(gv1.Z,2))); - return this.RadianToDegree(p); - } - } - public double Roll{ - get{ - GVector gv1=this; - //double p = Math.Atan(gv1.Z / gv1.X); - double p=Math.Atan(gv1.Y / Math.Sqrt(Math.Pow(gv1.X,2) + Math.Pow(gv1.Z,2))); - return this.RadianToDegree(p); - } - } - //public double Yaw - //{ - // get - // { - // GVector gv1 = this; - // double p = Math.Sqrt(Math.Pow(gv1.X, 2) + Math.Pow(gv1.Y, 2)) / gv1.Z; - // return this.RadianToDegree(p); - // } - //} - public double Tilt{ //was called theta - get{ - GVector gv1 = this; - double p = Math.Sqrt(Math.Pow(gv1.X, 2) + Math.Pow(gv1.Y, 2)) / gv1.Z; - return this.RadianToDegree(p); - } - } - [Obsolete ("Dont use")] - public double TiltDegrees{ // http://www.j2i.net/BlogEngine/post/2010/09/07/Introduction-to-Windows-Phone-Programming-Part-1.aspx - get{ - GVector e=this; - float tiltDirection = (180f/(float)Math.PI)*(float)Math.Atan2(e.Y, e.X); - return (double)tiltDirection; - } - } - #region segmented direction - // http://en.wikipedia.org/wiki/Boxing_the_compass - //attention: this here is based on +Y/+X (-1/0) equal 0 degree equal North - public enum Direction:int{ - None=-1, - W=0, - WSW, - SW, - SSW, - S, - SSE, - SE, - ESE, - E, - ENE, - NE, - NNE, - N, - NNW, - NW, - WNW, - } - public Direction direction - { //http://stackoverflow.com/questions/1437790/how-to-snap-a-directional-2d-vector-to-a-compass-n-ne-e-se-s-sw-w-nw - get{ - GVector gv=this; - int segmentCount=16; - int compassSegment = (((int) Math.Round(Math.Atan2(gv.Y, gv.X) / (2 * Math.PI / segmentCount))) + segmentCount) % segmentCount; - return (Direction)compassSegment; - } - } - #endregion - /// - /// the X angle of the vector - /// - public int angleX - { - get - { - return (int)(Math.Acos(myX / Length) * 360.0 / Math.PI); - } - } - /// - /// the Y angle of the vector - /// - public int angleY - { - get - { - return (int)(Math.Acos(myY / Length) * 360.0 / Math.PI); - } - } - /// - /// the Z angle of the vector - /// - public int angleZ - { - get - { - return (int)(Math.Acos(myZ / Length) * 360.0 / Math.PI); - } - } - - /// - /// although this is called length it is the max. acceleration force - /// - public double Length - { - get - { - return Math.Sqrt(myX * myX + myY * myY + myZ * myZ); - } - } - - /// - /// calc the distance between the end of two vectors - /// - /// the vector to compare to - /// - public double EuclideanDistance(GVector gvOld) - { - return Math.Sqrt(Math.Pow(this.X - gvOld.X, 2) + Math.Pow(this.Y - gvOld.Y, 2) + Math.Pow(this.Z - gvOld.Z, 2)); - } - public long TicksDiff(GVector gvNew) - { - GVector gvOld=this; - long diff = gvNew.Ticks - gvOld.Ticks; - //one tick is 100 nano seconds - return diff; - } - public override string ToString() - { - return string.Format("X={0} Y={1} Z={2} Accel={3} angleX={4} angleX={5} angleX={6} orientation={7} ticks={8}", - Math.Round(myX, 4), Math.Round(myY, 4), Math.Round(myZ, 4), - Length, - angleX, angleY,angleZ, - ToScreenOrientation(), - Ticks); - } - - //changed to match CN50 XYZ directions - public ScreenOrientation ToScreenOrientation() - { - if (Math.Abs(X) > Math.Abs(Y)) - { - if (Math.Abs(X) > Math.Abs(Z)) - { - if (X > 0) - return ScreenOrientation.ReverseLandscape; //changed from Landscape - return ScreenOrientation.Landscape; //changed from ReverseLandscape - } - } - else if (Math.Abs(Y) > Math.Abs(Z)) - { - if (Y > 0) - return ScreenOrientation.ReversePortrait; //changed from Portrait - return ScreenOrientation.Portrait; // changed from ReversePortrait - } - - if (Z > 0) - return ScreenOrientation.FaceUp; //this is different to HTC - return ScreenOrientation.FaceDown; //this is different to HTC - } - } -} - diff --git a/SensorScan5/ShakeClass/IShake.cs b/SensorScan5/ShakeClass/IShake.cs deleted file mode 100644 index 514a59e..0000000 --- a/SensorScan5/ShakeClass/IShake.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace ShakeDetection -{ - public interface IShake - { -// event EventHandler ShakeEventHandler; - void OnShakeDetected(GVector gv); - void addValues(GVector gv); - } - -} - diff --git a/SensorScan5/ShakeClass/ScreenOrientation.cs b/SensorScan5/ShakeClass/ScreenOrientation.cs deleted file mode 100644 index 95881ff..0000000 --- a/SensorScan5/ShakeClass/ScreenOrientation.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -namespace ShakeDetection -{ - public enum ScreenOrientation - { - Landscape = 0, - ReverseLandscape = 1, - Portrait = 2, - ReversePortrait = 3, // upside down - FaceDown = 4, - FaceUp = 5 - } -} - diff --git a/SensorScan5/ShakeClass/ShakeClass.cs b/SensorScan5/ShakeClass/ShakeClass.cs deleted file mode 100644 index ba67b69..0000000 --- a/SensorScan5/ShakeClass/ShakeClass.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -namespace ShakeDetection -{ - /// - /// Main abstract class to implement various Shake detector classes - /// - public abstract class ShakeClass:IShake,IDisposable - { - #region Properties - private string _name = "ShakeClass"; - /// - /// used to identify multiple classes that inherited this class - /// - public string name{ - get{return _name;} - set { _name = value; } - } - /// - /// generic constructor - /// - /// - public ShakeClass (String s) - { - this._name=s; - } - public ShakeClass() - { - this._name = "ShakeClass"; - } - private bool _logEnabled = false; - public bool logEnabled - { - get { return _logEnabled; } - set { _logEnabled = value; } - } - private bool _logToFile = false; - /// - /// enable logging to file - /// - public bool logToFile - { - get { return _logToFile; } - set { _logToFile = value; } - } - #endregion - /// - /// implemented for completeness - /// - public void Dispose(){ - } - - #region Events - /// - /// the shake detected event handler - /// - public event ShakeDetectedEventHandler ShakeDetected; - /// - /// the shake detected delegate - /// - /// - /// - public delegate void ShakeDetectedEventHandler(object sender, ShakeEventArgs bre); - private void ShakeDetectedEvent(object mySender, ShakeEventArgs myArgs) - { - if (this.ShakeDetected == null) - return; - this.ShakeDetected(this, myArgs); - } - /// - /// this eventhandler should be fired by the derived classes to signal a shake detection - /// - /// - public void OnShakeDetected(GVector gv) - { - ShakeDetectedEvent(this, new ShakeEventArgs(gv)); - } - - #endregion - #region Methods - /// - /// implement this with the actual vector and use OnShakeEvent to signal a 'Shake' - /// - /// - public abstract void addValues(GVector gv); - #endregion - #region Logging - public void Logger(string s) - { - if (!_logEnabled) - return; - System.Diagnostics.Debug.WriteLine(_name + ": " + s); - if (_logToFile) - { - string sFileName = @"\" + _name + ".log.txt"; - System.IO.TextWriter tw = new System.IO.StreamWriter(sFileName, true); - //tw.WriteLine(X.ToString() + "," + Y.ToString() + "," + Z.ToString() + "," + AngleX.ToString() + "," + AngleY.ToString()); - tw.WriteLine(_name + ": " + s); - tw.Close(); - } - } - #endregion - - } -} - diff --git a/SensorScan5/ShakeClass/ShakeClass1.cs b/SensorScan5/ShakeClass/ShakeClass1.cs deleted file mode 100644 index 7c12991..0000000 --- a/SensorScan5/ShakeClass/ShakeClass1.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ShakeDetection -{ - //http://www.google.com/codesearch/p?hl=en#L1VPiqAn_3g/trunk/simple/src/com/google/devtools/simple/runtime/components/impl/android/AccelerometerSensorImpl.java&q=Shaking%20package:http://simple\.googlecode\.com&sa=N&cd=1&ct=rc - /** - *

From the Android documentation: - *

"All values are in SI units (m/s^2) and measure the acceleration applied - * to the phone minus the force of gravity. - *
values[0]: Acceleration minus Gx on the x-axis - *
values[1]: Acceleration minus Gy on the y-axis - *
values[2]: Acceleration minus Gz on the z-axis " - Landing on a table, the values returned by the SensorEvent for the phone should be : - 1. 0 m/s2 along x axis - 2. 0 m/s2 along y axis - 3. 9,80665 m/s2 along z axis - */ - - public class ShakeClass1: ShakeClass - { - #region Properties - private double _shakeTreshold = 4; //default was 8 - public double shakeTreshold - { - get { return _shakeTreshold; } - set { _shakeTreshold = value; } - } - private int _sensor_cache_size = 10; - - private Queue _X_Cache; - private Queue _Y_Cache; - private Queue _Z_Cache; - - #endregion - #region Methods - ///

- /// This shake detection code uses three queues to fill them with x,y and z values - /// if the new added value exceeds the average of the queue by a treshold, the - /// shakedDetected event will be fired - /// - /// - public ShakeClass1(string name) - { - base.name = name; - _X_Cache=new Queue(_sensor_cache_size); - _Y_Cache=new Queue(_sensor_cache_size); - _Z_Cache=new Queue(_sensor_cache_size); - } - /// - /// this function uses every direction for its own shake detection - /// - /// - /// - /// - public override void addValues(GVector gv){ - //code is from android where 9.8m/s² is normal - //cn50 gives 0.98m/s² so we multiply the CN50 values with 10 - gv = gv.Scale(10); - - addToSensorCache(_X_Cache, gv.X); - addToSensorCache(_Y_Cache, gv.Y); - addToSensorCache(_Z_Cache, gv.Z); - - this.Logger(gv.ToString()); - if(isShaking(_X_Cache, gv.X) || - isShaking(_Y_Cache, gv.Y) || - isShaking(_Z_Cache, gv.Z) ) - { - this.OnShakeDetected(gv); - } - } - - private void addToSensorCache(Queue cache, double currentValue) - { - if (cache.Count > _sensor_cache_size) - cache.Dequeue(); - //add only positive values - cache.Enqueue(Math.Abs(currentValue)); - } - - private bool isShaking(Queue cache, double currentValue) - { - double average = 0; - foreach (double d in cache) - { - average += d; - } - average = average / cache.Count; - this.Logger(String.Format("ShakeClass1: isShaking: average: {0} current: {1} treshold:{2} diff:{3}", average, currentValue, _shakeTreshold, Math.Abs(average - currentValue))); - return Math.Abs(average - Math.Abs(currentValue)) > _shakeTreshold; - } - #endregion - } -} diff --git a/SensorScan5/ShakeClass/ShakeClass2.cs b/SensorScan5/ShakeClass/ShakeClass2.cs deleted file mode 100644 index 945e512..0000000 --- a/SensorScan5/ShakeClass/ShakeClass2.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ShakeDetection -{ - //http://www.google.com/codesearch/p?hl=en#L1VPiqAn_3g/trunk/simple/src/com/google/devtools/simple/runtime/components/impl/android/AccelerometerSensorImpl.java&q=Shaking%20package:http://simple\.googlecode\.com&sa=N&cd=1&ct=rc - /** - *

From the Android documentation: - *

"All values are in SI units (m/s^2) and measure the acceleration applied - * to the phone minus the force of gravity. - *
values[0]: Acceleration minus Gx on the x-axis - *
values[1]: Acceleration minus Gy on the y-axis - *
values[2]: Acceleration minus Gz on the z-axis " - Landing on a table, the values returned by the SensorEvent for the android phone should be : - 1. 0 m/s2 along x axis - 2. 0 m/s2 along y axis - 3. 9,80665 m/s2 along z axis - */ - - public class ShakeClass2 : ShakeClass - { - #region Methods - ///

- /// This shake detection uses the current and last vector - /// if the acceleration is above treshold and within a timeframe the - /// ShakeDetected event will be fired - /// - /// - public ShakeClass2(string name) - { - base.name = name; - } - public override void addValues(GVector gv) - { - now = DateTime.Now; - //was written for android which uses a normal value of 9.81m/s² - //cn50 comes with 1/10 G's - gv = gv.Scale(10); - double x = gv.X; - double y = gv.Y; - double z = gv.Z; - double force; - - if (lastUpdate.Equals(0)) - { - this.Logger("ignored due to no update"); - lastUpdate = now; - lastShake = now; - lastX = x; - lastY = y; - lastZ = z; - } - else - { - this.Logger("testing for shake"); - timeDiff = now - lastUpdate; - this.Logger("timediff: "+timeDiff.ToString()); - if (!timeDiff.Equals(0)) - { - force = Math.Abs(x + y + z - lastX - lastY - lastZ) - / timeDiff.TotalSeconds; - - this.Logger("force: "+force.ToString() + "treshold: " +_shakeTreshold.ToString()); - if (force > _shakeTreshold) - { - if (now - lastShake >= interval) - { - // trigger shake event - this.OnShakeDetected(gv); - } - lastShake = now; - } - lastX = x; - lastY = y; - lastZ = z; - lastUpdate = now; - } - } - } - #endregion - //http://blog.androgames.net/85/android-accelerometer-tutorial/ - #region Properties - private DateTime now, lastUpdate, lastShake; - private TimeSpan timeDiff, interval = TimeSpan.FromSeconds(2); - double lastX, lastY, lastZ; - private double _shakeTreshold = 1.2; - public double shakeTreshold - { - get { return _shakeTreshold; } - set { _shakeTreshold = value; } - } - #endregion - } -} \ No newline at end of file diff --git a/SensorScan5/ShakeClass/ShakeClass3.cs b/SensorScan5/ShakeClass/ShakeClass3.cs deleted file mode 100644 index 5fedcce..0000000 --- a/SensorScan5/ShakeClass/ShakeClass3.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ShakeDetection -{ - /// - /// very simple shake detect function - /// it just checks if acceleration is greater than treshold - /// - public class ShakeClass3 : ShakeClass - { - #region Methods - public ShakeClass3(string name) - { - base.name = name; - } - public override void addValues(GVector gv) - { - //calc the acceleration or the longest vector - double accel = gv.Length; //Math.Sqrt(x * x + y * y + z * z); - this.Logger(gv.ToString()); - if (accel > _shakeTreshold) - { - this.Logger("Shake detected"); - this.OnShakeDetected(gv); //fire the event in the base class - } - } - #endregion - #region Properties - private double _shakeTreshold = 1.2; - public double shakeTreshold - { - get { return _shakeTreshold; } - set { _shakeTreshold = value; } - } - #endregion - } -} \ No newline at end of file diff --git a/SensorScan5/ShakeClass/ShakeClass4.cs b/SensorScan5/ShakeClass/ShakeClass4.cs deleted file mode 100644 index 5a4efbb..0000000 --- a/SensorScan5/ShakeClass/ShakeClass4.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - - -namespace ShakeDetection -{ - /// - /// simple shake detect only checks accel>treshold but with a low cut filtered value - /// - public class ShakeClass4 : ShakeClass - { - #region Methods - public ShakeClass4(string s) - { - base.name = s; - } - public override void addValues(GVector gv1) - { - - //calc the acceleration or the longest vector - double accel = gv1.Length;// Math.Sqrt(x * x + y * y + z * z); - - //we are not interested in directions - accel = Math.Abs(accel); - - //a low cut filter - double delta = Math.Abs(accel - accelLast); - accel = accel * 0.9f + delta; - - this.Logger(gv1.ToString()); - - if (accel < _shakeTreshold && accelLast>_shakeTreshold) - { - this.OnShakeDetected(gv1); - this.Logger("Shake detected: " + gv1.ToString()); - } - accelLast = accel; - - } - #endregion - #region Properties - private static double accelLast; - private double _shakeTreshold = 1.2; - public double shakeTreshold - { - get { return _shakeTreshold; } - set { _shakeTreshold = value; } - } - #endregion - } -} \ No newline at end of file diff --git a/SensorScan5/ShakeClass/ShakeClass5.cs b/SensorScan5/ShakeClass/ShakeClass5.cs deleted file mode 100644 index a4d6151..0000000 --- a/SensorScan5/ShakeClass/ShakeClass5.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - - -namespace ShakeDetection -{ - public class ShakeClass5 : ShakeClass - { - #region Methods - /// - /// simple shake detect function - /// it just checks if acceleration between two readings is greater than treshold - /// - public ShakeClass5(string s) - { - base.name = s; - } - public override void addValues(GVector gv) - { - //private static int SHAKE_THRESHOLD = 800; - - long lastUpdate = 0; - long curTime = System.DateTime.Now.Millisecond; - // only allow one update every 100ms. - if ((curTime - lastUpdate) > 100) - { - long diffTime = (curTime - lastUpdate); - lastUpdate = curTime; - - double speed = Math.Abs(gv.X + gv.Y + gv.Z - last_x - last_y - last_z) / diffTime * 10000; - - //adjust for CN50 - speed = speed / 10; - if (speed > _shakeTreshold) - { - this.Logger("Shake detected"); - this.OnShakeDetected(gv); - } - else - { - //System.Diagnostics.Debug.WriteLine("sensor : shake speed: " + speed.ToString()); - } - gvLast = gv; - last_x = gv.X; - last_y = gv.Y; - last_z = gv.Z; - } - else - this.Logger("sensor : timespan to low "); - } - #endregion - #region Properties - // http://www.codeshogun.com/blog/category/mobile/ - static double last_x = 0; - static double last_y = 0; - static double last_z = 0; - static GVector gvLast = new GVector(0, 0, 0); - private double _shakeTreshold = 800; - public double shakeTreshold - { - get { return _shakeTreshold; } - set { _shakeTreshold = value; } - } - - #endregion - - } -} \ No newline at end of file diff --git a/SensorScan5/ShakeClass/ShakeClass6.cs b/SensorScan5/ShakeClass/ShakeClass6.cs deleted file mode 100644 index 09163ae..0000000 --- a/SensorScan5/ShakeClass/ShakeClass6.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - - -namespace ShakeDetection -{ - public class ShakeClass6 : ShakeClass - { - /// - /// shake detection using vector difference (distance) and counters - /// - /// - public ShakeClass6(string s) - { - base.name = s; - } - #region Properties - private int DetectWindowCount = 0; - private int ResetWindowCount = 0; - /// - /// how many shakes will trigger a shake event - /// - public int detectwindow=3; - /// - /// how many shakes will reset the shake counting - /// - public int resetwindow = 2; - - private double _shakeTreshold = 1.2; - /// - /// what will be counted as fast shake - /// - public double shakeTreshold - { - get { return _shakeTreshold; } - set { _shakeTreshold = value; } - } - private GVector gvOld; - private int FirstTimeEntryFlag=0; - #endregion - #region Methods - public override void addValues(GVector gvNew) - { - if (FirstTimeEntryFlag != 0) - { - //Set new values to old - gvOld = gvNew; - - //calculate Euclidean distance between old and data points - double EuclideanDistance = gvNew.EuclideanDistance(gvOld);// Math.Sqrt(Math.Pow(X - Xold, 2) + Math.Pow(Y - Yold, 2) + Math.Pow(Z - Zold, 2)); - - //set shake to true if distance between data points is greater than the defined threshold - if (EuclideanDistance > _shakeTreshold) - { - //System.Diagnostics.Debug.WriteLine("DetectShake : shake detected w/ speed: " + EuclideanDistance.ToString()); - DetectWindowCount++; - if (DetectWindowCount > detectwindow) { - DetectWindowCount = 0; - ResetWindowCount = 0; - Logger("Shake detected"); - OnShakeDetected(gvNew); - } - } - else - { - //movement to low - //System.Diagnostics.Debug.WriteLine("DetectShake : speed to low: " + EuclideanDistance.ToString()); - ResetWindowCount++; - if (ResetWindowCount > resetwindow) { - DetectWindowCount = 0; - ResetWindowCount = 0; - Logger("Windows counts reset"); - return; //no shake - } - } - - } - //no longer the first run. - FirstTimeEntryFlag = 1; - } - #endregion - } -} \ No newline at end of file diff --git a/SensorScan5/ShakeClass/ShakeClass7.cs b/SensorScan5/ShakeClass/ShakeClass7.cs deleted file mode 100644 index 9190827..0000000 --- a/SensorScan5/ShakeClass/ShakeClass7.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; - -namespace ShakeDetection -{ - public class ShakeClass7:ShakeClass - { - #region Methods - /// - /// shake detection using a list of directions - /// if acceleration is > treshold and current direction is != actual direction and - /// number of detected shakes is > min number of shakes then - /// the ShakeDetected event will be fired - /// - /// - public ShakeClass7(string s) - { - _minimumShakes=1; - _shakeRecordList = new ShakeRecord[_minimumShakes]; - base.name = s; - } - public ShakeClass7(string s, int minShakes) - { - _minimumShakes = minShakes; - _shakeRecordList = new ShakeRecord[minShakes]; - } - - public override void addValues(GVector gv) - { - //use new GVector 16 segmented direction - GVector.Direction direction = gv.direction; - - double accel = gv.Length;// Math.Sqrt(e.X * e.X + e.Y * e.Y);// + e.Z*e.Z); - //Does the currenet acceleration vector meet the minimum magnitude that we - //care about? - if (accel > MinimumAccelerationMagnitudeSquared) - { - //If the shake detected is in the same direction as the last one then ignore it - //if ((direction & _shakeRecordList[_shakeRecordIndex].ShakeDirection) != GVector.Direction.None)// Direction.None) - if((direction == _shakeRecordList[_shakeRecordIndex].ShakeDirection)) - return; - ShakeRecord record = new ShakeRecord(); - record.EventTime = DateTime.Now; - record.ShakeDirection = direction; - _shakeRecordIndex = (_shakeRecordIndex + 1)%_minimumShakes; - _shakeRecordList[_shakeRecordIndex] = record; - - CheckForShakes(gv); - - } - } - - private void CheckForShakes(GVector gv) - { - int startIndex = (_shakeRecordIndex - 1); - if (startIndex < 0) startIndex = _minimumShakes - 1; - int endIndex = _shakeRecordIndex; - if ((_shakeRecordList[endIndex].EventTime.Subtract(_shakeRecordList[startIndex].EventTime)) <= MinimumShakeTime) - { - Logger("Shake detected"); - OnShakeDetected(gv); - } - } -#endregion - #region Properties - private int _minimumShakes; - ShakeRecord[] _shakeRecordList; - private int _shakeRecordIndex = 0; - private const double MinimumAccelerationMagnitude = 1.1; - private const double MinimumAccelerationMagnitudeSquared = MinimumAccelerationMagnitude*MinimumAccelerationMagnitude; - private static readonly TimeSpan MinimumShakeTime = TimeSpan.FromMilliseconds(500); - - private struct ShakeRecord - { - //public Direction ShakeDirection; - public GVector.Direction ShakeDirection; - public DateTime EventTime; - } - #endregion - } -} diff --git a/SensorScan5/ShakeClass/ShakeClass8.cs b/SensorScan5/ShakeClass/ShakeClass8.cs deleted file mode 100644 index 3b6cb93..0000000 --- a/SensorScan5/ShakeClass/ShakeClass8.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ShakeDetection -{ - // http://mark.mymonster.nl/2010/10/24/shake-that-windows-phone-7-and-detect-it/ - public class ShakeClass8:ShakeClass - { - #region Properties - public double ShakeThreshold = 0.7; - private bool firstcall=true; //helper var as GVector is not Nullable - private GVector _lastReading; - private int _shakeCount; - private bool _shaking; - #endregion - #region Methods - /// - /// shake detection compairing difference of last acceleration and current accel. - /// if diffs of acceleration pairs exceeds min treshold and the number of shakes - /// exceeds 1 then the ShakeDetected event will be fired - /// - public ShakeClass8 () - { - base.name="ShakeClass8"; - } - public ShakeClass8 (string s) - { - base.name=s; - } - public override void addValues (GVector gv) - { - GVector reading=gv; - if (!firstcall)// _lastReading != null) - { - if (!_shaking && CheckForShake(_lastReading, reading, ShakeThreshold) && _shakeCount >= 1) - { - //We are shaking - _shaking = true; - _shakeCount = 0; - OnShakeDetected(gv); - - } - else if (CheckForShake(_lastReading, reading, ShakeThreshold)) - { - _shakeCount++; - } - else if (!CheckForShake(_lastReading, reading, 0.2)) - { - _shakeCount = 0; - _shaking = false; - } - } - _lastReading = reading; - firstcall=false; - - } - private static bool CheckForShake(GVector last, GVector current, - double threshold) - { - double deltaX = Math.Abs((last.X - current.X)); - double deltaY = Math.Abs((last.Y - current.Y)); - double deltaZ = Math.Abs((last.Z - current.Z)); - - return (deltaX > threshold && deltaY > threshold) || - (deltaX > threshold && deltaZ > threshold) || - (deltaY > threshold && deltaZ > threshold); - } - #endregion - } -} - diff --git a/SensorScan5/ShakeClass/ShakeClass9.cs b/SensorScan5/ShakeClass/ShakeClass9.cs deleted file mode 100644 index 8ca7164..0000000 --- a/SensorScan5/ShakeClass/ShakeClass9.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ShakeDetection -{ - // http://mark.mymonster.nl/2010/10/24/shake-that-windows-phone-7-and-detect-it/ - public class ShakeClass9:ShakeClass - { - #region Properties - private bool firstcall=true; //helper var as GVector is not Nullable - - private Queue myDeltaG; - private Queue myGVqueue; - private int _queueSize = 20; - - private double myGmin; - public double _Gmin - { - set { myGmin = value; } - } - private double myTmin; - public double _Tmin - { - set { myTmin = value; } - } - - #endregion - #region Methods - /// - /// shake detection compairing difference of last acceleration and current accel. - /// if diffs of acceleration pairs exceeds min treshold and the number of shakes - /// exceeds 1 then the ShakeDetected event will be fired - /// - public ShakeClass9 () - { - base.name="ShakeClass9"; - init(); - } - public ShakeClass9 (string s) - { - base.name=s; - init(); - } - private void init() - { - myDeltaG = new Queue(_queueSize); - myGVqueue = new Queue(_queueSize); - myGmin = 0.9d; - myTmin = 15; //equals 0.75 seconds if samples per seconds is 20 - } - public override void addValues (GVector gv) - { - GVector reading=gv; - myGVqueue.Enqueue(gv); - if (!firstcall)// _lastReading != null) - { - if (myDeltaG.Count == _queueSize) - { - myDeltaG.Dequeue(); - } - if (myGVqueue.Count == _queueSize) - { - myGVqueue.Dequeue(); - } - - //get and store delta - GVector gvOld = myGVqueue.Peek(); - double deltaG = Math.Abs(gv.Length - gvOld.Length); - myDeltaG.Enqueue(deltaG); - //get average - double sum = 0; - foreach (double d in myDeltaG) - { - sum += d; - } - double DeltaAverage = sum / myDeltaG.Count; - //rapid movement detection - if (DeltaAverage > myGmin) - if (myDeltaG.Count > myTmin) - OnShakeDetected(gv); - } - else - { - myDeltaG.Enqueue(0.9d); //enqueu first value - firstcall = false; - } - } - #endregion - } -} - diff --git a/SensorScan5/ShakeClass/ShakeEventArgs.cs b/SensorScan5/ShakeClass/ShakeEventArgs.cs deleted file mode 100644 index 1169b1b..0000000 --- a/SensorScan5/ShakeClass/ShakeEventArgs.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -namespace ShakeDetection -{ - public class ShakeEventArgs : EventArgs - { - /* HACK: fields are typically private, but making this internal so it - * can be accessed from other classes. In practice should use properties. - */ - internal GVector _gvector; - public ShakeEventArgs() - { - } - public ShakeEventArgs(GVector gvector) - : base() - { - this._gvector = gvector; - } - } -} - diff --git a/SensorScan5/_vectors.py b/SensorScan5/_vectors.py deleted file mode 100644 index 7a461af..0000000 --- a/SensorScan5/_vectors.py +++ /dev/null @@ -1,40 +0,0 @@ -from visual import * - -def pause(sec): - for i in range(1,sec): - rate(50) - -v0=vector(0,0,0) -v1=vector(-.8,-.8,-.58) -v2=vector(-.42,-.32,.12) - -f = frame() - -a1 = arrow(frame=f, pos=v0, axis=v1, shaftwidth=0.1, color=(.8,.8,0)) -a2 = arrow(frame=f, pos=v0, axis=v2, shaftwidth=0.1, color=(0,.8,.8)) - -mybox = box(frame=f, pos=(0,0,0), length=.3, height=.1, width=.6) -mybox2 = box(frame=f, pos=(0,.05,0), length=.3, height=.01, width=.6, color=(.8,.8,.8)) -mybox2 = box(frame=f, pos=(0,.05,0.055), length=.2, height=.01, width=.3, color=(1,1,1)) - -# -x = arrow(frame=f, pos=(-1,0,0), axis=(2,0,0), shaftwidth=0.0005, color=(1,0,0)) -y = arrow(frame=f, pos=(0,-1,0), axis=(0,2,0), shaftwidth=0.0005, color=(0,1,0)) -z = arrow(frame=f, pos=(0,0,-1), axis=(0,0,2), shaftwidth=0.0005, color=(0,0,1)) - -tx = text (frame=f, pos=(1.1,0,0), text='x', height=.2, depth=.01) -ty = text (frame=f, pos=(0,1.1,0), text='y', height=.2, depth=.01) -tz = text (frame=f, pos=(0,0,1.1), text='z', height=.2, depth=.01) -#t1 = text (frame=f, pos=(0,1,1.1), text='Hallo', height=.2, depth=.01) - -#rotate y plane -#f.rotate(angle=radians(12.5),axis=(0,0,-1), pos=(0,0,1)) -pause(100) -#rotate x plane -f.rotate(angle=radians(22.5),axis=(0,-1,0), pos=(0,1,0)) -pause(100) -#rotate z plane -f.rotate(angle=radians(-22.5),axis=(-1,0,0), pos=(1,0,0)) - -# a1.color = color(1,0,0) - diff --git a/SensorScan5/bgThread.cs b/SensorScan5/bgThread.cs deleted file mode 100644 index faaa20b..0000000 --- a/SensorScan5/bgThread.cs +++ /dev/null @@ -1,197 +0,0 @@ -// a background thread class enabled to do direct calls to GUI thread -// this variant uses locking and a global var to exchange data -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using Microsoft.WindowsCE.Forms; -using System.ComponentModel; -using System.Threading; -using System.Runtime.InteropServices; - - public class bgThread : Component - { - /// - /// the bgThreadEventHandler is the protoype of the eventhandler - /// - /// - /// - public delegate void bgThreadEventHandler(object sender, ShakeDetection.ShakeEventArgs bte); - /// - /// this event function is the 'link' back to the subscriber of the event handler - /// and will be used to fire the event in the other thread - /// - public event bgThreadEventHandler bgThreadEvent; - /// - /// global internal var to exchange data - /// - internal ShakeDetection.ShakeEventArgs _BGeventArgs; - private Container components; - /// - /// we will run a background thread. this is the thread object we use - /// - private Thread myThread; - /// - /// a var to let the thread stop - /// in reality the thread will be mostly aborted by using thread.Abort() - /// - private bool bRunThread; - /// - /// we will store the derived window handle for communication - /// - internal bgThreadWndProc bgWnd; - /// - /// we use a user window message ID, not any of the predefined WM_ constants - /// - internal const int msgID = 1025; - /// - /// object to lock access to class variable - /// - internal object theLock; - - #region Nested Class - /// - /// This is the message window we use to communicate back to the thread - /// where the bgThread object is created - /// so we avoid cross-threading updates problems especially with the GUI thread - /// - internal class bgThreadWndProc : MessageWindow - { - #region Fields - private bgThread _bgThread; - public IntPtr hwndControl; - #endregion - #region Constructors - public bgThreadWndProc(bgThread Parent) - { - System.Diagnostics.Debug.WriteLine("Creating ThreadWnd..."); - this._bgThread = Parent; - hwndControl = Hwnd; - System.Diagnostics.Debug.WriteLine("bgThreadWndProc hWnd is 0x: "+hwndControl.ToInt32().ToString("x")); - } - #endregion - #region Methods - public const int WM_COPYDATA = 0x004A; - protected override void WndProc(ref Message m) - { - int iMsg = m.Msg; - System.Diagnostics.Debug.WriteLine("WndProc called..."); - switch (iMsg) - { - case msgID: - { - System.Diagnostics.Debug.WriteLine("WndProc sending notification ..."); - //this._bgThread.NotifyData(m.WParam); - //this._bgThread.NotifyData((int)m.WParam, _bgThread.sMsg); - this._bgThread.NotifyData(); - break; - } - default: - { - base.WndProc(ref m); - break; - } - } - } - #endregion //Methods - - }//MsgWnd - #endregion - #region theClass - public bgThread() - { - bgWnd = new bgThreadWndProc(this); - myThread = new Thread(myThreadStart); - bRunThread = true; - myThread.Start(); - _BGeventArgs = new ShakeDetection.ShakeEventArgs(); - theLock = new object(); - } - #region TheTHREAD - private void myThreadStart() - { - System.Diagnostics.Debug.WriteLine("Entering thread proc"); - int _i=0; - Intermec.Device.Sensor theSensor = new Intermec.Device.Sensor(Intermec.Device.Sensor.SensorsEnabled.AccelerometerEnabled); - theSensor.SensorDataUpdateInterval = 50; - ShakeDetection.GVector gv = new ShakeDetection.GVector(); - try - { - do - { - //The blocking function... - gv.X = theSensor.Acceleration.GForceX; - gv.Y = theSensor.Acceleration.GForceY; - gv.Z = theSensor.Acceleration.GForceZ; - - System.Diagnostics.Debug.WriteLine("Calling into UI thread..."); - Microsoft.WindowsCE.Forms.Message msg = Message.Create(bgWnd.Hwnd, msgID, new IntPtr(_i), IntPtr.Zero); - //to avoid reading and writing to var at same time from different threads - lock (theLock) - { - _BGeventArgs._gvector = gv; - //the PostMessage is catched in WndProc and the arguments are stored - //retrived using the _BGeventArgs variable - MessageWindow.PostMessage(ref msg); //hopefully there is no other posted msg - } - System.Diagnostics.Debug.WriteLine("Thread sleeps..."); - _i++; - Thread.Sleep(50); - } while (bRunThread); - } - catch (ThreadAbortException) - { - System.Diagnostics.Debug.WriteLine("Thread will abort"); - bRunThread = false; - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in ThreadStart: " + ex.Message); - } - System.Diagnostics.Debug.WriteLine("ThreadProc ended"); - } - #endregion - protected override void Dispose (bool disposing) - { - if (disposing) - { - if (this.components != null) - { - this.components.Dispose (); - } - } - this.myThread.Abort(); - base.Dispose (disposing); - } - ~bgThread() - { - myThread.Abort(); - this.Dispose (false); - } - #region theNotifyHandlers - private void NotifyData() - { - ShakeDetection.ShakeEventArgs _m_bgThreadEventArgs; - lock (theLock) - { - _m_bgThreadEventArgs = _BGeventArgs; - } - //is there any subscriber - if (this.bgThreadEvent == null) - { - return; - } - try - { - //_bgThreadEventArgs = new BgThreadEventArgs(i1, s); - this.bgThreadEvent(this, _m_bgThreadEventArgs); - } - catch (MissingMethodException) - { - } - } - - #endregion - //============================================================================== - } - #endregion diff --git a/SensorScan5/bin/Intermec.DataCollection.CF2.dll b/SensorScan5/bin/Intermec.DataCollection.CF2.dll deleted file mode 100644 index 9e77db2..0000000 Binary files a/SensorScan5/bin/Intermec.DataCollection.CF2.dll and /dev/null differ diff --git a/SensorScan5/bin/Intermec.Device.Sensor.CF2.dll b/SensorScan5/bin/Intermec.Device.Sensor.CF2.dll deleted file mode 100644 index e6bf14b..0000000 Binary files a/SensorScan5/bin/Intermec.Device.Sensor.CF2.dll and /dev/null differ diff --git a/SensorScan5/bin/SensorScan5.exe b/SensorScan5/bin/SensorScan5.exe deleted file mode 100644 index 4ba8e86..0000000 Binary files a/SensorScan5/bin/SensorScan5.exe and /dev/null differ diff --git a/SensorScan5/bin/perfChartClass.dll b/SensorScan5/bin/perfChartClass.dll deleted file mode 100644 index b89d92c..0000000 Binary files a/SensorScan5/bin/perfChartClass.dll and /dev/null differ diff --git a/SensorScan5/doc/SensorScan5_01.gif b/SensorScan5/doc/SensorScan5_01.gif deleted file mode 100644 index 468af0d..0000000 Binary files a/SensorScan5/doc/SensorScan5_01.gif and /dev/null differ diff --git a/SensorScan5/doc/SensorScan5_02.gif b/SensorScan5/doc/SensorScan5_02.gif deleted file mode 100644 index ac95393..0000000 Binary files a/SensorScan5/doc/SensorScan5_02.gif and /dev/null differ diff --git a/SensorScan5/doc/SensorScan5_03.gif b/SensorScan5/doc/SensorScan5_03.gif deleted file mode 100644 index 1ac6f8f..0000000 Binary files a/SensorScan5/doc/SensorScan5_03.gif and /dev/null differ diff --git a/SensorScan5/doc/SensorScan5_04.gif b/SensorScan5/doc/SensorScan5_04.gif deleted file mode 100644 index c5d116f..0000000 Binary files a/SensorScan5/doc/SensorScan5_04.gif and /dev/null differ diff --git a/SensorScan5/doc/basicXYZ.ods b/SensorScan5/doc/basicXYZ.ods deleted file mode 100644 index cd2c383..0000000 Binary files a/SensorScan5/doc/basicXYZ.ods and /dev/null differ diff --git a/SensorScan5/doc/basicXYZ0.ods b/SensorScan5/doc/basicXYZ0.ods deleted file mode 100644 index 0d1bda5..0000000 Binary files a/SensorScan5/doc/basicXYZ0.ods and /dev/null differ diff --git a/SensorScan5/doc/basicxyz.log.txt b/SensorScan5/doc/basicxyz.log.txt deleted file mode 100644 index 42d5636..0000000 --- a/SensorScan5/doc/basicxyz.log.txt +++ /dev/null @@ -1,991 +0,0 @@ -Movement1 Class -x y z tick deltaG -Movement1 Class -x y z tick deltaG -0.0546875 -0.08984375 1.00390625 63428375900304 0.00719091883716616 -0.0546875 -0.0859375 0.9921875 63428375900743 0.00480744948150402 -0.046875 -0.08984375 1 63428375901246 0.00291138562086535 -0.046875 -0.09765625 1.01171875 63428375901749 0.0152911895074943 -0.05078125 -0.09375 1.00390625 63428375902251 0.00734207429122802 -0.05078125 -0.0859375 0.98828125 63428375902751 0.00890055421072922 -0.05078125 -0.08203125 0.9921875 63428375903253 0.00534304165778554 -0.046875 -0.0859375 1 63428375903759 0.00256975416543281 -0.046875 -0.0859375 1 63428375904267 0.00256975416543281 -0.05078125 -0.0859375 0.9921875 63428375904770 0.00501400095564808 -0.04296875 -0.0859375 0.99609375 63428375905272 0.00149317607368293 -0.04296875 -0.08984375 1 63428375905776 0.00273678849811154 -0.0390625 -0.08984375 1 63428375906279 0.00257734723749503 -0.03515625 -0.08984375 1.00390625 63428375906782 0.00632133533374035 -0.03125 -0.0859375 1 63428375907283 0.00196212237525351 -0.03125 -0.08203125 1.01953125 63428375907784 0.0210932248595794 -0.1171875 -0.2890625 1.01953125 63428375908283 0.0639672055089979 -0.171875 -0.51171875 0.859375 63428375908785 0.0126408848819712 -0.25390625 -0.61328125 0.76171875 63428375909288 0.00813526941383258 -0.3515625 -0.66796875 0.70703125 63428375909790 0.0320392257019713 -0.41015625 -0.68359375 0.66796875 63428375910310 0.0306522742647402 -0.44140625 -0.87109375 0.83203125 63428375910795 0.285531426323415 -0.37890625 -0.6875 0.92578125 63428375911298 0.208673044929651 -0.34765625 -0.6875 0.84375 63428375911799 0.125055151715086 -0.3359375 -0.69140625 0.7890625 63428375912302 0.0920449728579091 -0.28515625 -0.8203125 0.73828125 63428375912803 0.14655269557633 --0.1484375 -1.078125 1.7265625 63428375913306 1.04406541142899 -0.01953125 -0.93359375 1.0859375 63428375913842 0.427434886964203 -0.16796875 -0.80078125 0.90625 63428375914314 0.216184198269091 -0.31640625 -0.734375 0.77734375 63428375914815 0.118009218853931 -0.41796875 -0.7109375 0.6875 63428375915321 0.0729619354834674 -0.4765625 -0.66796875 0.61328125 63428375915834 0.0194592787467074 -0.49609375 -0.67578125 0.62890625 63428375916317 0.0432165676763052 -0.48046875 -0.6640625 0.65234375 63428375916819 0.039028409795312 -0.46484375 -0.65234375 0.66796875 63428375917322 0.0388111754895131 -0.42578125 -0.66796875 0.68359375 63428375917824 0.0230103834290534 -0.40234375 -0.67578125 0.703125 63428375918325 0.0112149392445211 -0.37890625 -0.66796875 0.70703125 63428375918828 0.0290098405829475 -0.37109375 -0.6875 0.71484375 63428375919330 0.0486014875808098 -0.27734375 -0.765625 0.5234375 63428375919832 0.06621624404035 -0.05859375 -0.83984375 0.61328125 63428375920335 0.00152468317805132 -0.17578125 -0.94921875 0.625 63428375920837 0.132916544721576 -0.19140625 -0.921875 0.359375 63428375921339 0.206004723744662 -1.88671875 0.1953125 0.109375 63428375921846 0.757395550957181 -1.44140625 -0.1875 0.359375 63428375922346 0.395720010810776 --0.8046875 0.41015625 -0.234375 63428375922849 0.206758926642859 -1.578125 0.14453125 0.78515625 63428375923351 0.272362935433121 -1.00390625 -0.33984375 0.65625 63428375923851 0.185625137400524 -0.55078125 -0.609375 0.578125 63428375924350 0.216510754667334 -0.2578125 -0.75 0.55859375 63428375924851 0.14515671227941 -0.078125 -0.8359375 0.56640625 63428375925391 0.0609048986166358 -0.0546875 -0.88671875 0.53515625 63428375925892 0.0127308117171618 -0.27734375 -0.671875 0.66015625 63428375926394 0.0660967480634547 --0.9609375 -0.296875 -0.31640625 63428375926901 0.0067876294456819 --1.99609375 -0.03515625 -0.92578125 63428375927399 1.15762952174963 --2.703125 0.07421875 -1.2265625 63428375927904 1.92300420340335 --2.9765625 0.16015625 -1.03515625 63428375928403 0.186173003392499 --1.31640625 -0.3359375 -0.234375 63428375928908 1.59065511437745 --0.515625 -0.609375 0.14453125 63428375929434 2.15808653755456 --0.12890625 -0.73046875 0.2890625 63428375929912 2.17322836064221 --0.078125 -0.8125 0.4453125 63428375930414 2.03949910062422 --0.109375 -0.84765625 0.51171875 63428375930917 1.97315521243598 --0.12890625 -0.859375 0.546875 63428375931453 1.94256842222174 --0.09375 -0.859375 0.58203125 63428375931927 1.92716875430678 --0.07421875 -0.86328125 0.59765625 63428375932426 1.91672303704811 --0.05859375 -0.85546875 0.62109375 63428375932928 1.91053677576988 --0.04296875 -0.84765625 0.62109375 63428375933430 1.91759317802445 --0.04296875 -0.84375 0.6171875 63428375933932 1.92304795445495 -0.0234375 -0.83203125 0.62890625 63428375934435 1.92607852121258 -0.1328125 -0.7265625 0.61328125 63428375934938 2.00929387429779 -0.1875 -0.42578125 0.828125 63428375935439 2.01945635739841 -0.1875 -0.23828125 0.8359375 63428375935941 2.08009030320496 --0.0078125 -0.15625 0.91015625 63428375936444 2.0458139701847 -0.09375 -0.2109375 0.96484375 63428375936947 1.97724574260703 -0.046875 -0.1484375 0.96875 63428375937459 1.98814129431079 -0.02734375 -0.1171875 0.984375 63428375937964 1.97761494871125 -0.01171875 -0.109375 0.9921875 63428375938466 2.1572242721197 -0 -0.1015625 1 63428375938967 0.373518540391831 --0.00390625 -0.09765625 1 63428375939469 0.193533293711739 -0 -0.08984375 1.00390625 63428375939970 0.211828944722792 --0.00390625 -0.0859375 1.00390625 63428375940469 0.0777665735968897 --0.00390625 -0.0859375 1.00390625 63428375940970 0.0114226854086442 -0.00390625 -0.08984375 1.00390625 63428375941473 0.0188234242701437 -0 -0.09375 1.00390625 63428375941975 0.0338749599472989 -0 -0.09375 1 63428375942503 0.0482099393270419 --0.00390625 -0.08984375 1.00390625 63428375942987 0.00354112988327637 --0.00390625 -0.08984375 1.0078125 63428375943491 0.00743186105275173 -0 -0.08984375 1.00390625 63428375943990 0.00353356045573827 -0 -0.08984375 1 63428375944494 0.000357079531577931 -0 -0.08203125 0.99609375 63428375945007 0.00491911780143117 --0.00390625 -0.0859375 1 63428375945499 0.000691481884924627 --0.00390625 -0.0859375 1 63428375946003 0.000691481884924627 -0 -0.09375 1.01171875 63428375946506 0.0116681773740139 -0.00390625 -0.08984375 1.00390625 63428375947009 0.00354112988327637 -0 -0.09375 1 63428375947510 0 -0 -0.09375 1.00390625 63428375948011 0.00388926212107421 -0 -0.09375 1 63428375948512 0 -0 -0.09375 0.99609375 63428375949010 0.00388912975747324 --0.00390625 -0.09375 1.00390625 63428375949513 0.00389682887826948 -0 -0.09375 1.00390625 63428375950015 0.00388926212107421 -0 -0.08984375 1.01171875 63428375950523 0.0113151999151375 -0 -0.0859375 1 63428375951019 0.000699083233255404 --0.00390625 -0.08984375 1 63428375951522 0.000349480772487532 --0.00390625 -0.0859375 1 63428375952024 0.000691481884924627 -0 -0.0859375 1.0078125 63428375952526 0.00708494812328819 -0 -0.0859375 1.0078125 63428375953029 0.00354381824001182 --0.00390625 -0.08984375 1 63428375953531 0.00778134182523926 -0 -0.08984375 1 63428375954033 0.0038906399873162 -0 -0.0859375 1 63428375954537 0.000342003701677474 --0.00390625 -0.08984375 1.0078125 63428375955053 0.0123509788541829 --0.00390625 -0.08984375 1.00390625 63428375955555 0.004232611768201 --0.00390625 -0.09375 1 63428375956056 0.000699077942519999 -0 -0.09375 1.00390625 63428375956572 0.00777891525293972 --0.00390625 -0.09375 1.0078125 63428375957074 0.00424506287763515 -0 -0.09765625 1.0078125 63428375957571 0.00814793545925419 -0.00390625 -0.08984375 1.0078125 63428375958075 0.00354259893167752 -0 -0.09375 1.00390625 63428375958588 0.00388926212107421 -0 -0.09765625 0.99609375 63428375959090 0.000373585330004644 -0.00390625 -0.09375 1 63428375959593 0.0038892328206741 -0 -0.09375 1.00390625 63428375960095 0 --0.00390625 -0.0859375 1.0078125 63428375960597 0.00422270894124832 --0.00390625 -0.0859375 1.0078125 63428375961100 0.0077915742071446 -0 -0.08984375 1.0078125 63428375961601 0.00777380150457918 -0 -0.08984375 1.0078125 63428375962102 0.00811580261701628 -0.00390625 -0.0859375 1.00390625 63428375962605 0.00388449877546515 -0 -0.08984375 1.0078125 63428375963110 0.000339372608803457 -0 -0.08203125 1.01171875 63428375963612 0.0110034566552106 -0.00390625 -0.0859375 1.00390625 63428375964115 0.00355752887940097 -0 -0.08984375 1.0078125 63428375964617 0.00812340396534705 -0.0078125 -0.08984375 1.0078125 63428375965121 2.26206248328253E-05 -0.00390625 -0.08984375 1.01171875 63428375965622 0.00778158146775576 -0 -0.08984375 1.0078125 63428375966120 0.00741672467449628 -0 -0.08984375 1.0078125 63428375966621 0.00353505861101744 -0 -0.08984375 1.0078125 63428375967124 0.000361872028819876 -0.00390625 -0.0859375 1.0078125 63428375967627 0.00105544448536499 -0 -0.09765625 1.0078125 63428375968129 0.000716074406502454 -0 -0.08984375 1 63428375968631 0.00424634165265214 -0.00390625 -0.08984375 1 63428375969133 0.00316606365498107 -0 -0.09375 1.0078125 63428375969635 0.007771059022323 -0 -0.09375 1.015625 63428375970137 0.0116685654026378 -0 -0.09375 1.01171875 63428376057347 0.00457568640012473 -0 -0.08203125 1.01171875 63428376096284 0.0035614849088339 -0 -0.0859375 1.0078125 63428376120514 0.000339372608803457 -0 -0.08984375 1.015625 63428376125635 0.00778187591149826 -0 -0.0859375 1.0078125 63428376125815 0.00388449877546515 --0.00390625 -0.08984375 1.01171875 63428376126034 0.00389839061894048 -0 -0.08984375 1.00390625 63428376126248 0.00712041542698483 -0 -0.0859375 1 63428376126526 0.00389953258107845 -0 -0.08984375 1 63428376126657 0.00778140026366958 -0.00390625 -0.0859375 1.00390625 63428376126915 0.00425403232976151 -0.00390625 -0.08984375 1.0078125 63428376127047 0.0038908502982804 -0 -0.0859375 1 63428376127176 0.00812340396534705 -0 -0.08203125 1.00390625 63428376127308 0.00455709265626258 -0 -0.09375 0.98828125 63428376127421 0.0190913066910988 -0 -0.09375 0.9921875 63428376127551 0.0148706165756398 --0.0078125 -0.09375 1 63428376127762 0.00811755157355143 --0.00390625 -0.09375 1.01171875 63428376127890 0.0120327657320285 -0 -0.08984375 1 63428376128019 7.5987590903992E-06 -0 -0.08984375 1.0078125 63428376128153 0.000354334347826724 -0 -0.09765625 1.0078125 63428376128274 0.00740989206445786 -0 -0.09765625 1.00390625 63428376128455 0.00740821090611643 -0 -0.1015625 1.00390625 63428376128574 0.00600831892186893 -0 -0.1015625 1.01171875 63428376128691 0.00533383741349414 -0.00390625 -0.09375 1.01171875 63428376128904 0.00353051044313935 -0 -0.09765625 1.0078125 63428376129036 0.00106298733596599 -0 -0.08984375 1 63428376129168 0.0116797908826101 -0 -0.09375 1 63428376129380 0.00353356045573827 --0.0078125 -0.08984375 1.00390625 63428376129511 0.00426292105807979 --0.00390625 -0.08984375 1.00390625 63428376129640 0.0038982094148543 -0 -0.0859375 0.99609375 63428376129775 0.0077913817204931 -0 -0.08984375 0.9921875 63428376129903 0.0155698540547222 -0.00390625 -0.08984375 0.9921875 63428376130114 0.00743125166205472 -0 -0.09375 0.99609375 63428376130247 0.00675635783330231 --0.00390625 -0.09375 0.99609375 63428376130386 0.00778548178631888 -0 -0.09375 0.99609375 63428376130809 0.00388899584427738 -0.00390625 -0.09375 0.9921875 63428376130938 0.0078008541460578 -0 -0.09375 1.00390625 63428376131067 0.00778642407937635 -0 -0.08984375 1 63428376131202 0 --0.00390625 -0.08984375 1.0078125 63428376131340 7.54032066008214E-06 -0 -0.08984375 1.0078125 63428376131543 0.000723614727162536 -0 -0.0859375 0.99609375 63428376131662 0.00885089884056756 -0 -0.08984375 1 63428376131783 0.0050027364924321 --0.00390625 -0.08984375 1 63428376131982 0.0127682663092699 -0 -0.08984375 0.99609375 63428376132122 0.0159232840264965 --0.00390625 -0.08984375 0.9921875 63428376132309 0.0162782703545643 -0 -0.09375 1 63428376132424 0.000357079531577931 -0 -0.09765625 1.0078125 63428376132554 0.00814793545925419 -0.00390625 -0.09375 1.00390625 63428376132682 0.000332991053445086 -0.00390625 -0.09375 1 63428376132821 0.003533533825681 -0 -0.08984375 1.01171875 63428376132953 0.0159061322878076 -0 -0.09765625 1.0078125 63428376133166 0.0162859284612247 -0.00390625 -0.0859375 1.0078125 63428376133296 0.0152228258691993 -0 -0.0859375 1.015625 63428376133431 0.0187585448618308 -0 -0.09375 1.015625 63428376133562 0.0194393316964003 -0.00390625 -0.09765625 1 63428376133784 0.00426886228981171 -0 -0.08984375 1.00390625 63428376133923 0.0113040307160933 -0.00390625 -0.08984375 1.00390625 63428376134145 0.000348132237797838 -0 -0.09375 1.0078125 63428376134281 0.0081357346114963 -0 -0.09765625 1.0078125 63428376134423 0.000716074406502454 --0.00390625 -0.08984375 1.00390625 63428376134800 0.00388319084881528 -0 -0.0859375 1 63428376135166 0.00389184913941465 -0 -0.0859375 1.00390625 63428376135448 0.00354995689250037 -0 -0.08984375 1 63428376135877 7.5987590903992E-06 -0 -0.0859375 1.00390625 63428376136009 0.00744047518696833 -0 -0.08984375 1 63428376136121 0.00777325536373219 -0 -0.08984375 1.0078125 63428376136366 0.00742432073209165 --0.00390625 -0.0859375 1.01171875 63428376136567 0.00283670626456534 -0 -0.08984375 1.00390625 63428376136681 0.000363268422531204 -0.00390625 -0.0859375 0.99609375 63428376136803 0.00459089749276309 -0 -0.0859375 1.0078125 63428376136939 0.00423025179184933 -0 -0.08984375 1.00390625 63428376137156 0.00461437500351591 -0 -0.08984375 1 63428376137359 0.00744957050546713 -0 -0.09375 1 63428376137494 0.0148694151043576 --0.00390625 -0.09375 1.0078125 63428376137749 0.00777163476280052 -0 -0.09375 1.01953125 63428376137921 0.019067871539463 -0 -0.09375 1.01171875 63428376138204 0.00813461691827566 -0 -0.08984375 1.01171875 63428376138488 0.00777407003186115 -0 -0.08984375 1.00390625 63428376138699 0.0042450946241801 -0 -0.0859375 0.99609375 63428376138832 0.0127388678319242 -0 -0.0859375 1 63428376138956 0.00424021311653178 -0 -0.09375 0.99609375 63428376139229 0.00319004652421784 -0.00390625 -0.09375 1 63428376139435 0.00318528130332707 -0 -0.08984375 1 63428376139704 0 -0.0078125 -0.08984375 0.99609375 63428376140073 0.00740996226438728 -0.01171875 -0.0859375 1 63428376140282 0.000273593639017689 -0.0078125 -0.0859375 1 63428376140681 0.00809299891742299 -0.0078125 -0.08984375 1.00390625 63428376140809 0.00742080389899513 -0.00390625 -0.08984375 1.00390625 63428376140946 7.56942753810108E-06 -0 -0.08984375 1.0078125 63428376141077 0.0120076221672594 -0.00390625 -0.08984375 1 63428376141293 0.00743442889577572 -0 -0.0859375 1 63428376141517 0.00423264368899368 --0.00390625 -0.08984375 1.01171875 63428376141913 0.0116797908826101 -0 -0.08984375 1 63428376142193 0.000357079531577931 -0.00390625 -0.08984375 0.9921875 63428376142325 0.0159165276562216 -0 -0.08984375 1.00390625 63428376142438 0.0159140436160632 -0 -0.08984375 1 63428376142550 0.0120252569055919 -0 -0.08984375 1 63428376142726 0.0116722794467155 -0.00390625 -0.09375 1.00390625 63428376142840 0.000363268422531204 -0 -0.08984375 1.0078125 63428376142973 0.0120152531047617 -0 -0.08203125 1.00390625 63428376143151 0.00356631130908447 --0.00390625 -0.08203125 1.00390625 63428376143264 0.0067639322682429 --0.00390625 -0.08203125 1.00390625 63428376143377 0.00286720645317429 -0 -0.0859375 1.00390625 63428376143642 0.00354995689250037 -0 -0.0859375 1.01171875 63428376143853 0.015194212690421 -0 -0.09375 0.99609375 63428376143990 0.00325845658687762 -0.00390625 -0.09375 0.99609375 63428376144202 0.00321282598735695 -0 -0.08984375 0.99609375 63428376144339 0.00781143565087028 --0.0078125 -0.08984375 1 63428376144614 0.00386781472353959 --0.00390625 -0.08984375 1.00390625 63428376144879 0.00388319084881528 -0 -0.09375 1 63428376145070 0.000349480772487532 -0 -0.09375 1.00390625 63428376145319 0.00458834535432961 -0 -0.09375 1.0078125 63428376145444 0.00354405627111376 -0.00390625 -0.09375 1.01171875 63428376145574 0.0120327657320285 --0.00390625 -0.08984375 1.0078125 63428376145783 0.0155621959480619 -0 -0.08984375 1.00390625 63428376145920 0 -0.00390625 -0.09375 1.01171875 63428376146192 0.0120327657320285 -0 -0.09765625 1.00390625 63428376146320 0.00461704599947543 -0.00390625 -0.08984375 1.00390625 63428376146534 0.000355698994993103 -0 -0.08984375 1.0234375 63428376146664 0.0155642166623926 -0.00390625 -0.0859375 1.015625 63428376146796 0.0120096722716838 -0 -0.09765625 1.0078125 63428376146935 0.00527313294848453 -0.00390625 -0.09375 1.00390625 63428376147164 0.00102202636749982 -0 -0.08984375 1.01171875 63428376147328 0.00812232255421508 -0 -0.08984375 1.00390625 63428376147556 0.00744356733121787 -0 -0.08984375 1.01171875 63428376147690 0.0152043296726108 -0 -0.0859375 1.01171875 63428376147826 0.0148586319596444 -0 -0.09375 1.0078125 63428376148036 0.0120262529059643 --0.00390625 -0.0859375 1.0078125 63428376148168 0.00741917581415241 -0 -0.09375 1.0078125 63428376148363 0.004237525196642 -0 -0.1015625 1 63428376148493 0.000759321605877439 -0 -0.09765625 1.015625 63428376148621 0.0120350302709897 -0 -0.09375 1.01171875 63428376148747 0.00388952229409556 -0.00390625 -0.09375 1 63428376148874 0.0116680901428552 -0.00390625 -0.09765625 1.0078125 63428376149090 0.000723609338451947 -0.00390625 -0.09375 1.00390625 63428376149223 0.000363268422531204 -0.00390625 -0.09375 1 63428376149355 0.0116680901428552 -0.00390625 -0.09765625 1.0078125 63428376149484 0.00389550392330618 -0 -0.09375 1.0078125 63428376149699 0.004237525196642 -0 -0.09375 1.01171875 63428376149832 0.0113203600204703 -0 -0.0859375 1.0078125 63428376150024 0.00779195222422469 -0 -0.08984375 1.015625 63428376150156 0.00705826118433572 -0 -0.08984375 1.0078125 63428376150445 0.00352749185382217 -0.00390625 -0.08984375 1.015625 63428376150672 0.00389847949917232 -0.00390625 -0.09375 1.015625 63428376150886 0.0120317472589864 -0.00390625 -0.09765625 1 63428376151016 0.010935467382799 -0.00390625 -0.08984375 1 63428376151144 0.0113266085594437 -0 -0.0859375 1.0078125 63428376151358 0.00069370695663018 -0 -0.08984375 1.0078125 63428376151487 0.000331829758202451 -0 -0.09375 1.0078125 63428376151614 0 -0.0078125 -0.09765625 1.01171875 63428376151758 0.0113067471317154 -0.0078125 -0.08984375 1.00390625 63428376151871 0.0123604545672396 -0.00390625 -0.09375 1.00390625 63428376152306 0.00777134849574446 -0 -0.08984375 1.01171875 63428376152431 0.0113076038575421 -0.00390625 -0.0859375 1.01171875 63428376152564 0.00282917133261584 -0 -0.0859375 1.0078125 63428376152696 0.00318811924501872 -0.00390625 -0.08984375 1.01171875 63428376152934 0.0113151152934368 -0 -0.0859375 1.00390625 63428376153086 0.00496259303028124 -0 -0.08984375 1.00390625 63428376153232 0.0042450946241801 --0.00390625 -0.0859375 1 63428376153456 0.0123596592589386 -0 -0.0859375 1.01171875 63428376153593 0.00389217966366795 --0.00390625 -0.0859375 1.0078125 63428376153725 0.00811370566970071 -0 -0.09375 1.01171875 63428376153939 0.00424385664192228 --0.00390625 -0.08984375 1 63428376154068 0.0155631601867974 -0 -0.0859375 1.00390625 63428376154198 0.0123724303538022 -0 -0.0859375 1.0078125 63428376154420 0.00670521559094972 -0 -0.08984375 1.01171875 63428376154548 0.0116646806876251 -0.00390625 -0.08203125 1.0078125 63428376154679 0.000316850534391122 -0 -0.0859375 1.01171875 63428376154812 0.00355280705486449 -0 -0.09375 1.0078125 63428376154942 0 -0.00390625 -0.08984375 1 63428376155158 0.0124155495100804 -0.00390625 -0.08984375 1.0078125 63428376155378 0.00386802322792734 -0 -0.0859375 1.00390625 63428376155510 0.000703951517347035 -0.00390625 -0.09375 1 63428376155679 0.0113076038575421 -0 -0.08984375 1 63428376155952 0.0113417212553975 -0.00390625 -0.08984375 1.00390625 63428376156118 0.00354381824001182 -0.00390625 -0.08203125 1.00390625 63428376156288 0.00844790884026247 -0 -0.078125 1.0078125 63428376156432 0.00325827037554394 -0.00390625 -0.0859375 1.00390625 63428376156617 0.000333111107915229 -0 -0.08984375 1 63428376156730 0.000334402353346697 -0 -0.08984375 1.00390625 63428376157127 0.00744356733121787 -0 -0.08203125 1 63428376157238 0.0081184866627344 --0.00390625 -0.08203125 1.00390625 63428376157500 0.00879337486324427 --0.00390625 -0.0859375 1 63428376157626 0.000342001112437096 -0 -0.0859375 1.00390625 63428376157761 0 -0.0078125 -0.0859375 1.00390625 63428376157895 0.00386178315617669 -0.0078125 -0.0859375 1.01171875 63428376158261 0.000308016714348547 -0.00390625 -0.08984375 1.0078125 63428376158527 0.000663763463854661 -0 -0.08984375 1.015625 63428376158673 0.00422906885663377 -0.0078125 -0.08203125 1.00390625 63428376158808 0.00488112960607134 -0.0078125 -0.0859375 1.0078125 63428376158949 0.00746459996069371 -0 -0.08984375 1.0078125 63428376159168 7.54032066008214E-06 --0.00390625 -0.08984375 1.0078125 63428376159302 0.00423898369182929 -0 -0.0859375 1.01171875 63428376159441 0.0109695317293608 -0 -0.09375 1.015625 63428376159736 0.01591490705529 -0 -0.09765625 1.01171875 63428376159867 0.00849491475156894 -0.0078125 -0.09375 1.01171875 63428376160002 0.00882340983605134 -0.0078125 -0.08984375 1.0078125 63428376160134 0.00100333394111818 -0.0078125 -0.08203125 1.01171875 63428376160328 0.00748359151701283 -0.00390625 -0.0859375 1.01171875 63428376160457 0.0113417212553975 -0 -0.08984375 1.01171875 63428376160745 0.00778163945939925 --0.00390625 -0.08984375 1.01171875 63428376160874 0.0123487070398773 -0 -0.08984375 1.01171875 63428376161178 0.00844039740436786 -0 -0.08984375 1.00390625 63428376161456 0.0042250423406629 -0.00390625 -0.0859375 1 63428376161588 0.00388435924584707 -0.00390625 -0.0859375 0.99609375 63428376161800 0.00780646640227922 -0.00390625 -0.0859375 1 63428376161929 0.0116986650857136 -0 -0.08984375 1.00390625 63428376162059 0.00389830059701346 -0 -0.08203125 1.00390625 63428376162282 0.0123389685677608 -0.00390625 -0.08203125 1.00390625 63428376162611 2.27229630773707E-05 -0 -0.08984375 1.00390625 63428376163051 0.0035815587324679 -0 -0.0859375 1.00390625 63428376163184 0.00423144337116921 -0.00390625 -0.09375 1 63428376163317 0.00742426499515636 -0 -0.09375 1.0078125 63428376163444 0.00319847270703777 -0.00390625 -0.08984375 1.0078125 63428376163636 0.00812596647096031 -0.00390625 -0.09375 1.0078125 63428376163768 0.00424985187393379 -0.00390625 -0.08984375 1 63428376164055 0.0120476931193085 -0 -0.0859375 1.01171875 63428376164283 0.00352264610937159 -0 -0.08984375 1.01171875 63428376164409 0.000631159050301644 -0 -0.09375 1.00390625 63428376164539 0.00709537960274531 -0.00390625 -0.09375 1.00390625 63428376164669 0.00741837103686804 -0.0078125 -0.08984375 1 63428376164804 0.0116493961912953 -0.0078125 -0.08984375 1.00390625 63428376165015 0.00775136209031313 -0.00390625 -0.08984375 1 63428376165147 0.0038830412282258 -0.00390625 -0.08984375 1.00390625 63428376165289 0.004232611768201 -0.00390625 -0.0859375 1.00390625 63428376165482 0.00778375078299076 -0.00390625 -0.08984375 1 63428376165683 0.000342001112437096 -0 -0.08984375 1.0078125 63428376165815 0.00389076027635338 --0.00390625 -0.08984375 1.0078125 63428376166102 0.00456463297692267 -0.00390625 -0.08984375 1.015625 63428376166316 0.0123388769035402 -0 -0.0859375 1.015625 63428376166528 0.0113358546486193 -0.00390625 -0.08984375 1.01953125 63428376166805 0.0159118865385519 -0.00390625 -0.08984375 1.01171875 63428376166939 0.0113151152934368 -0.00390625 -0.09375 1.015625 63428376167074 0.00778665263480627 -0 -0.09765625 1.01953125 63428376167442 0.0123808160998311 -0 -0.09765625 1.015625 63428376167740 0.00813809963115242 -0 -0.08984375 1.015625 63428376167867 0.0155556774160774 -0.00390625 -0.08984375 1.01171875 63428376167999 0.000345583564075991 -0.00390625 -0.08984375 1.0078125 63428376168133 0.00388333886238579 -0 -0.0859375 1.0078125 63428376168409 0.00319568600221398 -0.00390625 -0.0859375 1.00390625 63428376168832 0.000696379530446434 -0.00390625 -0.08984375 1.01171875 63428376168974 0.0116493961912953 -Movement1 Class -x y z tick deltaG -0.09375 -0.10546875 1.0078125 63428376192481 0.000779401746160424 -0.09375 -0.1015625 1.00390625 63428376192945 0.00504671155754766 -0.09375 -0.09765625 1.00390625 63428376204709 0.00543074739684402 -0.09375 -0.09765625 1 63428376227681 0.00930182489718279 -0.0859375 -0.09375 0.99609375 63428376227816 0.0142433264139066 -0.08984375 -0.1015625 1 63428376227980 0.00927158361623426 -0.0859375 -0.09765625 1.0078125 63428376228202 0.00224989920019225 -0.08984375 -0.09375 1.0078125 63428376228350 0.00227993150985251 -0.08984375 -0.09765625 1.00390625 63428376228471 0.0057847917344982 -0.07421875 -0.09765625 1.00390625 63428376228586 0.00705132519270379 -0.07421875 -0.1015625 1.0078125 63428376228730 0.0027906166467957 -0.08203125 -0.09765625 1.015625 63428376228908 0.00517836108596592 -0.08203125 -0.09765625 1.01171875 63428376229031 0.00130266697653036 -0.0859375 -0.1015625 1.0078125 63428376229159 0.00186706502505274 -0.09375 -0.1015625 1 63428376229361 0.00891631642435575 -0.08984375 -0.1015625 1.0078125 63428376229560 0.00152938985500262 -0.08203125 -0.1015625 1.0078125 63428376229688 0.00218983724346833 -0.0859375 -0.1015625 1.01171875 63428376229826 0.00200571474774103 -0.08203125 -0.09765625 1.01171875 63428376230020 0.00130266697653036 -0.08203125 -0.09375 1.0078125 63428376230143 0.00294086703403007 -0.0859375 -0.09765625 1.015625 63428376230226 0.00627821236662252 -0.0859375 -0.09765625 1.01953125 63428376230372 0.0144202392657191 -0.0859375 -0.1015625 1.01171875 63428376230661 0.00743646214458504 -0.0859375 -0.10546875 1.00390625 63428376230767 0.00396145197135933 -0.0859375 -0.10546875 0.99609375 63428376231022 0.00116176655806988 -0.0859375 -0.09765625 1 63428376231236 0.000726041045484349 -0.08984375 -0.09765625 1.01171875 63428376231389 0.00421075303113816 -0.08984375 -0.09765625 1.01171875 63428376231524 0.00424078534079841 -0.08984375 -0.1015625 1.0078125 63428376231671 0.00425540187949558 -0.08203125 -0.09765625 1.015625 63428376231853 0.0122296862786697 -0.08203125 -0.09765625 1.015625 63428376232016 0.00796897773276162 -0.0859375 -0.09765625 1.01171875 63428376232135 0.00355402701873775 -0.08984375 -0.09765625 1.0078125 63428376232253 0.00321476383284036 -0.0859375 -0.09375 1 63428376232369 0.00850134465878494 -0.08203125 -0.09765625 1.0078125 63428376232621 0.0063435233655571 -0.08203125 -0.09375 1.015625 63428376232741 0.00634246518022241 -0.0859375 -0.09375 1.015625 63428376232994 0.00732347646485154 -0.0859375 -0.1015625 1.01171875 63428376233187 0 -0.08984375 -0.09375 1 63428376233311 0.0113305546928135 -0.08203125 -0.1015625 1 63428376233432 0.006996234242997 -0.08203125 -0.10546875 1.0078125 63428376233556 0.00729082702606743 -0.08984375 -0.1015625 1.015625 63428376233833 0.00315965650436922 -0.08984375 -0.1015625 1.015625 63428376233962 0.00420815645606121 -0.08984375 -0.1015625 1.01171875 63428376234094 0.00768248170599373 -0.0859375 -0.1015625 1.0078125 63428376234225 0.011214494830784 -0.0859375 -0.1015625 1.01171875 63428376234531 0.0120033394094596 -0.0859375 -0.09765625 1.00390625 63428376234702 0.00808474021946282 -0.09375 -0.1015625 1.00390625 63428376235019 0.00700756538849356 -0.08984375 -0.10546875 1 63428376235390 0.00734158230957904 -0.08203125 -0.1015625 1.015625 63428376235598 0.000380056988331656 -0.08203125 -0.1015625 1.0078125 63428376235806 0.00736819832943425 -0.08203125 -0.109375 1.00390625 63428376235936 0.0068743405833831 -0.0859375 -0.10546875 1.0078125 63428376236067 0.000442726404277227 -0.0859375 -0.1015625 1 63428376236196 0.000756559388821021 -0.08984375 -0.09375 1.00390625 63428376236412 0.00358124057401077 -0.08984375 -0.09375 1 63428376236702 0.014840963041503 -0.08984375 -0.09375 1 63428376236831 0.0151615269376664 -0.0859375 -0.09765625 1.00390625 63428376236965 0.00812960113625794 -0.0859375 -0.09765625 1 63428376237274 3.02630545645499E-05 -0.0859375 -0.109375 1.00390625 63428376237677 0.00501084156355169 -0.08203125 -0.10546875 1.00390625 63428376238030 0.00387223570171225 -0.0859375 -0.09765625 1.01171875 63428376238316 0.00458953713657406 -0.08984375 -0.09765625 1.00390625 63428376238537 0.0119986629383004 -0.08984375 -0.09765625 1.00390625 63428376238677 0.00812690051466847 -0.0859375 -0.1015625 1.01171875 63428376238815 0.00387277977279377 -0.0859375 -0.10546875 1.00390625 63428376239029 0.00734608767356448 -0.09375 -0.09765625 1.00390625 63428376239157 0.000693138991672893 -0.08984375 -0.09375 1.0078125 63428376239289 0.00276678004769515 -0.0859375 -0.09765625 1.0078125 63428376239418 0.00662107296438941 -0.0859375 -0.09765625 1.00390625 63428376239478 0.0116823044628145 -0.0859375 -0.09765625 1 63428376239764 0.00780778741825028 -0.0859375 -0.1015625 1.01171875 63428376239982 0.00725572126389595 -0.0859375 -0.140625 1.09765625 63428376240116 0.0930056499433425 -0.08203125 -0.5546875 0.6328125 63428376240249 0.163317926039935 --0.015625 -0.625 0.00390625 63428376240380 0.387061609914237 -0.16796875 -0.640625 0.74609375 63428376240599 0.0107631567393089 -0.55859375 -0.55078125 0.63671875 63428376240829 0.00195011067430606 -0.44921875 -0.64453125 0.68359375 63428376241105 0.0291029051540432 --0.15234375 -0.64453125 0.44921875 63428376241239 0.208158901060856 --0.6328125 -0.39453125 0.4453125 63428376241543 0.144929203144457 --1 -0.38671875 0.3046875 63428376241674 0.101864765896332 -0.18359375 -0.51953125 0.48046875 63428376241803 0.288973181601161 --1.16015625 0 -0.265625 63428376241932 0.177537769829648 --0.44921875 -0.59375 0.6171875 63428376242142 0.0455514959179896 -0.32421875 -1.0234375 1.3984375 63428376242271 0.742571314204495 --0.515625 -0.14453125 0.1640625 63428376242404 0.453015860816989 --0.03125 -0.89453125 1.8515625 63428376242534 1.04356941241636 --0.4453125 -0.68359375 1.00390625 63428376242756 0.277468567074598 --0.03515625 -0.734375 0.82421875 63428376242902 0.0883081648781321 -0.0078125 -0.64453125 0.8671875 63428376243065 0.0682079199380388 -0.0390625 -0.62890625 0.85546875 63428376243517 0.0540601347131802 -0.00390625 -0.59765625 0.8359375 63428376243652 0.00718964411770506 --0.015625 -0.58984375 0.8515625 63428376243784 0.0739485580679777 --0.02734375 -0.58984375 0.84375 63428376243919 0.184350030244812 --0.0234375 -0.58984375 0.8515625 63428376244053 0.410950638568777 --0.01953125 -0.59375 0.8671875 63428376244269 0.0535266537740893 --0.01171875 -0.58984375 0.859375 63428376244398 0.0320453472976849 --0.0078125 -0.59765625 0.859375 63428376244622 0.00539268394825232 --0.0078125 -0.59375 0.86328125 63428376244992 0.247518973553968 --0.01171875 -0.59375 0.85546875 63428376245366 0.172827155518566 --0.00390625 -0.59375 0.8515625 63428376245795 0.0764940682914914 -0 -0.6015625 0.86328125 63428376246271 0.321129101330762 -0.00390625 -0.59375 0.87109375 63428376246772 0.135966145398309 -0 -0.58984375 0.8671875 63428376247273 0.0816885446761638 --0.00390625 -0.58203125 0.87109375 63428376247776 0.715345655354803 --0.0078125 -0.58203125 0.8671875 63428376267175 0.484363845407179 --0.0078125 -0.58203125 0.86328125 63428376272845 1.01537212422458 --0.00390625 -0.58984375 0.859375 63428376275369 0.251279620005123 -0 -0.59375 0.8671875 63428376275508 0.0535041240309286 -0 -0.59375 0.86328125 63428376275645 0.0327507119086186 -0.01171875 -0.5859375 0.87109375 63428376275871 0.0125978331138565 -0.0625 -0.546875 0.87109375 63428376276089 0.00280998498436147 -0.16015625 -0.4765625 0.84765625 63428376276220 0.0504739613636582 -0.11328125 -0.3203125 0.95703125 63428376276431 0.014293505518733 -0.06640625 -0.21484375 0.98046875 63428376276545 0.0302323825241371 -0.03515625 -0.1640625 0.99609375 63428376276751 0.0410323970422137 -0.0234375 -0.140625 1 63428376276883 0.032279463914731 -0.02734375 -0.1328125 1.0078125 63428376277171 0.0299010925687813 -0.01953125 -0.12109375 0.99609375 63428376277391 0.0441681569293597 -0.01953125 -0.1171875 1.00390625 63428376277521 0.0304832827991572 -0.01953125 -0.1171875 1 63428376277747 0.0310971119565138 -0.01953125 -0.109375 0.99609375 63428376278165 0.0499324015418712 -0.015625 -0.109375 1.00390625 63428376278292 0.0442422440098929 -0.01953125 -0.11328125 1.01171875 63428376278429 0.0305470515296959 -0.015625 -0.11328125 1.0078125 63428376278566 0.0333750449938333 -0.01171875 -0.109375 1.00390625 63428376278704 0.0345159030437348 -0.015625 -0.1171875 1.00390625 63428376278843 0.0303460566174723 -0.01953125 -0.11328125 1.0078125 63428376279118 0.0279849913530565 -0.01953125 -0.11328125 1.0078125 63428376279266 0.0366301174404455 -0.0234375 -0.109375 1.00390625 63428376279398 0.0376376623040353 -0.01953125 -0.11328125 1.00390625 63428376279615 0.0394216408196091 -0.0234375 -0.109375 1 63428376279744 0.0241918169088349 -0.01953125 -0.109375 1.01171875 63428376279876 0.032264265483547 -0.015625 -0.125 1.0078125 63428376280009 0.00010517060306503 -0.01953125 -0.12109375 1.01171875 63428376280231 0.0132013339226087 -0.01953125 -0.11328125 1.0078125 63428376280367 0.00422081193028223 -0.015625 -0.11328125 1.00390625 63428376280498 0.000286974152021724 -0.015625 -0.109375 1.0078125 63428376280709 0.00304312532667961 -0.01953125 -0.12109375 1.015625 63428376280848 0.0193876179060797 -0.0234375 -0.11328125 1.0078125 63428376281064 0.00351834728049405 -0.0234375 -0.109375 1.015625 63428376281282 0.0147338259983547 -0.0234375 -0.109375 1.01171875 63428376281414 0.0156126254846631 -0.01953125 -0.11328125 1.01171875 63428376281549 0.00826061680703183 -0.015625 -0.11328125 1.0078125 63428376281715 0.00394887689038037 -0.01171875 -0.12109375 1.01953125 63428376281861 0.0124848755615432 -0.015625 -0.1171875 1.01953125 63428376282139 0.0164481689469254 -0.01953125 -0.109375 1.00390625 63428376282304 0.000807910901847286 -0.01953125 -0.1171875 0.99609375 63428376282435 0.0111935560951038 -0.0234375 -0.12109375 1 63428376282563 0.00676935798462663 -0.02734375 -0.12109375 1.0078125 63428376282695 0.0053108807412261 -0.0234375 -0.12109375 1.00390625 63428376282825 0.000988614996355608 -0.01953125 -0.1171875 1.00390625 63428376283046 0.00467488292050389 -0.0234375 -0.11328125 1.0078125 63428376283468 0.00337126840125013 -0.01953125 -0.10546875 1.015625 63428376283594 0.0056183083198873 -0.0234375 -0.10546875 1.0078125 63428376283811 0.00553987664428957 -0.0234375 -0.10546875 1.0078125 63428376283943 0.000759954430652909 -0.01953125 -0.10546875 1.015625 63428376284174 0.0108751468210813 -0.01953125 -0.10546875 1.01171875 63428376284324 0.00353817951035706 -0.0234375 -0.109375 1.015625 63428376284484 0.00123874926874867 -0.01953125 -0.11328125 1.015625 63428376284647 0.00767982063740935 -0.01953125 -0.11328125 1.0078125 63428376284773 0.00741913533279837 -0.015625 -0.12109375 1.01171875 63428376284989 0.00117609060539858 -0.01171875 -0.12109375 1 63428376285268 0.0108550044323448 -0.015625 -0.125 1.0078125 63428376285398 0.00137559039059276 -0.015625 -0.1171875 1.01171875 63428376285619 0.00816142691571509 -0.015625 -0.12890625 1.0078125 63428376285743 0.0102198090774097 -0.015625 -0.12890625 1.015625 63428376285870 0.013856432316627 -0.01953125 -0.12109375 1.015625 63428376286000 0.0198514406966508 -0.0234375 -0.12109375 1.015625 63428376286133 0.015509275393522 -0.0234375 -0.12109375 1.015625 63428376286340 0.00765740153736694 -0.02734375 -0.12109375 1.015625 63428376286458 0.0117292298850267 -0.02734375 -0.1171875 1.01953125 63428376286650 0.0156967414916653 -0.02734375 -0.12109375 1.01171875 63428376286765 0.00487684237117159 -0.0234375 -0.1171875 1.01171875 63428376286968 0.00252065992445094 -0.02734375 -0.1171875 1.00390625 63428376287225 0.00249454706643193 -0.0234375 -0.1171875 1.0078125 63428376287357 0.00128632164573061 -0.0234375 -0.11328125 1.01171875 63428376287487 0.00296260421228056 -0.01953125 -0.11328125 1.01171875 63428376287620 0.000839541165305269 -0.01953125 -0.10546875 1.00390625 63428376287751 0.0121461191327419 -0.0234375 -0.10546875 1 63428376287879 0.0162901532010395 -0.01953125 -0.11328125 1.01171875 63428376288253 0.00388118128741444 -0.0234375 -0.11328125 1.0078125 63428376288690 0.00462981120304939 -0.0234375 -0.1171875 1.0078125 63428376289192 0.00750019036000804 -0.0234375 -0.11328125 1.00390625 63428376289694 0.0051058322070463 -0.02734375 -0.1171875 1 63428376290197 0.0113886333417008 -0.02734375 -0.1171875 1.0078125 63428376290698 0.00117195321230934 -0.0234375 -0.12109375 1.01171875 63428376291201 0.00468271424023103 -0.0234375 -0.12109375 1.01953125 63428376291706 0.00395989984306788 -0.0234375 -0.11328125 1.01171875 63428376292209 0.00477631851366178 -0.0234375 -0.12109375 1.01171875 63428376292710 0.00387765026345011 -0.02734375 -0.12109375 1.01171875 63428376293212 0.00387728148623601 -0.01953125 -0.11328125 1.0234375 63428376293713 0.00326473535291938 -0.015625 -0.109375 1.015625 63428376294211 0.00231021174095769 -0.01953125 -0.11328125 1.01171875 63428376294714 0.000524361895648751 -0.01953125 -0.109375 1.015625 63428376295216 0.0105914979746375 -0.0234375 -0.11328125 1.01953125 63428376295718 0.0111995415367865 -0.02734375 -0.12109375 1.01953125 63428376296220 0.00875075892019184 -0.02734375 -0.12109375 1.015625 63428376296722 0.0049556755053981 -0.0234375 -0.1171875 1.01171875 63428376297224 0.00913252698300671 -0.0234375 -0.11328125 1.0078125 63428376297727 0.0086103325636302 -0.02734375 -0.11328125 1.01171875 63428376298229 0.000179811636054961 -0.01953125 -0.11328125 1.00390625 63428376298731 0.00396372102397469 -0.01953125 -0.1171875 1.00390625 63428376299234 0.00396198156016681 -0.01953125 -0.11328125 1 63428376299748 0.00396384332418487 -0.0234375 -0.109375 1.00390625 63428376300251 0.00290451542914094 -0.02734375 -0.109375 1.01171875 63428376300754 0.00300979735660367 -0.0234375 -0.12109375 1.0078125 63428376301257 0.003877431007558 -0.01953125 -0.1171875 1.01171875 63428376301757 0.00829462311296258 -0.0234375 -0.1171875 1.015625 63428376302255 0.00432132637382887 -0.03125 -0.11328125 1.015625 63428376302758 0.00319135501265921 -0.02734375 -0.109375 1.01171875 63428376303271 0.00132568687870038 -0.0234375 -0.11328125 1.0078125 63428376303783 0.0154431295640907 -0.0234375 -0.11328125 1.0078125 63428376304273 0.00718705411212928 -0.01953125 -0.109375 1.015625 63428376304778 0.00345581519013827 -0.015625 -0.1015625 1.0078125 63428376305279 0.00864657983764849 -0.015625 -0.11328125 1.01171875 63428376305780 0.00791216501493919 -0.015625 -0.109375 1.0078125 63428376306286 0.0132108972036733 -0.015625 -0.10546875 1.01171875 63428376306788 0.0058627098738151 -0.01953125 -0.11328125 1.01171875 63428376307290 0.000524361895648751 -0.01953125 -0.11328125 1.00390625 63428376307808 0.00396372102397469 -0.0234375 -0.10546875 1.00390625 63428376308318 0.00870485646895625 -0.0234375 -0.11328125 1.0078125 63428376308823 0.00396372102397469 -0.02734375 -0.1171875 1.015625 63428376309323 0.0118175221245043 -0.0234375 -0.11328125 1.01953125 63428376309828 0.0194876894954685 -0.01953125 -0.12109375 1.01171875 63428376310326 0.00900828708333434 -0.015625 -0.12109375 1.01171875 63428376310830 0.00107865571057819 -0.01953125 -0.1171875 1.01171875 63428376311330 0.00333832519376509 -0.01953125 -0.11328125 1.01171875 63428376311836 0.0004419800442379 -0.01953125 -0.10546875 1.015625 63428376312336 0.00135872216154831 -0.02734375 -0.11328125 1.01171875 63428376312841 0.00399262923463506 -0.015625 -0.11328125 1.01171875 63428376313342 0.000179855309048849 -0.015625 -0.109375 1.01171875 63428376313844 0.00330380254476137 -0.0234375 -0.109375 1.0078125 63428376314347 0.000428780165681042 -0.02734375 -0.11328125 1.0078125 63428376314849 0.00715649695310749 -0.01953125 -0.12109375 1.015625 63428376315352 0.00996746796164283 -0.015625 -0.12109375 1.015625 63428376315871 0.00477701822006749 -0.01953125 -0.12109375 1.01171875 63428376316372 0.00527646160188455 -0.015625 -0.1171875 1.0078125 63428376316874 0.00259814247532919 -0.0234375 -0.125 1.0078125 63428376317377 0.00242306166978179 -0.02734375 -0.12890625 1.0078125 63428376317945 0.00592477238820921 -0.0234375 -0.125 1.01171875 63428376318434 0.00997761446803191 -0.0234375 -0.125 1.00390625 63428376318926 0.00250000916063908 -0.0234375 -0.12109375 1 63428376319427 0.0151512657640418 -0.0234375 -0.125 1.01171875 63428376319929 0.00639215782931912 -0.02734375 -0.11328125 1.0078125 63428376320453 0.00459942268919145 -0.0234375 -0.109375 1.01171875 63428376320955 0.00117609060539858 -0.015625 -0.125 1.00390625 63428376321461 0.00689123778969503 -0.01953125 -0.12109375 1 63428376321943 0.0107338348839048 -0.0234375 -0.1171875 1 63428376322445 0.0141575599474668 -0.01953125 -0.125 1.0078125 63428376322947 0.00268549421284114 -0.0234375 -0.12109375 1.0078125 63428376323450 0.00282890759903776 -0.02734375 -0.12109375 1.0078125 63428376323957 0.00230401960863791 -0.0234375 -0.125 1.01171875 63428376324462 0.00567979815282116 -0.02734375 -0.12109375 1.0078125 63428376324963 0.000902016347083201 -0.02734375 -0.12109375 1.01171875 63428376325468 0.0036983092949705 -0.02734375 -0.11328125 1.0078125 63428376325969 0.00841026243254728 -0.0234375 -0.1171875 1.0078125 63428376326468 0.00425355499855895 -0.02734375 -0.12109375 1.015625 63428376326971 0.00846085234914429 -0.0234375 -0.125 1.015625 63428376327480 0.00775149539718489 -0.0234375 -0.12109375 1.01171875 63428376327980 0.00281848284580577 -Movement1 Class -x y z tick deltaG -0.03515625 -0.8359375 0.6328125 63428376452693 0.000770629350894447 -0.05078125 -0.83984375 0.625 63428376453161 0.00169467666055478 -0.05078125 -0.84375 0.6171875 63428376453663 0.0031879703776776 -0.0390625 -0.84765625 0.60546875 63428376454166 0.00738789199242573 -0.03515625 -0.84765625 0.61328125 63428376454667 0.00296930653444516 -0.0390625 -0.84375 0.62109375 63428376455170 0.00138171905575057 -0.04296875 -0.84765625 0.61328125 63428376455671 0.0026778257729827 -0.03515625 -0.85546875 0.609375 63428376456175 0.00109680744175211 -0.04296875 -0.85546875 0.60546875 63428376456676 0.000872452912177746 -0.03515625 -0.85546875 0.61328125 63428376457179 0.00336668441115284 -0.0390625 -0.85546875 0.60546875 63428376457681 0.00102520678994544 -0.0546875 -0.8515625 0.63671875 63428376458405 0.0148799654945462 -0.05859375 -0.86328125 0.609375 63428376458767 0.00850476864388661 -0.05078125 -0.8671875 0.609375 63428376459273 0.0112909908500551 -0.05078125 -0.8671875 0.60546875 63428376459769 0.00905251224376924 -0.046875 -0.875 0.609375 63428376460274 0.0175065928701299 -0.0390625 -0.8671875 0.6015625 63428376460775 0.00632540132679571 -0.00390625 -0.8359375 0.6171875 63428376461282 0.010708654773619 -0.09375 -0.83984375 0.59765625 63428376461779 0.014762177150486 -0.13671875 -0.90625 0.46484375 63428376462300 0.0221596825450421 -0.0390625 -0.69140625 0.6484375 63428376462786 0.100333030401311 -0.453125 -0.89453125 0.98046875 63428376463289 0.354323044423235 -0.26171875 -0.8984375 0.80859375 63428376463791 0.19011390579613 -0.23828125 -1 0.82421875 63428376464307 0.275197003461697 --0.08203125 -0.9765625 0.640625 63428376464795 0.123974760694344 -0.0390625 -1.140625 0.4140625 63428376465297 0.165657466736006 --0.06640625 -1.25 0.27734375 63428376465799 0.23498904282897 --0.15234375 -1.3125 0.59765625 63428376466335 0.399287678773926 --0.2890625 -0.88671875 0.59765625 63428376466807 0.058774053087421 -0.0625 -1.0234375 1.515625 63428376467310 0.77670241358611 --0.3203125 -0.63671875 0.29296875 63428376467812 0.278171504871102 --0.1640625 -0.55078125 1.203125 63428376468312 0.268648679748386 -0.14453125 -0.73046875 1.87109375 63428376468810 0.955506049898127 -0 -0.72265625 1.296875 63428376469312 0.423527971116098 --0.078125 -0.734375 1.01953125 63428376469832 0.200049516647929 --0.0703125 -0.71875 0.87109375 63428376470317 0.0642109403940672 --0.0546875 -0.6796875 0.8203125 63428376470818 0.0105805723852379 --0.12890625 -0.72265625 0.73828125 63428376471321 0.00200985076971394 --0.14453125 -0.78125 0.6875 63428376472035 0.0156193827233124 --0.15234375 -0.80078125 0.6640625 63428376472438 0.0237500428689108 --0.1640625 -0.8046875 0.65625 63428376472940 0.102534366559502 --0.17578125 -0.80859375 0.65234375 63428376473442 0.348740230901708 --0.1796875 -0.80078125 0.65625 63428376473946 0.18592351006987 --0.18359375 -0.796875 0.65234375 63428376474449 0.271543941427385 --0.1875 -0.796875 0.65234375 63428376474950 0.124047643566785 --0.171875 -0.80078125 0.6953125 63428376475455 0.139722828616902 -0.41015625 -0.86328125 1.48046875 63428376475957 0.480058655486385 -1.140625 -0.71484375 1.69140625 63428376476457 0.711492656232693 -1.9140625 -1.046875 2.8359375 63428376482565 1.41632058353641 -1.640625 -1.30859375 3.12109375 63428376482716 1.59933801486903 -0.73828125 -0.9921875 1.96875 63428376482848 0.163282044458666 -0.26171875 -0.8359375 1.38671875 63428376483070 0.521478589632226 -0.015625 -0.75 1.0703125 63428376483285 0.85466053061156 --0.10546875 -0.703125 0.92578125 63428376483419 0.994389268986344 --0.14453125 -0.69921875 0.859375 63428376483553 1.04440190602252 --0.0546875 -0.62109375 0.828125 63428376483686 1.12508519053644 --0.06640625 -0.6171875 0.8515625 63428376483821 1.10788764201977 --0.05859375 -0.5703125 0.87109375 63428376484046 1.11885525513452 --0.046875 -0.5546875 0.87890625 63428376484276 1.12132368540358 --0.05078125 -0.55078125 0.890625 63428376484669 0.0080429926794523 --0.06640625 -0.546875 0.90625 63428376484803 0.0201909463134127 --0.05078125 -0.5859375 0.8828125 63428376485106 0.0204211227424567 --0.0625 -0.6015625 0.859375 63428376485329 0.0104997904842163 --0.0859375 -0.62109375 0.83984375 63428376485465 0.00772274920853255 --0.08984375 -0.62109375 0.8359375 63428376485842 0.00492373258200463 --0.08984375 -0.62109375 0.83203125 63428376486222 0.00180245707485738 --0.0859375 -0.62890625 0.83203125 63428376486595 0.00614922352259062 --0.0859375 -0.62890625 0.82421875 63428376487094 5.13351257220851E-05 --0.0859375 -0.63671875 0.82421875 63428376487597 0.00469014280135616 --0.08984375 -0.6328125 0.8203125 63428376488101 0.000440097593247923 --0.08984375 -0.63671875 0.83203125 63428376488601 0.0116293747988596 --0.08984375 -0.63671875 0.828125 63428376489104 0.00854130584921919 --0.0859375 -0.640625 0.82421875 63428376489607 0.00751478227677849 --0.08984375 -0.640625 0.82421875 63428376490108 0.00784250545013365 --0.09375 -0.640625 0.83203125 63428376490610 0.0143393931769495 --0.0859375 -0.64453125 0.82421875 63428376491116 0.00990844258161694 --0.08203125 -0.64453125 0.82421875 63428376491617 0.00959590349564721 --0.08203125 -0.64453125 0.82421875 63428376492119 0.00959590349564721 --0.08203125 -0.6484375 0.8203125 63428376492622 0.00894145046901729 --0.0703125 -0.73046875 0.8359375 63428376493123 0.0724276155431058 --0.3203125 -0.6484375 0.77734375 63428376493621 0.0218389134691632 -1.1875 0.14453125 0.78125 63428376494125 0.388853456528143 -0.69140625 -0.35546875 0.703125 63428376494628 0.00830842414441646 -0.4296875 -0.62109375 0.62890625 63428376495139 0.0571130736402183 -0.3046875 -0.75390625 0.6015625 63428376495644 0.0284438179793922 -0.25390625 -0.82421875 0.5859375 63428376496144 0.00273292787998236 --0.70703125 -0.828125 0.53125 63428376496648 0.171652447164361 -1.4609375 -0.6328125 1.5625 63428376497148 1.19081772937857 -0.79296875 -0.64453125 1.16015625 63428376497653 0.506100278933842 -0.3515625 -0.70703125 0.9765625 63428376498319 0.215930554725897 -0.16015625 -0.703125 0.87109375 63428376498742 0.079307087110897 -0.0703125 -0.68359375 0.828125 63428376499242 0.0276579434444766 -0.02734375 -0.67578125 0.81640625 63428376499747 0.0127277255847165 -0.01171875 -0.6953125 0.80078125 63428376500247 0.0128245068164663 -0 -0.703125 0.77734375 63428376500749 0.00609647633462629 --0.0078125 -0.68359375 0.80859375 63428376501248 0.00903071021060797 -0.1640625 -0.6953125 0.71484375 63428376501748 0.0388848706784986 -0.1328125 -0.80078125 0.53515625 63428376502250 0.077260999897125 -1.796875 0.1953125 1.35546875 63428376502752 1.21038548795715 -2.0625 -0.203125 2.4296875 63428376503255 2.08116761534119 -1 -0.46484375 1.55859375 63428376503757 1.28425110399982 -0.15625 -0.2421875 0.515625 63428376504259 2.60280672465822 --0.171875 -0.87890625 0.80859375 63428376504789 1.98693406709027 -0.40234375 -1.23828125 2.3984375 63428376505273 0.46446471933848 -0.140625 -0.92578125 1.58203125 63428376505775 1.35512879706137 -0.07421875 -0.87109375 1.09375 63428376506278 1.79330154288955 -1.12109375 -0.8984375 1.5 63428376506782 1.11648946240025 --1.21484375 -0.75390625 0.40234375 63428376507285 1.70822171760766 -0.35546875 -0.7265625 0.6953125 63428376507787 2.12688129417698 -0.265625 -0.83203125 0.703125 63428376508288 2.07225939170623 -0.078125 -0.53515625 0.99609375 63428376508791 2.0600710522431 -0.10546875 -0.4140625 1.24609375 63428376509292 1.87620060875615 -0.11328125 -0.13671875 1.359375 63428376509790 0.0536053923475091 --0.02734375 0.46875 0.76953125 63428376510292 0.415843393155336 -0.05078125 0.609375 1.1484375 63428376510794 0.0162296418354178 -0.1484375 -0.0703125 1.2734375 63428376511296 0.0333296315718239 -0.01171875 -0.37109375 1.01953125 63428376511799 0.232285033296083 --0.0625 -0.4765625 0.921875 63428376512300 0.277666108508948 --0.09375 -0.51953125 0.9140625 63428376512803 0.261753422130789 --0.0859375 -0.55078125 0.875 63428376513305 0.279833203300393 --0.0546875 -0.5859375 0.875 63428376513832 0.262830914329617 --0.0390625 -0.6015625 0.86328125 63428376514320 0.264387628370949 --0.03515625 -0.61328125 0.8515625 63428376514822 0.267311779578162 --0.046875 -0.6171875 0.84765625 63428376515327 0.000414247241044219 --0.05859375 -0.625 0.84765625 63428376515828 0.00478469928386005 --0.05078125 -0.625 0.84375 63428376516331 0.00124176230980266 --0.0546875 -0.62109375 0.859375 63428376516834 0.0117273280891768 --0.05859375 -0.609375 0.859375 63428376517334 0.00512460030233619 --0.0546875 -0.61328125 0.86328125 63428376517832 0.0103539511299957 --0.0625 -0.59375 0.86328125 63428376518350 0.000385171925330052 --0.0625 -0.5859375 0.86328125 63428376518850 0.00478470422410826 --0.06640625 -0.5859375 0.86328125 63428376519352 0.00454385428995185 --0.0703125 -0.58984375 0.859375 63428376519855 0.00531038772781889 --0.0703125 -0.5859375 0.859375 63428376520356 0.0075109073043369 --0.078125 -0.59765625 0.86328125 63428376520867 0.00287342880555785 --0.07421875 -0.59765625 0.86328125 63428376521360 0.00259078782377165 --0.0625 -0.59765625 0.86328125 63428376521863 0.00182945383538557 --0.05859375 -0.5859375 0.87109375 63428376522365 0.00145220813616787 --0.0546875 -0.5859375 0.86328125 63428376522870 0.00522275544257855 --0.046875 -0.59375 0.85546875 63428376523378 0.00762068926570914 --0.0625 -0.59765625 0.8671875 63428376523884 0.00503782747376991 --0.05859375 -0.57421875 0.8671875 63428376524380 0.00828694782861472 --0.05078125 -0.56640625 0.88671875 63428376524886 0.00340227092151979 --0.05078125 -0.56640625 0.875 63428376525384 0.0060287189071202 --0.0390625 -0.5546875 0.890625 63428376525885 0.00482829656019446 --0.03515625 -0.5625 0.89453125 63428376526384 0.00602819614725636 --0.02734375 -0.56640625 0.88671875 63428376526890 0.00919452728396353 --0.0234375 -0.5625 0.88671875 63428376527388 0.0047831509120817 --0.02734375 -0.55859375 0.875 63428376527893 0.0218977858418139 --0.0546875 -0.5390625 0.84375 63428376528393 0.0468760765780976 --0.0703125 -0.5234375 0.875 63428376528899 0.0231843046838596 --0.0625 -0.515625 0.91015625 63428376529399 0.00247098056650952 --0.05859375 -0.5 0.9140625 63428376529902 0.00116913367398142 --0.05859375 -0.49609375 0.9140625 63428376530402 0.000834633084151548 --0.046875 -0.4921875 0.92578125 63428376530908 0.00334582909446235 --0.05078125 -0.4921875 0.91796875 63428376531414 0.0097651025114518 --0.04296875 -0.50390625 0.90625 63428376531916 0.0140200112831566 --0.04296875 -0.50390625 0.91796875 63428376532417 0.00339404222982465 --0.04296875 -0.5078125 0.91015625 63428376532920 0.00165895829817764 --0.046875 -0.51171875 0.91015625 63428376533420 0.00281408684096407 --0.0390625 -0.51171875 0.90625 63428376533928 0.0135664908579975 --0.03515625 -0.51171875 0.91015625 63428376534430 0.00302037716223724 --0.03515625 -0.51171875 0.90234375 63428376534933 0.0154678618919064 --0.03125 -0.515625 0.89453125 63428376535435 0.0105887603632622 --0.0234375 -0.51953125 0.8984375 63428376535937 0.01186029470133 -0 -0.546875 0.890625 63428376536613 0.012149558197676 --0.00390625 -0.52734375 0.89453125 63428376536990 0.0141280646256596 -0 -0.51953125 0.89453125 63428376537487 0.0158896822387611 -0 -0.52734375 0.90625 63428376537994 0.0100532339890511 -Movement1 Class -x y z tick deltaG -0.0078125 -0.0625 1.01171875 63428376588701 0.00306790822895686 -0.01171875 -0.0625 1.01171875 63428376589107 0.00310553978716155 -0.0078125 -0.0625 1.015625 63428376589610 0.0069666389728138 -0.01171875 -0.0625 1.015625 63428376590111 0.00700412635519121 -0.01171875 -0.06640625 1.01171875 63428376590615 0.00335387304377455 -0.01171875 -0.06640625 1.0078125 63428376591116 0.000543695807456057 -0.01171875 -0.0703125 1.0078125 63428376591618 0.000279362689771245 -0.015625 -0.07421875 1.0078125 63428376592186 5.28437142051086E-05 -0.0234375 -0.0703125 1.0078125 63428376592635 7.54958138571293E-05 -0.01953125 -0.06640625 1.01171875 63428376593140 0.00347425515656163 -0.01171875 -0.0625 1.00390625 63428376593642 0.00469145496905932 -0.015625 -0.0625 1.00390625 63428376594145 0.00463836481248614 -0.01171875 -0.06640625 1 63428376594651 0.00833863073206409 -0.01171875 -0.0625 1.00390625 63428376595151 0.00469145496905932 -0.01171875 -0.0625 1.0078125 63428376595651 0.000792987550474633 -0.01171875 -0.0625 1.015625 63428376596151 0.00700412635519121 -0.01171875 -0.0625 1.015625 63428376596649 0.00700412635519121 -0.015625 -0.05859375 1.01953125 63428376597155 0.010723506358588 -0.015625 -0.06640625 1.01171875 63428376597659 0.00340654197664825 -0.0078125 -0.0625 1.015625 63428376598158 0.0069666389728138 -0.015625 -0.05859375 1.01171875 63428376598661 0.000143012663855302 -0.015625 -0.05859375 1.01171875 63428376599160 0.000180644222059989 -0.015625 -0.05859375 1.0078125 63428376599663 0.00794096827068991 -0.01953125 -0.05859375 1.0078125 63428376600199 0.00791044868113477 -0.01953125 -0.05859375 1.0078125 63428376600674 0.00426019536971811 -0.01953125 -0.0625 1.00390625 63428376601178 0.00402641434899542 -0.015625 -0.06640625 1.015625 63428376601681 0.00758333840336123 -0.01953125 -0.06640625 1.01171875 63428376602186 0.00342141144235653 -0.01171875 -0.06640625 1.0078125 63428376602688 0.000468199993598928 -0.015625 -0.0625 1.01953125 63428376603190 0.00748079605237528 -0.015625 -0.0703125 1.01171875 63428376603692 0.00836130058563667 -0.01171875 -0.0625 1.015625 63428376604193 0.0116424911676773 -0.01171875 -0.0625 1.01953125 63428376604690 0.0192414022075225 -0.015625 -0.06640625 1.01171875 63428376605195 0.00809799694570756 -0.015625 -0.06640625 1.015625 63428376605699 0.00809696326406462 -0.015625 -0.06640625 1.00390625 63428376606197 0.0113922467305829 -0.015625 -0.06640625 1.01171875 63428376606698 0.00359758437854296 -0.015625 -0.05859375 1.01171875 63428376607202 0.00779861079348643 -0.0234375 -0.0546875 1.0078125 63428376607704 0.00444888282757594 -0.02734375 -0.0625 1.0078125 63428376608207 0.0074574626229682 -0.0234375 -0.06640625 1.00390625 63428376608709 0.00716138292960355 -0.01953125 -0.0625 1.00390625 63428376609210 0.00749500572155304 -0.015625 -0.0625 1.00390625 63428376609712 0.00366403551461003 -0.01953125 -0.0546875 1.00390625 63428376610218 0.00411890637968337 -0.01171875 -0.06640625 1.01171875 63428376610721 0.00426019536971811 -0.01171875 -0.06640625 1.01171875 63428376611219 0.00792398320022603 -0.015625 -0.06640625 1.00390625 63428376611724 0.0116920960889817 -0.01953125 -0.06640625 1.0078125 63428376612224 0.00389710438495738 -0.015625 -0.0625 1.00390625 63428376612724 0.00409466900503008 -0.015625 -0.07421875 1.00390625 63428376613225 0.0147973996270498 -0.015625 -0.0703125 1.0078125 63428376613727 0.00389634998128741 -0.01953125 -0.0703125 1.0078125 63428376614229 0.00716267407926141 -0.01953125 -0.06640625 1.01171875 63428376614731 0.00742851631889674 -0.01953125 -0.06640625 1.01171875 63428376615232 6.77131799133868E-05 -0.01953125 -0.06640625 1.01171875 63428376615734 0.00382972055702835 -0.015625 -0.06640625 1.0078125 63428376616238 0.00389729672523731 -0.015625 -0.05859375 1.0078125 63428376616740 0.00438087127452436 -0.015625 -0.05859375 1.01171875 63428376617241 0 -0.01953125 -0.05859375 1.01171875 63428376617744 0.00403498177208506 -0.01953125 -0.05859375 1.015625 63428376618249 0.00738248371481665 -0.01171875 -0.0625 1.01953125 63428376618753 0.0151392588399604 -0.0078125 -0.06640625 1.01171875 63428376619254 0.00788636085883665 -0.015625 -0.0703125 1.01171875 63428376619757 0.00830821042906349 -0.01953125 -0.0703125 1.0078125 63428376620256 0.00486668098155674 -0.015625 -0.0703125 1.01171875 63428376620755 0.000315972572802803 -0.01171875 -0.0703125 1.00390625 63428376621258 0.00752971360068511 -0.01171875 -0.06640625 1.0078125 63428376621759 0.00384442456793566 -0.01171875 -0.0625 1.015625 63428376622261 0.00742697558358696 -0.01171875 -0.0625 1.01171875 63428376622762 0.00774390459964769 -0.0078125 -0.0625 1.015625 63428376623265 0.0108089873909267 -0.01171875 -0.06640625 1.01171875 63428376623773 0.0035803774084846 -0.01171875 -0.05859375 1.01171875 63428376624288 0.00303074932595004 -0.01171875 -0.05859375 1 63428376624788 0.0123001792321547 -0.015625 -0.05859375 1 63428376625318 0.0122468699784262 -0.01953125 -0.05078125 1.0078125 63428376625796 0.00480380642475753 -0.01953125 -0.0546875 1.00390625 63428376626301 0.00453440505547253 -0.01953125 -0.05859375 1.00390625 63428376626804 0.00383089972872397 -0.01171875 -0.0625 1.01171875 63428376627307 0.000180644222059989 -0.01171875 -0.0546875 1.015625 63428376627809 0.00356154566053624 -0.015625 -0.05859375 1.015625 63428376628308 6.74857416442798E-05 -0.01171875 -0.0625 1.01171875 63428376628809 0.00779723168829682 -0.015625 -0.0625 1.01171875 63428376629309 0.000158029080532085 -0.01171875 -0.06640625 1.00390625 63428376629812 0.00811104294447373 -0.01171875 -0.06640625 1.015625 63428376630312 0.00741005617640145 -0.015625 -0.0625 1.015625 63428376630822 0.00338676075401612 -0.01953125 -0.0546875 1.01953125 63428376631325 0.0147499352790241 -0.01953125 -0.05859375 1.015625 63428376631826 0.0074353558721183 -0.01953125 -0.0625 1.015625 63428376632328 0.000119950344518394 -0.015625 -0.05859375 1.015625 63428376632830 0.00371863453585641 -0.01953125 -0.0546875 1.0078125 63428376633332 0.00809211127787313 -0.015625 -0.05859375 1.0078125 63428376633834 0.00432820234165066 -0.015625 -0.05859375 1.0078125 63428376634337 0.00384653089975595 -0.015625 -0.05859375 1.0078125 63428376634840 0.00785159477771691 -0.015625 -0.05859375 1.0078125 63428376635342 0.00779828552398842 -0.015625 -0.0625 1.015625 63428376635847 0.00838615763878936 -0.015625 -0.05859375 1.015625 63428376636347 0.0118494030286449 --0.0625 -0.07421875 1.1015625 63428376636847 0.100023187259225 --0.05859375 -0.4921875 0.6484375 63428376637418 0.197533214524849 -0.09765625 -0.63671875 0.5703125 63428376637866 0.156812789942384 --0.01953125 -0.73828125 0.6328125 63428376638367 0.044863822406138 --0.1328125 -0.78515625 0.6484375 63428376638901 0.0132126398545918 -0.0078125 -0.88671875 0.6484375 63428376639402 0.084777736205536 -0.09375 -0.8671875 0.390625 63428376639907 0.0504534393800327 --0.0390625 -0.85546875 0.06640625 63428376640407 0.158930126823848 --0.50390625 -0.6484375 -0.46875 63428376640909 0.0720874202770714 --0.234375 -0.703125 0.140625 63428376641410 0.26680197481155 --0.125 -0.79296875 0.33203125 63428376641913 0.148784292776127 --0.5703125 -0.25390625 -0.35546875 63428376642418 0.299344682512754 -0.44140625 -0.42578125 1.33984375 63428376643095 0.45610292034874 -0.1796875 -0.640625 0.98046875 63428376643422 0.175423856267555 -0.07421875 -0.75 0.7890625 63428376643924 0.0815237582151922 --0.0078125 -0.73046875 0.75390625 63428376644454 0.0401362469454662 -0.87890625 -1.640625 2.34765625 63428376645096 1.98629803720396 -0.34375 -1.203125 1.43359375 63428376645489 0.893221745450592 -0.14453125 -1.03125 1.03125 63428376646043 0.437305115621146 -0.11328125 -1.19140625 1.0625 63428376646486 0.302485900776305 -0.01171875 -0.9765625 0.88671875 63428376646993 0.583735430991177 --0.03515625 -0.87890625 0.7890625 63428376647437 0.72119219073265 --0.05078125 -0.82421875 0.7578125 63428376647939 0.782055944463297 --0.46484375 -0.15625 -0.6875 63428376648442 1.05837492351877 --0.26953125 -0.4375 0.046875 63428376649000 1.38686225033197 --0.15234375 -0.6171875 0.33984375 63428376649447 1.18200835937776 --0.13671875 -0.84765625 0.46484375 63428376649949 0.926489859813141 -0.01953125 -0.875 0.54296875 63428376650454 0.872895119160425 -0.1875 -0.76953125 0.62890625 63428376650962 0.891492767970655 -0.24609375 -1.37890625 0.2734375 63428376651547 0.475722609972718 -0.12890625 -1.09765625 0.50390625 63428376652015 0.212479086757735 -0.0546875 -0.9609375 0.5546875 63428376652465 0.316247463962189 -0.23046875 -1.22265625 1.44140625 63428376653080 0.476981158500355 -0.109375 -0.96875 1.10546875 63428376653522 0.0468060865406734 -0.046875 -0.84765625 0.9296875 63428376654029 0.168151800194795 -0.01953125 -0.78125 0.84375 63428376654471 0.27707046535455 --0.015625 -0.84375 1.30859375 63428376655034 0.129970525884806 --0.03515625 -0.78125 1.07421875 63428376655547 0.0984006418871459 --0.04296875 -0.71484375 0.9375 63428376655992 0.247408114635491 --0.09375 -0.7265625 0.6953125 63428376656551 0.417113823182315 -0.29296875 -0.6484375 0.56640625 63428376657001 0.517674182323871 -0.4375 -0.83203125 0.88671875 63428376657620 0.382806142854792 -0.0859375 -0.546875 0.20703125 63428376658004 0.318427699991332 --0.15625 -0.6796875 0.85546875 63428376658509 0.194267965835764 --0.00390625 -0.81640625 1.8359375 63428376659182 1.09981847284515 --0.32421875 -0.19921875 0.6328125 63428376659514 0.171044655770773 --0.23046875 -0.9375 1.36328125 63428376660134 0.761036056441495 --0.6640625 0.21484375 -0.4296875 63428376660573 0.0898455769518138 --0.33984375 -0.4765625 1.0625 63428376661141 0.303598642240668 --0.71875 -0.0234375 -0.0234375 63428376661526 0.189946375078067 --0.51953125 -0.40625 0.296875 63428376662028 0.186213010909076 --0.34765625 -0.62109375 0.48828125 63428376662534 0.0463027217246723 --0.2578125 -0.734375 0.55859375 63428376663032 0.0948617466552545 --0.21484375 -0.78515625 0.5859375 63428376663534 0.13981353654053 --0.1953125 -0.80078125 0.61328125 63428376664036 0.164223367226262 --0.19921875 -0.66015625 0.91015625 63428376664595 0.278717603837004 -0.29296875 -0.90234375 2.015625 63428376665215 1.36457655301732 --0.328125 -0.546875 0.40234375 63428376665545 0.109089364042082 --0.35546875 -0.2578125 0.015625 63428376666047 0.423760815990556 --0.265625 -0.51953125 0.28515625 63428376666552 0.213708942070231 --0.57421875 -0.72265625 0.62109375 63428376667054 0.249369643127408 --0.71875 0.05859375 -0.27734375 63428376667556 0.0905293071119455 --0.24609375 -0.3984375 0.14453125 63428376668058 0.373051548253471 --0.0234375 -0.68359375 0.35546875 63428376668558 0.280742763931956 --0.51953125 -0.8671875 0.4375 63428376669058 0.611408051603572 --0.125 -0.8515625 0.5 63428376669560 0.505275213445923 --0.21875 -0.80859375 0.39453125 63428376670062 0.435815371471777 -0.05078125 -0.87109375 0.55078125 63428376670564 0.541757902452297 -0.3046875 -0.703125 0.48828125 63428376671066 0.418540179804597 --0.09375 -0.53125 0.703125 63428376671569 0.3961222165272 -0.0859375 -0.2265625 0.8515625 63428376672070 0.39526091422444 -0.12109375 -0.1171875 0.91796875 63428376672572 0.443201718179827 -0.09765625 -0.08984375 0.9609375 63428376673075 0.479950487227399 -0.078125 -0.07421875 1 63428376673580 0.515683246248675 -0.07421875 -0.0703125 0.98828125 63428376674136 0.0122339291383349 diff --git a/SensorScan5/doc/basicxyz.log0.txt b/SensorScan5/doc/basicxyz.log0.txt deleted file mode 100644 index 91d1509..0000000 --- a/SensorScan5/doc/basicxyz.log0.txt +++ /dev/null @@ -1,167 +0,0 @@ -Movement1 Class -x y z tick deltaG -0.0078125 -0.0703125 1.0234375 63428298408187 2.23110293011697E-05 -0.0078125 -0.07421875 1.0234375 63428298408573 0.000297440505137025 -0.0078125 -0.07421875 1.0234375 63428298409075 0.000297440505137025 -0.01171875 -0.07421875 1.02734375 63428298409578 0.00423041898793697 -0.0078125 -0.0703125 1.015625 63428298410081 0.00777144790415041 -0.0078125 -0.06640625 1.0234375 63428298410582 0.000238014511957152 -0.01171875 -0.06640625 1.0234375 63428298411085 0.000200821103564008 -0.0078125 -0.0625 1.01953125 63428298411655 0.00438236983935303 -0.0078125 -0.07421875 1.01953125 63428298412091 0.00359842592360748 -0.01171875 -0.06640625 1.01953125 63428298412593 0.00409858735331237 -0.00390625 -0.06640625 1.0234375 63428298413095 0.000260331204428477 -0 -0.06640625 1.0234375 63428298413598 0.000267770209831708 -0.0078125 -0.06640625 1.015625 63428298414101 0.00803376682858681 -0 -0.0703125 1.015625 63428298414603 0.00780142378887816 -0.00390625 -0.0703125 1.015625 63428298415107 0.00779392973495163 -0.04296875 -0.05078125 1.0234375 63428298415672 0.000260331204428477 --0.02734375 -0.0859375 1.05859375 63428298416106 0.0365707828721349 --0.0390625 -0.47265625 0.85546875 63428298416609 0.0477180567036706 -0.03515625 -0.73046875 0.35546875 63428298417111 0.212728520409404 -0.03125 -0.88671875 0.17578125 63428298417612 0.121343311479567 -0.01953125 -0.97265625 0.12109375 63428298418115 0.0455199149602052 -0.01171875 -0.97265625 0.1484375 63428298418616 0.0421674502514928 -0 -0.828125 0.5390625 63428298419117 0.0380357295340978 -0.08203125 -0.7734375 0.66796875 63428298419655 0.00484788333714681 -0.18359375 -0.7578125 0.68359375 63428298420123 0.0188744364078874 -0.2421875 -0.765625 0.68359375 63428298420625 0.0289595933501861 -0.26953125 -0.765625 0.68359375 63428298421561 0.0355357373514626 -0.23828125 -0.78125 0.68359375 63428298421904 0.0436211688965833 -0.140625 -0.76171875 0.69921875 63428298422380 0.0212436311223612 -0.03515625 -0.74609375 0.7265625 63428298422882 0.0202512132713037 -0.0625 -0.7109375 0.76953125 63428298423385 0.023934591282937 -0.328125 -0.640625 0.69921875 63428298423883 0.022109062329486 -0.60546875 -0.54296875 0.1875 63428298424383 0.183219711368193 -0.67578125 -0.5 0.375 63428298424885 0.097564106635704 -0.33984375 -0.55078125 0.625 63428298425388 0.118353103409463 -0.07421875 -0.57421875 0.7109375 63428298425890 0.108717737163186 --0.34375 -0.60546875 0.38671875 63428298426393 0.265993723815075 --0.375 -0.52734375 -0.14453125 63428298426894 0.315111665563357 --0.171875 -0.47265625 -0.47265625 63428298427396 0.122948566169859 --0.11328125 -0.03125 -0.6640625 63428298427913 0.23013422793657 --0.12109375 0.453125 -0.4375 63428298428415 0.338961167416871 --0.0703125 0.69921875 -0.21875 63428298428918 0.24798313904524 --0.0859375 0.7421875 -0.42578125 63428298429420 0.128167253561284 --0.12890625 0.04296875 -0.51171875 63428298429926 0.49578813923923 --0.12890625 -0.3125 0.15625 63428298430427 0.664553182132135 --0.15234375 -0.2734375 0.55078125 63428298430929 0.421067606421772 --0.48046875 -0.32421875 0.6484375 63428298431429 0.191457187623188 --0.64453125 -0.50390625 0.4609375 63428298431928 0.126051256733198 --0.34375 -0.484375 0.68359375 63428298432430 0.137917930789785 --0.2109375 -0.55078125 0.7421875 63428298432932 0.0940137795952853 --0.10546875 -0.55078125 0.6796875 63428298433434 0.168362706349216 -0.046875 -0.83984375 0.640625 63428298433938 0.0538439628533625 -0.015625 -0.87890625 0.3125 63428298434439 0.0983358248053001 -1.29296875 -0.33984375 0.20703125 63428298435101 0.43232884212427 -0.31640625 -0.3671875 0.23828125 63428298435516 0.359601563030776 -0.51953125 -0.5390625 0.25 63428298436015 0.127575153890154 -0.60546875 -0.66015625 0.21484375 63428298436526 0.12473680767125 -0.65625 -0.66796875 0.15234375 63428298437028 0.285684562757334 -0.6875 -0.8125 0.92578125 63428298437638 0.720451955630843 -0.52734375 -0.9453125 0.7734375 63428298438677 0.0802516104615008 -0.453125 -1.01171875 0.62890625 63428298439236 0.136104849180107 -0.58203125 -1.1171875 1.07421875 63428298439786 0.244908180587993 -0.3046875 -0.90234375 0.90234375 63428298440286 0.0986555404751064 -0.234375 -0.9140625 0.7578125 63428298440786 0.200375412518192 -0.09765625 -0.9140625 0.66015625 63428298441236 0.278884394329113 --0.00390625 -0.91015625 0.58203125 63428298441738 0.330280467312093 --0.08203125 -0.8984375 0.56640625 63428298442303 0.345392817554905 --0.11328125 -0.90234375 0.60546875 63428298442743 0.31808969636907 --0.00390625 -0.9453125 0.58203125 63428298443244 0.300501043362632 --0.26171875 -0.1953125 -0.2578125 63428298443747 0.994566222938102 --0.296875 -0.51171875 0.1015625 63428298444250 0.810377509998167 --0.07421875 -0.47265625 0.95703125 63428298444753 0.340669116174963 --0.4296875 -0.13671875 -0.2109375 63428298445253 0.912819066568249 --0.37109375 -0.46484375 0.41015625 63428298445790 0.688123846858942 --0.18359375 -0.65625 0.65234375 63428298446261 0.467274924557395 -0.17578125 -0.3203125 0.625 63428298446763 0.686668089685792 -0.234375 -0.734375 0.5625 63428298447266 0.456355309899044 -0.0625 -0.90234375 0.296875 63428298447765 0.458652625178798 -0.140625 -0.94921875 0.41796875 63428298448770 0.0946766912616894 --0.05859375 -1.45703125 0.546875 63428298449388 0.605404550776769 -0.328125 -1.87109375 0.61328125 63428298449886 1.04420964926576 --0.1171875 -1.37109375 0.05078125 63428298450336 0.425049656111519 -0.2109375 -1.22265625 0.3828125 63428298450843 0.34645338185566 -0.41796875 -1.0234375 0.375 63428298451291 0.215387981265973 -0.3828125 -0.97265625 0.3984375 63428298451791 0.166661501851514 -0.20703125 -0.984375 0.25 63428298452296 0.0845318424122299 --0.046875 -0.92578125 -0.05078125 63428298452853 0.0236225424321896 --0.03125 -0.5859375 -0.2578125 63428298453303 0.311068893070598 --0.3046875 -0.42578125 -0.43359375 63428298453809 0.272179913211926 -0.04296875 -0.66015625 -0.0625 63428298454312 0.287480715044021 -0.1953125 -0.83203125 0.13671875 63428298454813 0.086465360173929 -0.3828125 -1.125 0.41015625 63428298455431 0.305159384977736 --0.4765625 -0.28125 -0.796875 63428298455815 0.018186902538835 --1.39453125 0.27734375 -1.515625 63428298456540 1.12618206004375 --1.8984375 0.7421875 -1.703125 63428298456990 1.70424736945154 --1.8359375 0.6171875 -1.265625 63428298457434 1.36176051325996 --1.546875 0.24609375 -0.5078125 63428298457987 0.694610136896344 -1.1328125 -0.58203125 1.95703125 63428298458992 0.688361141474042 -2.5625 -0.78515625 2.734375 63428298459515 2.18220678752944 -2.26171875 -0.87109375 2.06640625 63428298459942 1.53840798381785 -0.93359375 -0.4375 0.55859375 63428298460331 0.473972836781553 --1.53125 -0.01171875 -0.71875 63428298460951 0.0449968782251633 --0.58203125 -0.62109375 -0.18359375 63428298461392 0.775828922515586 --0.17578125 -0.74609375 0.171875 63428298461902 0.861035241797507 -0 -0.81640625 0.3828125 63428298462418 0.744888854950191 -0.09375 -0.8515625 0.4921875 63428298462906 0.658563327682444 -0.1484375 -0.86328125 0.546875 63428298463420 0.613942476120172 -0.17578125 -0.86328125 0.55859375 63428298463865 0.603430864794869 -0.18359375 -0.87109375 0.56640625 63428298464363 0.591446658655061 --0.015625 -0.89453125 0.54296875 63428298464868 0.60005008097072 -0.3203125 -1.19921875 1.42578125 63428298465540 0.243801143937157 --0.0078125 -0.1953125 0.765625 63428298465870 0.856406488873601 -0 -0.52734375 0.6796875 63428298466372 0.786318594768324 -0.01171875 -0.9375 0.9296875 63428298466991 0.326225284141469 -0.04296875 0.02734375 0.75390625 63428298467377 0.890965128656802 --0.390625 0.359375 -0.05859375 63428298467879 1.11257526826361 -0.03125 -0.84765625 1.31640625 63428298468938 1.03200690135113 -0 -0.796875 1.04296875 63428298469453 0.778537793664973 -0 -0.87109375 0.87109375 63428298469957 0.697898074207803 --0.3671875 0.484375 0.05859375 63428298470471 0.0766236927964815 --0.71484375 0.51171875 -0.57421875 63428298470904 0.516025877542761 --0.48828125 -0.60546875 0.73046875 63428298471490 0.533035421952323 -0.625 -1.45703125 2.35546875 63428298472082 2.30531605061446 -0.25390625 -1.11328125 1.52734375 63428298472469 1.37298376308898 -0.09765625 -0.9375 1.14453125 63428298473025 0.948683956430116 -0.0234375 -0.84765625 0.9375 63428298473474 0.730096504272209 -0 -0.7890625 0.84375 63428298473917 0.621205670600424 --0.0078125 -0.7734375 0.78515625 63428298474418 0.568136529521914 --0.19921875 -0.7265625 0.80078125 63428298474931 0.565454344771162 --0.40234375 -0.66015625 0.6796875 63428298475468 0.495384267101499 --0.48828125 -0.6328125 0.6328125 63428298475932 0.485456861201244 --0.50390625 -0.63671875 0.640625 63428298476436 0.500264293307202 --0.45703125 -0.6328125 0.68359375 63428298476936 0.503593130465633 --0.4140625 -0.63671875 0.71875 63428298477438 0.51167189600736 --0.3203125 -0.69140625 0.75390625 63428298477945 0.537907740025898 -0.2421875 -0.6171875 0.69140625 63428298478948 0.113998570128692 -0.1171875 -0.55859375 0.74609375 63428298479449 0.132552381148884 -0.1328125 -0.51953125 0.86328125 63428298479951 0.0556514328513771 -0.17578125 -0.26953125 0.9296875 63428298480449 0.0881209650531496 -0.18359375 -0.18359375 0.9453125 63428298480954 0.0916013684307038 -0.19140625 -0.203125 1.08984375 63428298481454 0.0530913021197605 -0.11328125 -0.0078125 0.13671875 63428298481957 0.894198617946576 -0.16796875 -0.140625 0.61328125 63428298482457 0.420690518080307 -0.17578125 -0.23046875 0.79296875 63428298483012 0.227638937243405 -0.203125 -0.27734375 0.87109375 63428298483462 0.135448213166204 -0.21875 -0.31640625 0.91796875 63428298483964 0.0766177331372353 -0.22265625 -0.34375 0.9140625 63428298484466 0.0702985184016609 -0.2265625 -0.35546875 0.92578125 63428298484982 0.0546909593062466 -0.2265625 -0.35546875 0.93359375 63428298485469 0.0475756944851811 -0.1171875 -0.64453125 0.49609375 63428298486028 0.250178717734719 -0.1953125 -0.4140625 0.73046875 63428298486519 0.209843772112862 -0.2109375 -0.36328125 0.84765625 63428298487017 0.125883671217966 -0.23046875 -0.37109375 0.8984375 63428298487520 0.0729145747987687 -0.1875 -0.19140625 1.015625 63428298488020 0.021547688376397 -0.03515625 -0.13671875 1.0078125 63428298488519 0.082652934273412 --0.0078125 -0.10546875 1.01953125 63428298489022 0.0670780953554185 --0.03515625 -0.09375 1.00390625 63428298489523 0.0695170230607496 --0.04296875 -0.09375 1.0078125 63428298490025 0.00319560350072456 --0.05078125 -0.09765625 1.0078125 63428298490527 0.0300041653395884 --0.05078125 -0.0859375 1.0078125 63428298491029 0.0324229171263 --0.05078125 -0.08984375 1.0078125 63428298491531 0.111930807573872 --0.05078125 -0.0859375 1.015625 63428298492033 0.842794916083503 --0.05078125 -0.09765625 1.00390625 63428298492536 0.358690648637359 --0.05078125 -0.09375 1 63428298493037 0.161384512816001 --0.0546875 -0.08984375 1.01171875 63428298493587 0.080697250833782 diff --git a/SensorScan5/doc/sensorscan5.txt b/SensorScan5/doc/sensorscan5.txt deleted file mode 100644 index 7131c3b..0000000 --- a/SensorScan5/doc/sensorscan5.txt +++ /dev/null @@ -1,115 +0,0 @@ -Hello Readers - -it has been a long time since my last post, I was a little bit busy. - -This time I want to present some experimental code to visualize and analyze G-Sensor data. -The goal was to achieve a shake detection algorythm. Unfortunately the device under test -only provided 1 sample per second and that is not enough for a good shake detection. Beside that -the code and classes developed may help you to find your way and they help you at last to determine -the current orientation of the device. - -[image SensorScan5_01.gif] - -The development device was an Int*rm*c CN50. To be able to get the sensor data into a .NET app, first install -the sensor wrapper DLLs (sensor.cab) of the Int*rm*c Device Resource Kit. For other devices you just have to -change the code that is used to register for sensor data changes. - - - mySensor.AccelerationEvent += new AccelerationEventHandler(mySensor_AccelerationEvent); -... - void mySensor_AccelerationEvent(object sender, Sensor.AccelerationArgs AccelerationArgs) - { - ShakeDetection.GVector gv = new ShakeDetection.GVector(AccelerationArgs.GForceX, - AccelerationArgs.GForceY, - AccelerationArgs.GForceZ); - - processData(gv); - } - - -The class GVector implements some analysis on the vector data. The vector data is built of three acceleration values, -the X, Y, and Z part of the acceleration. If the device is layed on a desk, the Z vector is about -9.81 m/s and the -X and Y vector will be at 0.0 m/s. If you move the device or turn it, the xyz values will change and you can calculate -an orientation and if you collect and evaluate the datas over time, you can get the acceleration of the device. If it is -falling, the xyz values will all be zero. - -Here is a visualization of the vectors - -[image vectors.gif] -The device is facing upwards (see y arrow) with the top facing to you (the z arrow). The left side of the device is pointing -to the right (the x arrow). -The light green/blue and the yellow arrows demonstrate two different vectors which show the direction (the xyz angles) and the -force (the vectory lengths) to the device. - -One analysis done by GVector class is the segmented direction, which shows in which direction the top of the device is -pointing expressed in compass like directions. - - - #region segmented direction - // http://en.wikipedia.org/wiki/Boxing_the_compass - //attention: this here is based on +Y/+X (-1/0) equal 0 degree equal North - public enum Direction:int{ - None=-1, - W=0, - WSW, - SW, - SSW, - S, - SSE, - SE, - ESE, - E, - ENE, - NE, - NNE, - N, - NNW, - NW, - WNW, - } - public Direction direction - { //http://stackoverflow.com/questions/1437790/how-to-snap-a-directional-2d-vector-to-a-compass-n-ne-e-se-s-sw-w-nw - get{ - GVector gv=this; - int segmentCount=16; - int compassSegment = (((int) Math.Round(Math.Atan2(gv.Y, gv.X) / (2 * Math.PI / segmentCount))) + segmentCount) % segmentCount; - return (Direction)compassSegment; - } - } - #endregion - - -Another simply analysis gives you the orientation of the device, that means where the display is facing to. - - - //changed to match CN50 XYZ directions - public ScreenOrientation ToScreenOrientation() - { - if (Math.Abs(X) > Math.Abs(Y)) - { - if (Math.Abs(X) > Math.Abs(Z)) - { - if (X > 0) - return ScreenOrientation.ReverseLandscape; //changed from Landscape - return ScreenOrientation.Landscape; //changed from ReverseLandscape - } - } - else if (Math.Abs(Y) > Math.Abs(Z)) - { - if (Y > 0) - return ScreenOrientation.ReversePortrait; //changed from Portrait - return ScreenOrientation.Portrait; // changed from ReversePortrait - } - - if (Z > 0) - return ScreenOrientation.FaceUp; //this is different to HTC - return ScreenOrientation.FaceDown; //this is different to HTC - } - } - - -When you take a look at the vectors when you move the device slow and fast, you will see the xyz values changing and -if you add the absolute length over the time, you will get a cumulated 'force'. - -[image vectors-analysis.gif] - diff --git a/SensorScan5/doc/vectors-analysis.gif b/SensorScan5/doc/vectors-analysis.gif deleted file mode 100644 index c6d2ac8..0000000 Binary files a/SensorScan5/doc/vectors-analysis.gif and /dev/null differ diff --git a/SensorScan5/doc/vectors.gif b/SensorScan5/doc/vectors.gif deleted file mode 100644 index 540f329..0000000 Binary files a/SensorScan5/doc/vectors.gif and /dev/null differ diff --git a/SensorScan5/perfChartClass/Properties/AssemblyInfo.cs b/SensorScan5/perfChartClass/Properties/AssemblyInfo.cs deleted file mode 100644 index 3d8e5b2..0000000 --- a/SensorScan5/perfChartClass/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("perfChartClass")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec")] -[assembly: AssemblyProduct("perfChartClass")] -[assembly: AssemblyCopyright("Copyright © Intermec 2010")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("2695c1c3-9912-46d2-bb9d-939a8d6fdeab")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - diff --git a/SensorScan5/perfChartClass/Properties/Resources.Designer.cs b/SensorScan5/perfChartClass/Properties/Resources.Designer.cs deleted file mode 100644 index 55bd320..0000000 --- a/SensorScan5/perfChartClass/Properties/Resources.Designer.cs +++ /dev/null @@ -1,64 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -<<<<<<< .mine -// Runtime Version:2.0.50727.5466 -======= -// Runtime Version:2.0.50727.3634 ->>>>>>> .r143 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace perfChartClass.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("perfChartClass.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/SensorScan5/perfChartClass/Properties/Resources.resx b/SensorScan5/perfChartClass/Properties/Resources.resx deleted file mode 100644 index 451318b..0000000 --- a/SensorScan5/perfChartClass/Properties/Resources.resx +++ /dev/null @@ -1,105 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 diff --git a/SensorScan5/perfChartClass/perfChart/PerfChart.cs b/SensorScan5/perfChartClass/perfChart/PerfChart.cs deleted file mode 100644 index c5033ec..0000000 --- a/SensorScan5/perfChartClass/perfChart/PerfChart.cs +++ /dev/null @@ -1,494 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Text; -using System.Windows.Forms; -using System.Drawing.Drawing2D; - -namespace SpPerfChart -{ - /// - /// Scale mode for value aspect ratio - /// - public enum ScaleMode - { - /// - /// Absolute Scale Mode: Values from 0 to 100 are accepted and displayed - /// - Absolute, - /// - /// Relative Scale Mode: All values are allowed and displayed in a proper relation - /// - Relative - } - - - /// - /// Chart Refresh Mode Timer Control Mode - /// - public enum TimerMode - { - /// - /// Chart is refreshed when a value is added - /// - Disabled, - /// - /// Chart is refreshed every TimerInterval milliseconds, adding all values - /// in the queue to the chart. If there are no values in the queue, a 0 (zero) is added - /// - Simple, - /// - /// Chart is refreshed every TimerInterval milliseconds, adding an average of - /// all values in the queue to the chart. If there are no values in the queue, - /// 0 (zero) is added - /// - SynchronizedAverage, - /// - /// Chart is refreshed every TimerInterval milliseconds, adding the sum of - /// all values in the queue to the chart. If there are no values in the queue, - /// 0 (zero) is added - /// - SynchronizedSum - } - - - public partial class PerfChart : UserControl - { - #region *** Constants *** - - // Keep only a maximum MAX_VALUE_COUNT amount of values; This will allow - private const int MAX_VALUE_COUNT = 512; - // Draw a background grid with a fixed line spacing - private const int GRID_SPACING = 16; - - #endregion - - - #region *** Member Variables *** - - // Amount of currently visible values (calculated from control width and value spacing) - private int visibleValues = 0; - // Horizontal value space in Pixels - private int valueSpacing = 5; - // The currently highest displayed value, required for Relative Scale Mode - private decimal currentMaxValue = 0; - - // The currently highest displayed value, required for Relative Scale Mode - private decimal _currentValue = 0; - - // Offset value for the scrolling grid - private int gridScrollOffset = 0; - // The current average value - private decimal averageValue = 0; - // Border Style - //HGO private Border3DStyle b3dstyle = Border3DStyle.Sunken; - // Scale mode for value aspect ratio - private ScaleMode scaleMode = ScaleMode.Absolute; - // Timer Mode - private TimerMode timerMode; - // List of stored values - private List drawValues = new List(MAX_VALUE_COUNT); - // Value queue for Timer Modes - private Queue waitingValues = new Queue(); - // Style and Design - private PerfChartStyle perfChartStyle; - - #endregion - - - #region *** Constructors *** - - public PerfChart() { - InitializeComponent(); - - // Initialize Variables - perfChartStyle = new PerfChartStyle(); - - // Set Optimized Double Buffer to reduce flickering -//HGO this.SetStyle(ControlStyles.UserPaint, true); -//HGO this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); -//HGO this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); - - // Redraw when resized -//HGO this.SetStyle(ControlStyles.ResizeRedraw, true); - -//HGO this.Font = SystemInformation.MenuFont; - } - - #endregion - - - #region *** Properties *** - -//HGO [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Category("Appearance"), Description("Appearance and Style")] - public PerfChartStyle _PerfChartStyle { - get { return perfChartStyle; } - set { perfChartStyle = value; } - } - - - //[DefaultValue(typeof(Border3DStyle), "Sunken"), Description("BorderStyle"), Category("Appearance")] - //new public Border3DStyle BorderStyle { - // get { - // return b3dstyle; - // } - // set { - // b3dstyle = value; - // Invalidate(); - // } - //} - - public ScaleMode _ScaleMode { - get { return scaleMode; } - set { scaleMode = value; } - } - - /// - /// set the maximal value for input data - /// - private decimal _mMaxDecimal = 100M; - public decimal _maxDecimal - { - get { return _mMaxDecimal; } - set { _mMaxDecimal = value; } - } - - private bool _mSymmetricDisplay = true; - /// - /// use a symmetric display with negative and postive values - /// - public bool _SymmetricDisplay - { - get { return _mSymmetricDisplay; } - set { _mSymmetricDisplay = value; } - } - public TimerMode _TimerMode { - get { return timerMode; } - set { - if (value == TimerMode.Disabled) { - // Stop and append only when changed - if (timerMode != TimerMode.Disabled) { - timerMode = value; - - tmrRefresh.Enabled = false;// Stop(); - // If there are any values in the queue, append them - ChartAppendFromQueue(); - } - } - else { - timerMode = value; - tmrRefresh.Enabled = true;//.Start(); - } - } - } - - public int _TimerInterval { - get { return tmrRefresh.Interval; } - set { - if (value < 15) - throw new ArgumentOutOfRangeException("tmrRefresh", "The Timer interval must be greater then 15"); - else - tmrRefresh.Interval = value; - } - } - - #endregion - - - #region *** Public Methods *** - - /// - /// Clears the whole chart - /// - public void _Clear() { - drawValues.Clear(); - Invalidate(); - } - - - /// - /// Adds a value to the Chart Line - /// - /// progress value - public void _AddValue(decimal value) { - if (scaleMode == ScaleMode.Absolute && value > _mMaxDecimal) - throw new Exception(String.Format("Values greater then "+_mMaxDecimal+" not allowed in ScaleMode: Absolute ({0})", value)); - - _currentValue=value; - - switch (timerMode) { - case TimerMode.Disabled: - ChartAppend(value); - Invalidate(); - break; - case TimerMode.Simple: - case TimerMode.SynchronizedAverage: - case TimerMode.SynchronizedSum: - // For all Timer Modes, the Values are stored in the Queue - AddValueToQueue(value); - break; - default: - throw new Exception(String.Format("Unsupported TimerMode: {0}", timerMode)); - } - } - - #endregion - - - #region *** Private Methods: Common *** - - /// - /// Add value to the queue for a timed refresh - /// - /// - private void AddValueToQueue(decimal value) { - waitingValues.Enqueue(value); - } - - - /// - /// Appends value to the chart (without redrawing) - /// - /// performance value - private void ChartAppend(decimal value) { - // Insert at first position; Negative values are flatten to 0 (zero) - drawValues.Insert(0, value);//Math.Max(value, 0)); - - // Remove last item if maximum value count is reached - if (drawValues.Count > MAX_VALUE_COUNT) - drawValues.RemoveAt(MAX_VALUE_COUNT); - - // Calculate horizontal grid offset for "scrolling" effect - gridScrollOffset += valueSpacing; - if (gridScrollOffset > GRID_SPACING) - gridScrollOffset = gridScrollOffset % GRID_SPACING; - } - - - /// - /// Appends Values from queue - /// - private void ChartAppendFromQueue() { - // Proceed only if there are values at all - if (waitingValues.Count > 0) { - if (timerMode == TimerMode.Simple) { - while (waitingValues.Count > 0) - ChartAppend(waitingValues.Dequeue()); - } - else if (timerMode == TimerMode.SynchronizedAverage || - timerMode == TimerMode.SynchronizedSum) { - // appendValue variable is used for calculating the average or sum value - decimal appendValue = Decimal.Zero; - int valueCount = waitingValues.Count; - - while (waitingValues.Count > 0) - appendValue += waitingValues.Dequeue(); - - // Calculate Average value in SynchronizedAverage Mode - if (timerMode == TimerMode.SynchronizedAverage) - appendValue = appendValue / (decimal)valueCount; - - // Finally append the value - ChartAppend(appendValue); - } - } - else { - // Always add 0 (Zero) if there are no values in the queue - ChartAppend(Decimal.Zero); - } - - // Refresh the Chart - Invalidate(); - } - - /// - /// Calculates the vertical Position of a value in relation the chart size, - /// Scale Mode and, if ScaleMode is Relative, to the current maximum value - /// - /// performance value - /// vertical Point position in Pixels - private int CalcVerticalPosition(decimal value) { - decimal result = Decimal.Zero; - if (scaleMode == ScaleMode.Absolute) - result = value * this.Height / this._mMaxDecimal; - else if (scaleMode == ScaleMode.Relative) - { - if (_mSymmetricDisplay) - { //posY=(value * (currMax*2/height)) + (height/2); - // - if (currentMaxValue == 0) - currentMaxValue = 1; - result = value * (this.Height/(currentMaxValue*2))+this.Height/2; - //result = (Math.Abs(value) * (currentMaxValue * 2 / this.Height)) + (this.Height / 2); - } - else - result = (currentMaxValue > 0) ? (value * this.Height / currentMaxValue) : 0; - } - result = this.Height - result; - return Convert.ToInt32(Math.Round(result)); - } - - - /// - /// Returns the currently highest (displayed) value, for Relative ScaleMode - /// - /// - private decimal GetHighestValueForRelativeMode() { - decimal maxValue = 0; - - for (int i = 0; i < visibleValues; i++) { - // Set if higher then previous max value - if (_mSymmetricDisplay) - { - if (Math.Abs(drawValues[i]) > maxValue) - maxValue = Math.Abs(drawValues[i]); - } - else - { - if (drawValues[i] > maxValue) - maxValue = drawValues[i]; - } - } - - return maxValue; - } - - #endregion - - - #region *** Private Methods: Drawing *** - - /// - /// Draws the chart (w/o background or grid, but with border) to the Graphics canvas - /// - /// Graphics - private void DrawChart(Graphics g) { - visibleValues = Math.Min(this.Width / valueSpacing, drawValues.Count); - - if (scaleMode == ScaleMode.Relative) - { - currentMaxValue = GetHighestValueForRelativeMode(); - } - // Dirty little "trick": initialize the first previous Point outside the bounds - Point previousPoint = new Point(Width + valueSpacing, Height); - Point currentPoint = new Point(); - - // Only draw average line when possible (visibleValues) and needed (style setting) - if (visibleValues > 0 && perfChartStyle.ShowAverageLine) { - averageValue = 0; - DrawAverageLine(g); - } - - // Connect all visible values with lines - for (int i = 0; i < visibleValues; i++) { - currentPoint.X = previousPoint.X - valueSpacing; - currentPoint.Y = CalcVerticalPosition(drawValues[i]); - - // Actually draw the line - g.DrawLine(perfChartStyle.ChartLinePen.Pen, - previousPoint.X, previousPoint.Y, - currentPoint.X, currentPoint.Y); - - previousPoint = currentPoint; - } - - // Draw current relative maximum value string - if (scaleMode == ScaleMode.Relative) { - if(_mSymmetricDisplay){ - - SolidBrush sb = new SolidBrush(perfChartStyle.ChartLinePen.Color); - g.DrawString(_currentValue.ToString("####.####"), this.Font, sb, 4.0f, 2.0f); - } - else{ - SolidBrush sb = new SolidBrush(perfChartStyle.ChartLinePen.Color); - g.DrawString(currentMaxValue.ToString(), this.Font, sb, 4.0f, 2.0f); - } - } - - // Draw Border on top -//HGO ControlPaint.DrawBorder3D(g, 0, 0, Width, Height, b3dstyle); - } - - - private void DrawAverageLine(Graphics g) { - for (int i = 0; i < visibleValues; i++) - averageValue += drawValues[i]; - - averageValue = averageValue / visibleValues; - - int verticalPosition = CalcVerticalPosition(averageValue); - g.DrawLine(perfChartStyle.AvgLinePen.Pen, 0, verticalPosition, Width, verticalPosition); - } - - /// - /// Draws the background gradient and the grid into Graphics - /// - /// Graphic - private void DrawBackgroundAndGrid(Graphics g) { - // Draw the background Gradient rectangle - Rectangle baseRectangle = new Rectangle(0, 0, this.Width, this.Height); -//HGO using ( - Brush gradientBrush = new System.Drawing.SolidBrush(Color.LightGreen); //LinearGradientBrush(baseRectangle, perfChartStyle.BackgroundColorTop, perfChartStyle.BackgroundColorBottom, LinearGradientMode.Vertical)) { - g.FillRectangle(gradientBrush, baseRectangle); -//HGO } - - // Draw all visible, vertical gridlines (if wanted) - if (perfChartStyle.ShowVerticalGridLines) { - for (int i = Width - gridScrollOffset; i >= 0; i -= GRID_SPACING) { - g.DrawLine(perfChartStyle.VerticalGridPen.Pen, i, 0, i, Height); - } - } - - // Draw all visible, horizontal gridlines (if wanted) - if (perfChartStyle.ShowHorizontalGridLines) { - for (int i = 0; i < Height; i += GRID_SPACING) { - g.DrawLine(perfChartStyle.HorizontalGridPen.Pen, 0, i, Width, i); - } - } - } - - #endregion - - - #region *** Overrides *** - - /// Override OnPaint method - protected override void OnPaint(PaintEventArgs e) { - base.OnPaint(e); - - // Enable AntiAliasing, if needed - //if (perfChartStyle.AntiAliasing) - // e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; - - DrawBackgroundAndGrid(e.Graphics); - DrawChart(e.Graphics); - } - - protected override void OnResize(EventArgs e) { - base.OnResize(e); - - Invalidate(); - } - - #endregion - - - #region *** Event Handlers *** - - private void colorSet_ColorSetChanged(object sender, EventArgs e) { - //Refresh Chart on Resize - Invalidate(); - } - - private void tmrRefresh_Tick(object sender, EventArgs e) { - // Don't execute event if running in design time -//HGO if (this.DesignMode) return; - - ChartAppendFromQueue(); - } - - #endregion - } -} diff --git a/SensorScan5/perfChartClass/perfChart/PerfChart.designer.cs b/SensorScan5/perfChartClass/perfChart/PerfChart.designer.cs deleted file mode 100644 index 023c6d3..0000000 --- a/SensorScan5/perfChartClass/perfChart/PerfChart.designer.cs +++ /dev/null @@ -1,50 +0,0 @@ -namespace SpPerfChart -{ - partial class PerfChart - { - /// - /// Erforderliche Designervariable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Verwendete Ressourcen bereinigen. - /// - /// True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False. - protected override void Dispose(bool disposing) { - if (disposing && (components != null)) { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Vom Komponenten-Designer generierter Code - - /// - /// Erforderliche Methode für die Designerunterstützung. - /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. - /// - private void InitializeComponent() { - this.components = new System.ComponentModel.Container(); - this.tmrRefresh = new System.Windows.Forms.Timer();//HGO (this.components); - this.SuspendLayout(); - // - // tmrRefresh - // - this.tmrRefresh.Tick += new System.EventHandler(this.tmrRefresh_Tick); - // - // PerfChart - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.Name = "PerfChart"; - this.Size = new System.Drawing.Size(235, 87); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Timer tmrRefresh; - } -} diff --git a/SensorScan5/perfChartClass/perfChart/PerfChartStyle.cs b/SensorScan5/perfChartClass/perfChart/PerfChartStyle.cs deleted file mode 100644 index 5ab0308..0000000 --- a/SensorScan5/perfChartClass/perfChart/PerfChartStyle.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.ComponentModel; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; -using System.Drawing; - -namespace SpPerfChart -{ -// [TypeConverterAttribute(typeof(ExpandableObjectConverter))] - public class PerfChartStyle - { - private ChartPen verticalGridPen; - private ChartPen horizontalGridPen; - private ChartPen avgLinePen; - private ChartPen chartLinePen; - - private Color backgroundColorTop = Color.DarkGreen; - private Color backgroundColorBottom = Color.DarkGreen; - - private bool showVerticalGridLines = true; - private bool showHorizontalGridLines = true; - private bool showAverageLine = true; - private bool antiAliasing = true; - - public PerfChartStyle() { - verticalGridPen = new ChartPen(); - horizontalGridPen = new ChartPen(); - avgLinePen = new ChartPen(); - chartLinePen = new ChartPen(); - } - - public bool ShowVerticalGridLines { - get { return showVerticalGridLines; } - set { showVerticalGridLines = value; } - } - - public bool ShowHorizontalGridLines { - get { return showHorizontalGridLines; } - set { showHorizontalGridLines = value; } - } - - public bool ShowAverageLine { - get { return showAverageLine; } - set { showAverageLine = value; } - } - - public ChartPen VerticalGridPen { - get { return verticalGridPen; } - set { verticalGridPen = value; } - } - - public ChartPen HorizontalGridPen { - get { return horizontalGridPen; } - set { horizontalGridPen = value; } - } - - public ChartPen AvgLinePen { - get { return avgLinePen; } - set { avgLinePen = value; } - } - - public ChartPen ChartLinePen { - get { return chartLinePen; } - set { chartLinePen = value; } - } - - public bool AntiAliasing { - get { return antiAliasing; } - set { antiAliasing = value; } - } - - public Color BackgroundColorTop { - get { return backgroundColorTop; } - set { backgroundColorTop = value; } - } - - public Color BackgroundColorBottom { - get { return backgroundColorBottom; } - set { backgroundColorBottom = value; } - } - } - -//HGO [TypeConverterAttribute(typeof(ExpandableObjectConverter))] - public class ChartPen - { - private Pen pen; - - public ChartPen() { - pen = new Pen(Color.Black); - } - - public Color Color { - get { return pen.Color; } - set { pen.Color = value; } - } - - public System.Drawing.Drawing2D.DashStyle DashStyle { - get { return pen.DashStyle; } - set { pen.DashStyle = value; } - } - - public float Width { - get { return pen.Width; } - set { pen.Width = value; } - } - -//HGO [Browsable(false)] - [EditorBrowsable(EditorBrowsableState.Never)] - public Pen Pen { - get { return pen; } - } - } -} diff --git a/SensorScan5/perfChartClass/perfChartClass.csproj b/SensorScan5/perfChartClass/perfChartClass.csproj deleted file mode 100644 index d1dc396..0000000 --- a/SensorScan5/perfChartClass/perfChartClass.csproj +++ /dev/null @@ -1,109 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {31045968-12E1-457C-AD26-F540F4F1822B} - Library - Properties - perfChartClass - perfChartClass - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - b2c48bd2-963d-4549-9169-1fa021dce484 - 5.02 - perfChartClass - v2.0 - - - - -<<<<<<< .mine - - - - - 2.0 - Windows Mobile 6 Professional SDK - %25CSIDL_PROGRAM_FILES%25 -======= - - - - - 2.0 - Windows Mobile 6 Professional SDK ->>>>>>> .r143 - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - UserControl - - - PerfChart.cs - - - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - True - - - - - - - - - - - - - - \ No newline at end of file diff --git a/SensorScan5/perfChartClass/perfChartClass.csproj.user b/SensorScan5/perfChartClass/perfChartClass.csproj.user deleted file mode 100644 index d57a6ce..0000000 --- a/SensorScan5/perfChartClass/perfChartClass.csproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - b2c48bd2-963d-4549-9169-1fa021dce484d6518ffb-710f-11d3-99f2-00105a0df099 - false - - \ No newline at end of file diff --git a/TimeZoneSet/ReadMe.txt b/TimeZoneSet/ReadMe.txt deleted file mode 100644 index 7781644..0000000 --- a/TimeZoneSet/ReadMe.txt +++ /dev/null @@ -1,17 +0,0 @@ -======================================================================== - Windows CE APPLICATION : TimeZoneSet -======================================================================== - -the app only supports one argument, a positive or negative number specifying -the GMT offset in inverted notation. -If you want to set GMT+1 you need to run - -TimeZoneSet -1 - -You cannot specify a city or other informations like DST on/off. This would -require another tool. - -TimeZoneSet always dumps a list of known cities and timezones to -\TZ-cities.TXT - -///////////////////////////////////////////////////////////////////////////// diff --git a/TimeZoneSet/StdAfx.cpp b/TimeZoneSet/StdAfx.cpp deleted file mode 100644 index 5731a5f..0000000 --- a/TimeZoneSet/StdAfx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// TimeZoneSet.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/TimeZoneSet/StdAfx.h b/TimeZoneSet/StdAfx.h deleted file mode 100644 index 9d98dc8..0000000 --- a/TimeZoneSet/StdAfx.h +++ /dev/null @@ -1,25 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#if !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_) -#define AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include - -// Local Header Files - -// TODO: reference additional headers your program requires here - -//{{AFX_INSERT_LOCATION}} -// Microsoft eMbedded Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_) diff --git a/TimeZoneSet/TimeZoneSet.cpp b/TimeZoneSet/TimeZoneSet.cpp deleted file mode 100644 index 0dbaf9e..0000000 --- a/TimeZoneSet/TimeZoneSet.cpp +++ /dev/null @@ -1,322 +0,0 @@ -// TimeZoneSet.cpp : Defines the entry point for the application. -// - -#include "stdafx.h" - -typedef void (*INITCITYDB)(void); -typedef void (*UNINITCITYDB)(void); -typedef void (*LOADTZDATA)(void); -typedef void (*FREETZDATA)(void); -typedef int (*GETNUMZONES)(void); -typedef void * (*GETTZDATABYOFFSET)(int, int*); -typedef void * (*GETTZDATA)(int); - -struct TZData -{ - TCHAR *Name; - TCHAR *ShortName; - TCHAR *DSTName; - int GMTOffset; - int DSTOffset; -}; - -typedef struct tagTZREG { // 44 bytes - LONG Bias; // 4 bytes - LONG StandardBias; - LONG DaylightBias; - SYSTEMTIME StandardDate; // 8*2 bytes - SYSTEMTIME DaylightDate; -} TZREG; - -/* -typedef struct _SYSTEMTIME { - WORD wYear; - WORD wMonth; - WORD wDayOfWeek; - WORD wDay; - WORD wHour; - WORD wMinute; - WORD wSecond; - WORD wMilliseconds; -} SYSTEMTIME, *LPSYSTEMTIME; -*/ - /* - typedef struct _TIME_ZONE_INFORMATION { - LONG Bias; - WCHAR StandardName[ 32 ]; - SYSTEMTIME StandardDate; - LONG StandardBias; - WCHAR DaylightName[ 32 ]; - SYSTEMTIME DaylightDate; - LONG DaylightBias; - } TIME_ZONE_INFORMATION, *LPTIME_ZONE_INFORMATION; - 88,ff,ff,ff, - 45,00,2e,00,20,00,45,00,75,00,72,00,6f,00,70,00,65,00,20,00,53,00,74,00,61,00,6e,00,64,00,61,00,72,00,64,00,20,00,54,00,69,00,6d,00,65,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,09,00,00,00,05,00,01,00,00,00,00,00,00,00,00,00,00,00,45,00,2e,00,20,00,45,00,75,00,72,00,6f,00,70,00,65,00,20,00,44,00,61,00,79,00,6c,00,69,00,67,00,68,00,74,00,20,00,54,00,69,00,6d,00,65,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,03,00,00,00,05,00,00,00,00,00,00,00,00,00, - c4,ff,ff,ff - - */ - -void ShowError(LONG er) -{ - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - er, - 0, // Default language - (LPTSTR) &lpMsgBuf, - 0, - NULL - ); - TCHAR temp[MAX_PATH]; - wsprintf(temp, (LPTSTR)lpMsgBuf); - // Process any inserts in lpMsgBuf. - // ... - // Display the string. - DEBUGMSG(1, ((LPCTSTR)lpMsgBuf)); - // Free the buffer. - LocalFree( lpMsgBuf ); -} - -int getCityDB() -{ - TZData *pTZ = NULL; - int index; - - // load the library - HINSTANCE hLib = LoadLibrary(_T("CityDB.dll")); - if (hLib==NULL) - return -1; - // load the CityDB functions - INITCITYDB InitCityDB = (INITCITYDB)GetProcAddress( - hLib, _T("InitCityDb")); - UNINITCITYDB UninitCityDB = (UNINITCITYDB)GetProcAddress( - hLib, _T("UninitCityDb")); - LOADTZDATA ClockLoadAllTimeZoneData = (LOADTZDATA)GetProcAddress( - hLib, _T("ClockLoadAllTimeZoneData")); - FREETZDATA ClockFreeAllTimeZoneData = (FREETZDATA)GetProcAddress( - hLib, _T("ClockFreeAllTimeZoneData")); - GETNUMZONES ClockGetNumTimezones = (GETNUMZONES)GetProcAddress( - hLib, _T("ClockGetNumTimezones")); - GETTZDATABYOFFSET ClockGetTimeZoneDataByOffset = - (GETTZDATABYOFFSET)GetProcAddress(hLib, _T("ClockGetTimeZoneDataByOffset")); - GETTZDATA ClockGetTimeZoneData = (GETTZDATA)GetProcAddress( - hLib, _T("ClockGetTimeZoneData")); - - // Init the library - InitCityDB(); - - // load the TZ data - ClockLoadAllTimeZoneData(); - - // find out how many zones are defined - int zoneCount = ClockGetNumTimezones(); - - HANDLE hFile = CreateFile (TEXT("\\TZ-cities.TXT"), // Open Two.txt. - GENERIC_WRITE, // Open for writing - 0, // Do not share - NULL, // No security - OPEN_ALWAYS, // Open or create - FILE_ATTRIBUTE_NORMAL, // Normal file - NULL); // No template file - - if (hFile == INVALID_HANDLE_VALUE) - { - //wsprintf (szMsg, TEXT("Could not open TWO.TXT")); - CloseHandle (hFile); // Close the first file. - return -2; - } - char buff[4096]; - TCHAR wBuff[4096]; - DWORD numToWrit, numWritten; - - TIME_ZONE_INFORMATION tzi; - memset(&tzi, 0, sizeof(tzi)); - int ret=GetTimeZoneInformation(&tzi); - wsprintf(wBuff, L"===================TimeZoneInformation (API)==================\n"); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"Bias: %i\n", tzi.Bias ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightBias: %i\n", tzi.DaylightBias ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightDate: %i\n", tzi.DaylightDate ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightName: %s\n", tzi.DaylightName ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardBias: %i\n", tzi.StandardBias ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardBias: %i\n", tzi.StandardDate ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightName: %s\n", tzi.StandardName); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - HKEY phKey; - TIME_ZONE_INFORMATION *tzi2; - //memset(&tzi2, 0, sizeof(TIME_ZONE_INFORMATION)); - byte *data; - data = (byte *)malloc(4096); - DWORD count = 4096; - DWORD type; //=REG_BINARY; - - wsprintf(wBuff, L"===================TimeZoneInformation (reg)==================\n"); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - if (RegOpenKeyEx(HKEY_LOCAL_MACHINE , L"TIME", 0, 0, &phKey) == ERROR_SUCCESS) - { - int ret = RegQueryValueEx(phKey, L"TimeZoneInformation", NULL, &type, data, &count); - if (ret == ERROR_SUCCESS) - { - //TIME_ZONE_INFORMATION - tzi2 = (TIME_ZONE_INFORMATION *) data; - - wsprintf(wBuff, L"Bias: %i\n", tzi2->Bias ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightBias: %i\n", tzi2->DaylightBias); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightDate: %i\n", tzi2->DaylightDate); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightName: %s\n", tzi2->DaylightName); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardBias: %i\n", tzi2->StandardBias); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardDate: %i\n", tzi2->StandardDate); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardName: %i\n", tzi2->StandardName); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - } - else - ShowError(ret); - } - free (data); - - wsprintf(wBuff, L"=================CityDB====================\n"); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - // interate through them all - for(int zone = 0 ; zone < zoneCount ; zone++) - { - // these are pointers to a timezone data struct - pTZ = (TZData*)ClockGetTimeZoneDataByOffset(zone, &index); - - wsprintf(wBuff, L"index: %i\n", index ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tshort name: %s\n", pTZ->ShortName ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tname: %s\n", pTZ->Name ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tGMT offset: %i\n", pTZ->GMTOffset ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tdst name: %s\n", pTZ->DSTName ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tDST offset: %i\n", pTZ->DSTOffset ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - } - CloseHandle(hFile); - - // unload the TZ data - ClockFreeAllTimeZoneData(); - - // uninit the library - UninitCityDB(); - - return 0; -} - -int WINAPI WinMain( HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - // TODO: Place code here. - - byte lSize=sizeof(LONG); - - getCityDB(); - TIME_ZONE_INFORMATION tzi; - memset(&tzi, 0, sizeof(tzi)); - - int ret=GetTimeZoneInformation(&tzi); - switch (ret) - { - case TIME_ZONE_ID_UNKNOWN: - break; - case TIME_ZONE_ID_STANDARD: - break; - case TIME_ZONE_ID_DAYLIGHT: - break; - default: - //error - break; - } - - //The bias is the difference, in minutes, between UTC and local time - //so to get GMT+1 you have to specify -1 atoi - int hourOffset = 0; - int i=0; - - if (wcslen(lpCmdLine)>0) - { - i = _ttoi(lpCmdLine); - if (i!=0) - hourOffset=i; - } - - TCHAR s[32]; - tzi.Bias = hourOffset*60; - - wsprintf(s, L"GMT DST"); - wcscpy(tzi.DaylightName, L"GMT DST"); - - wsprintf(s, L"GMT"); - wcscpy(tzi.StandardName, L"GMT"); - - ret=SetTimeZoneInformation(&tzi); - if (ret==0) - return ret; //error - - //TZREG - return 0; -} - diff --git a/TimeZoneSet/TimeZoneSet.rc b/TimeZoneSet/TimeZoneSet.rc deleted file mode 100644 index a852f8f..0000000 --- a/TimeZoneSet/TimeZoneSet.rc +++ /dev/null @@ -1,58 +0,0 @@ -//Microsoft eMbedded Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "newres.h" -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -#ifdef _WIN32 -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) -#endif - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""newres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED diff --git a/TimeZoneSet/TimeZoneSet.sln b/TimeZoneSet/TimeZoneSet.sln deleted file mode 100644 index 43a7160..0000000 --- a/TimeZoneSet/TimeZoneSet.sln +++ /dev/null @@ -1,120 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TimeZoneSet", "TimeZoneSet.vcproj", "{899F983F-F9BB-432D-8A83-4F719BB7B4D8}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DST_set", "..\DST_set\DST_set.vcproj", "{BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|iCE-Premium (ARMV4I) = Debug|iCE-Premium (ARMV4I) - Debug|Pocket PC 2003 (ARMV4) = Debug|Pocket PC 2003 (ARMV4) - Debug|Smartphone 2003 (ARMV4) = Debug|Smartphone 2003 (ARMV4) - Debug|STANDARDSDK_420 (ARMV4I) = Debug|STANDARDSDK_420 (ARMV4I) - Debug|STANDARDSDK_500 (ARMV4I) = Debug|STANDARDSDK_500 (ARMV4I) - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - Debug|Windows Mobile 6 Professional SDK (ARMV4I) = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - Debug|Windows Mobile 6 Standard SDK (ARMV4I) = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) = Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - Release|iCE-Premium (ARMV4I) = Release|iCE-Premium (ARMV4I) - Release|Pocket PC 2003 (ARMV4) = Release|Pocket PC 2003 (ARMV4) - Release|Smartphone 2003 (ARMV4) = Release|Smartphone 2003 (ARMV4) - Release|STANDARDSDK_420 (ARMV4I) = Release|STANDARDSDK_420 (ARMV4I) - Release|STANDARDSDK_500 (ARMV4I) = Release|STANDARDSDK_500 (ARMV4I) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - Release|Windows Mobile 6 Professional SDK (ARMV4I) = Release|Windows Mobile 6 Professional SDK (ARMV4I) - Release|Windows Mobile 6 Standard SDK (ARMV4I) = Release|Windows Mobile 6 Standard SDK (ARMV4I) - Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) = Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|iCE-Premium (ARMV4I).ActiveCfg = Debug|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|iCE-Premium (ARMV4I).Build.0 = Debug|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|iCE-Premium (ARMV4I).Deploy.0 = Debug|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Pocket PC 2003 (ARMV4).ActiveCfg = Debug|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Pocket PC 2003 (ARMV4).Build.0 = Debug|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Pocket PC 2003 (ARMV4).Deploy.0 = Debug|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Smartphone 2003 (ARMV4).ActiveCfg = Debug|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Smartphone 2003 (ARMV4).Build.0 = Debug|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Smartphone 2003 (ARMV4).Deploy.0 = Debug|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_420 (ARMV4I).ActiveCfg = Debug|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_420 (ARMV4I).Build.0 = Debug|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_420 (ARMV4I).Deploy.0 = Debug|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_500 (ARMV4I).ActiveCfg = Debug|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_500 (ARMV4I).Build.0 = Debug|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_500 (ARMV4I).Deploy.0 = Debug|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I).Build.0 = Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|iCE-Premium (ARMV4I).ActiveCfg = Release|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|iCE-Premium (ARMV4I).Build.0 = Release|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|iCE-Premium (ARMV4I).Deploy.0 = Release|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Pocket PC 2003 (ARMV4).ActiveCfg = Release|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Pocket PC 2003 (ARMV4).Build.0 = Release|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Pocket PC 2003 (ARMV4).Deploy.0 = Release|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Smartphone 2003 (ARMV4).ActiveCfg = Release|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Smartphone 2003 (ARMV4).Build.0 = Release|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Smartphone 2003 (ARMV4).Deploy.0 = Release|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_420 (ARMV4I).ActiveCfg = Release|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_420 (ARMV4I).Build.0 = Release|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_420 (ARMV4I).Deploy.0 = Release|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_500 (ARMV4I).ActiveCfg = Release|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_500 (ARMV4I).Build.0 = Release|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_500 (ARMV4I).Deploy.0 = Release|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I).ActiveCfg = Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I).Build.0 = Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I).Deploy.0 = Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|iCE-Premium (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|Pocket PC 2003 (ARMV4).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|Smartphone 2003 (ARMV4).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|STANDARDSDK_420 (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|STANDARDSDK_500 (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|iCE-Premium (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|Pocket PC 2003 (ARMV4).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|Smartphone 2003 (ARMV4).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|STANDARDSDK_420 (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|STANDARDSDK_500 (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {BAA65078-57F0-4D9D-97A3-3473CEC2D6EB}.Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/TimeZoneSet/TimeZoneSet.vcproj b/TimeZoneSet/TimeZoneSet.vcproj deleted file mode 100644 index 457b07c..0000000 --- a/TimeZoneSet/TimeZoneSet.vcproj +++ /dev/null @@ -1,2396 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/TimeZoneSet/newres.h b/TimeZoneSet/newres.h deleted file mode 100644 index 89e6e23..0000000 --- a/TimeZoneSet/newres.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef __NEWRES_H__ -#define __NEWRES_H__ - -#if !defined(UNDER_CE) - #define UNDER_CE _WIN32_WCE -#endif - -#if defined(_WIN32_WCE) - #if !defined(WCEOLE_ENABLE_DIALOGEX) - #define DIALOGEX DIALOG DISCARDABLE - #endif - #include - #define SHMENUBAR RCDATA - #if defined(WIN32_PLATFORM_PSPC) && (_WIN32_WCE >= 300) - #include - #else - #define I_IMAGENONE (-2) - #define NOMENU 0xFFFF - #define IDS_SHNEW 1 - - #define IDM_SHAREDNEW 10 - #define IDM_SHAREDNEWDEFAULT 11 - #endif -#endif // _WIN32_WCE - - -#ifdef RC_INVOKED -#ifndef _INC_WINDOWS -#define _INC_WINDOWS - #include "winuser.h" // extract from windows header -#endif -#endif - -#ifdef IDC_STATIC -#undef IDC_STATIC -#endif -#define IDC_STATIC (-1) - -#endif //__NEWRES_H__ diff --git a/TimeZoneSet/resource.h b/TimeZoneSet/resource.h deleted file mode 100644 index 902d6ea..0000000 --- a/TimeZoneSet/resource.h +++ /dev/null @@ -1,4 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft eMbedded Visual C++ generated include file. -// Used by TIMEZONESET.RC -// diff --git a/agrcs/agr.zip b/agrcs/agr.zip deleted file mode 100644 index 8437579..0000000 Binary files a/agrcs/agr.zip and /dev/null differ diff --git a/agrcs/clustering.cs b/agrcs/clustering.cs deleted file mode 100644 index ca5fd28..0000000 --- a/agrcs/clustering.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -namespace AGR -{ - public class cClustering - { - public cClustering () - { - - } - } -} - diff --git a/agrcs/movement.cs b/agrcs/movement.cs deleted file mode 100644 index dcc4259..0000000 --- a/agrcs/movement.cs +++ /dev/null @@ -1,288 +0,0 @@ -using System; -namespace AGR -{ - public class cVector3int - { -/* friend class ::cTestVector3int; - - cVector3int(); - cVector3int( const cVector3int& original ); - cVector3int( int x, int y, int z); - - // Overloaded operators - cVector3int operator+=(const cVector3int &rhs); - cVector3int& operator-=(const cVector3int &rhs); - cVector3int& operator*=(const int &rhs); - cVector3int& operator/=(const int &rhs); - const cVector3int operator+(const cVector3int &other) const; - const cVector3int operator-(const cVector3int &other) const; - const cVector3int operator*(const int &value) const; - const cVector3int operator/(const int &value) const; - bool operator==(const cVector3int &rhs) const; - bool operator!=(const cVector3int &rhs) const; - - - // other vector feature - void copy( const cVector3int& original ); - bool copyTo( cVector3int* destination ) const; -*/ - private int _x; /**< X Vector Component */ - public int x{ - get{return _x;} - set{_x=value;} - } - private int _y; /**< Y Vector Component */ - public int y{ - get{return _y;} - set{_y=value;} - } - private int _z; /**< Z Vector Component */ - public int z{ - get{return _z;} - set{_z=value;} - } - - /*! Constructor with arguments - */ - public cVector3int(int x, int y, int z){ - this._x=x; - this._y=y; - this._z=z; - } - - /*! Copy constructor - */ - public cVector3int( cVector3int original) { - //: x(original.x), y(original.y), z(original.z) - this._x=original.x; - this.y=original.y; - this.z=original.z; - - } - - /*! Overloaded operator += - */ - public cVector3int Add( cVector3int rhs ) - { - this._x += rhs.x; - this._y += rhs.y; - this._z += rhs.z; - return this; - } - - } // class cVector3int - public struct iVector{ - public int x; - public int y; - public int z; - public iVector(int a, int b, int c){ - this.x=a; - this.y=b; - this.z=c; - } - public static iVector operator + (iVector iV1, iVector iV2){ - return new iVector(iV1.x+iV2.x, iV1.y+iV2.y, iV1.z+iV2.z); - } - public static iVector operator - (iVector iV1, iVector iV2){ - return new iVector(iV1.x-iV2.x, iV1.y-iV2.y, iV1.z-iV2.z); - } - public static iVector operator * (iVector iV1, iVector iV2){ - return new iVector(iV1.x*iV2.x, iV1.y*iV2.y, iV1.z*iV2.z); - } - public static iVector operator / (iVector iV1, iVector iV2){ - return new iVector(iV1.x/iV2.x, iV1.y/iV2.y, iV1.z/iV2.z); - } - public static bool operator == (iVector iV1, iVector iV2){ - return (iV1.x==iV2.x && iV1.y==iV2.y && iV1.z==iV2.z); - } -/* public static bool operator Equals(iVector iV1, iVector iV2){ - return (iV1.x==iV2.x && iV1.y==iV2.y && iV1.z==iV2.z); - } -*/ - public static bool operator != (iVector iV1, iVector iV2){ - return (iV1.x!=iV2.x || iV1.y != iV2.y || iV1.z!=iV2.z); - } - public iVector copy(iVector iv){ - return new iVector(iv.x,iv.y,iv.z); - } - public bool copyTo(iVector ivDest){ - ivDest.x=this.x; - ivDest.y=this.y; - ivDest.z=this.z; - return true; - } - public float getSize(){ - return (float)System.Math.Sqrt(Math.Pow(this.x,2)+Math.Pow(this.y,2)+Math.Pow(this.z,2)); - } - } - public class cMovement{ - public iVector[] m_buffer; - public int m_size; - cMovement(){ - m_buffer=new iVector[0]; - m_size=0; - } - public cMovement(cMovement original){ - this.m_size=original.m_size; - if(m_size>0){ - this.m_buffer=new iVector[m_size]; - for(int i=0;i0){ - this.m_buffer=new iVector[m_size]; - for(int i=0;i0) - this.clear(); - if(inMove.Length==0) - return false; - // create buffer - this.m_size=inMove.Length; - this.m_buffer=new iVector[this.m_size]; - iVector[] iterBuffer=this.m_buffer; - // copy data - for(int i=0;i0 ) { - m_buffer=new iVector[0]; - } - - // create buffer - m_size = size; - m_buffer = new iVector[ m_size ]; - if( vectorArray.Length>0 ) { - m_buffer=vectorArray; - m_size=m_buffer.Length; - } - - return true; - } - - /*! Change the size of a movement - * \note OutputVector buffer will be created automatically if needed - * \note The function have better results if input movements are positive (see note in the code) - * \return Success - */ - bool changeVectorSize( cMovement inputMovement, /**< Input movement used as model */ - int newSize, /**< Size of the new vector */ - cMovement ptOutputMovement ) /**< Output vector resized */ - { - // input checks - if( null == ptOutputMovement || - inputMovement == ptOutputMovement) - { - return false; - } - - if( ptOutputMovement.m_size != newSize ) - { - // output buffer creation - if( ptOutputMovement.m_buffer.Length==0 ) { - ptOutputMovement.m_buffer=new iVector[0]; - } - ptOutputMovement.m_size = newSize; - ptOutputMovement.m_buffer = new iVector[ newSize ]; - } - - - // Compute normalised vector - for( int i=0; i distanceSC ) - { - indexA = j-1; - indexB = j; - break; - } - } - - float distanceSA = distanceAB * indexA; - float distanceSB = distanceAB * indexB; - float distanceAC = distanceSC - distanceSA; - float distanceBC = distanceSB - distanceSC; - - if( indexA == indexB ) - { - ptOutputMovement.m_buffer[i] = inputMovement.m_buffer[indexA]; - } - else - { - // 0.5f added to have a better float to int cast - // NOTE : this works ONLY when the float value is greater than 0 - // In the case of the accelerometers values as used in AGR, this is not an issue. - ptOutputMovement.m_buffer[i].x = (int)( 0.5f + inputMovement.m_buffer[indexA].x*(distanceBC/distanceAB) + - inputMovement.m_buffer[indexB].x*(distanceAC/distanceAB) ); - ptOutputMovement.m_buffer[i].y = (int)( 0.5f + inputMovement.m_buffer[indexA].y*(distanceBC/distanceAB) + - inputMovement.m_buffer[indexB].y*(distanceAC/distanceAB) ); - ptOutputMovement.m_buffer[i].z = (int)( 0.5f + inputMovement.m_buffer[indexA].z*(distanceBC/distanceAB) + - inputMovement.m_buffer[indexB].z*(distanceAC/distanceAB) ); - } - } - - return true; - } - - } -} - diff --git a/cli-tools/ScannerCLI/ScannerCLI.sln b/cli-tools/ScannerCLI/ScannerCLI.sln deleted file mode 100644 index a6d95ec..0000000 --- a/cli-tools/ScannerCLI/ScannerCLI.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ScannerCLI", "ScannerCLI\ScannerCLI.vcproj", "{D89F1A23-8E62-497E-A20C-18BFE48F2A77}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D89F1A23-8E62-497E-A20C-18BFE48F2A77}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D89F1A23-8E62-497E-A20C-18BFE48F2A77}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D89F1A23-8E62-497E-A20C-18BFE48F2A77}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D89F1A23-8E62-497E-A20C-18BFE48F2A77}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D89F1A23-8E62-497E-A20C-18BFE48F2A77}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {D89F1A23-8E62-497E-A20C-18BFE48F2A77}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/cli-tools/ScannerCLI/ScannerCLI/ReadMe.txt b/cli-tools/ScannerCLI/ScannerCLI/ReadMe.txt deleted file mode 100644 index 9ee3c6e..0000000 --- a/cli-tools/ScannerCLI/ScannerCLI/ReadMe.txt +++ /dev/null @@ -1,16 +0,0 @@ -======================================================================== - CONSOLE APPLICATION : ScannerCLI Project Overview -======================================================================== - -Just issue the scanner for a max time of supplied arg - -default timeout is 1 second - -"ScannerCLI.exe x" will issue a barcode scan with a timeout of x seconds. - -x must be > 0 and < 10. - -"ScannerCLI.exe" will issue a barcode scan for max 1 second. The scan will -be stopped immediately if a barcode is read. - -/////////////////////////////////////////////////////////////////////////////s \ No newline at end of file diff --git a/cli-tools/ScannerCLI/ScannerCLI/ScannerCLI.cpp b/cli-tools/ScannerCLI/ScannerCLI/ScannerCLI.cpp deleted file mode 100644 index 175247f..0000000 --- a/cli-tools/ScannerCLI/ScannerCLI/ScannerCLI.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// ScannerCLI.cpp : Defines the entry point for the console application. -// - -#include "stdafx.h" - -INT32 hScan=NULL; -DWORD iTimeOut=1000; - -int doScanBarcode(){ - int iRet=0; - - HRESULT hRes = ITCSCAN_Open(&hScan, L"default"); - if(ITC_ISERROR(hRes)) - return -1; - hRes = ITCSCAN_SetScannerEnable(hScan, TRUE); - if(ITC_ISERROR(hRes)) - return -2; - - READ_DATA_STRUCT ReadDataBlock; - BYTE* pDataBytes = (BYTE*)malloc(2048); - ReadDataBlock.dwTimeout=iTimeOut; - ReadDataBlock.rgbDataBuffer = pDataBytes; - ReadDataBlock.dwDataBufferSize = 2048; - ReadDataBlock.dwBytesReturned = 0; - ReadDataBlock.iDataType=0; - ReadDataBlock.iSymbology=0; - - hRes = ITCSCAN_SetTriggerScanner(hScan, TRUE); - if(ITC_ISERROR(hRes)) - { - iRet=-3; - goto scanexit; - } - - hRes = ITCSCAN_SyncRead(hScan, &ReadDataBlock); - - if(hRes==E_ITCADC_OPERATION_TIMED_OUT) - { - DEBUGMSG(1, (L"Barcode read timed out with no barcode read\n")); - iRet=0; - goto scanexit; - } - - if(ITC_ISERROR(hRes)){ - iRet = -4; - goto scanexit; - } - - TCHAR* tStr = (TCHAR*)malloc(4096); - mbstowcs(tStr, (char*)ReadDataBlock.rgbDataBuffer, ReadDataBlock.dwBytesReturned); - - DEBUGMSG(1, (L"Barcode read= '%s'\n", tStr)); - delete(tStr); - delete(ReadDataBlock.rgbDataBuffer); - - iRet=1; - -scanexit: - //unset trigger - hRes = ITCSCAN_SetTriggerScanner(hScan, FALSE); - if(ITC_ISERROR(hRes)) - return -5; - hRes = ITCSCAN_Close(hScan); - if(ITC_ISERROR(hRes)) - return -6; - - return iRet; -} - -int _tmain(int argc, _TCHAR* argv[]) -{ - if(argc==2){ - int i = _wtoi(argv[1]); - if(i>0 && i<10) - iTimeOut=i * 1000; - } - - int iResult = doScanBarcode(); - DEBUGMSG(1, (L"doScanBarcode() = %i\n", iResult)); - return iResult; - - return 0; -} - diff --git a/cli-tools/ScannerCLI/ScannerCLI/ScannerCLI.vcproj b/cli-tools/ScannerCLI/ScannerCLI/ScannerCLI.vcproj deleted file mode 100644 index 42fd75d..0000000 --- a/cli-tools/ScannerCLI/ScannerCLI/ScannerCLI.vcproj +++ /dev/null @@ -1,256 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cli-tools/ScannerCLI/ScannerCLI/stdafx.cpp b/cli-tools/ScannerCLI/ScannerCLI/stdafx.cpp deleted file mode 100644 index b634470..0000000 --- a/cli-tools/ScannerCLI/ScannerCLI/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// ScannerCLI.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/cli-tools/ScannerCLI/ScannerCLI/stdafx.h b/cli-tools/ScannerCLI/ScannerCLI/stdafx.h deleted file mode 100644 index e7bbff5..0000000 --- a/cli-tools/ScannerCLI/ScannerCLI/stdafx.h +++ /dev/null @@ -1,61 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include - -#include -#pragma comment(lib, "aygshell.lib") - - - -#include -#include - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here -#include -#pragma comment (lib, "itcscan.lib") -#include -#pragma comment (lib, "itc50.lib") -#include diff --git a/cli-tools/SetDefaultLocale/SetDefaultLocale.sln b/cli-tools/SetDefaultLocale/SetDefaultLocale.sln deleted file mode 100644 index 0801a8d..0000000 --- a/cli-tools/SetDefaultLocale/SetDefaultLocale.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SetDefaultLocale", "SetDefaultLocale\SetDefaultLocale.vcproj", "{0DC732FF-D8A7-4DCC-9450-9CE0535F7577}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {0DC732FF-D8A7-4DCC-9450-9CE0535F7577}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {0DC732FF-D8A7-4DCC-9450-9CE0535F7577}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {0DC732FF-D8A7-4DCC-9450-9CE0535F7577}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {0DC732FF-D8A7-4DCC-9450-9CE0535F7577}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {0DC732FF-D8A7-4DCC-9450-9CE0535F7577}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {0DC732FF-D8A7-4DCC-9450-9CE0535F7577}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/cli-tools/SetDefaultLocale/SetDefaultLocale/ReadMe.txt b/cli-tools/SetDefaultLocale/SetDefaultLocale/ReadMe.txt deleted file mode 100644 index 68b3608..0000000 --- a/cli-tools/SetDefaultLocale/SetDefaultLocale/ReadMe.txt +++ /dev/null @@ -1,181 +0,0 @@ -======================================================================== - CONSOLE APPLICATION : SetDefaultLocale Project Overview -======================================================================== - -AppWizard has created this SetDefaultLocale application for you. - -This file contains a summary of what you will find in each of the files that -make up your SetDefaultLocale application. - - -SetDefaultLocale.vcproj - This is the main project file for VC++ projects generated using an Application Wizard. - It contains information about the version of Visual C++ that generated the file, and - information about the platforms, configurations, and project features selected with the - Application Wizard. - -SetDefaultLocale.cpp - This is the main application source file. - -///////////////////////////////////////////////////////////////////////////// -Other standard files: - -StdAfx.h, StdAfx.cpp - These files are used to build a precompiled header (PCH) file - named SetDefaultLocale.pch and a precompiled types file named StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Other notes: - -AppWizard uses "TODO:" comments to indicate parts of the source code you -should add to or customize. - -/////////////////////////////////////////////////////////////////////////////s - -Locale identifier Language Sublanguage - locale Default code page Language code -0x0436 Afrikaans South Africa 1252 AFK -0x041c Albanian Albania 1250 SQI -0x1401 Arabic Algeria 1256 ARG -0x3c01 Arabic Bahrain 1256 ARH -0x0c01 Arabic Egypt 1256 ARE -0x0801 Arabic Iraq 1256 ARI -0x2c01 Arabic Jordan 1256 ARJ -0x3401 Arabic Kuwait 1256 ARK -0x3001 Arabic Lebanon 1256 ARB -0x1001 Arabic Libya 1256 ARL -0x1801 Arabic Morocco 1256 ARM -0x2001 Arabic Oman 1256 ARO -0x4001 Arabic Qatar 1256 ARQ -0x0401 Arabic Saudi Arabia 1256 ARA -0x2801 Arabic Syria 1256 ARS -0x1c01 Arabic Tunisia 1256 ART -0x3801 Arabic U.A.E. 1256 ARU -0x2401 Arabic Yemen 1256 ARY -0x042b Armenian Armenia Unicode only HYE -0x044d Assamese India Unicode only ASM -0x082c Azeri Azerbaijan (Cyrillic) 1251 AZE -0x042c Azeri Azerbaijan (Latin) 1254 AZE -0x042d Basque Spain 1252 EUQ -0x0423 Belarusian Belarus 1251 BEL -0x0445 Bengali India BEN -0x0402 Bulgarian Bulgaria 1251 BGR -0x0403 Catalan Spain 1252 CAT -0x0c04 Chinese Hong Kong SAR 950 ZHH -0x1404 Chinese Macao SAR 950 ZHM -0x0804 Chinese PRC 936 CHS -0x1004 Chinese Singapore 936 ZHI -0x0404 Chinese Taiwan 950 CHT -0x0827 Classic Lithuanian Lithuania 1257 LTC -0x041a Croatian Croatia 1250 HRV -0x0405 Czech Czech Republic 1250 CSY -0x0406 Danish Denmark 1252 DAN -0x0465 Divehi Maldives Unicode only DIV -0x0813 Dutch Belgium 1252 NLB -0x0413 Dutch Netherlands 1252 NLD -0x0c09 English Australia 1252 ENA -0x2809 English Belize 1252 ENL -0x1009 English Canada 1252 ENC -0x2409 English Caribbean 1252 ENB -0x1809 English Ireland 1252 ENI -0x2009 English Jamaica 1252 ENJ -0x1409 English New Zealand 1252 ENZ -0x3409 English Philippines 1252 ENP -0x1c09 English South Africa 1252 ENS -0x2c09 English Trinidad 1252 ENT -0x0809 English United Kingdom 1252 ENG -0x0409 English United States 1252 USA -0x3009 English Zimbabwe 1252 ENW -0x0425 Estonian Estonia 1257 ETI -0x0438 Faeroese Faeroe Islands 1252 FOS -0x0429 Farsi Iran 1256 FAR -0x040b Finnish Finland 1252 FIN -0x080c French Belgium 1252 FRB -0x0c0c French Canada 1252 FRC -0x040c French France 1252 FRA -0x140c French Luxembourg 1252 FRL -0x180c French Monaco 1252 FRM -0x100c French Switzerland 1252 FRS -0x042f Macedonian (FYROM) Macedonian (FYROM) 1251 MKI -0x0456 Galician Spain 1252 GLC -0x0437 Georgian Georgia Unicode only KAT -0x0c07 German Austria 1252 DEA -0x0407 German Germany 1252 DEU -0x1407 German Liechtenstein 1252 DEC -0x1007 German Luxembourg 1252 DEL -0x0807 German Switzerland 1252 DES -0x0408 Greek Greece 1253 ELL -0x0447 Gujarati India Unicode only GUJ -0x040d Hebrew Israel 1255 HEB -0x0439 Hindi India Unicode only HIN -0x040e Hungarian Hungary 1250 HUN -0x040f Icelandic Iceland 1252 ISL -0x0421 Indonesian Indonesia (Bahasa) 1252 IND -0x0410 Italian Italy 1252 ITA -0x0810 Italian Switzerland 1252 ITS -0x0411 Japanese Japan 932 JPN -0x044b Kannada India (Kannada script) Unicode only KAN -0x043f Kazakh Kazakstan 1251 KKZ -0x0457 Konkani India Unicode only KNK -0x0412 Korean Korea 949 KOR -0x0440 Kyrgyz Kyrgyzstan 1251 KYR -0x0426 Latvian Latvia 1257 LVI -0x0427 Lithuanian Lithuania 1257 LTH -0x083e Malay Brunei Darussalam 1252 MSB -0x043e Malay Malaysia 1252 MSL -0x044c Malayalam India Unicode only MAL -0x044e Marathi India Unicode only MAR -0x0450 Mongolian (Cyrillic) Mongolia 1251 MON -0x0414 Norwegian Norway (Bokml) 1252 NOR -0x0814 Norwegian Norway (Nynorsk) 1252 NON -0x0448 Oriya India ORI -0x0415 Polish Poland 1250 PLK -0x0416 Portuguese Brazil 1252 PTB -0x0816 Portuguese Portugal 1252 PTG -0x0446 Punjabi India (Gurmukhi script) Unicode only PAN -0x0418 Romanian Romania 1250 ROM -0x0419 Russian Russia 1251 RUS -0x044f Sanskrit India Unicode only SAN -0x0c1a Serbian Serbia (Cyrillic) 1251 SRB -0x081a Serbian Serbia (Latin) 1250 SRL -0x041b Slovak Slovakia 1250 SKY -0x0424 Slovenian Slovenia 1250 SLV -0x2c0a Spanish Argentina 1252 ESS -0x400a Spanish Bolivia 1252 ESB -0x340a Spanish Chile 1252 ESL -0x240a Spanish Colombia 1252 ESO -0x140a Spanish Costa Rica 1252 ESC -0x1c0a Spanish Dominican Republic 1252 ESD -0x300a Spanish Ecuador 1252 ESF -0x440a Spanish El Salvador 1252 ESE -0x100a Spanish Guatemala 1252 ESG -0x480a Spanish Honduras 1252 ESH -0x080a Spanish Mexico 1252 ESM -0x4c0a Spanish Nicaragua 1252 ESI -0x180a Spanish Panama 1252 ESA -0x3c0a Spanish Paraguay 1252 ESZ -0x280a Spanish Peru 1252 ESR -0x500a Spanish Puerto Rico 1252 ESU -0x040a Spanish Spain (Traditional sort) 1252 ESP -0x0c0a Spanish Spain (International sort) 1252 ESN -0x380a Spanish Uruguay 1252 ESY -0x200a Spanish Venezuela 1252 ESV -0x0441 Swahili Kenya 1252 SWK -0x081d Swedish Finland 1252 SVF -0x041d Swedish Sweden 1252 SVE -0x045a Syriac Syria Unicode only SYR -0x0449 Tamil India Unicode only TAM -0x0444 Tatar Tatarstan 1251 TTT -0x044a Telugu India (Telugu script) Unicode only TEL -0x041e Thai Thailand 874 THA -0x041f Turkish Turkey 1254 TRK -0x0422 Ukrainian Ukraine 1251 UKR -0x0420 Urdu Pakistan 1256 URP -0x0820 Urdu India 1256 URI -0x0843 Uzbek Uzbekistan (Cyrillic) 1251 UZB -0x0443 Uzbek Uzbekistan (Latin) 1254 UZB -0x042a Vietnamese Viet Nam 1258 VIT - -The following special identifiers are also defined. -Identifier Sublanguage/locale -0x0000 Language-Neutral -0x0400 Process Default Language \ No newline at end of file diff --git a/cli-tools/SetDefaultLocale/SetDefaultLocale/SetDefaultLocale.cpp b/cli-tools/SetDefaultLocale/SetDefaultLocale/SetDefaultLocale.cpp deleted file mode 100644 index a9d86d3..0000000 --- a/cli-tools/SetDefaultLocale/SetDefaultLocale/SetDefaultLocale.cpp +++ /dev/null @@ -1,241 +0,0 @@ -// SetDefaultLocale.cpp : Defines the entry point for the console application. -// - -#include "stdafx.h" - -TCHAR* localeList[]; - -LANGID getLangID(){ - return GetUserDefaultLangID(); - //GetUserDefaultLCID(); - //GetUserDefaultUILanguage(); -} - -LANGID getSystemLangID(){ - return GetSystemDefaultUILanguage(); -} -BOOL setSystemDefaultLCID(LCID lcID){ - //you can not change the system default locale! - return SetSystemDefaultLCID(lcID); -} -BOOL setLangID(LANGID id){ - return SetUserDefaultUILanguage(id); - //SetUserDefaultLangID(); -} - -LCID getLCID(){ - return GetUserDefaultLCID(); -} - -BOOL setLCID(LCID lcID){ - return SetUserDefaultLCID(lcID); -} - -LANGID getUserLanguageID(){ - return GetUserDefaultLangID(); -} - -//argv[0] is the exe name! -int _tmain(int argc, _TCHAR* argv[]) -{ - initFileNames(); - Add2Log(L"SetDefaultLocale v 0.1 started\n==============================\n"); - TCHAR str[MAX_PATH]; - - if(argc==1){ - Add2Log(L"no args no fun.\ntry -help or a locale ID as hex (ie '0x407')\n---Program END\n"); - return -1; - } - - if(argc==2){ - if (wcsicmp(argv[1], L"-help")==0){ - int i=0; - do{ - Add2Log(localeList[i]); Add2Log(L"\n"); - i++; - }while (localeList[i]!=NULL); - } - if (wcsicmp(argv[1], L"-status")==0){ - wsprintf(str, L"current user default LCID is: 0x%03x\n", getLCID()); - Add2Log(str); - wsprintf(str, L"current user default langID is: 0x%03x\n", getLangID()); - Add2Log(str); - wsprintf(str, L"current system langID is: 0x%03x\n", getSystemLangID()); - Add2Log(str); - } - if (wcsncmp(argv[1], L"0x", 2)==0){ - int lcID = wcstol(argv[1], (TCHAR **)NULL, 16); - //set local ID - if(setLCID(lcID)) - wsprintf(str, L"new user default LCID is: 0x%03x\n", getLCID()); - else - wsprintf(str, L"setting LCID failed\n"); - Add2Log(str); - - if(setLangID(lcID)) - wsprintf(str, L"new user default langID is: 0x%03x\n", getLangID()); - else - wsprintf(str, L"setting langID failed\n"); - Add2Log(str); - - if(setSystemDefaultLCID(lcID)) - wsprintf(str, L"system langID is: 0x%03x\n", getSystemLangID()); - else - wsprintf(str, L"setting system langID failed\n"); - Add2Log(str); - - } - } - - Add2Log(L"\n---Program END\n"); - return 0; -} - -TCHAR* localeList[] = { - L"supported arguments:", - L"-help print this help to log", - L"-status get current locale ID (LCID)", - L"--------------------------------", -L"Locale identifier Language Sublanguage - locale Default code page Language code", -L"0x0436 Afrikaans South Africa 1252 AFK", -L"0x041c Albanian Albania 1250 SQI", -L"0x1401 Arabic Algeria 1256 ARG", -L"0x3c01 Arabic Bahrain 1256 ARH", -L"0x0c01 Arabic Egypt 1256 ARE", -L"0x0801 Arabic Iraq 1256 ARI", -L"0x2c01 Arabic Jordan 1256 ARJ", -L"0x3401 Arabic Kuwait 1256 ARK", -L"0x3001 Arabic Lebanon 1256 ARB", -L"0x1001 Arabic Libya 1256 ARL", -L"0x1801 Arabic Morocco 1256 ARM", -L"0x2001 Arabic Oman 1256 ARO", -L"0x4001 Arabic Qatar 1256 ARQ", -L"0x0401 Arabic Saudi Arabia 1256 ARA", -L"0x2801 Arabic Syria 1256 ARS", -L"0x1c01 Arabic Tunisia 1256 ART", -L"0x3801 Arabic U.A.E. 1256 ARU", -L"0x2401 Arabic Yemen 1256 ARY", -L"0x042b Armenian Armenia Unicode only HYE", -L"0x044d Assamese India Unicode only ASM", -L"0x082c Azeri Azerbaijan (Cyrillic) 1251 AZE", -L"0x042c Azeri Azerbaijan (Latin) 1254 AZE", -L"0x042d Basque Spain 1252 EUQ", -L"0x0423 Belarusian Belarus 1251 BEL", -L"0x0445 Bengali India BEN", -L"0x0402 Bulgarian Bulgaria 1251 BGR", -L"0x0403 Catalan Spain 1252 CAT", -L"0x0c04 Chinese Hong Kong SAR 950 ZHH", -L"0x1404 Chinese Macao SAR 950 ZHM", -L"0x0804 Chinese PRC 936 CHS", -L"0x1004 Chinese Singapore 936 ZHI", -L"0x0404 Chinese Taiwan 950 CHT", -L"0x0827 Classic Lithuanian Lithuania 1257 LTC", -L"0x041a Croatian Croatia 1250 HRV", -L"0x0405 Czech Czech Republic 1250 CSY", -L"0x0406 Danish Denmark 1252 DAN", -L"0x0465 Divehi Maldives Unicode only DIV", -L"0x0813 Dutch Belgium 1252 NLB", -L"0x0413 Dutch Netherlands 1252 NLD", -L"0x0c09 English Australia 1252 ENA", -L"0x2809 English Belize 1252 ENL", -L"0x1009 English Canada 1252 ENC", -L"0x2409 English Caribbean 1252 ENB", -L"0x1809 English Ireland 1252 ENI", -L"0x2009 English Jamaica 1252 ENJ", -L"0x1409 English New Zealand 1252 ENZ", -L"0x3409 English Philippines 1252 ENP", -L"0x1c09 English South Africa 1252 ENS", -L"0x2c09 English Trinidad 1252 ENT", -L"0x0809 English United Kingdom 1252 ENG", -L"0x0409 English United States 1252 USA", -L"0x3009 English Zimbabwe 1252 ENW", -L"0x0425 Estonian Estonia 1257 ETI", -L"0x0438 Faeroese Faeroe Islands 1252 FOS", -L"0x0429 Farsi Iran 1256 FAR", -L"0x040b Finnish Finland 1252 FIN", -L"0x080c French Belgium 1252 FRB", -L"0x0c0c French Canada 1252 FRC", -L"0x040c French France 1252 FRA", -L"0x140c French Luxembourg 1252 FRL", -L"0x180c French Monaco 1252 FRM", -L"0x100c French Switzerland 1252 FRS", -L"0x042f Macedonian (FYROM) Macedonian (FYROM) 1251 MKI", -L"0x0456 Galician Spain 1252 GLC", -L"0x0437 Georgian Georgia Unicode only KAT", -L"0x0c07 German Austria 1252 DEA", -L"0x0407 German Germany 1252 DEU", -L"0x1407 German Liechtenstein 1252 DEC", -L"0x1007 German Luxembourg 1252 DEL", -L"0x0807 German Switzerland 1252 DES", -L"0x0408 Greek Greece 1253 ELL", -L"0x0447 Gujarati India Unicode only GUJ", -L"0x040d Hebrew Israel 1255 HEB", -L"0x0439 Hindi India Unicode only HIN", -L"0x040e Hungarian Hungary 1250 HUN", -L"0x040f Icelandic Iceland 1252 ISL", -L"0x0421 Indonesian Indonesia (Bahasa) 1252 IND", -L"0x0410 Italian Italy 1252 ITA", -L"0x0810 Italian Switzerland 1252 ITS", -L"0x0411 Japanese Japan 932 JPN", -L"0x044b Kannada India (Kannada script) Unicode only KAN", -L"0x043f Kazakh Kazakstan 1251 KKZ", -L"0x0457 Konkani India Unicode only KNK", -L"0x0412 Korean Korea 949 KOR", -L"0x0440 Kyrgyz Kyrgyzstan 1251 KYR", -L"0x0426 Latvian Latvia 1257 LVI", -L"0x0427 Lithuanian Lithuania 1257 LTH", -L"0x083e Malay Brunei Darussalam 1252 MSB", -L"0x043e Malay Malaysia 1252 MSL", -L"0x044c Malayalam India Unicode only MAL", -L"0x044e Marathi India Unicode only MAR", -L"0x0450 Mongolian (Cyrillic) Mongolia 1251 MON", -L"0x0414 Norwegian Norway (Bokmål) 1252 NOR", -L"0x0814 Norwegian Norway (Nynorsk) 1252 NON", -L"0x0448 Oriya India ORI", -L"0x0415 Polish Poland 1250 PLK", -L"0x0416 Portuguese Brazil 1252 PTB", -L"0x0816 Portuguese Portugal 1252 PTG", -L"0x0446 Punjabi India (Gurmukhi script) Unicode only PAN", -L"0x0418 Romanian Romania 1250 ROM", -L"0x0419 Russian Russia 1251 RUS", -L"0x044f Sanskrit India Unicode only SAN", -L"0x0c1a Serbian Serbia (Cyrillic) 1251 SRB", -L"0x081a Serbian Serbia (Latin) 1250 SRL", -L"0x041b Slovak Slovakia 1250 SKY", -L"0x0424 Slovenian Slovenia 1250 SLV", -L"0x2c0a Spanish Argentina 1252 ESS", -L"0x400a Spanish Bolivia 1252 ESB", -L"0x340a Spanish Chile 1252 ESL", -L"0x240a Spanish Colombia 1252 ESO", -L"0x140a Spanish Costa Rica 1252 ESC", -L"0x1c0a Spanish Dominican Republic 1252 ESD", -L"0x300a Spanish Ecuador 1252 ESF", -L"0x440a Spanish El Salvador 1252 ESE", -L"0x100a Spanish Guatemala 1252 ESG", -L"0x480a Spanish Honduras 1252 ESH", -L"0x080a Spanish Mexico 1252 ESM", -L"0x4c0a Spanish Nicaragua 1252 ESI", -L"0x180a Spanish Panama 1252 ESA", -L"0x3c0a Spanish Paraguay 1252 ESZ", -L"0x280a Spanish Peru 1252 ESR", -L"0x500a Spanish Puerto Rico 1252 ESU", -L"0x040a Spanish Spain (Traditional sort) 1252 ESP", -L"0x0c0a Spanish Spain (International sort) 1252 ESN", -L"0x380a Spanish Uruguay 1252 ESY", -L"0x200a Spanish Venezuela 1252 ESV", -L"0x0441 Swahili Kenya 1252 SWK", -L"0x081d Swedish Finland 1252 SVF", -L"0x041d Swedish Sweden 1252 SVE", -L"0x045a Syriac Syria Unicode only SYR", -L"0x0449 Tamil India Unicode only TAM", -L"0x0444 Tatar Tatarstan 1251 TTT", -L"0x044a Telugu India (Telugu script) Unicode only TEL", -L"0x041e Thai Thailand 874 THA", -L"0x041f Turkish Turkey 1254 TRK", -L"0x0422 Ukrainian Ukraine 1251 UKR", -L"0x0420 Urdu Pakistan 1256 URP", -L"0x0820 Urdu India 1256 URI", -L"0x0843 Uzbek Uzbekistan (Cyrillic) 1251 UZB", -L"0x0443 Uzbek Uzbekistan (Latin) 1254 UZB", -L"0x042a Vietnamese Viet Nam 1258 VIT", -NULL}; diff --git a/cli-tools/SetDefaultLocale/SetDefaultLocale/SetDefaultLocale.vcproj b/cli-tools/SetDefaultLocale/SetDefaultLocale/SetDefaultLocale.vcproj deleted file mode 100644 index cf0f817..0000000 --- a/cli-tools/SetDefaultLocale/SetDefaultLocale/SetDefaultLocale.vcproj +++ /dev/null @@ -1,260 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cli-tools/SetDefaultLocale/SetDefaultLocale/localeIDs.txt b/cli-tools/SetDefaultLocale/SetDefaultLocale/localeIDs.txt deleted file mode 100644 index 82b097d..0000000 --- a/cli-tools/SetDefaultLocale/SetDefaultLocale/localeIDs.txt +++ /dev/null @@ -1,142 +0,0 @@ -Locale identifier Language Sublanguage - locale Default code page Language code -0x0436 Afrikaans South Africa 1252 AFK -0x041c Albanian Albania 1250 SQI -0x1401 Arabic Algeria 1256 ARG -0x3c01 Arabic Bahrain 1256 ARH -0x0c01 Arabic Egypt 1256 ARE -0x0801 Arabic Iraq 1256 ARI -0x2c01 Arabic Jordan 1256 ARJ -0x3401 Arabic Kuwait 1256 ARK -0x3001 Arabic Lebanon 1256 ARB -0x1001 Arabic Libya 1256 ARL -0x1801 Arabic Morocco 1256 ARM -0x2001 Arabic Oman 1256 ARO -0x4001 Arabic Qatar 1256 ARQ -0x0401 Arabic Saudi Arabia 1256 ARA -0x2801 Arabic Syria 1256 ARS -0x1c01 Arabic Tunisia 1256 ART -0x3801 Arabic U.A.E. 1256 ARU -0x2401 Arabic Yemen 1256 ARY -0x042b Armenian Armenia Unicode only HYE -0x044d Assamese India Unicode only ASM -0x082c Azeri Azerbaijan (Cyrillic) 1251 AZE -0x042c Azeri Azerbaijan (Latin) 1254 AZE -0x042d Basque Spain 1252 EUQ -0x0423 Belarusian Belarus 1251 BEL -0x0445 Bengali India BEN -0x0402 Bulgarian Bulgaria 1251 BGR -0x0403 Catalan Spain 1252 CAT -0x0c04 Chinese Hong Kong SAR 950 ZHH -0x1404 Chinese Macao SAR 950 ZHM -0x0804 Chinese PRC 936 CHS -0x1004 Chinese Singapore 936 ZHI -0x0404 Chinese Taiwan 950 CHT -0x0827 Classic Lithuanian Lithuania 1257 LTC -0x041a Croatian Croatia 1250 HRV -0x0405 Czech Czech Republic 1250 CSY -0x0406 Danish Denmark 1252 DAN -0x0465 Divehi Maldives Unicode only DIV -0x0813 Dutch Belgium 1252 NLB -0x0413 Dutch Netherlands 1252 NLD -0x0c09 English Australia 1252 ENA -0x2809 English Belize 1252 ENL -0x1009 English Canada 1252 ENC -0x2409 English Caribbean 1252 ENB -0x1809 English Ireland 1252 ENI -0x2009 English Jamaica 1252 ENJ -0x1409 English New Zealand 1252 ENZ -0x3409 English Philippines 1252 ENP -0x1c09 English South Africa 1252 ENS -0x2c09 English Trinidad 1252 ENT -0x0809 English United Kingdom 1252 ENG -0x0409 English United States 1252 USA -0x3009 English Zimbabwe 1252 ENW -0x0425 Estonian Estonia 1257 ETI -0x0438 Faeroese Faeroe Islands 1252 FOS -0x0429 Farsi Iran 1256 FAR -0x040b Finnish Finland 1252 FIN -0x080c French Belgium 1252 FRB -0x0c0c French Canada 1252 FRC -0x040c French France 1252 FRA -0x140c French Luxembourg 1252 FRL -0x180c French Monaco 1252 FRM -0x100c French Switzerland 1252 FRS -0x042f Macedonian (FYROM) Macedonian (FYROM) 1251 MKI -0x0456 Galician Spain 1252 GLC -0x0437 Georgian Georgia Unicode only KAT -0x0c07 German Austria 1252 DEA -0x0407 German Germany 1252 DEU -0x1407 German Liechtenstein 1252 DEC -0x1007 German Luxembourg 1252 DEL -0x0807 German Switzerland 1252 DES -0x0408 Greek Greece 1253 ELL -0x0447 Gujarati India Unicode only GUJ -0x040d Hebrew Israel 1255 HEB -0x0439 Hindi India Unicode only HIN -0x040e Hungarian Hungary 1250 HUN -0x040f Icelandic Iceland 1252 ISL -0x0421 Indonesian Indonesia (Bahasa) 1252 IND -0x0410 Italian Italy 1252 ITA -0x0810 Italian Switzerland 1252 ITS -0x0411 Japanese Japan 932 JPN -0x044b Kannada India (Kannada script) Unicode only KAN -0x043f Kazakh Kazakstan 1251 KKZ -0x0457 Konkani India Unicode only KNK -0x0412 Korean Korea 949 KOR -0x0440 Kyrgyz Kyrgyzstan 1251 KYR -0x0426 Latvian Latvia 1257 LVI -0x0427 Lithuanian Lithuania 1257 LTH -0x083e Malay Brunei Darussalam 1252 MSB -0x043e Malay Malaysia 1252 MSL -0x044c Malayalam India Unicode only MAL -0x044e Marathi India Unicode only MAR -0x0450 Mongolian (Cyrillic) Mongolia 1251 MON -0x0414 Norwegian Norway (Bokmål) 1252 NOR -0x0814 Norwegian Norway (Nynorsk) 1252 NON -0x0448 Oriya India ORI -0x0415 Polish Poland 1250 PLK -0x0416 Portuguese Brazil 1252 PTB -0x0816 Portuguese Portugal 1252 PTG -0x0446 Punjabi India (Gurmukhi script) Unicode only PAN -0x0418 Romanian Romania 1250 ROM -0x0419 Russian Russia 1251 RUS -0x044f Sanskrit India Unicode only SAN -0x0c1a Serbian Serbia (Cyrillic) 1251 SRB -0x081a Serbian Serbia (Latin) 1250 SRL -0x041b Slovak Slovakia 1250 SKY -0x0424 Slovenian Slovenia 1250 SLV -0x2c0a Spanish Argentina 1252 ESS -0x400a Spanish Bolivia 1252 ESB -0x340a Spanish Chile 1252 ESL -0x240a Spanish Colombia 1252 ESO -0x140a Spanish Costa Rica 1252 ESC -0x1c0a Spanish Dominican Republic 1252 ESD -0x300a Spanish Ecuador 1252 ESF -0x440a Spanish El Salvador 1252 ESE -0x100a Spanish Guatemala 1252 ESG -0x480a Spanish Honduras 1252 ESH -0x080a Spanish Mexico 1252 ESM -0x4c0a Spanish Nicaragua 1252 ESI -0x180a Spanish Panama 1252 ESA -0x3c0a Spanish Paraguay 1252 ESZ -0x280a Spanish Peru 1252 ESR -0x500a Spanish Puerto Rico 1252 ESU -0x040a Spanish Spain (Traditional sort) 1252 ESP -0x0c0a Spanish Spain (International sort) 1252 ESN -0x380a Spanish Uruguay 1252 ESY -0x200a Spanish Venezuela 1252 ESV -0x0441 Swahili Kenya 1252 SWK -0x081d Swedish Finland 1252 SVF -0x041d Swedish Sweden 1252 SVE -0x045a Syriac Syria Unicode only SYR -0x0449 Tamil India Unicode only TAM -0x0444 Tatar Tatarstan 1251 TTT -0x044a Telugu India (Telugu script) Unicode only TEL -0x041e Thai Thailand 874 THA -0x041f Turkish Turkey 1254 TRK -0x0422 Ukrainian Ukraine 1251 UKR -0x0420 Urdu Pakistan 1256 URP -0x0820 Urdu India 1256 URI -0x0843 Uzbek Uzbekistan (Cyrillic) 1251 UZB -0x0443 Uzbek Uzbekistan (Latin) 1254 UZB -0x042a Vietnamese Viet Nam 1258 VIT diff --git a/cli-tools/SetDefaultLocale/SetDefaultLocale/log2file.cpp b/cli-tools/SetDefaultLocale/SetDefaultLocale/log2file.cpp deleted file mode 100644 index d94a38d..0000000 --- a/cli-tools/SetDefaultLocale/SetDefaultLocale/log2file.cpp +++ /dev/null @@ -1,308 +0,0 @@ -//log2file.cpp - -#include "stdafx.h" -//#include "log2file.h" - -char logFileName[MAX_PATH]; -TCHAR logFileNameW[MAX_PATH]; - -//================================================================================= -//implementation -//================================================================================= - -//================================================================================= -// check the actual log file size -// if > 1MB move to bak and start new log file -// return true if new file started -// uses global logFileNameW -//================================================================================= -BOOL checkFileSize(){ - BOOL bRet=FALSE; - if(wcslen(logFileNameW)==0) - return bRet; - - TCHAR txtFileName[MAX_PATH+1]; - //make local copy - wsprintf(txtFileName, L"%s", logFileNameW); - - //#### we maintain two log files, an actual and a bak one - //get file size - HANDLE hFile = CreateFile(txtFileName, - GENERIC_READ, // open for writing - FILE_SHARE_READ, // share - NULL, // default security - OPEN_EXISTING, // open existing - FILE_ATTRIBUTE_NORMAL, // normal file - NULL); // no attr. template - DWORD dwFileSize = GetFileSize(hFile, NULL); - CloseHandle(hFile); - - if(dwFileSize != 0xFFFFFFFF){ //no error - if(dwFileSize>0x100000){ //more than 1MB? - //make a backup - //delete previous bak - TCHAR txtFileNameBAK[MAX_PATH]; - wsprintf(txtFileNameBAK, L"%s.bak", txtFileName); - DeleteFile(txtFileNameBAK); - //rename old file to .BAK - MoveFile(txtFileName, txtFileNameBAK); - bRet=TRUE; - } - } - //copy filename to global char and tchar var -// wsprintf(logFileNameW, txtFileName); -// wcstombs(logFileName, logFileNameW, sizeof(logFileNameW)*sizeof(logFileNameW[0])); - return bRet; -} - -//========================== start of file stuff ============================= - -int initFileNames(TCHAR* _logFileName) -{ - TCHAR txtFileName[MAX_PATH+1]; - wsprintf(txtFileName, L"%s", _logFileName); - //store the filename to use in char and tchar - TCHAR logFileNameW[MAX_PATH]; - - //#### we maintain two log files, an actual and a bak one - //get file size - HANDLE hFile = CreateFile(txtFileName, - GENERIC_READ, // open for writing - FILE_SHARE_READ, // share - NULL, // default security - OPEN_EXISTING, // open existing - FILE_ATTRIBUTE_NORMAL, // normal file - NULL); // no attr. template - DWORD dwFileSize = GetFileSize(hFile, NULL); - CloseHandle(hFile); - - if(dwFileSize != 0xFFFFFFFF){ //no error - if(dwFileSize>0x100000){ //more than 1MB? - //make a backup - //delete previous bak - TCHAR txtFileNameBAK[MAX_PATH]; - wsprintf(txtFileNameBAK, L"%s.bak", txtFileName); - DeleteFile(txtFileNameBAK); - //rename old file to .BAK - MoveFile(txtFileName, txtFileNameBAK); - } - } - - //copy filename to global char and tchar var - wsprintf(logFileNameW, txtFileName); - wcstombs(logFileName, logFileNameW, sizeof(logFileNameW)*sizeof(logFileNameW[0])); - - FILE *fp; - fp = fopen(logFileName, "a+"); - fclose(fp); - bFirstFileCall=false; - return 0; -} - -int initFileNames() -{ - // Get name of executable - TCHAR lpFileName1[MAX_PATH+1]; - GetModuleFileName(NULL, lpFileName1, MAX_PATH); //lpFileName will contain the exe name of this running app! - - //add txt extension - TCHAR txtFileName[MAX_PATH+1]; - wsprintf(txtFileName, L"%s.log.txt", lpFileName1); - //store the filename to use in char and tchar - TCHAR logFileNameW[MAX_PATH]; - - //#### we maintain two log files, an actual and a bak one - //get file size - HANDLE hFile = CreateFile(txtFileName, - GENERIC_READ, // open for writing - FILE_SHARE_READ, // share - NULL, // default security - OPEN_EXISTING, // open existing - FILE_ATTRIBUTE_NORMAL, // normal file - NULL); // no attr. template - DWORD dwFileSize = GetFileSize(hFile, NULL); - CloseHandle(hFile); - - if(dwFileSize != 0xFFFFFFFF){ //no error - if(dwFileSize>0x100000){ //more than 1MB? - //make a backup - //delete previous bak - TCHAR txtFileNameBAK[MAX_PATH]; - wsprintf(txtFileNameBAK, L"%s.bak", txtFileName); - DeleteFile(txtFileNameBAK); - //rename old file to .BAK - MoveFile(txtFileName, txtFileNameBAK); - } - } - - //copy filename to global char and tchar var - wsprintf(logFileNameW, txtFileName); - wcstombs(logFileName, logFileNameW, sizeof(logFileNameW)*sizeof(logFileNameW[0])); - - FILE *fp; - fp = fopen(logFileName, "a+"); - fclose(fp); - bFirstFileCall=false; - return 0; -} - -void Add2Log (TCHAR *txt) { - Add2Log(txt, false); -} - -//----------------------------------------------------------------------- -// Add2Log - Add string to the the file -// -void Add2Log (TCHAR *lpszFormat, ...) { - int nBuf;//, i; - TCHAR szBuffer[512]; - - va_list args; - va_start(args, lpszFormat); - - nBuf = vswprintf(szBuffer, lpszFormat, args); - writefile(szBuffer); - va_end(args); -} - -//----------------------------------------------------------------------- -// Add2Log - Add string to the the file -// -void Add2LogWtime (TCHAR *lpszFormat, ...) { - int nBuf;//, i; - TCHAR szBuffer[512]; - - va_list args; - va_start(args, lpszFormat); - - nBuf = vswprintf(szBuffer, lpszFormat, args); - Add2LogWithTime(szBuffer); - va_end(args); -} -//----------------------------------------------------------------------- -// appendfile - set the global filename to append text -// -int appendfile(char *filename) -{ - //store the filename to use in char and tchar - sprintf(logFileName, filename); - mbstowcs(logFileNameW, logFileName, sizeof(logFileName)*sizeof(logFileName[0])); - - FILE *fp; - fp = fopen(logFileName, "a+"); - fclose(fp); - return 0; -} - -int newfile(char *filename) -{ - //store the filename to use in char and tchar - sprintf(logFileName, filename); - mbstowcs(logFileNameW, logFileName, sizeof(logFileName)*sizeof(logFileName[0])); - - FILE *fp; - fp = fopen(logFileName, "w+"); - fclose(fp); - return 0; -} - -int newfile(TCHAR *filename) -{ - //store the filename to use in char and tchar - TCHAR logFileNameW[MAX_PATH]; - wsprintf(logFileNameW, filename); - wcstombs(logFileName, logFileNameW, sizeof(logFileNameW)*sizeof(logFileNameW[0])); - - FILE *fp; - fp = fopen(logFileName, "w+"); - fclose(fp); - return 0; -} - -int writefile(TCHAR *filetext) -{ -#ifdef UseLogging - /* File Write Function, written by professor chemicalX */ - FILE *fp; /* Declare FILE structure */ - TCHAR szTemp[512]; - char szTempA[512]; - - wsprintf(szTemp, L"%s", filetext); - wcstombs(szTempA, szTemp, sizeof(szTemp)/sizeof(TCHAR)); - - DEBUGMSG(UseLogging, (szTemp)); - - checkFileSize(); - - fp = fopen(logFileName, "a+"); - - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - /* First of we open the file supplied by the filename paremeter */ - - /* - * in the "a+" mode for appending, so if it doesnt exist its created. - * fp = fopen(filename,"w"); // Open using the "w" mode for writing. - */ - long fsize = strlen(szTempA); /* Declare the long fsize with the length of the filetext */ - /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ - - /* paremeter witch stores the text or data to right to the file. */ - fwrite(szTempA, 1, fsize, fp); /* Write File */ - fclose(fp); /* Remember to close the file stream after calling file functions, */ - - /* otherwise the file wont be created. */ -#endif - return 0; -} - -void Add2LogWithTime(TCHAR *txt) -{ - BOOL bLogTime = TRUE; - TCHAR str[512]; - TCHAR lpTimeStr[128]; - TCHAR lpDateStr[128]; - LONG res; - wsprintf(str,L""); - //Read the system time - res = GetTimeFormat(LOCALE_SYSTEM_DEFAULT, - TIME_FORCE24HOURFORMAT, - NULL, - L"hh:mm:ss", - lpTimeStr, - sizeof (lpTimeStr ) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpTimeStr, L"err"); - } - - //Read the system date - res = GetDateFormat( LOCALE_SYSTEM_DEFAULT, - NULL, - NULL, - L"dd.MM.yyyy", - lpDateStr, - sizeof (lpDateStr) * sizeof(TCHAR)); - if (res == 0) - { - wcscpy(lpDateStr, L"err"); - } - - if (bLogTime == TRUE) - wsprintf(str, L"%s %s\t%s", lpDateStr, lpTimeStr , txt); - else - wsprintf(str, L"%s", txt); - writefile(str); - -} - -void Add2Log(char *txt, BOOL bLogTime = TRUE) -{ - TCHAR szTemp[512]; - char szTempA[512]; - wsprintf(szTemp, L""); - sprintf(szTempA, ""); - sprintf(szTempA, "%s", txt); - mbstowcs(szTemp, szTempA, 512);//strlen(szTempA)*sizeof(szTempA[0])); - - Add2Log(szTemp, bLogTime); -} diff --git a/cli-tools/SetDefaultLocale/SetDefaultLocale/log2file.h b/cli-tools/SetDefaultLocale/SetDefaultLocale/log2file.h deleted file mode 100644 index 15e2222..0000000 --- a/cli-tools/SetDefaultLocale/SetDefaultLocale/log2file.h +++ /dev/null @@ -1,41 +0,0 @@ -//log2file.h - -#include - -#pragma once - -#ifndef _LOG2_FILE_ -#define _LOG2_FILE_ - -//use #define UseLogging to enable logging -#define UseLogging 1 //to enable logging to file - -//global -static BOOL bFirstFileCall=true; - -extern char logFileName[MAX_PATH]; -extern TCHAR logFileNameW[MAX_PATH]; -//bool FirstStart = FALSE; - -int initFileNames(); -int initFileNames(TCHAR* _logFileName); - -void Add2Log(TCHAR); -void Add2Log(LPSTR); - -//void Add2Log(TCHAR *txt, BOOL bLogTime); -void Add2LogWithTime(TCHAR *txt); - -void Add2Log(char *txt, BOOL bLogTime); -void Add2Log (TCHAR *lpszFormat, ...); - -void Add2LogWtime (TCHAR *lpszFormat, ...); - -int writefile(LPTSTR); -int newfile(LPSTR); -int newfile(TCHAR); -int appendfile(LPSTR); - - - -#endif //_LOG2_FILE_ \ No newline at end of file diff --git a/cli-tools/SetDefaultLocale/SetDefaultLocale/stdafx.cpp b/cli-tools/SetDefaultLocale/SetDefaultLocale/stdafx.cpp deleted file mode 100644 index b6235d1..0000000 --- a/cli-tools/SetDefaultLocale/SetDefaultLocale/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// SetDefaultLocale.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/cli-tools/SetDefaultLocale/SetDefaultLocale/stdafx.h b/cli-tools/SetDefaultLocale/SetDefaultLocale/stdafx.h deleted file mode 100644 index fd73e97..0000000 --- a/cli-tools/SetDefaultLocale/SetDefaultLocale/stdafx.h +++ /dev/null @@ -1,57 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include - -#include -#pragma comment(lib, "aygshell.lib") - - - -#include -#include - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here -#include "log2file.h" diff --git a/cli-tools/TimeZoneSet/ReadMe.txt b/cli-tools/TimeZoneSet/ReadMe.txt deleted file mode 100644 index 7781644..0000000 --- a/cli-tools/TimeZoneSet/ReadMe.txt +++ /dev/null @@ -1,17 +0,0 @@ -======================================================================== - Windows CE APPLICATION : TimeZoneSet -======================================================================== - -the app only supports one argument, a positive or negative number specifying -the GMT offset in inverted notation. -If you want to set GMT+1 you need to run - -TimeZoneSet -1 - -You cannot specify a city or other informations like DST on/off. This would -require another tool. - -TimeZoneSet always dumps a list of known cities and timezones to -\TZ-cities.TXT - -///////////////////////////////////////////////////////////////////////////// diff --git a/cli-tools/TimeZoneSet/StdAfx.cpp b/cli-tools/TimeZoneSet/StdAfx.cpp deleted file mode 100644 index 5731a5f..0000000 --- a/cli-tools/TimeZoneSet/StdAfx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// TimeZoneSet.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/cli-tools/TimeZoneSet/StdAfx.h b/cli-tools/TimeZoneSet/StdAfx.h deleted file mode 100644 index 9d98dc8..0000000 --- a/cli-tools/TimeZoneSet/StdAfx.h +++ /dev/null @@ -1,25 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#if !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_) -#define AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include - -// Local Header Files - -// TODO: reference additional headers your program requires here - -//{{AFX_INSERT_LOCATION}} -// Microsoft eMbedded Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STDAFX_H__A9DB83DB_A9FD_11D0_BFD1_444553540000__INCLUDED_) diff --git a/cli-tools/TimeZoneSet/TZ-cities.TXT b/cli-tools/TimeZoneSet/TZ-cities.TXT deleted file mode 100644 index 43ecc1f..0000000 --- a/cli-tools/TimeZoneSet/TZ-cities.TXT +++ /dev/null @@ -1,450 +0,0 @@ -index: 0 - short name: GMT-12 Kwajalein - name: Dateline Standard Time - GMT offset: 720 - dst name: Dateline Daylight Time - DST offset: 0 -index: 1 - short name: GMT-11 Samoa,Midway - name: Samoa Standard Time - GMT offset: 660 - dst name: Samoa Daylight Time - DST offset: 0 -index: 2 - short name: GMT-10 Hawaii - name: Hawaiian Standard Time - GMT offset: 600 - dst name: Hawaiian Daylight Time - DST offset: 0 -index: 3 - short name: GMT-9 Alaska - name: Alaskan Standard Time - GMT offset: 540 - dst name: Alaskan Daylight Time - DST offset: 0 -index: 4 - short name: GMT-8 Pacific US - name: Pacific Standard Time - GMT offset: 480 - dst name: Pacific Daylight Time - DST offset: 0 -index: 10 - short name: GMT-7 Mountain US - name: Mountain Standard Time - GMT offset: 420 - dst name: Mountain Daylight Time - DST offset: 0 -index: 13 - short name: GMT-7 Chihuahua, La Paz - name: Mexico Standard Time - GMT offset: 420 - dst name: Mexico Daylight Time - DST offset: 0 -index: 15 - short name: GMT-7 Arizona - name: US Mountain Standard Time - GMT offset: 420 - dst name: US Mountain Daylight Time - DST offset: 0 -index: 20 - short name: GMT-6 Central US - name: Central Standard Time - GMT offset: 360 - dst name: Central Daylight Time - DST offset: 0 -index: 25 - short name: GMT-6 Saskatchewan - name: Canada Central Standard Time - GMT offset: 360 - dst name: Canada Central Daylight Time - DST offset: 0 -index: 30 - short name: GMT-6 Mexico City, Monterrey - name: Mexico Standard Time - GMT offset: 360 - dst name: Mexico Daylight Time - DST offset: 0 -index: 33 - short name: GMT-6 Cent. America - name: Central America Standard Time - GMT offset: 360 - dst name: Central America Daylight Time - DST offset: 0 -index: 35 - short name: GMT-5 Eastern US - name: Eastern Standard Time - GMT offset: 300 - dst name: Eastern Daylight Time - DST offset: 0 -index: 40 - short name: GMT-5 Indiana (USA) - name: US Eastern Standard Time - GMT offset: 300 - dst name: US Eastern Daylight Time - DST offset: 0 -index: 45 - short name: GMT-5 Bogota,Lima - name: SA Pacific Standard Time - GMT offset: 300 - dst name: SA Pacific Daylight Time - DST offset: 0 -index: 50 - short name: GMT-4 Atlantic - name: Atlantic Standard Time - GMT offset: 240 - dst name: Atlantic Daylight Time - DST offset: 0 -index: 55 - short name: GMT-4 Caracas,La Paz - name: SA Western Standard Time - GMT offset: 240 - dst name: SA Western Daylight Time - DST offset: 0 -index: 56 - short name: GMT-4 Santiago - name: Pacific SA Standard Time - GMT offset: 240 - dst name: Pacific SA Daylight Time - DST offset: 0 -index: 60 - short name: GMT-3:30 Newfoundland - name: Newfoundland Standard Time - GMT offset: 210 - dst name: Newfoundland Daylight Time - DST offset: 0 -index: 65 - short name: GMT-3 Brasilia - name: E. South America Standard Time - GMT offset: 180 - dst name: E. South America Daylight Time - DST offset: 0 -index: 70 - short name: GMT-3 Buenos Aires - name: SA Eastern Standard Time - GMT offset: 180 - dst name: SA Eastern Daylight Time - DST offset: 0 -index: 73 - short name: GMT-3 Greenland - name: Greenland Standard Time - GMT offset: 180 - dst name: Greenland Daylight Time - DST offset: 0 -index: 75 - short name: GMT-2 Mid-Atlantic - name: Mid-Atlantic Standard Time - GMT offset: 120 - dst name: Mid-Atlantic Daylight Time - DST offset: 0 -index: 80 - short name: GMT-1 Azores - name: Azores Standard Time - GMT offset: 60 - dst name: Azores Daylight Time - DST offset: 0 -index: 83 - short name: GMT-1 Cape Verde - name: Cape Verde Standard Time - GMT offset: 60 - dst name: Cape Verde Daylight Time - DST offset: 0 -index: 85 - short name: GMT London,Dublin - name: GMT - GMT offset: 0 - dst name: British Summer Time - DST offset: 0 -index: 90 - short name: GMT Casablanca - name: GMT Standard Time - GMT offset: 0 - dst name: GMT DST - DST offset: 0 -index: 95 - short name: GMT+1 Prague,Budapest - name: Central Europe Standard Time - GMT offset: -60 - dst name: Central Europe Daylight Time - DST offset: 0 -index: 100 - short name: GMT+1 Warsaw,Sofija - name: Central European Standard Time - GMT offset: -60 - dst name: Central European Daylight Time - DST offset: 0 -index: 105 - short name: GMT+1 Paris,Madrid - name: Romance Standard Time - GMT offset: -60 - dst name: Romance Daylight Time - DST offset: 0 -index: 110 - short name: GMT+1 Berlin,Rome - name: W. Europe Standard Time - GMT offset: -60 - dst name: W. Europe Daylight Time - DST offset: 0 -index: 113 - short name: GMT+1 W Cent Africa - name: West Central Africa Standard Time - GMT offset: -60 - dst name: West Central Africa Daylight Time - DST offset: 0 -index: 115 - short name: GMT+2 Bucharest - name: E. Europe Standard Time - GMT offset: -120 - dst name: E. Europe Daylight Time - DST offset: 0 -index: 120 - short name: GMT+2 Cairo - name: Egypt Standard Time - GMT offset: -120 - dst name: Egypt Daylight Time - DST offset: 0 -index: 125 - short name: GMT+2 Helsinki,Riga - name: FLE Standard Time - GMT offset: -120 - dst name: FLE Daylight Time - DST offset: 0 -index: 130 - short name: GMT+2 Athens,Istanbul - name: GTB Standard Time - GMT offset: -120 - dst name: GTB Daylight Time - DST offset: 0 -index: 135 - short name: GMT+2 Jerusalem - name: Israel Standard Time - GMT offset: -120 - dst name: Israel Daylight Time - DST offset: 0 -index: 140 - short name: GMT+2 Pretoria - name: South Africa Standard Time - GMT offset: -120 - dst name: South Africa Daylight Time - DST offset: 0 -index: 145 - short name: GMT+3 Moscow - name: Russian Standard Time - GMT offset: -180 - dst name: Russian Daylight Time - DST offset: 0 -index: 150 - short name: GMT+3 Riyadh, Kuwait - name: Arab Standard Time - GMT offset: -180 - dst name: Arab Daylight Time - DST offset: 0 -index: 155 - short name: GMT+3 Nairobi - name: East Africa Standard Time - GMT offset: -180 - dst name: East Africa Daylight Time - DST offset: 0 -index: 158 - short name: GMT+3 Baghdad - name: Arabic Standard Time - GMT offset: -180 - dst name: Arabic Daylight Time - DST offset: 0 -index: 160 - short name: GMT+3:30 Tehran - name: Iran Standard Time - GMT offset: -210 - dst name: Iran Daylight Time - DST offset: 0 -index: 165 - short name: GMT+4 Abu Dhabi - name: Arabian Standard Time - GMT offset: -240 - dst name: Arabian Daylight Time - DST offset: 0 -index: 170 - short name: GMT+4 Baku,Tbilisi - name: Caucasus Standard Time - GMT offset: -240 - dst name: Caucasus Daylight Time - DST offset: 0 -index: 175 - short name: GMT+4:30 Kabul - name: Afghanistan Standard Time - GMT offset: -270 - dst name: Afghanistan Daylight Time - DST offset: 0 -index: 180 - short name: GMT+5 Yekaterinburg - name: Yekaterinburg Standard Time - GMT offset: -300 - dst name: Yekaterinburg Daylight Time - DST offset: 0 -index: 185 - short name: GMT+5 Islamabad - name: West Asia Standard Time - GMT offset: -300 - dst name: West Asia Daylight Time - DST offset: 0 -index: 190 - short name: GMT+5:30 New Delhi - name: India Standard Time - GMT offset: -330 - dst name: India Daylight Time - DST offset: 0 -index: 193 - short name: GMT+5:45 Kathmandu - name: Nepal Standard Time - GMT offset: -345 - dst name: Nepal Daylight Time - DST offset: 0 -index: 195 - short name: GMT+6 Astana,Dhaka - name: Central Asia Standard Time - GMT offset: -360 - dst name: Central Asia Daylight Time - DST offset: 0 -index: 200 - short name: GMT+6 Sri Lanka - name: Sri Lanka Standard Time - GMT offset: -360 - dst name: Sri Lanka Daylight Time - DST offset: 0 -index: 201 - short name: GMT+6 Almaty - name: N. Central Asia Standard Time - GMT offset: -360 - dst name: N. Central Asia Daylight Time - DST offset: 0 -index: 203 - short name: GMT+6:30 Yangoon - name: Myanmar Standard Time - GMT offset: -390 - dst name: Myanmar Asia Daylight Time - DST offset: 0 -index: 205 - short name: GMT+7 Bangkok,Hanoi - name: SE Asia Standard Time - GMT offset: -420 - dst name: SE Asia Daylight Time - DST offset: 0 -index: 207 - short name: GMT+7 Krasnoyarsk - name: North Asia Standard Time - GMT offset: -420 - dst name: North Asia Daylight Time - DST offset: 0 -index: 210 - short name: GMT+8 Beijing, HK - name: China Standard Time - GMT offset: -480 - dst name: China Daylight Time - DST offset: 0 -index: 215 - short name: GMT+8 Malaysia,Singapore - name: Malay Standard Time - GMT offset: -480 - dst name: Malay Daylight Time - DST offset: 0 -index: 220 - short name: GMT+8 Taipei - name: Taipei Standard Time - GMT offset: -480 - dst name: Taipei Daylight Time - DST offset: 0 -index: 225 - short name: GMT+8 Perth - name: West Australia Standard Time - GMT offset: -480 - dst name: West Australia Daylight Time - DST offset: 0 -index: 227 - short name: GMT+8 Ulaanbataar - name: North Asia East Standard Time - GMT offset: -480 - dst name: North Asia East Daylight Time - DST offset: 0 -index: 230 - short name: GMT+9 Seoul - name: Korea Standard Time - GMT offset: -540 - dst name: Korea Daylight Time - DST offset: 0 -index: 235 - short name: GMT+9 Tokyo,Osaka - name: Tokyo Standard Time - GMT offset: -540 - dst name: Tokyo Daylight Time - DST offset: 0 -index: 240 - short name: GMT+9 Yakutsk - name: Yakutsk Standard Time - GMT offset: -540 - dst name: Yakutsk Daylight Time - DST offset: 0 -index: 245 - short name: GMT+9:30 Darwin - name: AUS Central Standard Time - GMT offset: -570 - dst name: AUS Central Daylight Time - DST offset: 0 -index: 250 - short name: GMT+9:30 Adelaide - name: Cen. Australia Standard Time - GMT offset: -570 - dst name: Cen. Australia Daylight Time - DST offset: 0 -index: 255 - short name: GMT+10 Sydney - name: Sydney Standard Time - GMT offset: -600 - dst name: Sydney Daylight Time - DST offset: 0 -index: 260 - short name: GMT+10 Brisbane - name: E Australia Standard Time - GMT offset: -600 - dst name: E Australia Daylight Time - DST offset: 0 -index: 265 - short name: GMT+10 Hobart - name: Tasmania Standard Time - GMT offset: -600 - dst name: Tasmania Daylight Time - DST offset: 0 -index: 270 - short name: GMT+10 Vladivostok - name: Vladivostok Standard Time - GMT offset: -600 - dst name: Vladivostok Daylight Time - DST offset: 0 -index: 275 - short name: GMT+10 Guam - name: West Pacific Standard Time - GMT offset: -600 - dst name: West Pacific Daylight Time - DST offset: 0 -index: 280 - short name: GMT+11 Magadan - name: Central Pacific Standard Time - GMT offset: -660 - dst name: Central Pacific Daylight Time - DST offset: 0 -index: 285 - short name: GMT+12 Fiji Islands - name: Fiji Standard Time - GMT offset: -720 - dst name: Fiji Daylight Time - DST offset: 0 -index: 290 - short name: GMT+12 New Zealand - name: New Zealand Standard Time - GMT offset: -720 - dst name: New Zealand Daylight Time - DST offset: 0 -index: 300 - short name: GMT+13 Tonga - name: Tonga Standard Time - GMT offset: -780 - dst name: Tonga Daylight Time - DST offset: 0 diff --git a/cli-tools/TimeZoneSet/TimeZoneSet.cpp b/cli-tools/TimeZoneSet/TimeZoneSet.cpp deleted file mode 100644 index 0dbaf9e..0000000 --- a/cli-tools/TimeZoneSet/TimeZoneSet.cpp +++ /dev/null @@ -1,322 +0,0 @@ -// TimeZoneSet.cpp : Defines the entry point for the application. -// - -#include "stdafx.h" - -typedef void (*INITCITYDB)(void); -typedef void (*UNINITCITYDB)(void); -typedef void (*LOADTZDATA)(void); -typedef void (*FREETZDATA)(void); -typedef int (*GETNUMZONES)(void); -typedef void * (*GETTZDATABYOFFSET)(int, int*); -typedef void * (*GETTZDATA)(int); - -struct TZData -{ - TCHAR *Name; - TCHAR *ShortName; - TCHAR *DSTName; - int GMTOffset; - int DSTOffset; -}; - -typedef struct tagTZREG { // 44 bytes - LONG Bias; // 4 bytes - LONG StandardBias; - LONG DaylightBias; - SYSTEMTIME StandardDate; // 8*2 bytes - SYSTEMTIME DaylightDate; -} TZREG; - -/* -typedef struct _SYSTEMTIME { - WORD wYear; - WORD wMonth; - WORD wDayOfWeek; - WORD wDay; - WORD wHour; - WORD wMinute; - WORD wSecond; - WORD wMilliseconds; -} SYSTEMTIME, *LPSYSTEMTIME; -*/ - /* - typedef struct _TIME_ZONE_INFORMATION { - LONG Bias; - WCHAR StandardName[ 32 ]; - SYSTEMTIME StandardDate; - LONG StandardBias; - WCHAR DaylightName[ 32 ]; - SYSTEMTIME DaylightDate; - LONG DaylightBias; - } TIME_ZONE_INFORMATION, *LPTIME_ZONE_INFORMATION; - 88,ff,ff,ff, - 45,00,2e,00,20,00,45,00,75,00,72,00,6f,00,70,00,65,00,20,00,53,00,74,00,61,00,6e,00,64,00,61,00,72,00,64,00,20,00,54,00,69,00,6d,00,65,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,09,00,00,00,05,00,01,00,00,00,00,00,00,00,00,00,00,00,45,00,2e,00,20,00,45,00,75,00,72,00,6f,00,70,00,65,00,20,00,44,00,61,00,79,00,6c,00,69,00,67,00,68,00,74,00,20,00,54,00,69,00,6d,00,65,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,03,00,00,00,05,00,00,00,00,00,00,00,00,00, - c4,ff,ff,ff - - */ - -void ShowError(LONG er) -{ - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - er, - 0, // Default language - (LPTSTR) &lpMsgBuf, - 0, - NULL - ); - TCHAR temp[MAX_PATH]; - wsprintf(temp, (LPTSTR)lpMsgBuf); - // Process any inserts in lpMsgBuf. - // ... - // Display the string. - DEBUGMSG(1, ((LPCTSTR)lpMsgBuf)); - // Free the buffer. - LocalFree( lpMsgBuf ); -} - -int getCityDB() -{ - TZData *pTZ = NULL; - int index; - - // load the library - HINSTANCE hLib = LoadLibrary(_T("CityDB.dll")); - if (hLib==NULL) - return -1; - // load the CityDB functions - INITCITYDB InitCityDB = (INITCITYDB)GetProcAddress( - hLib, _T("InitCityDb")); - UNINITCITYDB UninitCityDB = (UNINITCITYDB)GetProcAddress( - hLib, _T("UninitCityDb")); - LOADTZDATA ClockLoadAllTimeZoneData = (LOADTZDATA)GetProcAddress( - hLib, _T("ClockLoadAllTimeZoneData")); - FREETZDATA ClockFreeAllTimeZoneData = (FREETZDATA)GetProcAddress( - hLib, _T("ClockFreeAllTimeZoneData")); - GETNUMZONES ClockGetNumTimezones = (GETNUMZONES)GetProcAddress( - hLib, _T("ClockGetNumTimezones")); - GETTZDATABYOFFSET ClockGetTimeZoneDataByOffset = - (GETTZDATABYOFFSET)GetProcAddress(hLib, _T("ClockGetTimeZoneDataByOffset")); - GETTZDATA ClockGetTimeZoneData = (GETTZDATA)GetProcAddress( - hLib, _T("ClockGetTimeZoneData")); - - // Init the library - InitCityDB(); - - // load the TZ data - ClockLoadAllTimeZoneData(); - - // find out how many zones are defined - int zoneCount = ClockGetNumTimezones(); - - HANDLE hFile = CreateFile (TEXT("\\TZ-cities.TXT"), // Open Two.txt. - GENERIC_WRITE, // Open for writing - 0, // Do not share - NULL, // No security - OPEN_ALWAYS, // Open or create - FILE_ATTRIBUTE_NORMAL, // Normal file - NULL); // No template file - - if (hFile == INVALID_HANDLE_VALUE) - { - //wsprintf (szMsg, TEXT("Could not open TWO.TXT")); - CloseHandle (hFile); // Close the first file. - return -2; - } - char buff[4096]; - TCHAR wBuff[4096]; - DWORD numToWrit, numWritten; - - TIME_ZONE_INFORMATION tzi; - memset(&tzi, 0, sizeof(tzi)); - int ret=GetTimeZoneInformation(&tzi); - wsprintf(wBuff, L"===================TimeZoneInformation (API)==================\n"); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"Bias: %i\n", tzi.Bias ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightBias: %i\n", tzi.DaylightBias ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightDate: %i\n", tzi.DaylightDate ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightName: %s\n", tzi.DaylightName ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardBias: %i\n", tzi.StandardBias ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardBias: %i\n", tzi.StandardDate ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightName: %s\n", tzi.StandardName); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - HKEY phKey; - TIME_ZONE_INFORMATION *tzi2; - //memset(&tzi2, 0, sizeof(TIME_ZONE_INFORMATION)); - byte *data; - data = (byte *)malloc(4096); - DWORD count = 4096; - DWORD type; //=REG_BINARY; - - wsprintf(wBuff, L"===================TimeZoneInformation (reg)==================\n"); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - if (RegOpenKeyEx(HKEY_LOCAL_MACHINE , L"TIME", 0, 0, &phKey) == ERROR_SUCCESS) - { - int ret = RegQueryValueEx(phKey, L"TimeZoneInformation", NULL, &type, data, &count); - if (ret == ERROR_SUCCESS) - { - //TIME_ZONE_INFORMATION - tzi2 = (TIME_ZONE_INFORMATION *) data; - - wsprintf(wBuff, L"Bias: %i\n", tzi2->Bias ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightBias: %i\n", tzi2->DaylightBias); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightDate: %i\n", tzi2->DaylightDate); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"DaylightName: %s\n", tzi2->DaylightName); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardBias: %i\n", tzi2->StandardBias); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardDate: %i\n", tzi2->StandardDate); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"StandardName: %i\n", tzi2->StandardName); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - } - else - ShowError(ret); - } - free (data); - - wsprintf(wBuff, L"=================CityDB====================\n"); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - // interate through them all - for(int zone = 0 ; zone < zoneCount ; zone++) - { - // these are pointers to a timezone data struct - pTZ = (TZData*)ClockGetTimeZoneDataByOffset(zone, &index); - - wsprintf(wBuff, L"index: %i\n", index ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tshort name: %s\n", pTZ->ShortName ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tname: %s\n", pTZ->Name ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tGMT offset: %i\n", pTZ->GMTOffset ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tdst name: %s\n", pTZ->DSTName ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - - wsprintf(wBuff, L"\tDST offset: %i\n", pTZ->DSTOffset ); - wcstombs(buff, wBuff, sizeof(wBuff)*sizeof(TCHAR)); - WriteFile(hFile, buff, strlen(buff), &numWritten, NULL); - } - CloseHandle(hFile); - - // unload the TZ data - ClockFreeAllTimeZoneData(); - - // uninit the library - UninitCityDB(); - - return 0; -} - -int WINAPI WinMain( HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - // TODO: Place code here. - - byte lSize=sizeof(LONG); - - getCityDB(); - TIME_ZONE_INFORMATION tzi; - memset(&tzi, 0, sizeof(tzi)); - - int ret=GetTimeZoneInformation(&tzi); - switch (ret) - { - case TIME_ZONE_ID_UNKNOWN: - break; - case TIME_ZONE_ID_STANDARD: - break; - case TIME_ZONE_ID_DAYLIGHT: - break; - default: - //error - break; - } - - //The bias is the difference, in minutes, between UTC and local time - //so to get GMT+1 you have to specify -1 atoi - int hourOffset = 0; - int i=0; - - if (wcslen(lpCmdLine)>0) - { - i = _ttoi(lpCmdLine); - if (i!=0) - hourOffset=i; - } - - TCHAR s[32]; - tzi.Bias = hourOffset*60; - - wsprintf(s, L"GMT DST"); - wcscpy(tzi.DaylightName, L"GMT DST"); - - wsprintf(s, L"GMT"); - wcscpy(tzi.StandardName, L"GMT"); - - ret=SetTimeZoneInformation(&tzi); - if (ret==0) - return ret; //error - - //TZREG - return 0; -} - diff --git a/cli-tools/TimeZoneSet/TimeZoneSet.rc b/cli-tools/TimeZoneSet/TimeZoneSet.rc deleted file mode 100644 index a852f8f..0000000 --- a/cli-tools/TimeZoneSet/TimeZoneSet.rc +++ /dev/null @@ -1,58 +0,0 @@ -//Microsoft eMbedded Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "newres.h" -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -#ifdef _WIN32 -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) -#endif - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""newres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED diff --git a/cli-tools/TimeZoneSet/TimeZoneSet.sln b/cli-tools/TimeZoneSet/TimeZoneSet.sln deleted file mode 100644 index 8b3f726..0000000 --- a/cli-tools/TimeZoneSet/TimeZoneSet.sln +++ /dev/null @@ -1,94 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TimeZoneSet", "TimeZoneSet.vcproj", "{899F983F-F9BB-432D-8A83-4F719BB7B4D8}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|iCE-Premium (ARMV4I) = Debug|iCE-Premium (ARMV4I) - Debug|Pocket PC 2003 (ARMV4) = Debug|Pocket PC 2003 (ARMV4) - Debug|Smartphone 2003 (ARMV4) = Debug|Smartphone 2003 (ARMV4) - Debug|STANDARDSDK_420 (ARMV4I) = Debug|STANDARDSDK_420 (ARMV4I) - Debug|STANDARDSDK_500 (ARMV4I) = Debug|STANDARDSDK_500 (ARMV4I) - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - Debug|Windows Mobile 6 Professional SDK (ARMV4I) = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - Debug|Windows Mobile 6 Standard SDK (ARMV4I) = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) = Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - Release|iCE-Premium (ARMV4I) = Release|iCE-Premium (ARMV4I) - Release|Pocket PC 2003 (ARMV4) = Release|Pocket PC 2003 (ARMV4) - Release|Smartphone 2003 (ARMV4) = Release|Smartphone 2003 (ARMV4) - Release|STANDARDSDK_420 (ARMV4I) = Release|STANDARDSDK_420 (ARMV4I) - Release|STANDARDSDK_500 (ARMV4I) = Release|STANDARDSDK_500 (ARMV4I) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - Release|Windows Mobile 6 Professional SDK (ARMV4I) = Release|Windows Mobile 6 Professional SDK (ARMV4I) - Release|Windows Mobile 6 Standard SDK (ARMV4I) = Release|Windows Mobile 6 Standard SDK (ARMV4I) - Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) = Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|iCE-Premium (ARMV4I).ActiveCfg = Debug|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|iCE-Premium (ARMV4I).Build.0 = Debug|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|iCE-Premium (ARMV4I).Deploy.0 = Debug|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Pocket PC 2003 (ARMV4).ActiveCfg = Debug|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Pocket PC 2003 (ARMV4).Build.0 = Debug|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Pocket PC 2003 (ARMV4).Deploy.0 = Debug|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Smartphone 2003 (ARMV4).ActiveCfg = Debug|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Smartphone 2003 (ARMV4).Build.0 = Debug|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Smartphone 2003 (ARMV4).Deploy.0 = Debug|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_420 (ARMV4I).ActiveCfg = Debug|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_420 (ARMV4I).Build.0 = Debug|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_420 (ARMV4I).Deploy.0 = Debug|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_500 (ARMV4I).ActiveCfg = Debug|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_500 (ARMV4I).Build.0 = Debug|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|STANDARDSDK_500 (ARMV4I).Deploy.0 = Debug|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I).Build.0 = Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|iCE-Premium (ARMV4I).ActiveCfg = Release|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|iCE-Premium (ARMV4I).Build.0 = Release|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|iCE-Premium (ARMV4I).Deploy.0 = Release|iCE-Premium (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Pocket PC 2003 (ARMV4).ActiveCfg = Release|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Pocket PC 2003 (ARMV4).Build.0 = Release|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Pocket PC 2003 (ARMV4).Deploy.0 = Release|Pocket PC 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Smartphone 2003 (ARMV4).ActiveCfg = Release|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Smartphone 2003 (ARMV4).Build.0 = Release|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Smartphone 2003 (ARMV4).Deploy.0 = Release|Smartphone 2003 (ARMV4) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_420 (ARMV4I).ActiveCfg = Release|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_420 (ARMV4I).Build.0 = Release|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_420 (ARMV4I).Deploy.0 = Release|STANDARDSDK_420 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_500 (ARMV4I).ActiveCfg = Release|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_500 (ARMV4I).Build.0 = Release|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|STANDARDSDK_500 (ARMV4I).Deploy.0 = Release|STANDARDSDK_500 (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Smartphone SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I).ActiveCfg = Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I).Build.0 = Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - {899F983F-F9BB-432D-8A83-4F719BB7B4D8}.Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I).Deploy.0 = Release|Windows Mobile 6.5.3 Professional DTK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/cli-tools/TimeZoneSet/TimeZoneSet.vcproj b/cli-tools/TimeZoneSet/TimeZoneSet.vcproj deleted file mode 100644 index 457b07c..0000000 --- a/cli-tools/TimeZoneSet/TimeZoneSet.vcproj +++ /dev/null @@ -1,2396 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cli-tools/TimeZoneSet/newres.h b/cli-tools/TimeZoneSet/newres.h deleted file mode 100644 index 89e6e23..0000000 --- a/cli-tools/TimeZoneSet/newres.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef __NEWRES_H__ -#define __NEWRES_H__ - -#if !defined(UNDER_CE) - #define UNDER_CE _WIN32_WCE -#endif - -#if defined(_WIN32_WCE) - #if !defined(WCEOLE_ENABLE_DIALOGEX) - #define DIALOGEX DIALOG DISCARDABLE - #endif - #include - #define SHMENUBAR RCDATA - #if defined(WIN32_PLATFORM_PSPC) && (_WIN32_WCE >= 300) - #include - #else - #define I_IMAGENONE (-2) - #define NOMENU 0xFFFF - #define IDS_SHNEW 1 - - #define IDM_SHAREDNEW 10 - #define IDM_SHAREDNEWDEFAULT 11 - #endif -#endif // _WIN32_WCE - - -#ifdef RC_INVOKED -#ifndef _INC_WINDOWS -#define _INC_WINDOWS - #include "winuser.h" // extract from windows header -#endif -#endif - -#ifdef IDC_STATIC -#undef IDC_STATIC -#endif -#define IDC_STATIC (-1) - -#endif //__NEWRES_H__ diff --git a/cli-tools/TimeZoneSet/resource.h b/cli-tools/TimeZoneSet/resource.h deleted file mode 100644 index 902d6ea..0000000 --- a/cli-tools/TimeZoneSet/resource.h +++ /dev/null @@ -1,4 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft eMbedded Visual C++ generated include file. -// Used by TIMEZONESET.RC -// diff --git a/cli-tools/TimeZoneSet/tzreg.txt b/cli-tools/TimeZoneSet/tzreg.txt deleted file mode 100644 index 32087f6..0000000 --- a/cli-tools/TimeZoneSet/tzreg.txt +++ /dev/null @@ -1,30 +0,0 @@ -BIAS: - -88,ff,ff,ff, - -StandardName: -45, 00, 2e, 00, 20, 00, 45, 00, 75, 00, 72, 00, 6f, 00, 70, 00, 65, 00, 20, 00, 53, 00, 74, 00, 61, 00, 6e, 00, 64, 00, 61, 00, 72, 00, 64, 00, 20, 00, 54, 00, 69, 00, 6d, 00, 65, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 - -StandardDate: -00, 00, 09, 00, 00, 00, 05, 00, 00, 00, 05, 00 - -StandardBias: -01, 00, 00, 00 - -DaylightName: -00, 00, 00, 00, 00, 00, 00, 00, 45, 00, 2e, 00, 20, 00, 45, 00, 75, 00, 72, 00, 6f, 00, 70, 00, 65, 00, 20, 00, 44, 00, 61, 00, 79, 00, 6c, 00, 69, 00, 67, 00, 68, 00, 74, 00, 20, 00, 54, 00, 69, 00, 6d, 00, 65, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00 - -DaylightDate: -00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 03, 00 - -DaylightBias: -00, 00, 05, 00 - -00 -00 -00 -00 -00 -00 -00 -00 diff --git a/cli-tools/iBacklightCLI/iBacklightCLI.sln b/cli-tools/iBacklightCLI/iBacklightCLI.sln deleted file mode 100644 index fd339d7..0000000 --- a/cli-tools/iBacklightCLI/iBacklightCLI.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "iBacklightCLI", "iBacklightCLI\iBacklightCLI.vcproj", "{A2BD0B7D-0716-4591-AD45-536ACED72F15}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A2BD0B7D-0716-4591-AD45-536ACED72F15}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {A2BD0B7D-0716-4591-AD45-536ACED72F15}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {A2BD0B7D-0716-4591-AD45-536ACED72F15}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {A2BD0B7D-0716-4591-AD45-536ACED72F15}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {A2BD0B7D-0716-4591-AD45-536ACED72F15}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {A2BD0B7D-0716-4591-AD45-536ACED72F15}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/cli-tools/iBacklightCLI/iBacklightCLI/ReadMe.txt b/cli-tools/iBacklightCLI/iBacklightCLI/ReadMe.txt deleted file mode 100644 index 1d78dfb..0000000 --- a/cli-tools/iBacklightCLI/iBacklightCLI/ReadMe.txt +++ /dev/null @@ -1,19 +0,0 @@ -======================================================================== - CONSOLE APPLICATION : iBacklightCLI Project Overview -======================================================================== - -iBacklightCLI - -arguments function - -on switch backlight on using current brightness -off switch backlight off -max switch backlight brightness to max and on -min switch backlight brightness to min and on - -state return 0 for is OFF, 1 for ON, -1 for error -level return current brightness level or -1 for error - -1 to max level set new brightness level, returns new level or -1 for error (ie val exceeds max level) - -/////////////////////////////////////////////////////////////////////////////s \ No newline at end of file diff --git a/cli-tools/iBacklightCLI/iBacklightCLI/iBacklightCLI.cpp b/cli-tools/iBacklightCLI/iBacklightCLI/iBacklightCLI.cpp deleted file mode 100644 index 071d93b..0000000 --- a/cli-tools/iBacklightCLI/iBacklightCLI/iBacklightCLI.cpp +++ /dev/null @@ -1,109 +0,0 @@ -// iBacklightCLI.cpp : Defines the entry point for the console application. -// - -#include "stdafx.h" - -DWORD maxBrightness=100; - -int setBacklightState(BOOL bOnOff); - -DWORD getMaxBrightness(){ - DWORD dwB; - HRESULT hRes = ITCGetMaxScreenBrightness(&dwB); - if( ITC_ISERROR (hRes) ) - return -1; //failed - maxBrightness=dwB; - return maxBrightness; -} - -int getBacklight(){ - DWORD dwBrightness; - HRESULT hRes = ITCGetScreenBrightness(&dwBrightness); - if( ITC_ISERROR (hRes) ) - return -1; //failed - - hRes = ITCGetScreenBrightnessAcDc(0xDC, &dwBrightness); - if( ITC_ISERROR (hRes) ) - DEBUGMSG(1,(L"DC brightness get not supported\n")); - else - DEBUGMSG(1,(L"DC brightness = %i\n", dwBrightness)); - - hRes = ITCGetScreenBrightnessAcDc(0xAC, &dwBrightness); - if( ITC_ISERROR (hRes) ) - DEBUGMSG(1,(L"AC brightness get not supported\n")); - else - DEBUGMSG(1,(L"AC brightness = %i\n", dwBrightness)); - - return dwBrightness; -} - -int setBacklight(DWORD dwBrightness){ - HRESULT hRes = ITCSetScreenBrightness(dwBrightness); - if( ITC_ISERROR (hRes) ) - return -1; //failed - - hRes = ITCSetScreenBrightnessAcDc(0xAC, dwBrightness); - if( ITC_ISERROR (hRes) ) - DEBUGMSG(1,(L"AC brightness setting not supported\n")); - hRes = ITCSetScreenBrightnessAcDc(0xDC, dwBrightness); - if( ITC_ISERROR (hRes) ) - DEBUGMSG(1,(L"DC brightness setting not supported\n")); - - setBacklightState(TRUE); - return 0; -} - -int setBacklightState(BOOL bOnOff){ - HRESULT hRes = ITCSetScreenLight(bOnOff, TRUE); - if( ITC_ISERROR (hRes) ) - return -1; //failed - return 0; -} - -int getBacklightState(){ - BOOL bOnOff=FALSE; - HRESULT hRes = ITCGetScreenLight(&bOnOff); - if( ITC_ISERROR (hRes) ) - return -1; //failed - if(bOnOff) - return 1; - else - return 0; -} - -int _tmain(int argc, _TCHAR* argv[]) -{ - getMaxBrightness(); - DEBUGMSG(1,(L"Max brightness = %i\n", maxBrightness)); - int iRet = 0; - - if(argc==2){ - //changes - if(wcsicmp(argv[1], L"on")==0) - setBacklightState(TRUE); - else if(wcsicmp(argv[1], L"off")==0) - setBacklightState(FALSE); - else if(wcsicmp(argv[1], L"max")==0) - setBacklight(maxBrightness); - else if(wcsicmp(argv[1], L"min")==0) - setBacklight((DWORD)1); - //queries - else if(wcsicmp(argv[1], L"state")==0) - return (getBacklightState()); - else if(wcsicmp(argv[1], L"level")==0) - return getBacklight(); - else{ - //change - DWORD dwLevel = _wtoi(argv[1]); - if(dwLevel>0 && dwLevel<=maxBrightness){ - setBacklight(dwLevel); - return getBacklight(); - } - else if(dwLevel>maxBrightness) - return -2; - } - } - - return iRet; -} - diff --git a/cli-tools/iBacklightCLI/iBacklightCLI/iBacklightCLI.vcproj b/cli-tools/iBacklightCLI/iBacklightCLI/iBacklightCLI.vcproj deleted file mode 100644 index f6adff4..0000000 --- a/cli-tools/iBacklightCLI/iBacklightCLI/iBacklightCLI.vcproj +++ /dev/null @@ -1,256 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cli-tools/iBacklightCLI/iBacklightCLI/stdafx.cpp b/cli-tools/iBacklightCLI/iBacklightCLI/stdafx.cpp deleted file mode 100644 index 4a6083f..0000000 --- a/cli-tools/iBacklightCLI/iBacklightCLI/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// iBacklightCLI.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/cli-tools/iBacklightCLI/iBacklightCLI/stdafx.h b/cli-tools/iBacklightCLI/iBacklightCLI/stdafx.h deleted file mode 100644 index 5858e82..0000000 --- a/cli-tools/iBacklightCLI/iBacklightCLI/stdafx.h +++ /dev/null @@ -1,58 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include - -#include -#pragma comment(lib, "aygshell.lib") - - - -#include -#include - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here -#include -#pragma comment (lib, "itc50.lib") diff --git a/cpumon.md b/cpumon.md new file mode 100644 index 0000000..c45dc7c --- /dev/null +++ b/cpumon.md @@ -0,0 +1,7 @@ +# Introduction # + +Cpumon2 is a device side cpu usage collector that broadcasts cpu statistics periodically + +CpuMonRcv is a PC side app the listens for cpumon broadcasts, visualizes the data and stores the captured data in a database for later analysis. + +http://code.google.com/p/win-mobile-code/source/browse/#svn%2Ftrunk%2Fcpumon \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMon2/AtomicCF.cs b/cpumon/ProcessorUsage/CpuMon2/AtomicCF.cs deleted file mode 100644 index 2238997..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/AtomicCF.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Runtime.InteropServices; -/* -[C#] -AtomicCF.Timer oTimer = new AtomicCF.Timer(); -oTimer.Start(); -DoSomething(); -long lDur = oTimer.Stop(); -MessageBox.Show("DoSomething executed in " + lDur + "ms"); -*/ -namespace AtomicCF -{ - class Timer - { - [DllImport("coredll.dll")] - extern static int QueryPerformanceCounter(ref long perfCounter); - - [DllImport("coredll.dll")] - extern static int QueryPerformanceFrequency(ref long frequency); - - static private Int64 m_frequency; - private Int64 m_start; - - // Static constructor to initialize frequency. - static Timer() - { - if (QueryPerformanceFrequency(ref m_frequency) == 0) - { - throw new ApplicationException(); - } - // Convert to ms. - m_frequency /= 1000; - } - - public void Start() - { - if (QueryPerformanceCounter(ref m_start) == 0) - { - throw new ApplicationException(); - } - } - - public Int64 Stop() - { - Int64 stop = 0; - if (QueryPerformanceCounter(ref stop) == 0) - { - throw new ApplicationException(); - } - return (stop - m_start) / m_frequency; - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMon2/CpuMon2.csproj b/cpumon/ProcessorUsage/CpuMon2/CpuMon2.csproj deleted file mode 100644 index 4d7337a..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/CpuMon2.csproj +++ /dev/null @@ -1,102 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {2E8B840E-BA26-4659-BD47-D88D307684D0} - WinExe - Properties - CpuMon2 - CpuMon2 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 2AC76CE7-3E8C-402d-85E7-AE9C98D7B6BA - 5.02 - CpuMon2 - v2.0 - Windows Mobile 6.5.3 Professional DTK - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - Form - - - cpumonForm.cs - - - - - - - - - - cpumonForm.cs - Designer - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMon2/MessageTypes.cs b/cpumon/ProcessorUsage/CpuMon2/MessageTypes.cs deleted file mode 100644 index ebe467f..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/MessageTypes.cs +++ /dev/null @@ -1,175 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace System.Process -{ - - class MessageTypes - { - public enum MessageType : byte - { - Process_Statistics, - End_Of_Transfer - } - - } - class ByteHelper - { - const UInt64 magicBytes = 0x524015240152401; - public static byte[] endOfTransferBytes{ - get - { - return BitConverter.GetBytes(magicBytes); - } - }//= new byte[] { 0xFF, 0xFa, 0xaf, 0xAA }; - - public static bool isEndOfTransfer(byte[] buf) - { - bool bRet = false; - if (buf.Length != 8) - return bRet; - try - { - UInt64 u64 = BitConverter.ToUInt64(buf,0); - if (u64 == magicBytes) - bRet = true; - } - catch (Exception) - { - bRet = false; - } - return bRet; - } - - public static byte[] addChkSum(byte[] buffer) - { - byte[] bOut = new byte[buffer.Length + 2]; - UInt32 iChkSum = GetUint32CRC32(buffer); - - byte[] bChkSum = GetCRC32(buffer);// BitConverter.GetBytes(iChkSum); - - Array.Copy(buffer, bOut, buffer.Length); - Array.Copy(bChkSum, 0, bOut, buffer.Length, 2); - return bOut; - } - - public static bool verifyChkSum(byte[] buffer) - { - bool bRet = false; - byte[] bOldChkSum = new byte[4]; - byte[] bufferWithoutChksum = new byte[buffer.Length - 4]; - //copy the member bytes - Array.Copy(buffer, 0, bufferWithoutChksum, 0, buffer.Length - 4); - //copy the exisiting chksum bytes - Array.Copy(buffer,buffer.Length-4,bOldChkSum,0,4); - - UInt32 iOldChkSum = BitConverter.ToUInt32(bOldChkSum,0); - UInt32 iNewChkSum = GetUint32CRC32(bufferWithoutChksum); - - if (iOldChkSum == iNewChkSum) - bRet = true; - return bRet; - } - - /* - // Example use - System.Text.ASCIIEncoding AsciiEncoding = new System.Text.ASCIIEncoding(); - byte[] Checksum = Calculate(AsciiEncoding.GetBytes("Checksum This!")); // String to bytes - MessageBox.Show(AsciiEncoding.GetString(Checksum)); // Return checksum - */ - #region CrcTable - // The CRC value table - private static readonly UInt32[] CRCTable = - { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, - 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, - 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, - 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, - 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, - 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, - 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, - 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, - 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, - 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, - 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, - 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, - 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, - 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, - 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, - 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, - 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, - 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, - 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, - 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, - 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, - 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, - 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, - 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, - 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, - 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, - 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, - 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, - 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, - 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, - 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, - 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, - 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, - 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, - 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, - 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, - 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, - 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, - 0x2d02ef8d - }; -#endregion - // The method that does the magic - public static byte[] GetCRC32(byte[] Value) - { - UInt32 CRCVal = 0xffffffff; - for (int i = 0; i < Value.Length; i++) - { - CRCVal = (CRCVal >> 8) ^ CRCTable[(CRCVal & 0xff) ^ Value[i]]; - } - CRCVal ^= 0xffffffff; // Toggle operation - byte[] Result = new byte[4]; - - Result[0] = (byte)(CRCVal >> 24); - Result[1] = (byte)(CRCVal >> 16); - Result[2] = (byte)(CRCVal >> 8); - Result[3] = (byte)(CRCVal); - - return Result; - } - public static UInt32 GetUint32CRC32(byte[] Value) - { - UInt32 CRCVal = 0xffffffff; - for (int i = 0; i < Value.Length; i++) - { - CRCVal = (CRCVal >> 8) ^ CRCTable[(CRCVal & 0xff) ^ Value[i]]; - } - CRCVal ^= 0xffffffff; // Toggle operation - - byte[] Result = new byte[4]; - Result[0] = (byte)(CRCVal >> 24); - Result[1] = (byte)(CRCVal >> 16); - Result[2] = (byte)(CRCVal >> 8); - Result[3] = (byte)(CRCVal); - - return CRCVal; - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMon2/ProcInfo.cs b/cpumon/ProcessorUsage/CpuMon2/ProcInfo.cs deleted file mode 100644 index d7f28b8..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/ProcInfo.cs +++ /dev/null @@ -1,315 +0,0 @@ -using System; -using System.Collections.Generic; - -using System.Process; - -using System.Net.Sockets; -using System.Net; - -using System.Runtime.InteropServices; - -using System.Threading; - -//using __int64 = System.UInt64; -using DWORD = System.UInt32; -using FILETIME = System.Int64; - -namespace ProcessUsage -{ - /// - /// Provide a list of processes and there thread's cpu load - /// Build a list of processes and another of threads - /// assign the threads to the processes - /// get statistics - /// - public class ProcInfo : IDisposable - { - /// - /// handle to release capture - /// - WaitHandle eventEnableCapture; - /// - /// handle to release data send - /// - WaitHandle eventEnableSend; - /// - /// how often to build a usage list - /// - public int _iTimeOut = 3000; - /// - /// stats for every process - /// - Dictionary statisticsTimes; - - bool bStopMainThread = false; - bool bStopSocketThread = false; - - /// - /// include ourself within statisics? - /// - public bool bIncludeMySelf - { - get; - set; - } - - Thread myThread = null; - - //for udo send - Thread myThreadSocket = null; - Socket sendSocket; - - //Queue procStatsQueue; - Queue procStatsQueueBytes; - - object lockQueue = new object(); - - public ProcInfo() - { - statisticsTimes = new Dictionary(); - - eventEnableCapture = new AutoResetEvent(true); - eventEnableSend = new AutoResetEvent(false); - - //procStatsQueue = new Queue(); - procStatsQueueBytes = new Queue(); - - myThreadSocket = new Thread(socketThread); - myThreadSocket.Start(); - - myThread = new Thread(usageThread); - myThread.Start(); - } - public void Dispose() - { - bStopMainThread = true; - bStopSocketThread = true; - if (myThread != null) - { - myThread.Abort(); - Thread.Sleep(100); - myThread = null; - } - if (myThreadSocket != null) - { - myThreadSocket.Abort(); - Thread.Sleep(100); - myThreadSocket = null; - } - } - - public void sendEndOfTransfer() - { - if (sendSocket != null) - sendSocket.Send(ByteHelper.endOfTransferBytes); - } - - /// - /// send enqueued objects via UDP broadcast - /// - void socketThread() - { - System.Diagnostics.Debug.WriteLine("Entering socketThread ..."); - try - { - const int ProtocolPort = 3001; - sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - sendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); - sendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 32768); - - IPAddress sendTo = IPAddress.Broadcast;// IPAddress.Parse("192.168.128.255"); //local broadcast - EndPoint sendEndPoint = new IPEndPoint(sendTo, ProtocolPort); - - //UdpClient udpC = new UdpClient("255.255.255.255", 1111); - System.Diagnostics.Debug.WriteLine("Socket ready to send"); - - while (!bStopSocketThread) - { - //block until released by capture - eventEnableSend.WaitOne(); - lock (lockQueue) - { - //if (procStatsQueue.Count > 0) - while (procStatsQueueBytes.Count > 0) - { - //ProcessStatistics.process_statistics pStat = procStatsQueue.Dequeue(); - //byte[] buf = pStat.ToByte(); - byte[] buf = procStatsQueueBytes.Dequeue(); - if (ByteHelper.isEndOfTransfer(buf)) - System.Diagnostics.Debug.WriteLine("sending "); - - sendSocket.SendTo(buf, buf.Length, SocketFlags.None, sendEndPoint); - //System.Diagnostics.Debug.WriteLine("Socket send " + buf.Length.ToString() + " bytes"); - //System.Diagnostics.Debug.WriteLine(pStat.dumpStatistics()); - System.Threading.Thread.Sleep(2); - } - } - ((AutoResetEvent)eventEnableCapture).Set(); - } - - } - catch (ThreadAbortException ex) - { - System.Diagnostics.Debug.WriteLine("ThreadAbortException: socketThread(): " + ex.Message); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception: socketThread(): " + ex.Message); - } - System.Diagnostics.Debug.WriteLine("socketThread ENDED"); - } - - - /// - /// build thread and process list periodically and fire update event and enqueue results for the socket thread - /// - void usageThread() - { - try - { - int interval = 3000; - - uint start = Process.GetTickCount(); - Dictionary old_thread_List;// = Process.GetThreadList(); - - string exeFile = Process.exefile; - //read all processes - Dictionary ProcList = Process.getProcessNameList(); - DateTime dtCurrent = DateTime.Now; - - //######### var declarations - Dictionary new_ThreadList; - uint duration; - long system_total; - long user_total, kernel_total; //total process spend in user/kernel - long thread_user, thread_kernel; //times the thread spend in user/kernel - DWORD dwProc; - float user_percent; - float kernel_percent; - ProcessStatistics.process_usage usage; - ProcessStatistics.process_statistics stats = null; - - string sProcessName = ""; - List processThreadList = new List(); - - //extended list - List processThreadStatsList = new List(); //to store thread stats - //threadtimes threadTimesTotal; - while (!bStopMainThread) - { - eventEnableCapture.WaitOne(); - old_thread_List = Process.GetThreadList(); //build a list of threads with user and kernel times - - System.Threading.Thread.Sleep(interval); - - //get a new thread list - new_ThreadList = Process.GetThreadList(); //build another list of threads with user and kernel times, to compare - - duration = Process.GetTickCount() - start; - - ProcList = Process.getProcessNameList(); //update process list - dtCurrent = DateTime.Now; - system_total = 0; - statisticsTimes.Clear(); - //look thru all processes - foreach (KeyValuePair p2 in ProcList) - { - //empty the process's thread list - processThreadList=new List(); - processThreadStatsList = new List(); - - user_total = 0; //hold sum of thread user times for a process - kernel_total = 0; //hold sum of thread kernel times for a process - sProcessName = p2.Value.sName; - - //SUM over all threads with that ProcID - dwProc = p2.Value.dwProcID; - foreach (KeyValuePair kpNew in new_ThreadList) - { - thread_user = 0; - thread_kernel = 0; - //if the thread belongs to the process - if (kpNew.Value.dwOwnerProcID == dwProc) - { - //is there an old thread entry we can use to calc? - thread threadOld; - if (old_thread_List.TryGetValue(kpNew.Value.dwThreadID, out threadOld)) - { - thread_user=Process.GetThreadTick(kpNew.Value.thread_times.user) - Process.GetThreadTick(old_thread_List[kpNew.Value.dwThreadID].thread_times.user); - user_total += thread_user; - thread_kernel =Process.GetThreadTick(kpNew.Value.thread_times.kernel) - Process.GetThreadTick(old_thread_List[kpNew.Value.dwThreadID].thread_times.kernel); - kernel_total += thread_kernel; - } - //simple list - thread threadsOfProcess = new thread(kpNew.Value.dwOwnerProcID, kpNew.Value.dwThreadID, kpNew.Value.thread_times); - processThreadList.Add(threadsOfProcess); - - //extended list - threadStatistic threadStats = - new threadStatistic( - kpNew.Value.dwOwnerProcID, - kpNew.Value.dwThreadID, - new threadtimes(thread_user, thread_kernel), - duration, - dtCurrent.Ticks); - processThreadStatsList.Add(threadStats); - - }//if dwProcID matches - } - //end of sum for process - user_percent = (float)user_total / (float)duration * 100f; - kernel_percent = (float)kernel_total / (float)duration * 100f; - system_total = user_total + kernel_total; - - // update the statistics with this process' info - usage = new ProcessStatistics.process_usage(kernel_total, user_total); - // update process statistics - //stats = new ProcessStatistics.process_statistics(p2.Value.dwProcID, p2.Value.sName, usage, dtCurrent.Ticks, duration, processThreadList); - stats = new ProcessStatistics.process_statistics(p2.Value.dwProcID, p2.Value.sName, usage, dtCurrent.Ticks, duration, processThreadStatsList); - - //add or update the proc stats - if (exeFile != p2.Value.sName || bIncludeMySelf) - { - //if (sProcessName == "device.exe") - // System.Diagnostics.Debug.WriteLine(stats.ToString()); - - statisticsTimes[p2.Value.sName] = stats; - //lock (lockQueue) - //{ - //System.Diagnostics.Debug.WriteLine("Queue Adding " + stats.sName); - //procStatsQueue.Enqueue(stats); - procStatsQueueBytes.Enqueue(stats.ToByte()); - //} - } - - start = Process.GetTickCount(); - }//foreach process - - onUpdateHandler(new ProcessStatsEventArgs(statisticsTimes, duration)); - procStatsQueueBytes.Enqueue(ByteHelper.endOfTransferBytes); - ((AutoResetEvent)eventEnableSend).Set(); - //dumpStatistics(statisticsTimes); - }//while true - } - catch (ThreadAbortException ex) - { - System.Diagnostics.Debug.WriteLine("ThreadAbortException: usageThread(): " + ex.Message); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception: usageThread(): " + ex.Message); - } - System.Diagnostics.Debug.WriteLine("Thread ENDED"); - } - - public delegate void updateEventHandler(object sender, ProcessStatsEventArgs eventArgs); - public event updateEventHandler updateEvent; - void onUpdateHandler(ProcessStatsEventArgs procStats) - { - //anyone listening? - if (this.updateEvent == null) - return; - this.updateEvent(this, procStats); - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMon2/Process.cs b/cpumon/ProcessorUsage/CpuMon2/Process.cs deleted file mode 100644 index 2d3568e..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/Process.cs +++ /dev/null @@ -1,281 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; - -//using __int64 = System.UInt64; -using DWORD = System.UInt32; -using FILETIME = System.Int64; - -namespace System.Process -{ - public class process - { - public UInt32 dwProcID; - public List threadsProc; - public string sName; - public process(UInt32 id, string n, List lth) - { - dwProcID = id; - threadsProc = lth; - sName = n; - } - } - - public partial class Process - { - public static string exefile - { - get { - string s = System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); - return s; - } - } - public Process() - { - - } - - //Dictionary _procList; - public static Dictionary procList - { - get { - Dictionary pList; - pList = getProcessNameList(); - return pList; - } - } - public static Dictionary getProcessNameList() - { - int iCnt = 0; - //List name_list = new List(); - Dictionary _pList = new Dictionary(); - uint procID = 0; - IntPtr pHandle = CreateToolhelp32Snapshot(SnapshotFlags.Process | SnapshotFlags.NoHeaps, procID); - if ((Int32)pHandle == INVALID_HANDLE_VALUE) - throw new Exception("CreateToolhelp32Snapshot error: " + Marshal.GetLastWin32Error().ToString()); - - if ((int)pHandle != INVALID_HANDLE_VALUE) - { - PROCESSENTRY32 pEntry = new PROCESSENTRY32(); - pEntry.dwSize = (uint)Marshal.SizeOf(pEntry); - if (Process32First(pHandle, ref pEntry) == 1) - { - do - { - //name_list.Add(new processnames(pEntry.th32ProcessID, pEntry.szExeFile)); - _pList[pEntry.th32ProcessID] = new process(pEntry.th32ProcessID, pEntry.szExeFile, new List()); - iCnt++; - } while (Process32Next(pHandle, ref pEntry) == 1); - } - else - System.Diagnostics.Debug.WriteLine("Process32First error: " + Marshal.GetLastWin32Error().ToString()); - CloseToolhelp32Snapshot(pHandle); - } - - return _pList; - } - - /// Convert a FILETIME to ticks (ms) - public static long GetThreadTick(FILETIME time) - { - //__int64 tick = MAKEDWORDLONG( time.dwLowDateTime, time.dwHighDateTime ); - long tick = time; - return (tick /= 10000); - } - - public static bool GetProcessTimes(ref PROCESSTIMES pTimes, uint procID) - { - bool bRet = true; - pTimes.lpCreationTime = 0; - pTimes.lpExitTime = 0; - pTimes.lpKernelTime = 0; - pTimes.lpUserTime = 0; - pTimes.processID = procID; - - List threads = new List(); - //CosmicPowers we_are_powerful; - UInt32 old_permissions = SetProcPermissions(0xffffffff); - IntPtr snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread | SnapshotFlags.NoHeaps, 0); - if ((int)snapshot != -1) - { - THREADENTRY32 te = new THREADENTRY32(); - te.dwSize = (uint)Marshal.SizeOf(te); - Int32 bRes = Thread32First(snapshot, ref te); - FILETIME creation, exit, kernel, user; - if (bRes > 0) - { - do - { - if (te.th32OwnerProcessID == procID) - { - creation = new FILETIME(); - exit = new FILETIME(); - kernel = new FILETIME(); - user = new FILETIME(); - uint hThread = te.th32ThreadID; - if (GetThreadTimes(hThread, - out creation, - out exit, - out kernel, - out user)) - { - threads.Add(te); - pTimes.lpKernelTime += kernel; - pTimes.lpUserTime += user; - } - } - } while (Thread32Next(snapshot, out te) > 0); - } - else - { - System.Diagnostics.Debug.WriteLine("error=" + Marshal.GetLastWin32Error()); - bRet = false; - } - - CloseToolhelp32Snapshot(snapshot); - } - SetProcPermissions(old_permissions); - //threadList=threads.ToArray(); - return bRet; - } - - /// Gets the list of currently running threads - public static Dictionary GetThreadList() - { - Dictionary process_list = new Dictionary(); - //CosmicPowers we_are_powerful; - UInt32 old_permissions = SetProcPermissions(0xffffffff); - IntPtr snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread | SnapshotFlags.NoHeaps, 0); - if ((int)snapshot != -1) - { - THREADENTRY32 te = new THREADENTRY32(); - te.dwSize = (uint)Marshal.SizeOf(te); - Int32 bRes = Thread32First(snapshot, ref te); - if (bRes > 0) - { - do - { - FILETIME creation = new FILETIME(); - FILETIME exit = new FILETIME(); - FILETIME kernel = new FILETIME(); - FILETIME user = new FILETIME(); - uint hThread = te.th32ThreadID; - if (GetThreadTimes(hThread, - out creation, - out exit, - out kernel, - out user)) - { - threadtimes t = new threadtimes(user, kernel);// = { kernel, user }; - //t.kernel = kernel; - //t.user = user; - process_list[te.th32ThreadID] = new thread(te.th32OwnerProcessID, te.th32ThreadID, t); - //System.Diagnostics.Debug.WriteLine(te.th32OwnerProcessID.ToString() + ": " + - // te.th32ThreadID.ToString("x08") + - // ", " + DateTime.FromFileTime(t.kernel).Ticks.ToString() + - // ", " + DateTime.FromFileTime(t.user).Ticks.ToString() - // ); - } - } while (Thread32Next(snapshot, out te) > 0); - } - else - { - System.Diagnostics.Debug.WriteLine("error=" + Marshal.GetLastWin32Error()); - } - - CloseToolhelp32Snapshot(snapshot); - } - SetProcPermissions(old_permissions); - return process_list; - } - - class obsolete - { - ///// Time a thread has spent working - //public struct thread_times - //{ - // /// Time a thread has spent in kernel space - // public FILETIME kernel; - // /// Time a thread has spent in user space - // public FILETIME user; - //}; - - /// - /// return the sum of all thread times of this process - /// - /// - /// - /// - /// - public static int GetProcessTimes(uint processID, ref FILETIME lpKernelTime, ref FILETIME lpUserTime, - ref long duration) - { - //threadStruct[] myThreads = new threadStruct[255];//hopefully enough - int iCount = 0; - uint startTicks = 0;//, duration=0; - long FTprocKernel = 0, FTprocUser = 0, FTprocTotal = 0; - CosmicPowers cosmicPower = new CosmicPowers(); - IntPtr snapshot = CreateToolhelp32Snapshot(SnapshotFlags.Thread | SnapshotFlags.NoHeaps, 0); - if ((int)snapshot != INVALID_HANDLE_VALUE) - { - THREADENTRY32 te = new THREADENTRY32(); - te.dwSize = (uint)Marshal.SizeOf(te); - startTicks = GetTickCount(); - Int32 bRes = Thread32First(snapshot, ref te); - if (bRes > 0) - { - do - { - FILETIME creation = new FILETIME(); - FILETIME exit = new FILETIME(); - FILETIME kernel = new FILETIME(); - FILETIME user = new FILETIME(); - uint hThread = te.th32ThreadID; - if (te.th32OwnerProcessID == processID) - { - if (GetThreadTimes(hThread, - out creation, - out exit, - out kernel, - out user)) - { - //add the thread's values to our sum - FTprocKernel += kernel; - FTprocUser += user; - FTprocTotal += kernel + user; - //System.Diagnostics.Debug.WriteLine( - // te.th32OwnerProcessID.ToString() + ": \t" + - // kernel.ToString() + "\t" + - // user.ToString()); - iCount++; - } - } - } while (Thread32Next(snapshot, out te) > 0); - } - else - { - System.Diagnostics.Debug.WriteLine("error=" + Marshal.GetLastWin32Error()); - } - CloseToolhelp32Snapshot(snapshot); - } - cosmicPower.Dispose(); - lpKernelTime = FTprocKernel; - lpUserTime = FTprocUser; - //System.Diagnostics.Debug.WriteLine("usage: " + ((float)(((FTprocKernelDuration+FTprocUserDuration) / 100f) * duration)).ToString("0.00%")); - return iCount; - } - - } - public struct PROCESSTIMES - { - public uint processID; - public FILETIME lpCreationTime; - public FILETIME lpExitTime; - public FILETIME lpKernelTime; - public FILETIME lpUserTime; - } - } - -} diff --git a/cpumon/ProcessorUsage/CpuMon2/ProcessStatistics.cs b/cpumon/ProcessorUsage/CpuMon2/ProcessStatistics.cs deleted file mode 100644 index 1d970ce..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/ProcessStatistics.cs +++ /dev/null @@ -1,234 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -namespace System.Process -{ - public class ProcessStatistics - { - static void dumpStatistics(Dictionary stats) - { - foreach (KeyValuePair kp in stats) - { - System.Diagnostics.Debug.WriteLine(kp.Value.sName + ": " + kp.Value.procUsage.kernel.ToString() + "/" + kp.Value.procUsage.user.ToString()); - } - } - public static string dumpProcStats(List procStats) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - foreach (process_statistics ps in procStats) - { - sb.Append(ps.sName + "\t"); - sb.Append((ps.procUsage.kernel + ps.procUsage.user).ToString() + "\n"); - } - return sb.ToString(); - } - - public static string dumpProcStats(ProcessStatsEventArgs procStats) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - foreach (KeyValuePair ps in procStats.procStatistics) - { - sb.Append(ps.Value.sName + "\t"); - sb.Append((ps.Value.procUsage.kernel + ps.Value.procUsage.user).ToString() + "\r\n"); - } - sb.Append("Duration:\t" + procStats.duration + "\r\n"); - return sb.ToString(); - } - - public class process_usage - { - /// % time the kernel spent in kernel space - public long kernel; - /// % time the kernel spent in user space - public long user; - public process_usage(long k, long u) - { - kernel = k; - user = u; - } - public byte[] ToByte() - { - List buf = new List(); - buf.AddRange(BitConverter.GetBytes(kernel)); - buf.AddRange(BitConverter.GetBytes(user)); - return buf.ToArray(); - } - public process_usage FromByte(ref byte[] buf, ref int offs) - { - int offset = offs; - kernel = BitConverter.ToInt64(buf, offset); - offset += sizeof(Int64); - user = BitConverter.ToInt64(buf, offset); - offs = offset; - return this; - } - public process_usage(ref byte[] buf, ref int offs) - { - int offset = offs; - kernel = BitConverter.ToInt64(buf, offset); - offset += sizeof(Int64); - user = BitConverter.ToInt64(buf, offset); - offset += sizeof(Int64); - offs = offset; - } - - } - public class process_statistics - { - public string sName; - /// - /// DateTime as Ticks - /// - public long dateTime; - public UInt32 duration; - public process_usage procUsage; - public UInt32 processID; - public List ThreadStatList = new List(); - - public string remoteIP = "0.0.0.0"; - - //public process_statistics(uint uProcessID, string s, process_usage u, long dt, uint du) - //{ - // sName = s; - // processID = uProcessID; - // procUsage = u; - // dateTime = dt; - // duration = du; - //} - - /// - /// an object to hold informations about a process - /// - /// the Process ID - /// the process name - /// the process usage (kernel and user times) - /// a timestamp - /// the elapsed time since last statistic - /// a list of all threads of this process - public process_statistics(uint uProcessID, string s, process_usage u, long dt, uint du, List threadList) - { - sName = s; - processID = uProcessID; - procUsage = u; - dateTime = dt; - duration = du; - ThreadStatList = threadList; - } - public process_statistics(uint uProcessID, string s, process_usage u, long dt, uint du, List threadList, string sRemoteIP) - { - sName = s; - processID = uProcessID; - procUsage = u; - dateTime = dt; - duration = du; - ThreadStatList = threadList; - remoteIP = sRemoteIP; - } - - public override string ToString() - { - return dumpStatistics(); - } - public string dumpStatistics() - { - StringBuilder sb = new StringBuilder(); - sb.Append( this.processID.ToString("x") + ", " + - this.sName + ", " + - "packetsize: " + this.ToByte().Length.ToString() + ", " + - this.procUsage.kernel.ToString() + "/" + - this.procUsage.user.ToString() + ", " + - this.duration.ToString() + - this.remoteIP + "\r\n"); - foreach (threadStatistic th in this.ThreadStatList) - { - sb.Append(" 0x" + th.dwThreadID.ToString("x") + ":" + th.thread_times.kernel.ToString() + "/" + th.thread_times.user.ToString() + "\r\n"); - } - - return sb.ToString(); - } - - public process_statistics(byte[] buffer) - { - this.FromByte(buffer); - } - public byte[] ToByte() - { - List buf = new List(); - //string length - Int16 bLen = (Int16)System.Text.Encoding.UTF8.GetByteCount(sName); - buf.AddRange(BitConverter.GetBytes(bLen)); - byte[] bName = System.Text.Encoding.UTF8.GetBytes(sName); - //string as byte[] - buf.AddRange(bName); - - buf.AddRange(BitConverter.GetBytes(dateTime)); - buf.AddRange(BitConverter.GetBytes(duration)); - buf.AddRange(procUsage.ToByte()); - buf.AddRange(BitConverter.GetBytes(processID)); - - //list count - Int16 iCnt = (Int16) ThreadStatList.Count; - threadStatistic[] threadsArray = ThreadStatList.ToArray(); - buf.AddRange(BitConverter.GetBytes(iCnt)); - //now add the threads of the list - foreach (threadStatistic th in threadsArray) - buf.AddRange(th.ToByte()); - - return buf.ToArray(); - } - public process_statistics FromByte(byte[] buf) - { - int offset = 0; - Int16 bLen = BitConverter.ToInt16(buf, 0); //2 bytes - offset += sizeof(System.Int16); - if (bLen > 0) - this.sName = System.Text.Encoding.UTF8.GetString(buf, offset, bLen); - offset += bLen; - this.dateTime = BitConverter.ToInt64(buf, offset); - offset += sizeof(System.Int64); - this.duration = BitConverter.ToUInt32(buf, offset); - offset += sizeof(System.Int32); - this.procUsage = new process_usage(ref buf, ref offset); - //offset = offset; //has been changed by process_usage - - this.processID = BitConverter.ToUInt32(buf, offset); - offset += sizeof(System.UInt32); - - //how many thtreads are in the byte stream - Int16 iCnt = BitConverter.ToInt16(buf, offset); - offset += sizeof(System.Int16); - //start reading the threads - List thList = new List(); - for (int x = 0; x < iCnt; x++) - { - threadStatistic th = new threadStatistic(buf, ref offset); - thList.Add(th); - } - this.ThreadStatList = thList; - this.remoteIP = "0.0.0.0"; //unknown - return this; - } - } - } - public class ProcessStatsEventArgs : EventArgs - { - //fields - Dictionary _procStatList; - public Dictionary procStatistics - { - get { return _procStatList; } - } - uint _duration = 0; - public uint duration - { - get { return _duration; } - } - public ProcessStatsEventArgs(Dictionary _list, uint durat) - { - _procStatList = _list; - _duration = durat; - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMon2/Program.cs b/cpumon/ProcessorUsage/CpuMon2/Program.cs deleted file mode 100644 index 3833fa3..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace CpuMon2 -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new cpumonForm()); - } - } -} \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMon2/Properties/AssemblyInfo.cs b/cpumon/ProcessorUsage/CpuMon2/Properties/AssemblyInfo.cs deleted file mode 100644 index 89d433f..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("CpuMon2")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("CpuMon2")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("6de81d94-3609-4d83-b54a-336846d8b3b5")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/cpumon/ProcessorUsage/CpuMon2/Properties/Resources.Designer.cs b/cpumon/ProcessorUsage/CpuMon2/Properties/Resources.Designer.cs deleted file mode 100644 index 04cd9ff..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5466 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace CpuMon2.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("CpuMon2.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMon2/Properties/Resources.resx b/cpumon/ProcessorUsage/CpuMon2/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMon2/Thread.cs b/cpumon/ProcessorUsage/CpuMon2/Thread.cs deleted file mode 100644 index 7b423e6..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/Thread.cs +++ /dev/null @@ -1,166 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using DWORD = System.UInt32; -using FILETIME = System.Int64; - -namespace System.Process -{ - /// - /// FILETIME times spend in user and kernel - /// - public class threadtimes - { - public FILETIME kernel; - public FILETIME user; - public threadtimes(FILETIME u, FILETIME k) - { - kernel = k; - user = u; - } - public byte[] ToByte() - { - List bufL = new List(); - bufL.AddRange(BitConverter.GetBytes(kernel)); - bufL.AddRange(BitConverter.GetBytes(user)); - return bufL.ToArray(); - } - public threadtimes FromByte(byte[] buf, ref int offset) - { - kernel = BitConverter.ToInt64(buf, offset); //8 bytes - offset += sizeof(System.Int64); - - user = BitConverter.ToInt64(buf, offset); - offset += sizeof(System.Int64); - - return this; - } - /// - /// return a threadtimes object - /// - /// - /// start offset - public threadtimes (byte[] buf, ref int offset) - { - this.FromByte(buf, ref offset); - } - } - //struct threadStruct - //{ - // public UInt32 dwOwnerProcID; - // public UInt32 dwThreadID; - // public FILETIME ftUser; - // public FILETIME ftKernel; - //} - public class thread - { - public UInt32 dwOwnerProcID; - public threadtimes thread_times; - public UInt32 dwThreadID; - public thread(UInt32 id, UInt32 thID, threadtimes tht) - { - dwOwnerProcID = id; - thread_times = tht; - dwThreadID = thID; - if (thID == 0) - System.Diagnostics.Debugger.Break(); - } - public byte[] ToByte() - { - List bufL = new List(); - bufL.AddRange(BitConverter.GetBytes(dwOwnerProcID)); - - bufL.AddRange(thread_times.ToByte()); - - bufL.AddRange(BitConverter.GetBytes(dwThreadID)); - return bufL.ToArray(); - } - public thread FromByte(byte[] buf, ref int offset) - { - dwOwnerProcID = BitConverter.ToUInt32(buf, offset); //4 bytes - offset += sizeof(System.UInt32); - - thread_times = new threadtimes(buf, ref offset); - - dwThreadID = BitConverter.ToUInt32(buf, offset); - offset += sizeof(System.UInt32); - - return this; - } - public thread(byte[] buf, ref int offs) - { - this.FromByte(buf, ref offs); - } - } - /// - /// class to store a thread's statistic data - /// the timestamp of the capture and the spend user and kernel times - /// and the measure interval - /// - public class threadStatistic - { - public UInt32 dwOwnerProcID; - /// - /// store the spend times of in-user and in-kernel - /// - public threadtimes thread_times; - public UInt32 dwThreadID; - /// - /// the measured time interval in ms - /// - public UInt32 duration; - /// - /// the timestamp of this captured statistic - /// - public long timestamp; - public threadStatistic(UInt32 id, UInt32 thID, threadtimes tht, UInt32 _duration, long _timestamp) - { - dwOwnerProcID = id; - thread_times = tht; - dwThreadID = thID; - if (thID == 0) - System.Diagnostics.Debugger.Break(); - duration=_duration; - timestamp=_timestamp; - } - public byte[] ToByte() - { - List bufL = new List(); - bufL.AddRange(BitConverter.GetBytes(dwOwnerProcID)); - - bufL.AddRange(thread_times.ToByte()); - - bufL.AddRange(BitConverter.GetBytes(dwThreadID)); - - bufL.AddRange(BitConverter.GetBytes(duration)); - - bufL.AddRange(BitConverter.GetBytes(timestamp)); - - return bufL.ToArray(); - } - public threadStatistic FromByte(byte[] buf, ref int offset) - { - dwOwnerProcID = BitConverter.ToUInt32(buf, offset); //4 bytes - offset += sizeof(System.UInt32); - - thread_times = new threadtimes(buf, ref offset); - - dwThreadID = BitConverter.ToUInt32(buf, offset); - offset += sizeof(System.UInt32); - - duration=BitConverter.ToUInt32(buf, offset); - offset += sizeof(System.UInt32); - - timestamp=BitConverter.ToInt64(buf, offset); - offset += sizeof(System.UInt64); - - return this; - } - public threadStatistic(byte[] buf, ref int offs) - { - this.FromByte(buf, ref offs); - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMon2/bin/Debug/CpuMon2.exe b/cpumon/ProcessorUsage/CpuMon2/bin/Debug/CpuMon2.exe deleted file mode 100644 index 0c06650..0000000 Binary files a/cpumon/ProcessorUsage/CpuMon2/bin/Debug/CpuMon2.exe and /dev/null differ diff --git a/cpumon/ProcessorUsage/CpuMon2/cpumonForm.Designer.cs b/cpumon/ProcessorUsage/CpuMon2/cpumonForm.Designer.cs deleted file mode 100644 index 87ad753..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/cpumonForm.Designer.cs +++ /dev/null @@ -1,133 +0,0 @@ -namespace CpuMon2 -{ - partial class cpumonForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.listView1 = new System.Windows.Forms.ListView(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.mnuFile = new System.Windows.Forms.MenuItem(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.dataGrid1 = new System.Windows.Forms.DataGrid(); - this.mnuView = new System.Windows.Forms.MenuItem(); - this.mnuTextView = new System.Windows.Forms.MenuItem(); - this.mnuDataView = new System.Windows.Forms.MenuItem(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuFile); - this.mainMenu1.MenuItems.Add(this.mnuView); - // - // listView1 - // - this.listView1.Dock = System.Windows.Forms.DockStyle.Fill; - this.listView1.Location = new System.Drawing.Point(0, 0); - this.listView1.Name = "listView1"; - this.listView1.Size = new System.Drawing.Size(240, 268); - this.listView1.TabIndex = 0; - // - // textBox1 - // - this.textBox1.AcceptsReturn = true; - this.textBox1.AcceptsTab = true; - this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill; - this.textBox1.Location = new System.Drawing.Point(0, 0); - this.textBox1.Multiline = true; - this.textBox1.Name = "textBox1"; - this.textBox1.ReadOnly = true; - this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.textBox1.Size = new System.Drawing.Size(240, 268); - this.textBox1.TabIndex = 1; - this.textBox1.Visible = false; - // - // mnuFile - // - this.mnuFile.MenuItems.Add(this.mnuExit); - this.mnuFile.Text = "File"; - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // dataGrid1 - // - this.dataGrid1.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); - this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Fill; - this.dataGrid1.Location = new System.Drawing.Point(0, 0); - this.dataGrid1.Name = "dataGrid1"; - this.dataGrid1.Size = new System.Drawing.Size(240, 268); - this.dataGrid1.TabIndex = 2; - // - // mnuView - // - this.mnuView.MenuItems.Add(this.mnuTextView); - this.mnuView.MenuItems.Add(this.mnuDataView); - this.mnuView.Text = "View"; - // - // mnuTextView - // - this.mnuTextView.Text = "Text"; - this.mnuTextView.Click += new System.EventHandler(this.mnuTextView_Click); - // - // mnuDataView - // - this.mnuDataView.Text = "Data"; - this.mnuDataView.Click += new System.EventHandler(this.mnuDataView_Click); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.Controls.Add(this.dataGrid1); - this.Controls.Add(this.textBox1); - this.Controls.Add(this.listView1); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "CPU Mon"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.ListView listView1; - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.MenuItem mnuFile; - private System.Windows.Forms.MenuItem mnuExit; - private System.Windows.Forms.DataGrid dataGrid1; - private System.Windows.Forms.MenuItem mnuView; - private System.Windows.Forms.MenuItem mnuTextView; - private System.Windows.Forms.MenuItem mnuDataView; - } -} - diff --git a/cpumon/ProcessorUsage/CpuMon2/cpumonForm.cs b/cpumon/ProcessorUsage/CpuMon2/cpumonForm.cs deleted file mode 100644 index 8573ec6..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/cpumonForm.cs +++ /dev/null @@ -1,248 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using System.Process; - -namespace CpuMon2 -{ - public partial class cpumonForm : Form - { - ProcessUsage.ProcInfo pInfo; - public cpumonForm() - { - InitializeComponent(); - showProcList(); - //start the process usage analysis thread - pInfo = new ProcessUsage.ProcInfo(); - //show ourself in the stats? - pInfo.bIncludeMySelf = false; - - //init data - createTable(); - - pInfo.updateEvent += new ProcessUsage.ProcInfo.updateEventHandler(pInfo_updateEvent); - } - - void showProcList() - { - //show an initial list of processes - Dictionary pList = System.Process.Process.procList; - foreach (KeyValuePair pEntry in pList) - addText(pEntry.Value.sName); - } - void pInfo_updateEvent(object sender, ProcessStatsEventArgs eventArgs) - { - setText( ProcessStatistics.dumpProcStats(eventArgs)); - addData(eventArgs); - } - delegate void SetTextCallback(string text); - public void setText(string text) - { - // InvokeRequired required compares the thread ID of the - // calling thread to the thread ID of the creating thread. - // If these threads are different, it returns true. - if (this.textBox1.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(setText); - this.Invoke(d, new object[] { text }); - } - else - { - textBox1.Text = text; - } - } - delegate void addTextCallback(string text); - public void addText(string text) - { - // InvokeRequired required compares the thread ID of the - // calling thread to the thread ID of the creating thread. - // If these threads are different, it returns true. - if (this.textBox1.InvokeRequired) - { - addTextCallback d = new addTextCallback(setText); - this.Invoke(d, new object[] { text }); - } - else - { - if (textBox1.Text.Length > 2000) - textBox1.Text = ""; - textBox1.Text += text + "\r\n"; - textBox1.SelectionLength = 0; - textBox1.SelectionStart = textBox1.Text.Length - 1; - textBox1.ScrollToCaret(); - } - } - - private void mnuExit_Click(object sender, EventArgs e) - { - pInfo.Dispose(); - System.Threading.Thread.Sleep(500); - Application.Exit(); - } - - //################### data display etc... - BindingSource bsProcesses; - DataSet dsProcesses; - DataTable dtProcesses; - void createTable() - { - dtProcesses = new DataTable("Processes"); - dsProcesses = new DataSet(); - bsProcesses = new BindingSource(); - - DataColumn[] dc = new DataColumn[6]; - string[] _fieldNames = new string[6] { "procID", "Process", "User", "Kernel", "Time", "Duration" }; - //build the table columns - for (int i = 0; i < _fieldNames.Length; i++) - { - dc[i] = new DataColumn(); - dc[i].Caption = _fieldNames[i]; // "App"; - dc[i].ColumnName = _fieldNames[i]; // "App"; - dc[i].DataType = System.Type.GetType("System.String"); - dc[i].MaxLength = 256; - if (dc[i].Caption == "procID") - { - dc[i].Unique = true; - } - else - { - dc[i].Unique = false; - } - dc[i].AllowDBNull = false; - - } - //add header - dtProcesses.Columns.AddRange(dc); - - DataColumn[] dcKey = new DataColumn[1]; - dcKey[0] = dc[0]; - dtProcesses.PrimaryKey = dcKey; - - dsProcesses.Tables.Add(dtProcesses); - - bsProcesses.DataSource = dsProcesses; - bsProcesses.DataMember = dsProcesses.Tables[0].TableName; - - dataGrid1.DataSource = bsProcesses; - dataGrid1.Refresh(); - } - delegate void addDataCallback(ProcessStatsEventArgs procStats); - void addData (ProcessStatsEventArgs procStats) - { - if (this.dataGrid1.InvokeRequired) - { - addDataCallback d = new addDataCallback(addData); - this.Invoke(d, new object[] { procStats }); - } - else - { - dataGrid1.SuspendLayout(); - //dtProcesses.Rows.Clear(); - foreach (KeyValuePair ps in procStats.procStatistics) - { - object[] o = new object[] { - ps.Value.processID, - ps.Value.sName, - ps.Value.procUsage.user, - ps.Value.procUsage.kernel, - ps.Value.dateTime, - ps.Value.duration - }; - DataRow dr; - //check if data already exists - dr = dsProcesses.Tables[0].Rows.Find(ps.Value.processID.ToString()); - if (dr == null) - { //add a new row - dr = dtProcesses.NewRow(); - dr.ItemArray = o; - dtProcesses.Rows.Add(dr); - } - else - dr.ItemArray = o; - } - dataGrid1.Refresh(); - dataGrid1.ResumeLayout(); - //object[] o = new object[7]{ procUsage.procStatistics. .procStatistics. [i].sApp, eventEntries[i].sArg, eventEntries[i].sEvent, - // eventEntries[i].sStartTime, eventEntries[i].sEndTime, eventEntries[i].sType, eventEntries[i].sHandle }; - } - - } - - private void mnuDataView_Click(object sender, EventArgs e) - { - dataGrid1.Visible = true; - textBox1.Visible = false; - } - - private void mnuTextView_Click(object sender, EventArgs e) - { - textBox1.Visible = true; - dataGrid1.Visible = false; - } - /* - public void applyTableStyle(DataGrid dataGrid1) - { - // Creates two DataGridTableStyle objects, one for the Machine - // array, and one for the Parts ArrayList. - - DataGridTableStyle EventsTable = new DataGridTableStyle(); - // Sets the MappingName to the class name plus brackets. - EventsTable.MappingName = "EventEntry[]"; - - // Sets the AlternatingBackColor so you can see the difference. - //EventsTable.AlternatingBackColor = System.Drawing.Color.LightBlue; - - // Creates column styles. - DataGridTextBoxColumn eventApp = new DataGridTextBoxColumn(); - eventApp.MappingName = "sApp"; - eventApp.HeaderText = "sApp"; - eventApp.Width = dataGrid1.Width / 6 * 2; - - DataGridTextBoxColumn eventArg = new DataGridTextBoxColumn(); - eventArg.MappingName = "sArg"; - eventArg.HeaderText = "Arg"; - - DataGridTextBoxColumn eventEvent = new DataGridTextBoxColumn(); - eventEvent.MappingName = "sEvent"; - eventEvent.HeaderText = "Event"; - - DataGridTextBoxColumn eventStart = new DataGridTextBoxColumn(); - eventStart.MappingName = "sStartTime"; - eventStart.HeaderText = "Start"; - - DataGridTextBoxColumn eventEnd = new DataGridTextBoxColumn(); - eventEnd.MappingName = "sEndTime"; - eventEnd.HeaderText = "End"; - - DataGridTextBoxColumn eventType = new DataGridTextBoxColumn(); - eventType.MappingName = "sType"; - eventType.HeaderText = "Type"; - - DataGridTextBoxColumn eventHandle = new DataGridTextBoxColumn(); - eventHandle.MappingName = "sHandle"; - eventHandle.HeaderText = "handle"; - - // Adds the column styles to the grid table style. - EventsTable.GridColumnStyles.Add(eventApp); - EventsTable.GridColumnStyles.Add(eventArg); - EventsTable.GridColumnStyles.Add(eventEvent); - EventsTable.GridColumnStyles.Add(eventStart); - EventsTable.GridColumnStyles.Add(eventEnd); - EventsTable.GridColumnStyles.Add(eventType); - EventsTable.GridColumnStyles.Add(eventHandle); - - // Add the table style to the collection, but clear the - // collection first. - dataGrid1.TableStyles.Clear(); - dataGrid1.TableStyles.Add(EventsTable); - - } - */ - } -} \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMon2/cpumonForm.resx b/cpumon/ProcessorUsage/CpuMon2/cpumonForm.resx deleted file mode 100644 index 1e86201..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/cpumonForm.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC_Phone - - - True - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMon2/toolhelp.cs b/cpumon/ProcessorUsage/CpuMon2/toolhelp.cs deleted file mode 100644 index 35c7248..0000000 --- a/cpumon/ProcessorUsage/CpuMon2/toolhelp.cs +++ /dev/null @@ -1,205 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; - -//using __int64 = System.UInt64; -using DWORD = System.UInt32; -using FILETIME = System.Int64; - -namespace System.Process -{ - public partial class Process - { - #region process_stuff - [DllImport("toolhelp.dll", SetLastError = true)] - static extern IntPtr CreateToolhelp32Snapshot(SnapshotFlags dwFlags, uint th32ProcessID); - - [DllImport("toolhelp.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - static extern int Process32First([In]IntPtr hSnapshot, ref PROCESSENTRY32 lppe); - - [DllImport("toolhelp.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] - static extern int Process32Next([In]IntPtr hSnapshot, ref PROCESSENTRY32 lppe); - - [DllImport("toolhelp.dll")] - private static extern int CloseToolhelp32Snapshot(IntPtr snapshot); - - [DllImport("toolhelp.dll", SetLastError = true)] - static extern Int32 Thread32First(IntPtr hSnapshot, ref THREADENTRY32 lpte); - [DllImport("toolhelp.dll", SetLastError = true)] - static extern Int32 Thread32Next(IntPtr hSnapshot, out THREADENTRY32 lpte); - - [DllImport("coredll.dll", SetLastError = true)] - static extern bool GetThreadTimes(IntPtr hThread, out FILETIME lpCreationTime, out FILETIME lpExitTime, out FILETIME lpKernelTime, out FILETIME lpUserTime); - [DllImport("coredll.dll", SetLastError = true)] - static extern bool GetThreadTimes(uint hThread, out FILETIME lpCreationTime, out FILETIME lpExitTime, out FILETIME lpKernelTime, out FILETIME lpUserTime); - - [DllImport("coredll.dll")] - public static extern uint GetTickCount(); - - [DllImport("coredll.dll")] - static extern UInt32 SetProcPermissions(UInt32 uPerm); - - //inner enum used only internally - [Flags] - private enum SnapshotFlags : uint - { - HeapList = 0x00000001, - Process = 0x00000002, - Thread = 0x00000004, - Module = 0x00000008, - Module32 = 0x00000010, - Inherit = 0x80000000, - All = 0x0000001F, - NoHeaps = 0x40000000 - } - /* -typedef struct tagPROCESSENTRY32 { - DWORD dwSize; - DWORD cntUsage; - DWORD th32ProcessID; - DWORD th32DefaultHeapID; - DWORD th32ModuleID; - DWORD cntThreads; - DWORD th32ParentProcessID; - LONG pcPriClassBase; - DWORD dwFlags; - TCHAR szExeFile[MAX_PATH]; - DWORD th32MemoryBase; - DWORD th32AccessKey; -} PROCESSENTRY32, *PPROCESSENTRY32, *LPPROCESSENTRY32; - */ - //inner struct used only internally - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - private struct PROCESSENTRY32 - { - const int MAX_PATH = 260; - internal UInt32 dwSize; - internal UInt32 cntUsage; - internal UInt32 th32ProcessID; - internal IntPtr th32DefaultHeapID; - internal UInt32 th32ModuleID; - internal UInt32 cntThreads; - internal UInt32 th32ParentProcessID; - internal Int32 pcPriClassBase; - internal UInt32 dwFlags; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)] - internal string szExeFile; - public uint th32MemoryBase; - public uint th32AccessKey; - } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - public struct THREADENTRY32 - { - - internal UInt32 dwSize; - internal UInt32 cntUsage; - internal UInt32 th32ThreadID; - internal UInt32 th32OwnerProcessID; - internal UInt32 tpBasePri; - internal UInt32 tpDeltaPri; - internal UInt32 dwFlags; - internal UInt32 th32AccessKey; - internal UInt32 th32CurrentProcessID; - } - - #endregion - - #region SYSTEM_TIME - [DllImport("coredll.dll", EntryPoint = "SystemTimeToFileTime", SetLastError = true)] - static extern bool SystemTimeToFileTime(ref SYSTEMTIME lpSystemTime, ref FILETIME lpFileTime); - - [DllImport("coredll.dll", SetLastError = true)] - static extern bool FileTimeToSystemTime([In] ref FILETIME lpFileTime, out SYSTEMTIME lpSystemTime); - - [DllImport("coredll.dll")] - static extern bool FileTimeToLocalFileTime([In] ref FILETIME lpFileTime, out FILETIME lpLocalFileTime); - - [DllImport("coredll.dll")] - static extern int OpenProcess(UInt32 dwAccess, bool bInherit, UInt32 dwIDProcess); - - //[StructLayout(LayoutKind.Sequential)] - //public struct FILETIME - //{ - // public UInt32 dwLowDateTime; - // public UInt32 dwHighDateTime; - //} - - [StructLayout(LayoutKind.Sequential)] - public struct SYSTEMTIME - { - [MarshalAs(UnmanagedType.U2)] - public short Year; - [MarshalAs(UnmanagedType.U2)] - public short Month; - [MarshalAs(UnmanagedType.U2)] - public short DayOfWeek; - [MarshalAs(UnmanagedType.U2)] - public short Day; - [MarshalAs(UnmanagedType.U2)] - public short Hour; - [MarshalAs(UnmanagedType.U2)] - public short Minute; - [MarshalAs(UnmanagedType.U2)] - public short Second; - [MarshalAs(UnmanagedType.U2)] - public short Milliseconds; - - public SYSTEMTIME(DateTime dt) - { - dt = dt.ToUniversalTime(); // SetSystemTime expects the SYSTEMTIME in UTC - Year = (short)dt.Year; - Month = (short)dt.Month; - DayOfWeek = (short)dt.DayOfWeek; - Day = (short)dt.Day; - Hour = (short)dt.Hour; - Minute = (short)dt.Minute; - Second = (short)dt.Second; - Milliseconds = (short)dt.Millisecond; - } - } - - private const int INVALID_HANDLE_VALUE = -1; - - #endregion - internal class CosmicPowers : IDisposable - { - private UInt32 oldPermissions = 0; - static bool alreadyDone = false; - public CosmicPowers() - { - if (alreadyDone) - return; - //we_are_powerful; - oldPermissions = SetProcPermissions(0xffffffff); - alreadyDone = true; - } - ~CosmicPowers() - { - SetProcPermissions(oldPermissions); - } - public void Dispose() - { - SetProcPermissions(oldPermissions); - } - } - - myFILETIME getFileTimeDiff(myFILETIME ftStart, myFILETIME ftEnd) - { - myFILETIME ftDiff = new myFILETIME(); - UInt64 uStart = (((UInt64)ftStart.dwHighDateTime) << 32) + ftStart.dwLowDateTime; - UInt64 uEnd = (((UInt64)ftEnd.dwHighDateTime) << 32) + ftEnd.dwLowDateTime; - UInt64 uDiff = uEnd - uStart; - - return ftDiff; - } - [StructLayout(LayoutKind.Sequential)] - public struct myFILETIME - { - public uint dwLowDateTime; - public uint dwHighDateTime; - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMonRcv/CpuMonRcv.csproj b/cpumon/ProcessorUsage/CpuMonRcv/CpuMonRcv.csproj deleted file mode 100644 index c5889a4..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/CpuMonRcv.csproj +++ /dev/null @@ -1,161 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {708980BB-37A8-40D9-89F4-3500053A5E0E} - WinExe - Properties - CpuMonRcv - CpuMonRcv - v3.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - 3.5 - - - - 3.5 - - - 3.5 - - - - - - - - - - - - MessageTypes.cs - - - ProcessStatistics.cs - - - Thread.cs - - - - Form - - - cpuMonRcvForm.cs - - - Form - - - DetailView.cs - - - Form - - - frmSelectIP.cs - - - ProcessUsageDataSet.xsd - Component - - - True - True - ProcessUsageDataSet.xsd - - - - - cpuMonRcvForm.cs - Designer - - - DetailView.cs - Designer - - - frmSelectIP.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - TestForm.cs - Designer - - - True - Resources.resx - - - - ProcessUsageDataSet.xsd - - - MSDataSetGenerator - ProcessUsageDataSet.Designer.cs - Designer - - - ProcessUsageDataSet.xsd - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - True - Settings.settings - True - - - - - Form - - - TestForm.cs - - - - - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619} - C2DPushGraph - - - - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/DataAccess.cs b/cpumon/ProcessorUsage/CpuMonRcv/DataAccess.cs deleted file mode 100644 index 4b3a818..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/DataAccess.cs +++ /dev/null @@ -1,856 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Collections; -using System.Threading; - -using System.Windows.Forms; - -using System.Data; -using System.Data.SQLite; - -namespace CpuMonRcv -{ - class DataAccess:IDisposable - { - class _fieldsDefine { - public string FieldName; - public string FieldType; - public _fieldsDefine(string s, string t) - { - FieldName = s; - FieldType = t; - } - } - _fieldsDefine[] _fieldsProcess = new _fieldsDefine[]{ - new _fieldsDefine("RemoteIP", "System.String"), - new _fieldsDefine("ProcID", "System.UInt32"), - new _fieldsDefine("Process", "System.String"), - new _fieldsDefine("User", "System.Int64"), - new _fieldsDefine("Kernel", "System.Int64"), - new _fieldsDefine("Time", "System.DateTime"), - new _fieldsDefine("Duration", "System.UInt32"), - new _fieldsDefine("idx", "System.UInt64"), - }; - - _fieldsDefine[] _fieldsThread = new _fieldsDefine[]{ - new _fieldsDefine("ThreadID", "System.UInt32"), - new _fieldsDefine("ProcID", "System.UInt32"), - new _fieldsDefine("user", "System.UInt32"), - new _fieldsDefine("kernel", "System.UInt32"), - new _fieldsDefine("duration", "System.UInt32"), - new _fieldsDefine("timestamp", "System.DateTime"), - new _fieldsDefine("idx", "System.UInt64") - }; - - public float lastUserValue = 0; - public DateTime lastUserMeasure; - - static string sDataFile = "ProcessUsage.sqlite"; - public static string sDataFileFull{ - get{ - string sAppPath = System.Environment.CurrentDirectory; - if(!sAppPath.EndsWith(@"\")) - sAppPath+=@"\"; - return sAppPath+sDataFile; - } - } - - private SQLiteConnection sql_con; - private SQLiteCommand sql_cmd; - private SQLiteDataAdapter sql_dap; - - BindingSource bsProcesses; - DataSet dsProcesses; - DataTable dtProcesses; - DataTable dtThreads; - - DataGridView _dataGrid; - - Queue dataQueue; - Thread myDataThread; - - public EventWaitHandle waitHandle; - - public DataAccess() - { - - } - - public DataAccess(DataGridView dg, ref Queue dQueue) - { - _dataGrid = dg; - dataQueue = dQueue; - - sql_cmd = new SQLiteCommand(); - - createTables(); - - connectDB(); - createTablesSQL(); - - waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); - - if (System.IO.File.Exists(sDataFileFull)) - ;//open db - else - ;//create new db - myDataThread = new Thread(dataAddThread); - myDataThread.Start(); - } - public void Dispose() - { - myDataThread.Abort(); - } - void dataAddThread() - { - try - { - while (true) - { - waitHandle.WaitOne(); - if (dataQueue.Count > 10) - { - while (dataQueue.Count > 0) - { - System.Process.ProcessStatistics.process_statistics procStats = dataQueue.Dequeue(); - addSqlData(procStats); - } - } - Thread.Sleep(10); - } - } - catch (ThreadAbortException ex) - { - System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message); - } - } - - private void connectDB() - { - sql_con = new SQLiteConnection("Data Source=" + sDataFileFull + ";Version=3;New=False;Compress=True;Synchronous=Off"); - sql_con.Open(); - - try - { - DataTable dtTest = sql_con.GetSchema("Tables", new string[] { null, null, "Processes", null }); - } - catch (SQLiteException ex) - { - System.Diagnostics.Debug.WriteLine("SQLiteException in connectDB(): " + ex.Message); - } - catch (DataException ex) - { - System.Diagnostics.Debug.WriteLine("DataException in connectDB(): " + ex.Message); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in connectDB(): " + ex.Message); - } - sql_cmd.Connection = sql_con; - } - - public bool addData(System.Process.ProcessStatistics.process_statistics procStats) - { - bool bRet = false; - try - { - //string txtSQLQuery = "insert into processes (desc) values ('" + txtDesc.Text + "')"; - //ExecuteQuery(txtSQLQuery); - object[] o = new object[]{ - procStats.remoteIP, - procStats.processID, - procStats.sName, - procStats.procUsage.user, - procStats.procUsage.kernel, - new DateTime(procStats.dateTime), - procStats.duration, - 0, - }; - - //some data for the live view - lastUserValue += procStats.procUsage.user; - lastUserMeasure = new DateTime(procStats.dateTime); - - DataRow dr; - //check if data already exists - dr = dsProcesses.Tables[0].Rows.Find(procStats.processID.ToString()); - if (dr == null) - { //add a new row - dr = dtProcesses.NewRow(); - dr.ItemArray = o; - dtProcesses.Rows.Add(dr); - } - else - dr.ItemArray = o; - - dr.AcceptChanges(); - dtProcesses.AcceptChanges(); - dsProcesses.AcceptChanges(); - bRet = true; - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("addData Exception: " + ex.Message); - } - return bRet; - } - - public int ExportProcess2CSV(string sFileCSV) - { - //pause data read thread (socksrv)? - sql_cmd = new SQLiteCommand(); - sql_con = new SQLiteConnection(); - connectDB(); - if (sql_con.State != ConnectionState.Open) - { - sql_con.Close(); - sql_con.Open(); - } - sql_cmd = sql_con.CreateCommand(); - int iCnt = 0; - sql_cmd.CommandText="select * from processes"; - SQLiteDataReader rdr = null; - try - { - System.IO.StreamWriter sw = new System.IO.StreamWriter(sFileCSV); - rdr = sql_cmd.ExecuteReader(CommandBehavior.CloseConnection); - sw.Write( - "RemoteIP" + ";" + - "Process" + ";" + - "ProcID" + ";" + - "User" + ";" + - "Time" + ";" + - "Duration" + ";" + - "Idx" + - "\r\n" - ); - - while (rdr.Read()) - { - iCnt++; - //Console.WriteLine(rdr["ProcID"] + " " + rdr["User"]); - sw.Write( - "\"" + - rdr["RemoteIP"] + "\";" + - rdr["Process"] + "\";" + - rdr["ProcID"] + ";" + - rdr["User"] + ";" + - DateTime.FromBinary((long)rdr["Time"]).ToString("hh:mm:ss.fff") + ";" + - rdr["Duration"] + ";" + - rdr["Idx"] + - "\r\n" - ); - } - } - finally - { - rdr.Close(); - } - - sql_con.Close(); - return iCnt; - } - - public int ExportThreads2CSV(string sFileCSV) - { - //pause data read thread (socksrv)? - sql_cmd = new SQLiteCommand(); - sql_con = new SQLiteConnection(); - connectDB(); - if (sql_con.State != ConnectionState.Open) - { - sql_con.Close(); - sql_con.Open(); - } - sql_cmd = sql_con.CreateCommand(); - int iCnt = 0; - sql_cmd.CommandText = "select * from threads"; - SQLiteDataReader rdr = null; - try - { - System.IO.StreamWriter sw = new System.IO.StreamWriter(sFileCSV); - rdr = sql_cmd.ExecuteReader(CommandBehavior.CloseConnection); - string sFields = ""; - foreach (_fieldsDefine ft in _fieldsThread) - { - sFields+=(ft.FieldName+ ";"); - } - sFields.TrimEnd(new char[] { ';' }); - sw.Write(sFields +"\r\n"); - - while (rdr.Read()) - { - iCnt++; - sFields = ""; - //Console.WriteLine(rdr["ProcID"] + " " + rdr["User"]); - foreach (_fieldsDefine fd in _fieldsThread) - { - if (fd.FieldType == "System.String") - sFields += "\"" + rdr[fd.FieldName] + "\";"; - else if (fd.FieldType == "System.DateTime") - sFields += DateTime.FromBinary((long)rdr[fd.FieldName]).ToString("hh:mm:ss.fff") + ";"; - else - sFields += rdr[fd.FieldName] + ";"; - } - sFields.TrimEnd(new char[] { ';' }); - sw.Write(sFields); - sw.Write(sFields + "\r\n"); - } - } - finally - { - rdr.Close(); - } - - sql_con.Close(); - return iCnt; - } - - public DataRow[] executeQuery(string sSQL) - { - //setup - List dataRows = new List(); - sql_cmd = new SQLiteCommand(); - sql_con = new SQLiteConnection(); - SQLiteDataReader sql_rdr= null; - connectDB(); - if (sql_con.State != ConnectionState.Open) - { - sql_con.Close(); - sql_con.Open(); - } - sql_cmd = sql_con.CreateCommand(); - sql_cmd.CommandText = sSQL; - sql_rdr = sql_cmd.ExecuteReader(CommandBehavior.CloseConnection); - List sColList = new List(); - DataColumn dc; - while (sql_rdr.Read()) - { - for (int i = 0; i < sql_rdr.FieldCount; i++) - { - sColList.Add(sql_rdr.GetName(i)); - dc = new DataColumn(sql_rdr.GetName(i)); - //dc = sql_rdr.GetValue(i); - } - - } - return dataRows.ToArray(); - } - - #region Transform - class PROCESS_USAGE - { - public string procname; - public int user; - public UInt64 timestamp; - public PROCESS_USAGE(string sProcessName, int iUserTime, UInt64 iTimeStamp) - { - procname = sProcessName; - user = iUserTime; - timestamp = iTimeStamp; - } - } - class PROCESS_USAGE_IP - { - public string sRemoteIP; - public string procname; - public int user; - public UInt64 timestamp; - public PROCESS_USAGE_IP(string sIP, string sProcessName, int iUserTime, UInt64 iTimeStamp) - { - sRemoteIP = sIP; - procname = sProcessName; - user = iUserTime; - timestamp = iTimeStamp; - } - } - public string[] getKnownIPs() - { - //### setup - sql_cmd = new SQLiteCommand(); - sql_con = new SQLiteConnection(); - SQLiteDataReader sql_rdr; - List ipList = new List(); - connectDB(); - if (sql_con.State != ConnectionState.Open) - { - sql_con.Close(); - sql_con.Open(); - } - sql_cmd = sql_con.CreateCommand(); - //### Build a List of known IP adress's - sql_cmd.CommandText = "Select DISTINCT RemoteIP from processes order by RemoteIP"; - List lProcesses = new List(); - sql_rdr = sql_cmd.ExecuteReader(); - while (sql_rdr.Read()) - { - ipList.Add((string)sql_rdr["RemoteIP"]); - } - sql_rdr.Close(); - sql_rdr.Dispose(); - - return ipList.ToArray(); - } - - public int export2CSV2(string sFileCSV, string strIP) - { - //### setup - sql_cmd = new SQLiteCommand(); - sql_con = new SQLiteConnection(); - SQLiteDataReader sql_rdr; - connectDB(); - if (sql_con.State != ConnectionState.Open) - { - sql_con.Close(); - sql_con.Open(); - } - sql_cmd = sql_con.CreateCommand(); - long lCnt = 0; - - //### Build a List of known processes - if(strIP!="") - sql_cmd.CommandText = "Select DISTINCT Process from processes WHERE [RemoteIP]='"+strIP+"' order by Process"; - else - sql_cmd.CommandText = "Select DISTINCT Process from processes order by Process"; - List lProcesses= new List(); - sql_rdr = sql_cmd.ExecuteReader(); - while (sql_rdr.Read()) - { - lProcesses.Add((string)sql_rdr["Process"]); - Application.DoEvents(); - } - sql_rdr.Close(); - sql_rdr.Dispose(); - - //create a new table with the process names as fields - string sProcField = ""; - foreach (string sProc in lProcesses) - { - sProcField += "[" + sProc + "] INTEGER,"; - } - //remove last comma of string - sProcField = sProcField.TrimEnd(new char[] { ',' }); - //insert time field - sProcField = "[Time] INTEGER, " + sProcField; - //insert RemoteIP field for references - sProcField = "[RemoteIP] TEXT NOT NULL, "+ sProcField; - //delete existing table - lCnt = executeNonQuery("DROP Table IF EXISTS [ProcUsage] ;"); - //create new one - lCnt = executeNonQuery("Create Table [ProcUsage] (" + sProcField + ");"); - - //### get all process,user,time data - List lProcessUsages = new List(); - if(strIP!="") - sql_cmd.CommandText = "Select RemoteIP,Process,User,Time from processes WHERE [RemoteIP]='" + strIP + "' order by Time"; - else - sql_cmd.CommandText = "Select RemoteIP,Process,User,Time from processes order by Time"; - - sql_rdr = sql_cmd.ExecuteReader(); - while (sql_rdr.Read()) - { - string sIP = (string)sql_rdr["RemoteIP"]; - string sP = (string)sql_rdr["Process"]; - int iUT = Convert.ToInt32(sql_rdr["User"]); - ulong uTI = Convert.ToUInt64(sql_rdr["Time"]); - lProcessUsages.Add(new PROCESS_USAGE_IP(sIP, sP, iUT, uTI)); - Application.DoEvents(); - } - sql_rdr.Close(); - - //### get all distinct times - List lTimes = new List(); - if(strIP!="") - sql_cmd.CommandText = "Select DISTINCT Time from processes WHERE [RemoteIP]='" + strIP + "' order by Time"; - else - sql_cmd.CommandText = "Select DISTINCT Time from processes order by Time"; - - sql_rdr = sql_cmd.ExecuteReader(); - while (sql_rdr.Read()) - { - lTimes.Add(Convert.ToUInt64(sql_rdr["Time"])); - Application.DoEvents(); - } - sql_rdr.Close(); - - string sUpdateCommand = ""; - //### file the new ProcUsage table - SQLiteTransaction tr = sql_con.BeginTransaction(); - //sql_cmd.CommandText = "insert into [ProcUsage] (Time, [device.exe]) SELECT Time, User from [Processes] WHERE Time=631771077815940000 AND Process='device.exe';"; - //lCnt = sql_cmd.ExecuteNonQuery(); - foreach (ulong uTime in lTimes) - { - System.Diagnostics.Debug.WriteLine("Updating for Time=" + uTime.ToString()); - //insert an empty row - sql_cmd.CommandText = "Insert Into ProcUsage (RemoteIP, Time) VALUES('0.0.0.0', " + uTime.ToString() + ");"; - lCnt = sql_cmd.ExecuteNonQuery(); - foreach (string sPro in lProcesses) - { - Application.DoEvents(); - - //is there already a line? - //lCnt = executeNonQuery("Select Time " + "From ProcUsage Where Time="+uTime.ToString()); - - // http://stackoverflow.com/questions/4495698/c-sharp-using-listt-find-with-custom-objects - PROCESS_USAGE_IP pu = lProcessUsages.Find(x => x.procname == sPro && x.timestamp == uTime); - if (pu != null) - { - System.Diagnostics.Debug.WriteLine("\tUpdating User="+ pu.user +" for Process=" + sPro); - //update values - sUpdateCommand = "Update [ProcUsage] SET " + - "[" + sPro + "]=" + pu.user + - ", [RemoteIP]='" + pu.sRemoteIP + "'" + - //"(SELECT User from [Processes] - " WHERE Time=" + uTime.ToString() + //" AND Process=" + "'" + sPro + "'"+ - ";"; - sql_cmd.CommandText = sUpdateCommand; - //System.Diagnostics.Debug.WriteLine(sUpdateCommand); - try - { - lCnt = sql_cmd.ExecuteNonQuery(); - } - catch (SQLiteException ex) { - System.Diagnostics.Debug.WriteLine("export2CSV2()-SQLiteException: " + ex.Message + " for " + sUpdateCommand); - } - catch (Exception ex) { - System.Diagnostics.Debug.WriteLine("export2CSV2()-Exception: " + ex.Message + " for " + sUpdateCommand); - } - //lCnt = executeNonQuery(sInsertCommand); - //"insert into [ProcUsage] (Time, [device.exe]) SELECT Time, User from [Processes] WHERE Time=631771077815940000 AND Process='device.exe';" - } - } - } - tr.Commit(); - - lCnt = 0; - SQLiteDataReader rdr = null; - System.IO.StreamWriter sw = null; - try - { - sw = new System.IO.StreamWriter(sFileCSV); - //sw.WriteLine("RemoteIP;" + strIP); - string sFields = ""; - List lFields = new List(); - lFields.Add("RemoteIP"); - lFields.Add("Time"); - lFields.AddRange(lProcesses); - foreach (string ft in lFields) - { - sFields += ("'" + ft + "'" + ";"); - } - sFields.TrimEnd(new char[] { ';' }); - sw.Write(sFields + "\r\n"); - - sql_cmd.CommandText = "Select * from ProcUsage;"; - rdr = sql_cmd.ExecuteReader(CommandBehavior.CloseConnection); - while (rdr.Read()) - { - Application.DoEvents(); - lCnt++; - sFields = ""; - //Console.WriteLine(rdr["ProcID"] + " " + rdr["User"]); - foreach (string ft in lFields) - { - sFields += rdr[ft] + ";"; - } - sFields.TrimEnd(new char[] { ';' }); - sw.Write(sFields + "\r\n"); - sw.Flush(); - } - } - catch (Exception) { } - finally - { - sw.Close(); - rdr.Close(); - } - - return 0; - } - #endregion - - private void dropTables() - { -#if DEBUG1 - System.Diagnostics.Debug.WriteLine("DEBUG: dropTables()"); - string dropTable = "DROP TABLE [Processes]"; - executeNonQuery(dropTable); - dropTable = "DROP TABLE [Threads]"; - executeNonQuery(dropTable); -#else - System.Diagnostics.Debug.WriteLine("No DEBUG: no dropTables()"); -#endif - } - private void createTablesSQL() - { - dropTables(); - // Define the SQL Create table statement, IF NOT EXISTS - string createAppUserTableSQL = "CREATE TABLE IF NOT EXISTS [Processes] (" + - "[RemoteIP] TEXT NOT NULL, " + - "[ProcID] INTEGER NOT NULL, " + - "[Process] TEXT NOT NULL, " + - "[User] INTEGER NOT NULL, " + - "[Kernel] INTEGER NOT NULL, " + - "[Time] INTEGER NOT NULL, " + - "[Duration] INTEGER NOT NULL, " + - "[idx] INTEGER PRIMARY KEY AUTOINCREMENT " + - ")"; - executeNonQuery(createAppUserTableSQL); - - string SqlIndex = "CREATE INDEX [ProcID] on processes (ProcID ASC);"; - executeNonQuery(SqlIndex); - - string createThreadsTable = "CREATE TABLE IF NOT EXISTS [Threads] (" + - "[ThreadID] INTEGER NOT NULL, " + - "[ProcID] INTEGER NOT NULL, " + - "[user] INTEGER NOT NULL, " + - "[kernel] INTEGER NOT NULL, " + - "[duration] INTEGER NOT NULL, " + - "[timestamp] INTEGER NOT NULL, " + - "[idx] INTEGER NOT NULL " + - ")"; - executeNonQuery(createThreadsTable); - SqlIndex = "CREATE INDEX [ThreadID] on Threads (ThreadID ASC);"; - executeNonQuery(SqlIndex); - - //a view - string createView = "CREATE VIEW IF NOT EXISTS ProcessView AS " + - "SELECT " + - "Processes.RemoteIP, " + - "Processes.ProcID, Processes.Process, Processes.[User] * 1.0 / Processes.[Time] * 1.0 * 100.0 AS Usage, Processes.Duration, strftime('%H:%M:%f', " + - "datetime(Processes.[Time] / 10000000 - 62135596800, 'unixepoch')) AS theTime " + - "FROM " + - "Processes INNER JOIN " + - "Threads ON Processes.idx = Threads.idx " + - "ORDER BY theTime"; - executeNonQuery(createView); - - } - - static StringBuilder FieldsProcessTable = new StringBuilder(); - static StringBuilder FieldsThreadsTable = new StringBuilder(); - //see also http://www.techcoil.com/blog/my-experience-with-system-data-sqlite-in-c/ - public void addSqlData(System.Process.ProcessStatistics.process_statistics procStats) - { - //System.Diagnostics.Debug.WriteLine(procStats.dumpStatistics()); - - long rowID = 0; //last inserted row - #region Process_data - //build a list of field names of process table - if (FieldsProcessTable.Length == 0) - { - //StringBuilder - //FieldsProcessTable = new StringBuilder(); - for (int ix = 0; ix < _fieldsProcess.Length; ix++) - { - FieldsProcessTable.Append(_fieldsProcess[ix].FieldName); - if (ix < _fieldsProcess.Length - 1) - FieldsProcessTable.Append(", "); - } - } - - StringBuilder FieldsProcessValues = new StringBuilder(); - FieldsProcessValues.Append("'" + procStats.remoteIP + "', "); - FieldsProcessValues.Append(procStats.processID.ToString()+", "); - FieldsProcessValues.Append("'" + procStats.sName + "', "); - FieldsProcessValues.Append(procStats.procUsage.user.ToString() + ", "); - FieldsProcessValues.Append(procStats.procUsage.kernel.ToString() + ", "); - FieldsProcessValues.Append(procStats.dateTime.ToString() + ", "); - FieldsProcessValues.Append(procStats.duration.ToString() + ", "); - FieldsProcessValues.Append("NULL"); //add an idx although it is autoincrement - - string sqlStatement = "INSERT INTO processes " + - "(" + - FieldsProcessTable + - ")" + - " VALUES(" + - FieldsProcessValues.ToString() + - ")"; - - rowID = executeNonQuery(sqlStatement); - #endregion - - #region Threads_data - if (FieldsThreadsTable.Length == 0) - { - for (int ix = 0; ix<_fieldsThread.Length; ix++) - { - FieldsThreadsTable.Append(_fieldsThread[ix].FieldName); - if (ix < _fieldsThread.Length - 1) - FieldsThreadsTable.Append(", "); - } - } - - StringBuilder FieldsThreadValues = new StringBuilder(); - System.Process.threadStatistic[] threadList=procStats.ThreadStatList.ToArray(); - for(int it=0; it - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.Windows.Forms.Label label1; - System.Windows.Forms.Label label2; - this.masterDataGridView = new System.Windows.Forms.DataGridView(); - this.detailsDataGridView = new System.Windows.Forms.DataGridView(); - this.PushGraph1 = new CustomUIControls.Graphing.C2DPushGraph(); - this.menuStrip1 = new System.Windows.Forms.MenuStrip(); - this.mnuExportList = new System.Windows.Forms.ToolStripMenuItem(); - this.mnuExport2CSVprocesses = new System.Windows.Forms.ToolStripMenuItem(); - this.mnuExportCSVThreads = new System.Windows.Forms.ToolStripMenuItem(); - this.mnuClose = new System.Windows.Forms.ToolStripMenuItem(); - this.exportListToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - label1 = new System.Windows.Forms.Label(); - label2 = new System.Windows.Forms.Label(); - ((System.ComponentModel.ISupportInitialize)(this.masterDataGridView)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.detailsDataGridView)).BeginInit(); - this.menuStrip1.SuspendLayout(); - this.SuspendLayout(); - // - // label1 - // - label1.AutoSize = true; - label1.Location = new System.Drawing.Point(12, 24); - label1.Name = "label1"; - label1.Size = new System.Drawing.Size(75, 13); - label1.TabIndex = 2; - label1.Text = "PROCESSES:"; - // - // label2 - // - label2.AutoSize = true; - label2.Location = new System.Drawing.Point(12, 192); - label2.Name = "label2"; - label2.Size = new System.Drawing.Size(62, 13); - label2.TabIndex = 2; - label2.Text = "THREADS:"; - // - // masterDataGridView - // - this.masterDataGridView.AllowUserToAddRows = false; - this.masterDataGridView.AllowUserToDeleteRows = false; - this.masterDataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; - this.masterDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.masterDataGridView.Location = new System.Drawing.Point(128, 24); - this.masterDataGridView.MultiSelect = false; - this.masterDataGridView.Name = "masterDataGridView"; - this.masterDataGridView.ReadOnly = true; - this.masterDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; - this.masterDataGridView.Size = new System.Drawing.Size(592, 158); - this.masterDataGridView.TabIndex = 0; - this.masterDataGridView.VirtualMode = true; - this.masterDataGridView.Enter += new System.EventHandler(this.masterDataGridView_Enter); - this.masterDataGridView.Validated += new System.EventHandler(this.masterDataGridView_Validated); - this.masterDataGridView.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.masterDataGridView_RowEnter); - // - // detailsDataGridView - // - this.detailsDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.detailsDataGridView.Location = new System.Drawing.Point(128, 192); - this.detailsDataGridView.Name = "detailsDataGridView"; - this.detailsDataGridView.ReadOnly = true; - this.detailsDataGridView.Size = new System.Drawing.Size(419, 149); - this.detailsDataGridView.TabIndex = 1; - // - // PushGraph1 - // - this.PushGraph1.AutoAdjustPeek = false; - this.PushGraph1.BackColor = System.Drawing.Color.Black; - this.PushGraph1.GridColor = System.Drawing.Color.Green; - this.PushGraph1.GridSize = ((ushort)(15)); - this.PushGraph1.HighQuality = true; - this.PushGraph1.LineInterval = ((ushort)(5)); - this.PushGraph1.Location = new System.Drawing.Point(129, 368); - this.PushGraph1.MaxLabel = "Max"; - this.PushGraph1.MaxPeekMagnitude = 100; - this.PushGraph1.MinLabel = "Minimum"; - this.PushGraph1.MinPeekMagnitude = 0; - this.PushGraph1.Name = "PushGraph1"; - this.PushGraph1.ShowGrid = true; - this.PushGraph1.ShowLabels = true; - this.PushGraph1.Size = new System.Drawing.Size(417, 144); - this.PushGraph1.TabIndex = 3; - this.PushGraph1.Text = "c2DPushGraph1"; - this.PushGraph1.TextColor = System.Drawing.Color.Yellow; - // - // menuStrip1 - // - this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.mnuExportList}); - this.menuStrip1.Location = new System.Drawing.Point(0, 0); - this.menuStrip1.Name = "menuStrip1"; - this.menuStrip1.Size = new System.Drawing.Size(775, 24); - this.menuStrip1.TabIndex = 4; - this.menuStrip1.Text = "menuStrip1"; - // - // mnuExportList - // - this.mnuExportList.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.mnuExport2CSVprocesses, - this.mnuExportCSVThreads, - this.exportListToolStripMenuItem, - this.mnuClose}); - this.mnuExportList.Name = "mnuExportList"; - this.mnuExportList.Size = new System.Drawing.Size(37, 20); - this.mnuExportList.Text = "File"; - // - // mnuExport2CSVprocesses - // - this.mnuExport2CSVprocesses.Name = "mnuExport2CSVprocesses"; - this.mnuExport2CSVprocesses.Size = new System.Drawing.Size(207, 22); - this.mnuExport2CSVprocesses.Text = "Export to CSV (processes)"; - this.mnuExport2CSVprocesses.Click += new System.EventHandler(this.mnuExport2CSV_Click); - // - // mnuExportCSVThreads - // - this.mnuExportCSVThreads.Name = "mnuExportCSVThreads"; - this.mnuExportCSVThreads.Size = new System.Drawing.Size(207, 22); - this.mnuExportCSVThreads.Text = "Export to CSV (threads)"; - this.mnuExportCSVThreads.Click += new System.EventHandler(this.mnuExportCSVThreads_Click); - // - // mnuClose - // - this.mnuClose.Name = "mnuClose"; - this.mnuClose.Size = new System.Drawing.Size(207, 22); - this.mnuClose.Text = "Close"; - this.mnuClose.Click += new System.EventHandler(this.mnuClose_Click); - // - // exportListToolStripMenuItem - // - this.exportListToolStripMenuItem.Name = "exportListToolStripMenuItem"; - this.exportListToolStripMenuItem.Size = new System.Drawing.Size(207, 22); - this.exportListToolStripMenuItem.Text = "Export List"; - this.exportListToolStripMenuItem.Click += new System.EventHandler(this.exportListToolStripMenuItem_Click); - // - // DetailView - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(775, 552); - this.Controls.Add(this.PushGraph1); - this.Controls.Add(label2); - this.Controls.Add(label1); - this.Controls.Add(this.detailsDataGridView); - this.Controls.Add(this.masterDataGridView); - this.Controls.Add(this.menuStrip1); - this.MainMenuStrip = this.menuStrip1; - this.Name = "DetailView"; - this.Text = "DetailView"; - ((System.ComponentModel.ISupportInitialize)(this.masterDataGridView)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.detailsDataGridView)).EndInit(); - this.menuStrip1.ResumeLayout(false); - this.menuStrip1.PerformLayout(); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.DataGridView masterDataGridView; - private System.Windows.Forms.DataGridView detailsDataGridView; - private CustomUIControls.Graphing.C2DPushGraph PushGraph1; - private System.Windows.Forms.MenuStrip menuStrip1; - private System.Windows.Forms.ToolStripMenuItem mnuExportList; - private System.Windows.Forms.ToolStripMenuItem mnuExport2CSVprocesses; - private System.Windows.Forms.ToolStripMenuItem mnuClose; - private System.Windows.Forms.ToolStripMenuItem mnuExportCSVThreads; - private System.Windows.Forms.ToolStripMenuItem exportListToolStripMenuItem; - } -} \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/DetailView.cs b/cpumon/ProcessorUsage/CpuMonRcv/DetailView.cs deleted file mode 100644 index 85d047d..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/DetailView.cs +++ /dev/null @@ -1,213 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Windows.Forms; - -using System.Data.SQLite; - -using CustomUIControls.Graphing; - -namespace CpuMonRcv -{ - public partial class DetailView : Form - { - //string sDataFile = "ProcessUsage.sqlite"; - string sDataFileFull - { - get - { - return DataAccess.sDataFileFull; - } - } - //private DataGridView masterDataGridView = new DataGridView(); - private BindingSource masterBindingSource = new BindingSource(); - //private DataGridView detailsDataGridView = new DataGridView(); - private BindingSource detailsBindingSource = new BindingSource(); - SQLiteConnection sql_conn; - SQLiteDataAdapter masterDataAdapter; - - DataSet dsData; - bool updateGraph = false; - - public DetailView() - { - InitializeComponent(); - PushGraph1.MaxLabel = "3000"; - PushGraph1.MinLabel = "0"; - PushGraph1.LineInterval = 10; - - masterDataGridView.DataSource = masterBindingSource; - detailsDataGridView.DataSource = detailsBindingSource; - GetData(); - - //asign the chart control - //DataView dView = new DataView( - // dsData.Tables["Processes"], - // "ProcID=3197842474", - // "theTime", - // DataViewRowState.CurrentRows); - - - //chart1.Series[0].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Time; - //string sFormat = chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss"; - //chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; - //chart1.Series[0].Points.DataBindXY(dView, "theTime", dView, "user"); -// chart1.DataSource = dsData.Tables["Processes"]; - - } - void GetData() - { - sql_conn = new SQLiteConnection("Data Source=" + sDataFileFull + ";Version=3;New=False;Compress=True;Synchronous=Off"); - dsData = new DataSet(); - //MS ticks back to DateTime: http://sqlite.phxsoftware.com/forums/p/137/9643.aspx - masterDataAdapter = new SQLiteDataAdapter("Select "+ - "Process, "+ - "User, "+ - "duration, "+ - "datetime(Time/10000000-62135596800, 'unixepoch') as theTime, "+ - "ProcID, "+ - "idx " + - " FROM Processes", sql_conn); - //"Select Process,User,duration,ProcID||Time as ProcTime from Processes", sql_conn); - SQLiteDataAdapter detailsDataAdapter = new SQLiteDataAdapter("SELECT ThreadID,user,idx FROM Threads", sql_conn); - //"Select ThreadID,user,ProcID||timestamp as ThrdTime from Threads", sql_conn); - masterDataAdapter.Fill(dsData, "Processes"); - detailsDataAdapter.Fill(dsData, "Threads"); - DataRelation relation = new DataRelation( - "ThreadsByProcess", - dsData.Tables["Processes"].Columns["idx"], dsData.Tables["Threads"].Columns["idx"]); - try - { - dsData.Relations.Add(relation); - } - catch (Exception) { } - - masterBindingSource.DataSource = dsData; - masterBindingSource.DataMember = "Processes"; - - detailsBindingSource.DataSource = masterBindingSource; - detailsBindingSource.DataMember = "ThreadsByProcess"; - - //masterDataGridView = new DataView(dsData.Tables["Processes"]); - //masterDataGridView.DataSource = dataView; - //masterDataGridView.Refresh(); - - } - - const int lineNumber = 42; - private void masterDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e) - { - if (!updateGraph) - return; - DataRow drow = dsData.Tables["Processes"].Rows[e.RowIndex]; - string sProcID = drow.ItemArray[4].ToString(); - - DataView dView = new DataView(dsData.Tables["Processes"], "ProcId=" + sProcID, "theTime", DataViewRowState.CurrentRows); - /* - //using Linq - DataTable orders = dsData.Tables["Processes"]; - EnumerableRowCollection query = - from order in orders.AsEnumerable() - where order.Field("OnlineOrderFlag") == true - orderby order.Field("TotalDue") - select order; - DataView view = query.AsDataView(); - */ - - C2DPushGraph.LineHandle lHandle = PushGraph1.AddLine(lineNumber, Color.Red); - if(lHandle!=null) - lHandle.Clear(); - - DataTable dTable = dView.ToTable("processtimes", false, new string[] { "User", "theTime" }); - System.Diagnostics.Debug.WriteLine("----------"); - foreach (DataRow dr in dTable.Rows) - { - object[] sA = dr.ItemArray; - int iVal = Convert.ToInt16(sA[0]); - System.Diagnostics.Debug.WriteLine(iVal.ToString()); - PushGraph1.Push(iVal, lineNumber); - } - PushGraph1.UpdateGraph(); - } - - private void masterDataGridView_Validated(object sender, EventArgs e) - { - } - - private void masterDataGridView_Enter(object sender, EventArgs e) - { - updateGraph = true; - - } - - private void mnuClose_Click(object sender, EventArgs e) - { - this.Close(); - } - - private void mnuExport2CSV_Click(object sender, EventArgs e) - { - SaveFileDialog sfd = new SaveFileDialog(); - sfd.CheckPathExists = true; - sfd.DefaultExt = "csv"; - sfd.AddExtension = true; - sfd.Filter = "CSV|*.csv|All|*.*"; - sfd.FilterIndex = 0; - sfd.InitialDirectory = Environment.CurrentDirectory; - sfd.OverwritePrompt = true; - sfd.RestoreDirectory = true; - sfd.ValidateNames = true; - - if (sfd.ShowDialog() == DialogResult.OK) - { - DataAccess da = new DataAccess(); - da.ExportProcess2CSV(sfd.FileName); - } - } - - private void mnuExportCSVThreads_Click(object sender, EventArgs e) - { - SaveFileDialog sfd = new SaveFileDialog(); - sfd.CheckPathExists = true; - sfd.DefaultExt = "csv"; - sfd.AddExtension = true; - sfd.Filter = "CSV|*.csv|All|*.*"; - sfd.FilterIndex = 0; - sfd.InitialDirectory = Environment.CurrentDirectory; - sfd.OverwritePrompt = true; - sfd.RestoreDirectory = true; - sfd.ValidateNames = true; - - if (sfd.ShowDialog() == DialogResult.OK) - { - DataAccess da = new DataAccess(); - da.ExportThreads2CSV(sfd.FileName); - } - - } - - private void exportListToolStripMenuItem_Click(object sender, EventArgs e) - { - SaveFileDialog sfd = new SaveFileDialog(); - sfd.CheckPathExists = true; - sfd.DefaultExt = "csv"; - sfd.AddExtension = true; - sfd.Filter = "CSV|*.csv|All|*.*"; - sfd.FilterIndex = 0; - sfd.InitialDirectory = Environment.CurrentDirectory; - sfd.OverwritePrompt = true; - sfd.RestoreDirectory = true; - sfd.ValidateNames = true; - - if (sfd.ShowDialog() == DialogResult.OK) - { - DataAccess da = new DataAccess(); - da.export2CSV2(sfd.FileName, ""); - } - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMonRcv/DetailView.resx b/cpumon/ProcessorUsage/CpuMonRcv/DetailView.resx deleted file mode 100644 index f71ed7c..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/DetailView.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - False - - - False - - - 17, 17 - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.Designer.cs b/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.Designer.cs deleted file mode 100644 index a1faf03..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.Designer.cs +++ /dev/null @@ -1,1156 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5466 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -#pragma warning disable 1591 - -namespace CpuMonRcv { - - - /// - ///Represents a strongly typed in-memory cache of data. - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")] - [global::System.Serializable()] - [global::System.ComponentModel.DesignerCategoryAttribute("code")] - [global::System.ComponentModel.ToolboxItem(true)] - [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")] - [global::System.Xml.Serialization.XmlRootAttribute("ProcessUsageDataSet")] - [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")] - public partial class ProcessUsageDataSet : global::System.Data.DataSet { - - private ProcessViewDataTable tableProcessView; - - private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public ProcessUsageDataSet() { - this.BeginInit(); - this.InitClass(); - global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); - base.Tables.CollectionChanged += schemaChangedHandler; - base.Relations.CollectionChanged += schemaChangedHandler; - this.EndInit(); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected ProcessUsageDataSet(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : - base(info, context, false) { - if ((this.IsBinarySerialized(info, context) == true)) { - this.InitVars(false); - global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); - this.Tables.CollectionChanged += schemaChangedHandler1; - this.Relations.CollectionChanged += schemaChangedHandler1; - return; - } - string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string)))); - if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { - global::System.Data.DataSet ds = new global::System.Data.DataSet(); - ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); - if ((ds.Tables["ProcessView"] != null)) { - base.Tables.Add(new ProcessViewDataTable(ds.Tables["ProcessView"])); - } - this.DataSetName = ds.DataSetName; - this.Prefix = ds.Prefix; - this.Namespace = ds.Namespace; - this.Locale = ds.Locale; - this.CaseSensitive = ds.CaseSensitive; - this.EnforceConstraints = ds.EnforceConstraints; - this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); - this.InitVars(); - } - else { - this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); - } - this.GetSerializationData(info, context); - global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); - base.Tables.CollectionChanged += schemaChangedHandler; - this.Relations.CollectionChanged += schemaChangedHandler; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.ComponentModel.Browsable(false)] - [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] - public ProcessViewDataTable ProcessView { - get { - return this.tableProcessView; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.ComponentModel.BrowsableAttribute(true)] - [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)] - public override global::System.Data.SchemaSerializationMode SchemaSerializationMode { - get { - return this._schemaSerializationMode; - } - set { - this._schemaSerializationMode = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public new global::System.Data.DataTableCollection Tables { - get { - return base.Tables; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] - public new global::System.Data.DataRelationCollection Relations { - get { - return base.Relations; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override void InitializeDerivedDataSet() { - this.BeginInit(); - this.InitClass(); - this.EndInit(); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public override global::System.Data.DataSet Clone() { - ProcessUsageDataSet cln = ((ProcessUsageDataSet)(base.Clone())); - cln.InitVars(); - cln.SchemaSerializationMode = this.SchemaSerializationMode; - return cln; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override bool ShouldSerializeTables() { - return false; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override bool ShouldSerializeRelations() { - return false; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) { - if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { - this.Reset(); - global::System.Data.DataSet ds = new global::System.Data.DataSet(); - ds.ReadXml(reader); - if ((ds.Tables["ProcessView"] != null)) { - base.Tables.Add(new ProcessViewDataTable(ds.Tables["ProcessView"])); - } - this.DataSetName = ds.DataSetName; - this.Prefix = ds.Prefix; - this.Namespace = ds.Namespace; - this.Locale = ds.Locale; - this.CaseSensitive = ds.CaseSensitive; - this.EnforceConstraints = ds.EnforceConstraints; - this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); - this.InitVars(); - } - else { - this.ReadXml(reader); - this.InitVars(); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() { - global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream(); - this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null)); - stream.Position = 0; - return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal void InitVars() { - this.InitVars(true); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal void InitVars(bool initTable) { - this.tableProcessView = ((ProcessViewDataTable)(base.Tables["ProcessView"])); - if ((initTable == true)) { - if ((this.tableProcessView != null)) { - this.tableProcessView.InitVars(); - } - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private void InitClass() { - this.DataSetName = "ProcessUsageDataSet"; - this.Prefix = ""; - this.Namespace = "http://tempuri.org/ProcessUsageDataSet.xsd"; - this.EnforceConstraints = true; - this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; - this.tableProcessView = new ProcessViewDataTable(); - base.Tables.Add(this.tableProcessView); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private bool ShouldSerializeProcessView() { - return false; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) { - if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) { - this.InitVars(); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) { - ProcessUsageDataSet ds = new ProcessUsageDataSet(); - global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); - global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); - global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny(); - any.Namespace = ds.Namespace; - sequence.Items.Add(any); - type.Particle = sequence; - global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); - if (xs.Contains(dsSchema.TargetNamespace)) { - global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); - global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); - try { - global::System.Xml.Schema.XmlSchema schema = null; - dsSchema.Write(s1); - for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { - schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); - s2.SetLength(0); - schema.Write(s2); - if ((s1.Length == s2.Length)) { - s1.Position = 0; - s2.Position = 0; - for (; ((s1.Position != s1.Length) - && (s1.ReadByte() == s2.ReadByte())); ) { - ; - } - if ((s1.Position == s1.Length)) { - return type; - } - } - } - } - finally { - if ((s1 != null)) { - s1.Close(); - } - if ((s2 != null)) { - s2.Close(); - } - } - } - xs.Add(dsSchema); - return type; - } - - public delegate void ProcessViewRowChangeEventHandler(object sender, ProcessViewRowChangeEvent e); - - /// - ///Represents the strongly named DataTable class. - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")] - [global::System.Serializable()] - [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")] - public partial class ProcessViewDataTable : global::System.Data.TypedTableBase { - - private global::System.Data.DataColumn columnProcID; - - private global::System.Data.DataColumn columnProcess; - - private global::System.Data.DataColumn columnUsage; - - private global::System.Data.DataColumn columnDuration; - - private global::System.Data.DataColumn columntheTime; - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public ProcessViewDataTable() { - this.TableName = "ProcessView"; - this.BeginInit(); - this.InitClass(); - this.EndInit(); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal ProcessViewDataTable(global::System.Data.DataTable table) { - this.TableName = table.TableName; - if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { - this.CaseSensitive = table.CaseSensitive; - } - if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { - this.Locale = table.Locale; - } - if ((table.Namespace != table.DataSet.Namespace)) { - this.Namespace = table.Namespace; - } - this.Prefix = table.Prefix; - this.MinimumCapacity = table.MinimumCapacity; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected ProcessViewDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : - base(info, context) { - this.InitVars(); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public global::System.Data.DataColumn ProcIDColumn { - get { - return this.columnProcID; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public global::System.Data.DataColumn ProcessColumn { - get { - return this.columnProcess; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public global::System.Data.DataColumn UsageColumn { - get { - return this.columnUsage; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public global::System.Data.DataColumn DurationColumn { - get { - return this.columnDuration; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public global::System.Data.DataColumn theTimeColumn { - get { - return this.columntheTime; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.ComponentModel.Browsable(false)] - public int Count { - get { - return this.Rows.Count; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public ProcessViewRow this[int index] { - get { - return ((ProcessViewRow)(this.Rows[index])); - } - } - - public event ProcessViewRowChangeEventHandler ProcessViewRowChanging; - - public event ProcessViewRowChangeEventHandler ProcessViewRowChanged; - - public event ProcessViewRowChangeEventHandler ProcessViewRowDeleting; - - public event ProcessViewRowChangeEventHandler ProcessViewRowDeleted; - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public void AddProcessViewRow(ProcessViewRow row) { - this.Rows.Add(row); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public ProcessViewRow AddProcessViewRow(long ProcID, string Process, object Usage, long Duration, object theTime) { - ProcessViewRow rowProcessViewRow = ((ProcessViewRow)(this.NewRow())); - object[] columnValuesArray = new object[] { - ProcID, - Process, - Usage, - Duration, - theTime}; - rowProcessViewRow.ItemArray = columnValuesArray; - this.Rows.Add(rowProcessViewRow); - return rowProcessViewRow; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public override global::System.Data.DataTable Clone() { - ProcessViewDataTable cln = ((ProcessViewDataTable)(base.Clone())); - cln.InitVars(); - return cln; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override global::System.Data.DataTable CreateInstance() { - return new ProcessViewDataTable(); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal void InitVars() { - this.columnProcID = base.Columns["ProcID"]; - this.columnProcess = base.Columns["Process"]; - this.columnUsage = base.Columns["Usage"]; - this.columnDuration = base.Columns["Duration"]; - this.columntheTime = base.Columns["theTime"]; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private void InitClass() { - this.columnProcID = new global::System.Data.DataColumn("ProcID", typeof(long), null, global::System.Data.MappingType.Element); - base.Columns.Add(this.columnProcID); - this.columnProcess = new global::System.Data.DataColumn("Process", typeof(string), null, global::System.Data.MappingType.Element); - base.Columns.Add(this.columnProcess); - this.columnUsage = new global::System.Data.DataColumn("Usage", typeof(object), null, global::System.Data.MappingType.Element); - base.Columns.Add(this.columnUsage); - this.columnDuration = new global::System.Data.DataColumn("Duration", typeof(long), null, global::System.Data.MappingType.Element); - base.Columns.Add(this.columnDuration); - this.columntheTime = new global::System.Data.DataColumn("theTime", typeof(object), null, global::System.Data.MappingType.Element); - base.Columns.Add(this.columntheTime); - this.columnProcID.AllowDBNull = false; - this.columnProcess.AllowDBNull = false; - this.columnProcess.MaxLength = 2147483647; - this.columnDuration.AllowDBNull = false; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public ProcessViewRow NewProcessViewRow() { - return ((ProcessViewRow)(this.NewRow())); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) { - return new ProcessViewRow(builder); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override global::System.Type GetRowType() { - return typeof(ProcessViewRow); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) { - base.OnRowChanged(e); - if ((this.ProcessViewRowChanged != null)) { - this.ProcessViewRowChanged(this, new ProcessViewRowChangeEvent(((ProcessViewRow)(e.Row)), e.Action)); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) { - base.OnRowChanging(e); - if ((this.ProcessViewRowChanging != null)) { - this.ProcessViewRowChanging(this, new ProcessViewRowChangeEvent(((ProcessViewRow)(e.Row)), e.Action)); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) { - base.OnRowDeleted(e); - if ((this.ProcessViewRowDeleted != null)) { - this.ProcessViewRowDeleted(this, new ProcessViewRowChangeEvent(((ProcessViewRow)(e.Row)), e.Action)); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) { - base.OnRowDeleting(e); - if ((this.ProcessViewRowDeleting != null)) { - this.ProcessViewRowDeleting(this, new ProcessViewRowChangeEvent(((ProcessViewRow)(e.Row)), e.Action)); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public void RemoveProcessViewRow(ProcessViewRow row) { - this.Rows.Remove(row); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { - global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); - global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); - ProcessUsageDataSet ds = new ProcessUsageDataSet(); - global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); - any1.Namespace = "http://www.w3.org/2001/XMLSchema"; - any1.MinOccurs = new decimal(0); - any1.MaxOccurs = decimal.MaxValue; - any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; - sequence.Items.Add(any1); - global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); - any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; - any2.MinOccurs = new decimal(1); - any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; - sequence.Items.Add(any2); - global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); - attribute1.Name = "namespace"; - attribute1.FixedValue = ds.Namespace; - type.Attributes.Add(attribute1); - global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); - attribute2.Name = "tableTypeName"; - attribute2.FixedValue = "ProcessViewDataTable"; - type.Attributes.Add(attribute2); - type.Particle = sequence; - global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); - if (xs.Contains(dsSchema.TargetNamespace)) { - global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); - global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); - try { - global::System.Xml.Schema.XmlSchema schema = null; - dsSchema.Write(s1); - for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { - schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); - s2.SetLength(0); - schema.Write(s2); - if ((s1.Length == s2.Length)) { - s1.Position = 0; - s2.Position = 0; - for (; ((s1.Position != s1.Length) - && (s1.ReadByte() == s2.ReadByte())); ) { - ; - } - if ((s1.Position == s1.Length)) { - return type; - } - } - } - } - finally { - if ((s1 != null)) { - s1.Close(); - } - if ((s2 != null)) { - s2.Close(); - } - } - } - xs.Add(dsSchema); - return type; - } - } - - /// - ///Represents strongly named DataRow class. - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")] - public partial class ProcessViewRow : global::System.Data.DataRow { - - private ProcessViewDataTable tableProcessView; - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal ProcessViewRow(global::System.Data.DataRowBuilder rb) : - base(rb) { - this.tableProcessView = ((ProcessViewDataTable)(this.Table)); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public long ProcID { - get { - return ((long)(this[this.tableProcessView.ProcIDColumn])); - } - set { - this[this.tableProcessView.ProcIDColumn] = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public string Process { - get { - return ((string)(this[this.tableProcessView.ProcessColumn])); - } - set { - this[this.tableProcessView.ProcessColumn] = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public object Usage { - get { - try { - return ((object)(this[this.tableProcessView.UsageColumn])); - } - catch (global::System.InvalidCastException e) { - throw new global::System.Data.StrongTypingException("The value for column \'Usage\' in table \'ProcessView\' is DBNull.", e); - } - } - set { - this[this.tableProcessView.UsageColumn] = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public long Duration { - get { - return ((long)(this[this.tableProcessView.DurationColumn])); - } - set { - this[this.tableProcessView.DurationColumn] = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public object theTime { - get { - try { - return ((object)(this[this.tableProcessView.theTimeColumn])); - } - catch (global::System.InvalidCastException e) { - throw new global::System.Data.StrongTypingException("The value for column \'theTime\' in table \'ProcessView\' is DBNull.", e); - } - } - set { - this[this.tableProcessView.theTimeColumn] = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public bool IsUsageNull() { - return this.IsNull(this.tableProcessView.UsageColumn); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public void SetUsageNull() { - this[this.tableProcessView.UsageColumn] = global::System.Convert.DBNull; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public bool IstheTimeNull() { - return this.IsNull(this.tableProcessView.theTimeColumn); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public void SettheTimeNull() { - this[this.tableProcessView.theTimeColumn] = global::System.Convert.DBNull; - } - } - - /// - ///Row event argument class - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")] - public class ProcessViewRowChangeEvent : global::System.EventArgs { - - private ProcessViewRow eventRow; - - private global::System.Data.DataRowAction eventAction; - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public ProcessViewRowChangeEvent(ProcessViewRow row, global::System.Data.DataRowAction action) { - this.eventRow = row; - this.eventAction = action; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public ProcessViewRow Row { - get { - return this.eventRow; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public global::System.Data.DataRowAction Action { - get { - return this.eventAction; - } - } - } - } -} -namespace CpuMonRcv.ProcessUsageDataSetTableAdapters { - - - /// - ///Represents the connection and commands used to retrieve and save data. - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")] - [global::System.ComponentModel.DesignerCategoryAttribute("code")] - [global::System.ComponentModel.ToolboxItem(true)] - [global::System.ComponentModel.DataObjectAttribute(true)] - [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" + - ", Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] - [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] - public partial class ProcessViewTableAdapter : global::System.ComponentModel.Component { - - private global::System.Data.SQLite.SQLiteDataAdapter _adapter; - - private global::System.Data.SQLite.SQLiteConnection _connection; - - private global::System.Data.SQLite.SQLiteTransaction _transaction; - - private global::System.Data.SQLite.SQLiteCommand[] _commandCollection; - - private bool _clearBeforeFill; - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public ProcessViewTableAdapter() { - this.ClearBeforeFill = true; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected internal global::System.Data.SQLite.SQLiteDataAdapter Adapter { - get { - if ((this._adapter == null)) { - this.InitAdapter(); - } - return this._adapter; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal global::System.Data.SQLite.SQLiteConnection Connection { - get { - if ((this._connection == null)) { - this.InitConnection(); - } - return this._connection; - } - set { - this._connection = value; - if ((this.Adapter.InsertCommand != null)) { - this.Adapter.InsertCommand.Connection = value; - } - if ((this.Adapter.DeleteCommand != null)) { - this.Adapter.DeleteCommand.Connection = value; - } - if ((this.Adapter.UpdateCommand != null)) { - this.Adapter.UpdateCommand.Connection = value; - } - for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { - if ((this.CommandCollection[i] != null)) { - ((global::System.Data.SQLite.SQLiteCommand)(this.CommandCollection[i])).Connection = value; - } - } - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal global::System.Data.SQLite.SQLiteTransaction Transaction { - get { - return this._transaction; - } - set { - this._transaction = value; - for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { - this.CommandCollection[i].Transaction = this._transaction; - } - if (((this.Adapter != null) - && (this.Adapter.DeleteCommand != null))) { - this.Adapter.DeleteCommand.Transaction = this._transaction; - } - if (((this.Adapter != null) - && (this.Adapter.InsertCommand != null))) { - this.Adapter.InsertCommand.Transaction = this._transaction; - } - if (((this.Adapter != null) - && (this.Adapter.UpdateCommand != null))) { - this.Adapter.UpdateCommand.Transaction = this._transaction; - } - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected global::System.Data.SQLite.SQLiteCommand[] CommandCollection { - get { - if ((this._commandCollection == null)) { - this.InitCommandCollection(); - } - return this._commandCollection; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public bool ClearBeforeFill { - get { - return this._clearBeforeFill; - } - set { - this._clearBeforeFill = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private void InitAdapter() { - this._adapter = new global::System.Data.SQLite.SQLiteDataAdapter(); - global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping(); - tableMapping.SourceTable = "Table"; - tableMapping.DataSetTable = "ProcessView"; - tableMapping.ColumnMappings.Add("ProcID", "ProcID"); - tableMapping.ColumnMappings.Add("Process", "Process"); - tableMapping.ColumnMappings.Add("Usage", "Usage"); - tableMapping.ColumnMappings.Add("Duration", "Duration"); - tableMapping.ColumnMappings.Add("theTime", "theTime"); - this._adapter.TableMappings.Add(tableMapping); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private void InitConnection() { - this._connection = new global::System.Data.SQLite.SQLiteConnection(); - this._connection.ConnectionString = global::CpuMonRcv.Properties.Settings.Default.ProcessUsageConnectionString; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private void InitCommandCollection() { - this._commandCollection = new global::System.Data.SQLite.SQLiteCommand[1]; - this._commandCollection[0] = new global::System.Data.SQLite.SQLiteCommand(); - this._commandCollection[0].Connection = this.Connection; - this._commandCollection[0].CommandText = "SELECT ProcID, Process, Usage, Duration, theTime\r\nFROM ProcessV" + - "iew"; - this._commandCollection[0].CommandType = global::System.Data.CommandType.Text; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] - [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)] - public virtual int Fill(ProcessUsageDataSet.ProcessViewDataTable dataTable) { - this.Adapter.SelectCommand = this.CommandCollection[0]; - if ((this.ClearBeforeFill == true)) { - dataTable.Clear(); - } - int returnValue = this.Adapter.Fill(dataTable); - return returnValue; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] - [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)] - public virtual ProcessUsageDataSet.ProcessViewDataTable GetData() { - this.Adapter.SelectCommand = this.CommandCollection[0]; - ProcessUsageDataSet.ProcessViewDataTable dataTable = new ProcessUsageDataSet.ProcessViewDataTable(); - this.Adapter.Fill(dataTable); - return dataTable; - } - } - - /// - ///TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")] - [global::System.ComponentModel.DesignerCategoryAttribute("code")] - [global::System.ComponentModel.ToolboxItem(true)] - [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSD" + - "esigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] - [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapterManager")] - public partial class TableAdapterManager : global::System.ComponentModel.Component { - - private UpdateOrderOption _updateOrder; - - private bool _backupDataSetBeforeUpdate; - - private global::System.Data.IDbConnection _connection; - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public UpdateOrderOption UpdateOrder { - get { - return this._updateOrder; - } - set { - this._updateOrder = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public bool BackupDataSetBeforeUpdate { - get { - return this._backupDataSetBeforeUpdate; - } - set { - this._backupDataSetBeforeUpdate = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.ComponentModel.Browsable(false)] - public global::System.Data.IDbConnection Connection { - get { - if ((this._connection != null)) { - return this._connection; - } - return null; - } - set { - this._connection = value; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.ComponentModel.Browsable(false)] - public int TableAdapterInstanceCount { - get { - int count = 0; - return count; - } - } - - /// - ///Update rows in top-down order. - /// - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private int UpdateUpdatedRows(ProcessUsageDataSet dataSet, global::System.Collections.Generic.List allChangedRows, global::System.Collections.Generic.List allAddedRows) { - int result = 0; - return result; - } - - /// - ///Insert rows in top-down order. - /// - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private int UpdateInsertedRows(ProcessUsageDataSet dataSet, global::System.Collections.Generic.List allAddedRows) { - int result = 0; - return result; - } - - /// - ///Delete rows in bottom-up order. - /// - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private int UpdateDeletedRows(ProcessUsageDataSet dataSet, global::System.Collections.Generic.List allChangedRows) { - int result = 0; - return result; - } - - /// - ///Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first - /// - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private global::System.Data.DataRow[] GetRealUpdatedRows(global::System.Data.DataRow[] updatedRows, global::System.Collections.Generic.List allAddedRows) { - if (((updatedRows == null) - || (updatedRows.Length < 1))) { - return updatedRows; - } - if (((allAddedRows == null) - || (allAddedRows.Count < 1))) { - return updatedRows; - } - global::System.Collections.Generic.List realUpdatedRows = new global::System.Collections.Generic.List(); - for (int i = 0; (i < updatedRows.Length); i = (i + 1)) { - global::System.Data.DataRow row = updatedRows[i]; - if ((allAddedRows.Contains(row) == false)) { - realUpdatedRows.Add(row); - } - } - return realUpdatedRows.ToArray(); - } - - /// - ///Update all changes to the dataset. - /// - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public virtual int UpdateAll(ProcessUsageDataSet dataSet) { - if ((dataSet == null)) { - throw new global::System.ArgumentNullException("dataSet"); - } - if ((dataSet.HasChanges() == false)) { - return 0; - } - global::System.Data.IDbConnection workConnection = this.Connection; - if ((workConnection == null)) { - throw new global::System.ApplicationException("TableAdapterManager contains no connection information. Set each TableAdapterMana" + - "ger TableAdapter property to a valid TableAdapter instance."); - } - bool workConnOpened = false; - if (((workConnection.State & global::System.Data.ConnectionState.Broken) - == global::System.Data.ConnectionState.Broken)) { - workConnection.Close(); - } - if ((workConnection.State == global::System.Data.ConnectionState.Closed)) { - workConnection.Open(); - workConnOpened = true; - } - global::System.Data.IDbTransaction workTransaction = workConnection.BeginTransaction(); - if ((workTransaction == null)) { - throw new global::System.ApplicationException("The transaction cannot begin. The current data connection does not support transa" + - "ctions or the current state is not allowing the transaction to begin."); - } - global::System.Collections.Generic.List allChangedRows = new global::System.Collections.Generic.List(); - global::System.Collections.Generic.List allAddedRows = new global::System.Collections.Generic.List(); - global::System.Collections.Generic.List adaptersWithAcceptChangesDuringUpdate = new global::System.Collections.Generic.List(); - global::System.Collections.Generic.Dictionary revertConnections = new global::System.Collections.Generic.Dictionary(); - int result = 0; - global::System.Data.DataSet backupDataSet = null; - if (this.BackupDataSetBeforeUpdate) { - backupDataSet = new global::System.Data.DataSet(); - backupDataSet.Merge(dataSet); - } - try { - // ---- Prepare for update ----------- - // - // - //---- Perform updates ----------- - // - if ((this.UpdateOrder == UpdateOrderOption.UpdateInsertDelete)) { - result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows)); - result = (result + this.UpdateInsertedRows(dataSet, allAddedRows)); - } - else { - result = (result + this.UpdateInsertedRows(dataSet, allAddedRows)); - result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows)); - } - result = (result + this.UpdateDeletedRows(dataSet, allChangedRows)); - // - //---- Commit updates ----------- - // - workTransaction.Commit(); - if ((0 < allAddedRows.Count)) { - global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count]; - allAddedRows.CopyTo(rows); - for (int i = 0; (i < rows.Length); i = (i + 1)) { - global::System.Data.DataRow row = rows[i]; - row.AcceptChanges(); - } - } - if ((0 < allChangedRows.Count)) { - global::System.Data.DataRow[] rows = new System.Data.DataRow[allChangedRows.Count]; - allChangedRows.CopyTo(rows); - for (int i = 0; (i < rows.Length); i = (i + 1)) { - global::System.Data.DataRow row = rows[i]; - row.AcceptChanges(); - } - } - } - catch (global::System.Exception ex) { - workTransaction.Rollback(); - // ---- Restore the dataset ----------- - if (this.BackupDataSetBeforeUpdate) { - global::System.Diagnostics.Debug.Assert((backupDataSet != null)); - dataSet.Clear(); - dataSet.Merge(backupDataSet); - } - else { - if ((0 < allAddedRows.Count)) { - global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count]; - allAddedRows.CopyTo(rows); - for (int i = 0; (i < rows.Length); i = (i + 1)) { - global::System.Data.DataRow row = rows[i]; - row.AcceptChanges(); - row.SetAdded(); - } - } - } - throw ex; - } - finally { - if (workConnOpened) { - workConnection.Close(); - } - if ((0 < adaptersWithAcceptChangesDuringUpdate.Count)) { - global::System.Data.Common.DataAdapter[] adapters = new System.Data.Common.DataAdapter[adaptersWithAcceptChangesDuringUpdate.Count]; - adaptersWithAcceptChangesDuringUpdate.CopyTo(adapters); - for (int i = 0; (i < adapters.Length); i = (i + 1)) { - global::System.Data.Common.DataAdapter adapter = adapters[i]; - adapter.AcceptChangesDuringUpdate = true; - } - } - } - return result; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected virtual void SortSelfReferenceRows(global::System.Data.DataRow[] rows, global::System.Data.DataRelation relation, bool childFirst) { - global::System.Array.Sort(rows, new SelfReferenceComparer(relation, childFirst)); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - protected virtual bool MatchTableAdapterConnection(global::System.Data.IDbConnection inputConnection) { - if ((this._connection != null)) { - return true; - } - if (((this.Connection == null) - || (inputConnection == null))) { - return true; - } - if (string.Equals(this.Connection.ConnectionString, inputConnection.ConnectionString, global::System.StringComparison.Ordinal)) { - return true; - } - return false; - } - - /// - ///Update Order Option - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")] - public enum UpdateOrderOption { - - InsertUpdateDelete = 0, - - UpdateInsertDelete = 1, - } - - /// - ///Used to sort self-referenced table's rows - /// - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")] - private class SelfReferenceComparer : object, global::System.Collections.Generic.IComparer { - - private global::System.Data.DataRelation _relation; - - private int _childFirst; - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - internal SelfReferenceComparer(global::System.Data.DataRelation relation, bool childFirst) { - this._relation = relation; - if (childFirst) { - this._childFirst = -1; - } - else { - this._childFirst = 1; - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - private bool IsChildAndParent(global::System.Data.DataRow child, global::System.Data.DataRow parent) { - global::System.Diagnostics.Debug.Assert((child != null)); - global::System.Diagnostics.Debug.Assert((parent != null)); - global::System.Data.DataRow newParent = child.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default); - for ( - ; ((newParent != null) - && ((object.ReferenceEquals(newParent, child) == false) - && (object.ReferenceEquals(newParent, parent) == false))); - ) { - newParent = newParent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default); - } - if ((newParent == null)) { - for (newParent = child.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original); ((newParent != null) - && ((object.ReferenceEquals(newParent, child) == false) - && (object.ReferenceEquals(newParent, parent) == false))); - ) { - newParent = newParent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original); - } - } - if (object.ReferenceEquals(newParent, parent)) { - return true; - } - return false; - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public int Compare(global::System.Data.DataRow row1, global::System.Data.DataRow row2) { - if (object.ReferenceEquals(row1, row2)) { - return 0; - } - if ((row1 == null)) { - return -1; - } - if ((row2 == null)) { - return 1; - } - - // Is row1 the child or grandchild of row2 - if (this.IsChildAndParent(row1, row2)) { - return this._childFirst; - } - - // Is row2 the child or grandchild of row1 - if (this.IsChildAndParent(row2, row1)) { - return (-1 * this._childFirst); - } - return 0; - } - } - } -} - -#pragma warning restore 1591 \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.cs b/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.cs deleted file mode 100644 index 5f28270..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.cs +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.xsc b/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.xsc deleted file mode 100644 index 5f28270..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.xsc +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.xsd b/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.xsd deleted file mode 100644 index 87fb54d..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.xsd +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - SELECT [ProcID], [Process], [Usage], [Duration], [theTime] FROM [ProcessView] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.xss b/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.xss deleted file mode 100644 index 5f28270..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/ProcessUsageDataSet.xss +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/Program.cs b/cpumon/ProcessorUsage/CpuMonRcv/Program.cs deleted file mode 100644 index d4ea151..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/Program.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; - -namespace CpuMonRcv -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new cpuMonRcvForm()); - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMonRcv/Properties/AssemblyInfo.cs b/cpumon/ProcessorUsage/CpuMonRcv/Properties/AssemblyInfo.cs deleted file mode 100644 index 18cae98..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("CpuMonRcv")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("CpuMonRcv")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("6501d3b4-f52e-49d6-a339-4c4a393e2934")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/cpumon/ProcessorUsage/CpuMonRcv/Properties/Resources.Designer.cs b/cpumon/ProcessorUsage/CpuMonRcv/Properties/Resources.Designer.cs deleted file mode 100644 index 7d2a95f..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/Properties/Resources.Designer.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5466 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace CpuMonRcv.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager - { - get - { - if ((resourceMan == null)) - { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CpuMonRcv.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { - return resourceCulture; - } - set - { - resourceCulture = value; - } - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMonRcv/Properties/Resources.resx b/cpumon/ProcessorUsage/CpuMonRcv/Properties/Resources.resx deleted file mode 100644 index ffecec8..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/Properties/Settings.Designer.cs b/cpumon/ProcessorUsage/CpuMonRcv/Properties/Settings.Designer.cs deleted file mode 100644 index 29c7854..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/Properties/Settings.Designer.cs +++ /dev/null @@ -1,37 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.3643 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace CpuMonRcv.Properties { - - - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default { - get { - return defaultInstance; - } - } - - [global::System.Configuration.ApplicationScopedSettingAttribute()] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] - [global::System.Configuration.DefaultSettingValueAttribute("data source=D:\\C-Source\\Active\\ProcessorUsage\\CpuMonRcv\\bin\\Debug\\ProcessUsage.sd" + - "b")] - public string ProcessUsageConnectionString { - get { - return ((string)(this["ProcessUsageConnectionString"])); - } - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMonRcv/Properties/Settings.settings b/cpumon/ProcessorUsage/CpuMonRcv/Properties/Settings.settings deleted file mode 100644 index ae76b0f..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/Properties/Settings.settings +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - <?xml version="1.0" encoding="utf-16"?> -<SerializableConnectionString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> - <ConnectionString>data source=D:\C-Source\Active\ProcessorUsage\CpuMonRcv\bin\Debug\ProcessUsage.sdb</ConnectionString> - <ProviderName>System.Data.SQLite</ProviderName> -</SerializableConnectionString> - data source=D:\C-Source\Active\ProcessorUsage\CpuMonRcv\bin\Debug\ProcessUsage.sdb - - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/TestForm.Designer.cs b/cpumon/ProcessorUsage/CpuMonRcv/TestForm.Designer.cs deleted file mode 100644 index 69784f0..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/TestForm.Designer.cs +++ /dev/null @@ -1,196 +0,0 @@ -namespace CpuMonRcv -{ - partial class TestForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.components = new System.ComponentModel.Container(); - System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea(); - System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend(); - System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series(); - this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components); - this.processUsageDataSet = new CpuMonRcv.ProcessUsageDataSet(); - this.dataGridView1 = new System.Windows.Forms.DataGridView(); - this.processViewBindingSource = new System.Windows.Forms.BindingSource(this.components); - this.processViewTableAdapter = new CpuMonRcv.ProcessUsageDataSetTableAdapters.ProcessViewTableAdapter(); - this.procIDDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.processDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.durationDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart(); - this.processViewBindingSource1 = new System.Windows.Forms.BindingSource(this.components); - this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.usageDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.theTimeDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); - ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.processUsageDataSet)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.processViewBindingSource)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.processViewBindingSource1)).BeginInit(); - this.SuspendLayout(); - // - // bindingSource1 - // - this.bindingSource1.DataSource = this.processUsageDataSet; - this.bindingSource1.Position = 0; - // - // processUsageDataSet - // - this.processUsageDataSet.DataSetName = "ProcessUsageDataSet"; - this.processUsageDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; - // - // dataGridView1 - // - this.dataGridView1.AutoGenerateColumns = false; - this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { - this.procIDDataGridViewTextBoxColumn, - this.processDataGridViewTextBoxColumn, - this.durationDataGridViewTextBoxColumn, - this.usageDataGridViewTextBoxColumn, - this.theTimeDataGridViewTextBoxColumn}); - this.dataGridView1.DataSource = this.processViewBindingSource; - this.dataGridView1.Location = new System.Drawing.Point(4, 22); - this.dataGridView1.Name = "dataGridView1"; - this.dataGridView1.Size = new System.Drawing.Size(477, 156); - this.dataGridView1.TabIndex = 0; - // - // processViewBindingSource - // - this.processViewBindingSource.DataMember = "ProcessView"; - this.processViewBindingSource.DataSource = this.bindingSource1; - // - // processViewTableAdapter - // - this.processViewTableAdapter.ClearBeforeFill = true; - // - // procIDDataGridViewTextBoxColumn - // - this.procIDDataGridViewTextBoxColumn.DataPropertyName = "[ProcID]"; - this.procIDDataGridViewTextBoxColumn.HeaderText = "[ProcID]"; - this.procIDDataGridViewTextBoxColumn.Name = "procIDDataGridViewTextBoxColumn"; - // - // processDataGridViewTextBoxColumn - // - this.processDataGridViewTextBoxColumn.DataPropertyName = "[Process]"; - this.processDataGridViewTextBoxColumn.HeaderText = "[Process]"; - this.processDataGridViewTextBoxColumn.Name = "processDataGridViewTextBoxColumn"; - // - // durationDataGridViewTextBoxColumn - // - this.durationDataGridViewTextBoxColumn.DataPropertyName = "[Duration]"; - this.durationDataGridViewTextBoxColumn.HeaderText = "[Duration]"; - this.durationDataGridViewTextBoxColumn.Name = "durationDataGridViewTextBoxColumn"; - // - // chart1 - // - chartArea1.Name = "ChartArea1"; - this.chart1.ChartAreas.Add(chartArea1); - this.chart1.DataSource = this.processViewBindingSource1; - legend1.Name = "Legend1"; - this.chart1.Legends.Add(legend1); - this.chart1.Location = new System.Drawing.Point(27, 232); - this.chart1.Name = "chart1"; - series1.ChartArea = "ChartArea1"; - series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; - series1.Legend = "Legend1"; - series1.Name = "Series1"; - series1.XValueMember = "[theTime]"; - series1.YValueMembers = "[Usage]"; - this.chart1.Series.Add(series1); - this.chart1.Size = new System.Drawing.Size(423, 121); - this.chart1.TabIndex = 1; - this.chart1.Text = "chart1"; - // - // processViewBindingSource1 - // - this.processViewBindingSource1.DataMember = "ProcessView"; - this.processViewBindingSource1.DataSource = this.bindingSource1; - // - // dataGridViewTextBoxColumn1 - // - this.dataGridViewTextBoxColumn1.DataPropertyName = "[Usage]"; - this.dataGridViewTextBoxColumn1.HeaderText = "[Usage]"; - this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; - // - // dataGridViewTextBoxColumn2 - // - this.dataGridViewTextBoxColumn2.DataPropertyName = "[theTime]"; - this.dataGridViewTextBoxColumn2.HeaderText = "[theTime]"; - this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; - // - // usageDataGridViewTextBoxColumn - // - this.usageDataGridViewTextBoxColumn.DataPropertyName = "[Usage]"; - this.usageDataGridViewTextBoxColumn.HeaderText = "[Usage]"; - this.usageDataGridViewTextBoxColumn.Name = "usageDataGridViewTextBoxColumn"; - // - // theTimeDataGridViewTextBoxColumn - // - this.theTimeDataGridViewTextBoxColumn.DataPropertyName = "[theTime]"; - this.theTimeDataGridViewTextBoxColumn.HeaderText = "[theTime]"; - this.theTimeDataGridViewTextBoxColumn.Name = "theTimeDataGridViewTextBoxColumn"; - // - // TestForm - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(493, 383); - this.Controls.Add(this.chart1); - this.Controls.Add(this.dataGridView1); - this.Name = "TestForm"; - this.Text = "TestForm"; - this.Load += new System.EventHandler(this.TestForm_Load); - ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.processUsageDataSet)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.processViewBindingSource)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.processViewBindingSource1)).EndInit(); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.BindingSource bindingSource1; - private ProcessUsageDataSet processUsageDataSet; - private System.Windows.Forms.DataGridView dataGridView1; - private System.Windows.Forms.BindingSource processViewBindingSource; - private CpuMonRcv.ProcessUsageDataSetTableAdapters.ProcessViewTableAdapter processViewTableAdapter; - private System.Windows.Forms.DataGridViewTextBoxColumn procIDDataGridViewTextBoxColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn processDataGridViewTextBoxColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn usageDataGridViewTextBoxColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn durationDataGridViewTextBoxColumn; - private System.Windows.Forms.DataGridViewTextBoxColumn theTimeDataGridViewTextBoxColumn; - private System.Windows.Forms.DataVisualization.Charting.Chart chart1; - private System.Windows.Forms.BindingSource processViewBindingSource1; - private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; - private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; - } -} \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/TestForm.cs b/cpumon/ProcessorUsage/CpuMonRcv/TestForm.cs deleted file mode 100644 index 90eb0d9..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/TestForm.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Windows.Forms; - -namespace CpuMonRcv -{ - public partial class TestForm : Form - { - public TestForm() - { - InitializeComponent(); - } - - private void TestForm_Load(object sender, EventArgs e) - { - // TODO: This line of code loads data into the 'processUsageDataSet.ProcessView' table. You can move, or remove it, as needed. - this.processViewTableAdapter.Fill(this.processUsageDataSet.ProcessView); - - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMonRcv/TestForm.resx b/cpumon/ProcessorUsage/CpuMonRcv/TestForm.resx deleted file mode 100644 index 57e2a34..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/TestForm.resx +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - 145, 17 - - - 304, 17 - - - 488, 17 - - - 17, 54 - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/app.config b/cpumon/ProcessorUsage/CpuMonRcv/app.config deleted file mode 100644 index d773b40..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/app.config +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/C2DPushGraph.dll b/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/C2DPushGraph.dll deleted file mode 100644 index 4498384..0000000 Binary files a/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/C2DPushGraph.dll and /dev/null differ diff --git a/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/CpuMonRcv.exe b/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/CpuMonRcv.exe deleted file mode 100644 index 9ae7134..0000000 Binary files a/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/CpuMonRcv.exe and /dev/null differ diff --git a/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/ProcessUsage.sqlite b/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/ProcessUsage.sqlite deleted file mode 100644 index 0c96de8..0000000 Binary files a/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/ProcessUsage.sqlite and /dev/null differ diff --git a/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/cpumon_before_after_external_power.xlsx b/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/cpumon_before_after_external_power.xlsx deleted file mode 100644 index b47f9c4..0000000 Binary files a/cpumon/ProcessorUsage/CpuMonRcv/bin/Debug/cpumon_before_after_external_power.xlsx and /dev/null differ diff --git a/cpumon/ProcessorUsage/CpuMonRcv/cpuMonRcvForm.Designer.cs b/cpumon/ProcessorUsage/CpuMonRcv/cpuMonRcvForm.Designer.cs deleted file mode 100644 index 7d89bcb..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/cpuMonRcvForm.Designer.cs +++ /dev/null @@ -1,224 +0,0 @@ -namespace CpuMonRcv -{ - partial class cpuMonRcvForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (recvr != null) - { - recvr.bRunThread = false; - recvr.Dispose(); - recvr = null; - } - dataAccess.Dispose(); - - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.txtLog = new System.Windows.Forms.TextBox(); - this.menuStrip1 = new System.Windows.Forms.MenuStrip(); - this.menuFile = new System.Windows.Forms.ToolStripMenuItem(); - this.menuExit = new System.Windows.Forms.ToolStripMenuItem(); - this.mnuView = new System.Windows.Forms.ToolStripMenuItem(); - this.mnuViewDetails = new System.Windows.Forms.ToolStripMenuItem(); - this.mnuTestForm = new System.Windows.Forms.ToolStripMenuItem(); - this.statusStrip1 = new System.Windows.Forms.StatusStrip(); - this.splitContainer1 = new System.Windows.Forms.SplitContainer(); - this.dataGridView1 = new System.Windows.Forms.DataGridView(); - this.c2DPushGraph1 = new CustomUIControls.Graphing.C2DPushGraph(); - this.mnuUsage = new System.Windows.Forms.ToolStripMenuItem(); - this.menuStrip1.SuspendLayout(); - this.splitContainer1.Panel1.SuspendLayout(); - this.splitContainer1.Panel2.SuspendLayout(); - this.splitContainer1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); - this.SuspendLayout(); - // - // txtLog - // - this.txtLog.AcceptsReturn = true; - this.txtLog.AcceptsTab = true; - this.txtLog.Location = new System.Drawing.Point(118, 68); - this.txtLog.Multiline = true; - this.txtLog.Name = "txtLog"; - this.txtLog.ReadOnly = true; - this.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.txtLog.Size = new System.Drawing.Size(357, 146); - this.txtLog.TabIndex = 0; - this.txtLog.WordWrap = false; - // - // menuStrip1 - // - this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.menuFile, - this.mnuView}); - this.menuStrip1.Location = new System.Drawing.Point(0, 0); - this.menuStrip1.Name = "menuStrip1"; - this.menuStrip1.Size = new System.Drawing.Size(487, 24); - this.menuStrip1.TabIndex = 2; - this.menuStrip1.Text = "menuStrip1"; - // - // menuFile - // - this.menuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.menuExit, - this.mnuUsage}); - this.menuFile.Name = "menuFile"; - this.menuFile.Size = new System.Drawing.Size(37, 20); - this.menuFile.Text = "File"; - // - // menuExit - // - this.menuExit.Name = "menuExit"; - this.menuExit.Size = new System.Drawing.Size(152, 22); - this.menuExit.Text = "Exit"; - this.menuExit.Click += new System.EventHandler(this.menuExit_Click); - // - // mnuView - // - this.mnuView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.mnuViewDetails, - this.mnuTestForm}); - this.mnuView.Name = "mnuView"; - this.mnuView.Size = new System.Drawing.Size(44, 20); - this.mnuView.Text = "View"; - // - // mnuViewDetails - // - this.mnuViewDetails.Name = "mnuViewDetails"; - this.mnuViewDetails.Size = new System.Drawing.Size(124, 22); - this.mnuViewDetails.Text = "Details"; - this.mnuViewDetails.Click += new System.EventHandler(this.mnuViewDetails_Click); - // - // mnuTestForm - // - this.mnuTestForm.Name = "mnuTestForm"; - this.mnuTestForm.Size = new System.Drawing.Size(124, 22); - this.mnuTestForm.Text = "TestForm"; - this.mnuTestForm.Click += new System.EventHandler(this.mnuTestForm_Click); - // - // statusStrip1 - // - this.statusStrip1.Location = new System.Drawing.Point(0, 412); - this.statusStrip1.Name = "statusStrip1"; - this.statusStrip1.Size = new System.Drawing.Size(487, 22); - this.statusStrip1.TabIndex = 5; - this.statusStrip1.Text = "statusStrip1"; - // - // splitContainer1 - // - this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; - this.splitContainer1.Location = new System.Drawing.Point(0, 24); - this.splitContainer1.Name = "splitContainer1"; - this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; - // - // splitContainer1.Panel1 - // - this.splitContainer1.Panel1.Controls.Add(this.dataGridView1); - // - // splitContainer1.Panel2 - // - this.splitContainer1.Panel2.Controls.Add(this.c2DPushGraph1); - this.splitContainer1.Size = new System.Drawing.Size(487, 388); - this.splitContainer1.SplitterDistance = 288; - this.splitContainer1.TabIndex = 6; - // - // dataGridView1 - // - this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; - this.dataGridView1.Location = new System.Drawing.Point(0, 0); - this.dataGridView1.Name = "dataGridView1"; - this.dataGridView1.Size = new System.Drawing.Size(487, 288); - this.dataGridView1.TabIndex = 2; - // - // c2DPushGraph1 - // - this.c2DPushGraph1.AutoAdjustPeek = false; - this.c2DPushGraph1.BackColor = System.Drawing.Color.Black; - this.c2DPushGraph1.Dock = System.Windows.Forms.DockStyle.Fill; - this.c2DPushGraph1.GridColor = System.Drawing.Color.Green; - this.c2DPushGraph1.GridSize = ((ushort)(15)); - this.c2DPushGraph1.HighQuality = true; - this.c2DPushGraph1.LineInterval = ((ushort)(5)); - this.c2DPushGraph1.Location = new System.Drawing.Point(0, 0); - this.c2DPushGraph1.MaxLabel = "Max"; - this.c2DPushGraph1.MaxPeekMagnitude = 100; - this.c2DPushGraph1.MinLabel = "Minimum"; - this.c2DPushGraph1.MinPeekMagnitude = 0; - this.c2DPushGraph1.Name = "c2DPushGraph1"; - this.c2DPushGraph1.ShowGrid = true; - this.c2DPushGraph1.ShowLabels = true; - this.c2DPushGraph1.Size = new System.Drawing.Size(487, 96); - this.c2DPushGraph1.TabIndex = 4; - this.c2DPushGraph1.Text = "c2DPushGraph1"; - this.c2DPushGraph1.TextColor = System.Drawing.Color.Yellow; - // - // mnuUsage - // - this.mnuUsage.Name = "mnuUsage"; - this.mnuUsage.Size = new System.Drawing.Size(152, 22); - this.mnuUsage.Text = "Export Usage"; - this.mnuUsage.Click += new System.EventHandler(this.mnuUsage_Click); - // - // cpuMonRcvForm - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(487, 434); - this.Controls.Add(this.splitContainer1); - this.Controls.Add(this.statusStrip1); - this.Controls.Add(this.txtLog); - this.Controls.Add(this.menuStrip1); - this.MainMenuStrip = this.menuStrip1; - this.Name = "cpuMonRcvForm"; - this.Text = "Waiting for connect ..."; - this.menuStrip1.ResumeLayout(false); - this.menuStrip1.PerformLayout(); - this.splitContainer1.Panel1.ResumeLayout(false); - this.splitContainer1.Panel2.ResumeLayout(false); - this.splitContainer1.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.TextBox txtLog; - private System.Windows.Forms.MenuStrip menuStrip1; - private System.Windows.Forms.ToolStripMenuItem menuFile; - private System.Windows.Forms.ToolStripMenuItem menuExit; - private System.Windows.Forms.ToolStripMenuItem mnuView; - private System.Windows.Forms.ToolStripMenuItem mnuViewDetails; - private System.Windows.Forms.StatusStrip statusStrip1; - private System.Windows.Forms.SplitContainer splitContainer1; - private System.Windows.Forms.DataGridView dataGridView1; - private CustomUIControls.Graphing.C2DPushGraph c2DPushGraph1; - private System.Windows.Forms.ToolStripMenuItem mnuTestForm; - private System.Windows.Forms.ToolStripMenuItem mnuUsage; - } -} - diff --git a/cpumon/ProcessorUsage/CpuMonRcv/cpuMonRcvForm.cs b/cpumon/ProcessorUsage/CpuMonRcv/cpuMonRcvForm.cs deleted file mode 100644 index 3d5e43b..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/cpuMonRcvForm.cs +++ /dev/null @@ -1,226 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using System.Process; - -namespace CpuMonRcv -{ - public partial class cpuMonRcvForm : Form - { - RecvBroadcst recvr; - DataAccess dataAccess; - Queue dataQueue; - bool _bAllowGUIupdate=true; - bool bAllowGUIupdate { - get { return _bAllowGUIupdate; } - set - { - _bAllowGUIupdate = value; - if (_bAllowGUIupdate) - recvr.StartReceive(); - else - recvr.StopReceive(); - } - } - - public cpuMonRcvForm() - { - InitializeComponent(); - //dataGridView1.AutoGenerateColumns = false; - //DataColumn dc = new DataColumn("ProcID"); - //dataGridView1.Columns.Add(dc); - //dataGridView1. - - //the plot graph - c2DPushGraph1.MaxLabel = "3000"; - c2DPushGraph1.MaxPeekMagnitude = 3000; - c2DPushGraph1.MinPeekMagnitude = 0; - c2DPushGraph1.MinLabel = "0"; - - dataQueue = new Queue(); - - dataAccess = new DataAccess(this.dataGridView1, ref dataQueue); - - recvr = new RecvBroadcst(); - recvr.onUpdate += new RecvBroadcst.delegateUpdate(recvr_onUpdate); - recvr.onEndOfTransfer += new RecvBroadcst.delegateEndOfTransfer(recvr_onEndOfTransfer); - } - - void recvr_onEndOfTransfer(object sender, EventArgs e) - { - System.Diagnostics.Debug.WriteLine(""); - if (!bAllowGUIupdate) - return; - //get data - float fUser = dataAccess.lastUserValue; - dataAccess.lastUserValue = 0f; - DateTime dtUser = dataAccess.lastUserMeasure; - if(fUser!=0) - updateGraph((int)fUser); - - //asign the chart control - //DataView dView = new DataView( - // dsData.Tables["Processes"], - // "ProcID=3197842474", - // "theTime", - // DataViewRowState.CurrentRows); - - //chart1.Series[0].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Time; - //string sFormat = chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss"; - //chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; - //chart1.Series[0].Points.DataBindXY(dView, "theTime", dView, "user"); - // chart1.DataSource = dsData.Tables["Processes"]; - } - delegate void updateGraphCallback(int val); - void updateGraph(int val) - { - if (this.c2DPushGraph1.InvokeRequired) - { - updateGraphCallback d = new updateGraphCallback(updateGraph); - this.Invoke(d, new object[] { val }); - } - else - { - c2DPushGraph1.AddLine(42, Color.Red); - c2DPushGraph1.Push(val, 42); - c2DPushGraph1.UpdateGraph(); - } - } - public void myDispose() - { - recvr.onUpdate -= recvr_onUpdate; - recvr.bRunThread = false; - recvr.Dispose(); - recvr = null; - - base.Dispose(); - } - //################### data display etc... - - - delegate void addDataCallback(ProcessStatistics.process_statistics procStats); - void addData(ProcessStatistics.process_statistics procStats) - { - if (this.dataGridView1.InvokeRequired) - { - addDataCallback d = new addDataCallback(addData); - this.Invoke(d, new object[] { procStats }); - } - else - { - dataGridView1.SuspendLayout(); - //enqueue data to be saved to sqlite - dataQueue.Enqueue(procStats); - - if (bAllowGUIupdate) - { - //dataAccess.addSqlData(procStats); - - //dtProcesses.Rows.Clear(); - - dataAccess.addData(procStats); - - - //release queue data - dataAccess.waitHandle.Set(); - - //object[] o = new object[7]{ procUsage.procStatistics. .procStatistics. [i].sApp, eventEntries[i].sArg, eventEntries[i].sEvent, - // eventEntries[i].sStartTime, eventEntries[i].sEndTime, eventEntries[i].sType, eventEntries[i].sHandle }; - } - dataGridView1.Refresh(); - dataGridView1.ResumeLayout(); - } - } - - void recvr_onUpdate(object sender, ProcessStatistics.process_statistics data) - { - //string s = data.processID.ToString() + ", " + - // data.sName + ", " + - // data.procUsage.user.ToString() + ", " + - // data.duration.ToString(); - ////addLog(s); - - //System.Diagnostics.Debug.WriteLine( data.dumpStatistics() ); - addData(data); - } - delegate void SetTextCallback(string text); - public void addLog(string text) - { - // InvokeRequired required compares the thread ID of the - // calling thread to the thread ID of the creating thread. - // If these threads are different, it returns true. - if (this.txtLog.InvokeRequired) - { - SetTextCallback d = new SetTextCallback(addLog); - this.Invoke(d, new object[] { text }); - } - else - { - if (txtLog.Text.Length > 4000) - txtLog.Text = ""; - txtLog.Text += text + "\r\n"; - txtLog.SelectionLength = 0; - txtLog.SelectionStart = txtLog.Text.Length - 1; - txtLog.ScrollToCaret(); - } - } - - private void mnuViewDetails_Click(object sender, EventArgs e) - { - DetailView dv = new DetailView(); - bAllowGUIupdate = false; - dv.ShowDialog(); - bAllowGUIupdate = true; - } - - private void menuExit_Click(object sender, EventArgs e) - { - myDispose(); - Application.Exit(); - } - - private void mnuTestForm_Click(object sender, EventArgs e) - { - TestForm tf = new TestForm(); - tf.Show(); - } - - private void mnuUsage_Click(object sender, EventArgs e) - { - frmSelectIP frmIP = new frmSelectIP(); - string sIP = ""; - if (frmIP.ShowDialog() == DialogResult.OK) - { - sIP = frmIP.sIP; - } - else - return; - - bAllowGUIupdate = false; - - SaveFileDialog sfd = new SaveFileDialog(); - sfd.CheckPathExists = true; - sfd.DefaultExt = "csv"; - sfd.AddExtension = true; - sfd.Filter = "CSV|*.csv|All|*.*"; - sfd.FilterIndex = 0; - sfd.InitialDirectory = Environment.CurrentDirectory; - sfd.OverwritePrompt = true; - sfd.RestoreDirectory = true; - sfd.ValidateNames = true; - - if (sfd.ShowDialog() == DialogResult.OK) - { - DataAccess da = new DataAccess(); - da.export2CSV2(sfd.FileName, sIP); - } - bAllowGUIupdate = true; - - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMonRcv/cpuMonRcvForm.resx b/cpumon/ProcessorUsage/CpuMonRcv/cpuMonRcvForm.resx deleted file mode 100644 index 9fa74ae..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/cpuMonRcvForm.resx +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - 126, 17 - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/frmSelectIP.Designer.cs b/cpumon/ProcessorUsage/CpuMonRcv/frmSelectIP.Designer.cs deleted file mode 100644 index b7180fb..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/frmSelectIP.Designer.cs +++ /dev/null @@ -1,113 +0,0 @@ -namespace CpuMonRcv -{ - partial class frmSelectIP - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.label1 = new System.Windows.Forms.Label(); - this.btnOK = new System.Windows.Forms.Button(); - this.btnCancel = new System.Windows.Forms.Button(); - this.label2 = new System.Windows.Forms.Label(); - this.lbIP = new System.Windows.Forms.ComboBox(); - this.SuspendLayout(); - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(11, 87); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(105, 13); - this.label1.TabIndex = 0; - this.label1.Text = "IP address selection:"; - // - // btnOK - // - this.btnOK.Location = new System.Drawing.Point(162, 139); - this.btnOK.Name = "btnOK"; - this.btnOK.Size = new System.Drawing.Size(109, 24); - this.btnOK.TabIndex = 2; - this.btnOK.Text = "OK"; - this.btnOK.UseVisualStyleBackColor = true; - this.btnOK.Click += new System.EventHandler(this.btnOK_Click); - // - // btnCancel - // - this.btnCancel.Location = new System.Drawing.Point(12, 139); - this.btnCancel.Name = "btnCancel"; - this.btnCancel.Size = new System.Drawing.Size(109, 24); - this.btnCancel.TabIndex = 2; - this.btnCancel.Text = "Cancel"; - this.btnCancel.UseVisualStyleBackColor = true; - this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); - // - // label2 - // - this.label2.AutoSize = true; - this.label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.label2.Location = new System.Drawing.Point(13, 11); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(270, 15); - this.label2.TabIndex = 3; - this.label2.Text = "Select the IP address of the device data to export/view"; - // - // lbIP - // - this.lbIP.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.lbIP.FormattingEnabled = true; - this.lbIP.Location = new System.Drawing.Point(142, 82); - this.lbIP.Name = "lbIP"; - this.lbIP.Size = new System.Drawing.Size(129, 21); - this.lbIP.TabIndex = 4; - // - // frmSelectIP - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(288, 181); - this.Controls.Add(this.lbIP); - this.Controls.Add(this.label2); - this.Controls.Add(this.btnCancel); - this.Controls.Add(this.btnOK); - this.Controls.Add(this.label1); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; - this.MinimizeBox = false; - this.Name = "frmSelectIP"; - this.Text = "frmSelectIP"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Button btnOK; - private System.Windows.Forms.Button btnCancel; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.ComboBox lbIP; - } -} \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/frmSelectIP.cs b/cpumon/ProcessorUsage/CpuMonRcv/frmSelectIP.cs deleted file mode 100644 index f70144f..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/frmSelectIP.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Windows.Forms; - -namespace CpuMonRcv -{ - public partial class frmSelectIP : Form - { - public string sIP = ""; - public frmSelectIP() - { - InitializeComponent(); - DataAccess da = new DataAccess(); - string[] listIP = da.getKnownIPs(); - lbIP.Items.Clear(); - foreach (string s in listIP) - { - lbIP.Items.Add(s); - } - lbIP.Items.Insert(0, "[ALL]"); - lbIP.SelectedIndex = 0; - } - - private void btnOK_Click(object sender, EventArgs e) - { - if (lbIP.SelectedIndex != -1) - sIP = lbIP.SelectedItem.ToString(); - if (sIP == "[ALL]") - sIP = ""; - DialogResult = DialogResult.OK; - } - - private void btnCancel_Click(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - } - } -} diff --git a/cpumon/ProcessorUsage/CpuMonRcv/frmSelectIP.resx b/cpumon/ProcessorUsage/CpuMonRcv/frmSelectIP.resx deleted file mode 100644 index ff31a6d..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/frmSelectIP.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/CpuMonRcv/sockrcv.cs b/cpumon/ProcessorUsage/CpuMonRcv/sockrcv.cs deleted file mode 100644 index d98d796..0000000 --- a/cpumon/ProcessorUsage/CpuMonRcv/sockrcv.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; -using System.Text; - -using System.Collections.Generic; - -using System.Process; - -using System.Threading; - -class RecvBroadcst:IDisposable -{ - public bool bRunThread = true; - - // Thread signal. - public static ManualResetEvent allDone = new ManualResetEvent(false); - - public RecvBroadcst() - { - //dataStream = new byte[1024]; - //serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - //myThread = new Thread(startReceive); - //myThread.Start(); - StartReceive(); - } - - void listener_onUpdate(object sender, ProcessStatistics.process_statistics data) - { - updateStatus(data); - } - public void Dispose(){ - if (receiveSocket != null) - receiveSocket.Close(); - bRunThread = false; - //if (myThread != null) - // myThread.Abort(); - } - - //####################################################################################### - - Socket receiveSocket; - byte[] recBuffer; - EndPoint bindEndPoint; - const int maxBuffer = 32768; - - public bool StopReceive() - { - bool bRet = false; - try - { - //receiveSocket.Disconnect(false); - receiveSocket.Close(); - receiveSocket = null; - bRet = true; - } - catch(SocketException ex) { - System.Diagnostics.Debug.WriteLine("StopReceive(): SocketException=" + ex.Message); - } - catch (Exception ex) { System.Diagnostics.Debug.WriteLine("StopReceive(): Exception=" + ex.Message); } - return bRet; - } - - public void StartReceive() - { - if (receiveSocket != null) - StopReceive(); - receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - bindEndPoint = new IPEndPoint(IPAddress.Any, 3001); - recBuffer = new byte[maxBuffer]; - receiveSocket.Bind(bindEndPoint); - receiveSocket.BeginReceiveFrom(recBuffer, 0, recBuffer.Length, SocketFlags.None, ref bindEndPoint, new AsyncCallback(MessageReceivedCallback), (object)this); - } - - void MessageReceivedCallback(IAsyncResult result) - { - EndPoint remoteEndPoint = new IPEndPoint(0, 0); - - //IPEndPoint LocalIPEndPoint = new IPEndPoint(IPAddress.Any, 3001); - //EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint; - //IPEndPoint remoteEP = (IPEndPoint)LocalEndPoint; - //System.Diagnostics.Debug.WriteLine("Remote IP: " + remoteEP.Address.ToString()); - - try - { - //all data should fit in one package! - int bytesRead = receiveSocket.EndReceiveFrom(result, ref remoteEndPoint); - //System.Diagnostics.Debug.WriteLine("Remote IP: " + ((IPEndPoint)(remoteEndPoint)).Address.ToString()); - - byte[] bData = new byte[bytesRead]; - Array.Copy(recBuffer, bData, bytesRead); - if (ByteHelper.isEndOfTransfer(bData)) - updateEndOfTransfer();// end of transfer - else - { - ProcessStatistics.process_statistics stats = new ProcessStatistics.process_statistics(bData); - stats.remoteIP = ((IPEndPoint)(remoteEndPoint)).Address.ToString(); - //System.Diagnostics.Debug.WriteLine( stats.dumpStatistics() ); - updateStatus(stats); - } - } - catch (SocketException e) - { - System.Diagnostics.Debug.WriteLine(String.Format("MessageReceivedCallback SocketException: {0} {1}", e.ErrorCode, e.Message)); - } - catch (Exception e) - { - System.Diagnostics.Debug.WriteLine(String.Format("MessageReceivedCallback Exception: {0}", e.Message)); - } - try - { - //ready to receive next packet - receiveSocket.BeginReceiveFrom(recBuffer, 0, recBuffer.Length, SocketFlags.None, ref bindEndPoint, new AsyncCallback(MessageReceivedCallback), (object)this); - } - catch (Exception) { } - } - - public delegate void delegateUpdate(object sender, ProcessStatistics.process_statistics data); - public event delegateUpdate onUpdate; - - private void updateStatus(ProcessStatistics.process_statistics data) - { - //System.Diagnostics.Debug.WriteLine("updateStatus: " + data.dumpStatistics()); - if (this.onUpdate != null) - this.onUpdate(this, data); - } - - public delegate void delegateEndOfTransfer(object sender, EventArgs e); - public event delegateEndOfTransfer onEndOfTransfer; - private void updateEndOfTransfer() - { - if (this.onEndOfTransfer != null) - this.onEndOfTransfer(this, new EventArgs()); - } - //####################################################################################### - -} \ No newline at end of file diff --git a/cpumon/ProcessorUsage/ProcessorUsage.sln b/cpumon/ProcessorUsage/ProcessorUsage.sln deleted file mode 100644 index 7f14f3f..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage.sln +++ /dev/null @@ -1,88 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ProcessorUsage", "ProcessorUsage\ProcessorUsage.vcproj", "{24707907-D62F-42AD-9DD2-E6956F14E136}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CpuMon2", "CpuMon2\CpuMon2.csproj", "{2E8B840E-BA26-4659-BD47-D88D307684D0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CpuMonRcv", "CpuMonRcv\CpuMonRcv.csproj", "{708980BB-37A8-40D9-89F4-3500053A5E0E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "C2DPushGraph", "PushGraph\C2DPushGraph.csproj", "{290BF7F1-91BB-4AE0-A89B-9320EC1B2619}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Debug|Windows Mobile 6 Professional SDK (ARMV4I) = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 6 Professional SDK (ARMV4I) = Release|Windows Mobile 6 Professional SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {24707907-D62F-42AD-9DD2-E6956F14E136}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Mixed Platforms.Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Mixed Platforms.Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {24707907-D62F-42AD-9DD2-E6956F14E136}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Release|Any CPU.Build.0 = Release|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Release|Any CPU.Deploy.0 = Release|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Release|Mixed Platforms.Deploy.0 = Release|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Any CPU - {2E8B840E-BA26-4659-BD47-D88D307684D0}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Release|Any CPU.Build.0 = Release|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Any CPU - {708980BB-37A8-40D9-89F4-3500053A5E0E}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Debug|Any CPU.Build.0 = Debug|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Release|Any CPU.ActiveCfg = Release|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Release|Any CPU.Build.0 = Release|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Any CPU - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/cpumon/ProcessorUsage/ProcessorUsage/ProcessInfo.hpp b/cpumon/ProcessorUsage/ProcessorUsage/ProcessInfo.hpp deleted file mode 100644 index 8048692..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/ProcessInfo.hpp +++ /dev/null @@ -1,137 +0,0 @@ -#include -#pragma comment( lib, "toolhelp.lib" ) - -/// required for SetProcPermissions(). It's part of platform builder. If you -/// don't have it, do some quick internet searching to get the function -/// prototype. -#include - -#define LODWORD(l) ((DWORD)((DWORDLONG)(l))) -#define HIDWORD(l) ((DWORD)(((DWORDLONG)(l)>>32)&0xFFFFFFFF)) -#define MAKEDWORDLONG(a,b) ((DWORDLONG)(((DWORD)(a))|(((DWORDLONG)((DWORD)(b)))<<32))) - -namespace ProcessInfo { - -/// Time a thread has spent working -struct thread_times { - /// Time a thread has spent in kernel space - FILETIME kernel; - /// Time a thread has spent in user space - FILETIME user; -}; - -/// Time each process has spent working -/// @param DWORD - TID -/// @param thread_times - Thread working times -typedef std::map< DWORD, thread_times > Threads; - -/// Time each Process has spent working -/// @param DWORD - PID -/// @param Threads - Process' thread working times -typedef std::map< DWORD, Threads > Processes; - -/// Associates process IDs to process names -/// @param DWORD - PID -/// @Param std::wstring - process name -typedef std::map< DWORD, std::wstring > ProcessNames; - -/// Get the combined time a thread has spent in user and kernel space in ms -static DWORD GetThreadTick( const FILETIME& user, const FILETIME& kernel ) -{ - __int64 tick = MAKEDWORDLONG( user.dwLowDateTime, user.dwHighDateTime ); - tick += MAKEDWORDLONG( kernel.dwLowDateTime, kernel.dwHighDateTime ); - tick /= 10000; - return static_cast< DWORD >( tick ); -} - -/// Convert a FILETIME to ticks (ms) -static DWORD GetThreadTick( const FILETIME& time ) -{ - __int64 tick = MAKEDWORDLONG( time.dwLowDateTime, time.dwHighDateTime ); - return static_cast< DWORD >( tick /= 10000 ); -} - -/// Get a list associating currently running process IDs with names -static ProcessNames GetProcessNameList() -{ - ProcessNames name_list; - - HANDLE snapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS | - TH32CS_SNAPNOHEAPS, - 0 ); - if( INVALID_HANDLE_VALUE != snapshot ) - { - PROCESSENTRY32 pe = { 0 }; - pe.dwSize = sizeof( PROCESSENTRY32 ); - - if( ::Process32First( snapshot, &pe ) ) - { - do - { - name_list[ pe.th32ProcessID ] = pe.szExeFile; - } while( ::Process32Next( snapshot, &pe ) ); - } - ::CloseToolhelp32Snapshot( snapshot ); - } - - return name_list; -} - -/// Temporarily grant phenomenal cosmic powers. This may not be necessary for -/// versions of windows mobile earlier than 6.5. -struct CosmicPowers -{ - CosmicPowers() - { - old_permissions_ = ::SetProcPermissions( 0xFFFFFFFF ); - } - - ~CosmicPowers() - { - ::SetProcPermissions( old_permissions_ ); - } - -private: - DWORD old_permissions_; -}; // struct CosmicPowers - -/// Gets the list of currently running processes -static Processes GetProcessList() -{ - Processes process_list; - CosmicPowers we_are_powerful; - - HANDLE snapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 ); - if( INVALID_HANDLE_VALUE != snapshot ) - { - THREADENTRY32 te = { 0 }; - te.dwSize = sizeof( THREADENTRY32 ); - - if( ::Thread32First( snapshot, &te ) ) - { - do - { - FILETIME creation = { 0 }, - exit = { 0 }, - kernel = { 0 }, - user = { 0 }; - - if( ::GetThreadTimes( ( HANDLE )te.th32ThreadID, - &creation, - &exit, - &kernel, - &user ) ) - { - thread_times t = { kernel, user }; - process_list[ te.th32OwnerProcessID ][ te.th32ThreadID ] = t; - } - } while( ::Thread32Next( snapshot, &te ) ); - } - - ::CloseToolhelp32Snapshot( snapshot ); - } - - return process_list; -} - -} // namespace ProcessInfo diff --git a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorMeter.cpp b/cpumon/ProcessorUsage/ProcessorUsage/ProcessorMeter.cpp deleted file mode 100644 index 05755b5..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorMeter.cpp +++ /dev/null @@ -1,129 +0,0 @@ -#include "StdAfx.h" -#include "ProcessorMeter.h" -#include "ProcessInfo.hpp" - -namespace PI = ProcessInfo; - -ProcessorMeter::ProcessorMeter( void ) - : stop_event_( ::CreateEvent( NULL, TRUE, FALSE, NULL ), ::CloseHandle ), - interval_( 1000 ) -{ -} - -ProcessorMeter::~ProcessorMeter( void ) -{ -} - -void ProcessorMeter::Start( OnUsageUpdate callback, unsigned int interval ) -{ - ::ResetEvent( stop_event_.get() ); - interval_ = interval; - callback_ = callback; - monitor_thread_.reset( new CThread( - boost::bind( &ProcessorMeter::MonitorThread, this ) ) ); -} - -void ProcessorMeter::Stop( DWORD timeout ) -{ - ::SetEvent( stop_event_.get() ); - if( !monitor_thread_->Join( timeout ) ) - { - // TODO: throw exception. The thread is frozen. - } -} - -unsigned int ProcessorMeter::Interval() const -{ - return interval_; -} - -/// This thread collects the statistical information on running processes. -/// 1. Get an initial list of the names and PIDs of all running processes. -/// 2. Get an initial list of how long each PID has spent in kernel and user time. -/// 3. After the interval has expired, get another list of each PID and its -/// kernel and user time. -/// 4. Calculate how much time was spent for each process in kernel and user -/// space during the wait interval. -/// 5. If any process PID isn't in our list of names, refresh our process name -/// list. It means we have a new process. -/// 6. Send the user callback that statistical information. -/// 7. Repeat at step 3. -void ProcessorMeter::MonitorThread() -{ - PI::ProcessNames names = PI::GetProcessNameList(); - PI::Processes old_list = PI::GetProcessList(); - - ProcessStatistics statistics; - - DWORD start = ::GetTickCount(); - - while( ::WaitForSingleObject( stop_event_.get(), interval_ ) == WAIT_TIMEOUT ) - { - PI::Processes new_list = PI::GetProcessList(); //thread list - DWORD duration = ::GetTickCount() - start; - - statistics.clear(); - - DWORD system_total = 0; - for( PI::Processes::const_iterator p2 = new_list.begin(); - p2 != new_list.end(); - ++p2 ) - { - PI::Processes::const_iterator p1 = old_list.find( p2->first ); - if( p1 != old_list.end() ) - { - DWORD user_total = 0; - DWORD kernel_total = 0; - - for( PI::Threads::const_iterator t2 = p2->second.begin(); - t2 != p2->second.end(); - ++t2 ) - { - PI::Threads::const_iterator t1 = p1->second.find( t2->first ); - if( t1 != p1->second.end() ) - { - kernel_total += PI::GetThreadTick( t2->second.kernel ) - - PI::GetThreadTick( t1->second.kernel ); - user_total += PI::GetThreadTick( t2->second.user ) - - PI::GetThreadTick( t1->second.user ); - } - } - - float user_percent = ( user_total ) / static_cast< float >( duration ) * 100.0f; - float kernel_percent = ( kernel_total ) / static_cast< float >( duration ) * 100.0f; - system_total += user_total + kernel_total; - - // locate the process name by its ID - PI::ProcessNames::const_iterator found_name = names.find( p2->first ); - - // if the process ID isn't in the name list, it must be new. - // refresh the name list and try again. - if( found_name == names.end() ) - { - names = PI::GetProcessNameList(); - - found_name = names.find( p2->first ); - - // still can't find the process ID? Just move on. - if( found_name == names.end() ) - continue; - } - - // update the statistics with this process' info - ProcessUsage usage = { - static_cast< unsigned int >( kernel_percent ), - static_cast< unsigned int >( user_percent ) }; - statistics[ found_name->second ] = usage; - } - } - - // calculate the total processor percent used - float percent_used = system_total / static_cast< float >( duration ) * 100.0f; - - // activate the user-defined callback - callback_( statistics, static_cast< unsigned int >( percent_used ) ); - - old_list = new_list; - start = ::GetTickCount(); - } -} diff --git a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorMeter.h b/cpumon/ProcessorUsage/ProcessorUsage/ProcessorMeter.h deleted file mode 100644 index a2907e9..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorMeter.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include - -#include "Thread.hpp" - -/// Process statistics -typedef struct process_usage { - /// % time the kernel spent in kernel space - unsigned int kernel; - /// % time the kernel spent in user space - unsigned int user; -} ProcessUsage; - -/// Statistics for all running processes -/// @param std::wstring - name of the process -/// @param ProcessUsage - process statistics -typedef std::map< std::wstring, ProcessUsage > ProcessStatistics; - -/// Active object that updates a callback with process usage statistics. -class ProcessorMeter : private boost::noncopyable -{ -public: - ProcessorMeter( void ); - - ~ProcessorMeter( void ); - - typedef boost::function< void( const ProcessStatistics& statistics, unsigned int total_used ) > OnUsageUpdate; - - /// start receiving updates on processor usage statistics - /// @param OnUsageUpdate - activated every interval ms. - /// @param interval - how often (in ms) to activate the callback. - void Start( OnUsageUpdate callback, unsigned int interval ); - - /// stop receiving updates. - void Stop( DWORD timeout = INFINITE ); - - /// Get the interval between updates (in ms). - unsigned int Interval() const; - -private: - - void MonitorThread(); - - /// callback updated when new statistics are updated - OnUsageUpdate callback_; - - /// interval at which the statistics are updated. (in ms) - unsigned int interval_; - - /// event activated when we should stop sending updates - boost::shared_ptr< void > stop_event_; - - /// handle to the statistics thread. - boost::shared_ptr< CThread > monitor_thread_; - -}; // class ProcessorMeter diff --git a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsage.cpp b/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsage.cpp deleted file mode 100644 index 7037e2d..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsage.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// ProcessorUsage.cpp : main source file for ProcessorUsage.exe -// - -#include "stdafx.h" - -#include "resourceppc.h" - -#include "ProcessorUsageDialog.h" - -CAppModule _Module; - -int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow) -{ - HRESULT hRes = CProcessorUsageDialog::ActivatePreviousInstance(hInstance, lpstrCmdLine); - - if(FAILED(hRes) || S_FALSE == hRes) - { - return hRes; - } - - hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED); - ATLASSERT(SUCCEEDED(hRes)); - - AtlInitCommonControls(ICC_DATE_CLASSES); - SHInitExtraControls(); - - hRes = _Module.Init(NULL, hInstance); - ATLASSERT(SUCCEEDED(hRes)); - - int nRet = CProcessorUsageDialog::AppRun(lpstrCmdLine, nCmdShow); - - _Module.Term(); - ::CoUninitialize(); - - return nRet; -} - diff --git a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsage.vcproj b/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsage.vcproj deleted file mode 100644 index 02efe83..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsage.vcproj +++ /dev/null @@ -1,504 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageDialog.cpp b/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageDialog.cpp deleted file mode 100644 index 8831687..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageDialog.cpp +++ /dev/null @@ -1,190 +0,0 @@ -// ProcessorUsageDialog.cpp : implementation of the CProcessorUsageDialog class -// -///////////////////////////////////////////////////////////////////////////// -/* -AdditionalIncludeDirectories=" -C:\WTL80\include; -C:\WINCE500\PUBLIC\COMMON\OAK\INC; -.\WTL\INCLUDE -C:\Program Files (x86)\boost\boost_1_51 -*/ - -#include "stdafx.h" -#include "resourceppc.h" - -#include "ProcessorUsageDialog.h" -#include -#include -#include -#include -#include - -BOOL CProcessorUsageDialog::PreTranslateMessage( MSG* pMsg ) -{ - return CWindow::IsDialogMessage( pMsg ); -} - -bool CProcessorUsageDialog::AppHibernate( bool bHibernate ) -{ - // Insert your code here or delete member if not relevant - return bHibernate; -} - -bool CProcessorUsageDialog::AppNewInstance( LPCTSTR /*lpstrCmdLine*/ ) -{ - // Insert your code here or delete member if not relevant - return false; -} - -void CProcessorUsageDialog::AppSave() -{ - CAppInfo info; - // Insert your code here or delete member if not relevant -} - -BOOL CProcessorUsageDialog::OnIdle() -{ - return FALSE; -} - -LRESULT CProcessorUsageDialog::OnInitDialog( UINT /*uMsg*/, - WPARAM /*wParam*/, - LPARAM /*lParam*/, - BOOL& bHandled ) -{ - HWND hMenuBar = CreateMenuBar( ATL_IDM_MENU_DONECANCEL ); - UIAddToolBar( hMenuBar ); - UIAddChildWindowContainer( m_hWnd ); - - // register object for message filtering and idle updates - CMessageLoop* pLoop = _Module.GetMessageLoop(); - ATLASSERT( pLoop != NULL ); - pLoop->AddMessageFilter( this ); - pLoop->AddIdleHandler( this ); - - DoDataExchange( FALSE ); - - process_list_ctrl_.AddColumn( L"Process", 0 ); - process_list_ctrl_.AddColumn( L"User", 1 ); - process_list_ctrl_.AddColumn( L"Kernel", 2 ); - process_list_ctrl_.SetExtendedListViewStyle( LVS_EX_DOUBLEBUFFER | - LVS_EX_FULLROWSELECT ); - - CRect list_rc; - process_list_ctrl_.GetClientRect( &list_rc ); - - process_list_ctrl_.SetColumnWidth( 0, - static_cast< int >( list_rc.Width() * 0.5 ) ); - process_list_ctrl_.SetColumnWidth( 1, - static_cast< int >( list_rc.Width() * 0.25 ) ); - process_list_ctrl_.SetColumnWidth( 2, LVSCW_AUTOSIZE_USEHEADER ); - - meter_.Start( boost::bind( - &CProcessorUsageDialog::OnUsageUpdate, this, _1, _2 ), 3000 ); - - return bHandled = FALSE; -} - -LRESULT CProcessorUsageDialog::OnDestroy( UINT /*uMsg*/, - WPARAM /*wParam*/, - LPARAM /*lParam*/, - BOOL& bHandled ) -{ - meter_.Stop(); - return bHandled = FALSE; -} - -void CProcessorUsageDialog::OnUsageUpdate( const ProcessStatistics& statistics, - unsigned int total_used ) -{ - // We copy the statistical data to marshal it to the UI thread. - // - Don't touch the UI from a different thread. - // - Don't us a SendMessage here as the app can freeze if meter_.Stop() is - // called while we're updating the UI. - PostMessage( UWM_USAGE_UPDATE, - ( WPARAM )new ProcessStatistics( statistics ), - ( LPARAM )total_used ); -} - -LRESULT CProcessorUsageDialog::OnUsageUpdate( UINT /*uMsg*/, - WPARAM wParam, - LPARAM lParam, - BOOL& /*bHandled*/ ) -{ - std::auto_ptr< ProcessStatistics > statistics( ( ProcessStatistics* )wParam ); - unsigned int total_used = static_cast< unsigned int >( lParam ); - - static short int token = 0; - - LVFINDINFO find = { 0 }; - find.flags = LVFI_STRING; - - process_list_ctrl_.SetRedraw( FALSE ); - - for( ProcessStatistics::const_iterator it = statistics->begin(); - it != statistics->end(); - ++it ) - { - // locate the process name in our list view. if it doesn't exist, add it. - find.psz = it->first.c_str(); - int found = process_list_ctrl_.FindItem( &find, -1 ); - if( found == -1 ) - { - found = process_list_ctrl_.InsertItem( 0, it->first.c_str() ); - } - - // format the user time and display it in the list view - std::wstringstream user_time; - user_time.precision( 1 ); - user_time << std::fixed << it->second.user << L"%"; - process_list_ctrl_.AddItem( found, 1, user_time.str().c_str() ); - - // format the kernel time and display it in the list view - std::wstringstream kernel_time; - kernel_time.precision( 1 ); - kernel_time << std::fixed << it->second.kernel << L"%"; - process_list_ctrl_.AddItem( found, 2, kernel_time.str().c_str() ); - - // mark the item with our token to show that it is still active - process_list_ctrl_.SetItemData( found, token + 1 ); - } - - // locate all the list view items that were not updated with the new token - // in this round and remove them - they represent processes that have exited. - find.flags = LVFI_PARAM; - find.psz = NULL; - find.lParam = token; - int found = -1; - while( ( found = process_list_ctrl_.FindItem( &find, found ) ) > -1 ) - { - process_list_ctrl_.DeleteItem( found ); - } - - // if the list view has grown longer than 1 page, scroll bars will appear. - // re-layout the columns to account for that. - if( process_list_ctrl_.GetItemCount() > process_list_ctrl_.GetCountPerPage() ) - { - CRect list_rc; - process_list_ctrl_.GetClientRect( &list_rc ); - - process_list_ctrl_.SetColumnWidth( 0, static_cast< int >( list_rc.Width() * 0.5 ) ); - process_list_ctrl_.SetColumnWidth( 1, static_cast< int >( list_rc.Width() * 0.25 ) ); - process_list_ctrl_.SetColumnWidth( 2, LVSCW_AUTOSIZE_USEHEADER ); - } - - process_list_ctrl_.SetRedraw( TRUE ); - - /// format & display the number of running processes - std::wstringstream count_str; - count_str << statistics->size(); - process_count_.SetWindowText( count_str.str().c_str() ); - - /// format & display the total cpu usage - std::wstringstream usage_str; - usage_str.precision( 1 ); - usage_str << total_used << L"%"; - cpu_usage_.SetWindowText( usage_str.str().c_str() ); - - ++token; - return 0; -} diff --git a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageDialog.h b/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageDialog.h deleted file mode 100644 index 63ab0cd..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageDialog.h +++ /dev/null @@ -1,85 +0,0 @@ -// ProcessorUsageDialog.h : interface of the CProcessorUsageDialog class -// -///////////////////////////////////////////////////////////////////////////// - -#pragma once -#include "ProcessorMeter.h" - -/// @brief Internal message sent from the CProcessorUsageDialog to itself when -/// it needs to update the UI. -/// @param WPARAM wParam - [ ProcessStatistics* ] - per-process cpu usage -/// statistics. -/// @param LPARAM lParam - [ float ] - total cpu usage % -static const UINT UWM_USAGE_UPDATE = - ::RegisterWindowMessage( _T( "UWM_USAGE_UPDATE" ) ); - -class CProcessorUsageDialog : - public CAppStdDialogImpl< CProcessorUsageDialog >, - public CUpdateUI< CProcessorUsageDialog >, - public CWinDataExchange< CProcessorUsageDialog >, - public CMessageFilter, - public CIdleHandler -{ -public: - DECLARE_APP_DLG_CLASS( NULL, IDR_MAINFRAME, L"Software\\WTL\\ProcessorUsage" ) - - enum { IDD = IDD_MAINDLG }; - - virtual BOOL PreTranslateMessage( MSG* pMsg ); - -// CAppWindow operations - bool AppHibernate( bool bHibernate ); - - bool AppNewInstance( LPCTSTR lpstrCmdLine ); - - void AppSave(); - - virtual BOOL OnIdle(); - - BEGIN_UPDATE_UI_MAP( CProcessorUsageDialog ) - END_UPDATE_UI_MAP() - - BEGIN_MSG_MAP( CProcessorUsageDialog ) - MESSAGE_HANDLER( WM_INITDIALOG, OnInitDialog ) - MESSAGE_HANDLER( WM_DESTROY, OnDestroy ) - MESSAGE_HANDLER( UWM_USAGE_UPDATE, OnUsageUpdate ) - CHAIN_MSG_MAP( CAppStdDialogImpl< CProcessorUsageDialog > ) - END_MSG_MAP() - - BEGIN_DDX_MAP( CProcessorUsageDialog ) - DDX_CONTROL_HANDLE( IDC_PROCESS_LIST, process_list_ctrl_ ) - DDX_CONTROL_HANDLE( IDC_PROCESS_COUNT_STATIC, process_count_ ); - DDX_CONTROL_HANDLE( IDC_CPU_USAGE_STATIC, cpu_usage_ ); - END_DDX_MAP() - -// Handler prototypes (uncomment arguments if needed): -// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) -// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) -// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) - - LRESULT OnInitDialog( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled ); - - LRESULT OnDestroy( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled ); - - LRESULT OnUsageUpdate( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled ); - -private: - - /// callback activated by ProcessorMeter alerting us of new statistics - void OnUsageUpdate( const ProcessStatistics& statistics, - unsigned int total_used ); - - /// active object watching CPU usage - ProcessorMeter meter_; - - /// list of processes and their CPU usage - CListViewCtrl process_list_ctrl_; - - /// number of processes in the list - CStatic process_count_; - - /// total cpu usage - CStatic cpu_usage_; - -}; // class CProcessorUsageDialog - diff --git a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageppc.rc b/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageppc.rc deleted file mode 100644 index 1c1b0f8..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageppc.rc +++ /dev/null @@ -1,233 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resourceppc.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "C:\WTL80\include\atlresce.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resourceppc.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""atlresce.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "#include ""ProcessorUsageppc.rc2""\r\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON "res\\ProcessorUsage.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_MAINDLG DIALOG 0, 0, 156, 166 -STYLE DS_SETFONT | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION -CAPTION "ProcessorUsage" -FONT 8, "MS Shell Dlg" -BEGIN - CONTROL "",IDC_PROCESS_LIST,"SysListView32",LVS_REPORT | LVS_ALIGNLEFT | WS_BORDER | WS_TABSTOP,7,7,142,139 - RTEXT "CPU Usage:",IDC_STATIC,79,150,41,8 - RTEXT "Processes:",IDC_STATIC,7,150,36,8 - LTEXT "0",IDC_PROCESS_COUNT_STATIC,45,150,33,8 - LTEXT "0%",IDC_CPU_USAGE_STATIC,123,150,26,8 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_MAINDLG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 149 - TOPMARGIN, 7 - BOTTOMMARGIN, 158 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Accelerator -// - -IDR_MAINFRAME ACCELERATORS -BEGIN - "Q", ID_APP_EXIT, VIRTKEY, CONTROL - "N", ID_FILE_NEW, VIRTKEY, CONTROL - "O", ID_FILE_OPEN, VIRTKEY, CONTROL - "S", ID_FILE_SAVE, VIRTKEY, CONTROL - "Z", ID_EDIT_UNDO, VIRTKEY, CONTROL - "X", ID_EDIT_CUT, VIRTKEY, CONTROL - "C", ID_EDIT_COPY, VIRTKEY, CONTROL - "V", ID_EDIT_PASTE, VIRTKEY, CONTROL -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "FileDescription", "ProcessorUsage Module" - VALUE "FileVersion", "1, 0, 0, 1" - VALUE "InternalName", "ProcessorUsage" - VALUE "LegalCopyright", "Copyright 2011" - VALUE "OriginalFilename", "ProcessorUsage.exe" - VALUE "ProductName", "ProcessorUsage Module" - VALUE "ProductVersion", "1, 0, 0, 1" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE -BEGIN - IDR_MAINFRAME "ProcessorUsage" -END - -STRINGTABLE -BEGIN - ID_FILE_NEW "New" - ID_FILE_OPEN "Open" - ID_FILE_CLOSE "Close" - ID_FILE_SAVE "Save" -END - -STRINGTABLE -BEGIN - ID_APP_ABOUT "Program information" - ID_APP_EXIT "Quit" -END - -STRINGTABLE -BEGIN - ID_NEXT_PANE "Next Pane" - ID_PREV_PANE "Previous Pane" -END - -STRINGTABLE -BEGIN - ID_WINDOW_SPLIT "Split to panes" -END - -STRINGTABLE -BEGIN - ID_EDIT_CLEAR "Erase" - ID_EDIT_CLEAR_ALL "Erase All" - ID_EDIT_COPY "Copy" - ID_EDIT_CUT "Cut" - ID_EDIT_FIND "Find" - ID_EDIT_PASTE "Paste" - ID_EDIT_REPEAT "Repeat" - ID_EDIT_REPLACE "Replace" - ID_EDIT_SELECT_ALL "Select All" - ID_EDIT_UNDO "Undo" - ID_EDIT_REDO "Redo" -END - -STRINGTABLE -BEGIN - ATL_IDS_IDLEMESSAGE "Ready" -END - -STRINGTABLE -BEGIN - ID_MENU_OK "Done" - ID_MENU_CANCEL "Cancel" - ID_MENU "Menu" - ID_ACTION "Action" -END - -STRINGTABLE -BEGIN - ID_VIEW_FULLSCREEN "Full screen" -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// -#include "ProcessorUsageppc.rc2" - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageppc.rc2 b/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageppc.rc2 deleted file mode 100644 index a80e251..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/ProcessorUsageppc.rc2 +++ /dev/null @@ -1,40 +0,0 @@ -///////////////////////////////////////////////////////////////////////////// -// -// Menubars for standard dialogs declared in atlresce.h -// - -ATL_IDM_MENU_DONE RCDATA -BEGIN - ATL_IDM_MENU_DONE, 1, - I_IMAGENONE, ID_MENU_OK, TBSTATE_ENABLED, TBSTYLE_AUTOSIZE, - ID_MENU_OK, 0, NOMENU, -END - - -ATL_IDM_MENU_CANCEL RCDATA -BEGIN - ATL_IDM_MENU_CANCEL, 1, - I_IMAGENONE, ID_MENU_CANCEL, TBSTATE_ENABLED, TBSTYLE_AUTOSIZE, - ID_MENU_CANCEL, 0, NOMENU, -END - - -ATL_IDM_MENU_DONECANCEL RCDATA -BEGIN - ATL_IDM_MENU_DONECANCEL, 2, - I_IMAGENONE, ID_MENU_OK, TBSTATE_ENABLED, TBSTYLE_AUTOSIZE, - ID_MENU_OK, 0, NOMENU, - I_IMAGENONE, ID_MENU_CANCEL, TBSTATE_ENABLED, TBSTYLE_AUTOSIZE, - ID_MENU_CANCEL, 0, NOMENU, -END - -ATL_IDW_MENU_BAR SHMENUBAR DISCARDABLE -BEGIN - IDR_MAINFRAME, - 2, - I_IMAGENONE, ID_ACTION, TBSTATE_ENABLED, TBSTYLE_AUTOSIZE, ID_ACTION, 0, NOMENU, - I_IMAGENONE, ID_MENU, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE, ID_MENU, 0, 0, -END - - - diff --git a/cpumon/ProcessorUsage/ProcessorUsage/Thread.hpp b/cpumon/ProcessorUsage/ProcessorUsage/Thread.hpp deleted file mode 100644 index 547aaaf..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/Thread.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/// example usage: -/// void thread_function( int, bool, char ); -/// CThread my_thread( boost::bind( thread_function, 1, true, 'a' ) ); -/// // do interesting things... -/// my_thread.Join(); -/// -#pragma once -#include -#include - -/// A thread wrapper that provides exception-safe management of the thread -/// handle and type-safe thread functions. -class CThread -{ -public: - explicit CThread( HANDLE handle ) - : handle_( handle, &::CloseHandle ) - { - }; - - template< typename ThreadFunc > - explicit CThread( const ThreadFunc& f ) - : handle_( DoCreateThread( f ), &::CloseHandle ) - { - }; - - /// Block until the thread completes - BOOL Join( DWORD max_wait_time = INFINITE ) - { - _ASSERT( NULL != handle_ ); - return ( WAIT_OBJECT_0 == ::WaitForSingleObject( handle_.get(), max_wait_time ) ); - }; - -private: - - /// thread handle - boost::shared_ptr< void > handle_; - - friend DWORD WINAPI thread_function( LPVOID arg ); - - /// The actual thread creation function. - /// - /// Yes, this adds slightly to the cost of creating a thread, but makes the - /// actual thread-function typesafe from the user's point of view. If - /// performance is an issue, use the other constructor. - template< typename ThreadFunc > - static HANDLE DoCreateThread( const ThreadFunc& f ) - { - DWORD thread_id = 0; - std::auto_ptr< func_base > arg( new func< ThreadFunc >( f ) ); - HANDLE thread = ::CreateThread( NULL, - 0, - thread_function, - arg.get(), - 0, - &thread_id ); - if( NULL != thread ) - arg.release(); - return thread; - }; - - class func_base - { - public: - virtual ~func_base() {}; - virtual void run() = 0; - }; // class func_base - - template< typename Function > - class func : public func_base - { - public: - func( Function f ) : f_( f ) {}; - virtual void run() { f_(); }; - private: - Function f_; - }; // class func - -}; // class CThread - -/// @brief a wrapper for the actual user thread function -inline DWORD WINAPI thread_function( LPVOID arg ) -{ - std::auto_ptr< CThread::func_base > func( - static_cast< CThread::func_base* >( arg ) ); - func->run(); - return 0; -} diff --git a/cpumon/ProcessorUsage/ProcessorUsage/res/ProcessorUsage.ico b/cpumon/ProcessorUsage/ProcessorUsage/res/ProcessorUsage.ico deleted file mode 100644 index 3bf85d3..0000000 Binary files a/cpumon/ProcessorUsage/ProcessorUsage/res/ProcessorUsage.ico and /dev/null differ diff --git a/cpumon/ProcessorUsage/ProcessorUsage/resourceppc.h b/cpumon/ProcessorUsage/ProcessorUsage/resourceppc.h deleted file mode 100644 index 6a5ed12..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/resourceppc.h +++ /dev/null @@ -1,20 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by ProcessorUsageppc.rc -// -#define IDR_MAINFRAME 128 -#define IDD_MAINDLG 129 -#define IDC_PROCESS_LIST 1000 -#define IDC_PROCESS_COUNT_STATIC 1001 -#define IDC_CPU_USAGE_STATIC 1002 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 201 -#define _APS_NEXT_COMMAND_VALUE 32772 -#define _APS_NEXT_CONTROL_VALUE 1003 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/cpumon/ProcessorUsage/ProcessorUsage/stdafx.cpp b/cpumon/ProcessorUsage/ProcessorUsage/stdafx.cpp deleted file mode 100644 index b9f55bc..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/stdafx.cpp +++ /dev/null @@ -1,5 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// ProcessorUsage.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" diff --git a/cpumon/ProcessorUsage/ProcessorUsage/stdafx.h b/cpumon/ProcessorUsage/ProcessorUsage/stdafx.h deleted file mode 100644 index 965cb33..0000000 --- a/cpumon/ProcessorUsage/ProcessorUsage/stdafx.h +++ /dev/null @@ -1,38 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma warning( push ) -// disable all of the "warning C4201: nonstandard extension used : -// nameless struct/union" warnings from old windows headers. -#pragma warning( disable : 4201 ) - -// Change this value to use different versions -//#define WINVER 0x0500 -#define _WIN32_WCE_AYGSHELL 1 -#define _SECURE_ATL 1 -#define _WTL_CE_NO_ZOOMSCROLL - -#define NOMINMAX -#include -using std::max; -using std::min; - -#include -#include - -extern CAppModule _Module; - -#include -#include -#include -#include -#include -#include -#include - -#include -#pragma comment(lib, "aygshell.lib") - -#pragma warning( pop ) diff --git a/cpumon/ProcessorUsage/PushGraph/2DPushGraph.cs b/cpumon/ProcessorUsage/PushGraph/2DPushGraph.cs deleted file mode 100644 index d6cdc68..0000000 --- a/cpumon/ProcessorUsage/PushGraph/2DPushGraph.cs +++ /dev/null @@ -1,1116 +0,0 @@ -// =================================================================== -// C2DPushGraph Control -// ------------------------------------------------------------------- -// Author: Stuart D. Konen -// E-mail: skonen _|a.t|_ gmail.com -// Date of Release: December 2nd, 2006 -// =================================================================== - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Data; -using System.Windows.Forms; -using System.Text; - - -namespace CustomUIControls -{ - namespace Graphing - { - public class C2DPushGraph : Control - { - // =================================================================== - // PUBLIC LINEHANDLE CLASS - // (Provides public method access to line data members) - // =================================================================== - - public class LineHandle - { - private Line m_Line = null; - private C2DPushGraph m_Owner = null; - - // =================================================================== - - public LineHandle(ref Object line, C2DPushGraph owner) - { - /* A small hack to get around the compiler error CS0051: */ - if (string.Compare(line.GetType().Name, "Line") != 0) - { - throw new System.ArithmeticException( - "LineHandle: First Parameter must be " + - "type of 'Line' cast to base 'Object'"); - } - - m_Line = (Line)line; - m_Owner = owner; - } - - // =================================================================== - - /// - /// Clears any currently displayed magnitudes. - /// - - public void Clear() - { - m_Line.m_MagnitudeList.Clear(); - m_Owner.UpdateGraph(); - } - - // =================================================================== - - /// - /// Sets or gets the line's current color. - /// - - public Color Color - { - set - { - if (m_Line.m_Color != value) - { - m_Line.m_Color = value; - m_Owner.Refresh(); - } - } - get { return m_Line.m_Color; } - - } - - // =================================================================== - - /// - /// Sets or gets the line's thickness in pixels. NOTE: It is advisable - /// to set HighQuality to false if using a thickness greater than - /// 2 pixels as the antialiasing creates imperfections. - /// - - public uint Thickness - { - set - { - if (m_Line.m_Thickness != value) - { - m_Line.m_Thickness = value; - m_Owner.Refresh(); - } - } - get { return m_Line.m_Thickness; } - } - - // =================================================================== - - /// - /// Gets or sets a value indicating whether the line is visible. - /// - - public bool Visible - { - set - { - if (m_Line.m_bVisible != value) - { - m_Line.m_bVisible = value; - m_Owner.Refresh(); - } - } - get { return m_Line.m_bVisible; } - } - - // =================================================================== - - /// - /// Gets or sets a value indicating whether this line's magnitudes are - /// displayed in a bar graph style. - /// - - public bool ShowAsBar - { - set - { - if (m_Line.m_bShowAsBar != value) - { - m_Line.m_bShowAsBar = value; - m_Owner.Refresh(); - } - } - get { return m_Line.m_bShowAsBar; } - } - } - - // =================================================================== - // PRIVATE LINE CLASS (Contains Line Data Members) - // =================================================================== - - private class Line - { - public List m_MagnitudeList = new List(); - public Color m_Color = Color.Green; - public string m_NameID = ""; - public int m_NumID = -1; - public uint m_Thickness = 1; - public bool m_bShowAsBar = false; - public bool m_bVisible = true; - - // =================================================================== - - public Line(string name) - { - m_NameID = name; - } - - // =================================================================== - - public Line(int num) - { - m_NumID = num; - } - } - - - // =================================================================== - // MAIN CONTROL CLASS - // =================================================================== - - private Color m_TextColor = Color.Yellow; - private Color m_GridColor = Color.Green; - private string m_MaxLabel = "Max"; - private string m_MinLabel = "Minimum"; - private bool m_bHighQuality = true; - private bool m_bAutoScale = false; - private bool m_bMinLabelSet = false; - private bool m_bMaxLabelSet = false; - private bool m_bShowMinMax = true; - private bool m_bShowGrid = true; - private int m_MoveOffset = 0; - private int m_MaxCoords = -1; - private int m_LineInterval = 5; - private int m_MaxPeek = 100; - private int m_MinPeek = 0; - private int m_GridSize = 15; - private int m_OffsetX = 0; - - private List m_Lines = new List(); - private System.ComponentModel.IContainer components = null; - - // =================================================================== - - public C2DPushGraph() - { - InitializeComponent(); - InitializeStyles(); - } - - // =================================================================== - - public C2DPushGraph(Form Parent) - { - Parent.Controls.Add(this); - - InitializeComponent(); - InitializeStyles(); - } - - // =================================================================== - - public C2DPushGraph(Form parent, Rectangle rectPos) - { - parent.Controls.Add(this); - - Location = rectPos.Location; - Height = rectPos.Height; - Width = rectPos.Width; - - InitializeComponent(); - InitializeStyles(); - } - - // =================================================================== - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Component Designer generated code - - // =================================================================== - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - } - - #endregion - - // =================================================================== - - private void InitializeStyles() - { - BackColor = Color.Black; - - /* Enable double buffering and similiar techniques to - * eliminate flicker */ - - SetStyle(ControlStyles.OptimizedDoubleBuffer, true); - SetStyle(ControlStyles.UserPaint, true); - SetStyle(ControlStyles.AllPaintingInWmPaint, true); - DoubleBuffered = true; - - SetStyle(ControlStyles.ResizeRedraw, true); - } - - // =================================================================== - - /// - /// Gets or sets the color of any text displayed in the graph (labels). - /// - - public Color TextColor - { - set - { - if (m_TextColor != value) - { - m_TextColor = value; - Refresh(); - } - } - get { return m_TextColor; } - } - - // =================================================================== - - /// - /// Gets or sets the graph's grid color. - /// - - public Color GridColor - { - set - { - if (m_GridColor != value) - { - m_GridColor = value; - Refresh(); - } - } - get { return m_GridColor; } - } - - // =================================================================== - - /// - /// Gets or sets the number of pixels between each displayed magnitude. - /// - - public ushort LineInterval - { - set - { - if ((ushort)m_LineInterval != value) - { - m_LineInterval = (int)value; - m_MaxCoords = -1; // Recalculate - Refresh(); - } - } - get { return (ushort)m_LineInterval; } - } - - // =================================================================== - - /// - /// Gets or sets the string to display as the graph's 'maximum label'. - /// - - public string MaxLabel - { - set - { - m_bMaxLabelSet = true; - - if (string.Compare(m_MaxLabel, value) != 0) - { - m_MaxLabel = value; - m_MaxCoords = -1; // Recalculate - Refresh(); - } - } - get { return m_MaxLabel; } - } - - // =================================================================== - - /// - /// Gets or sets the string to display as the graph's 'minimum label'. - /// - - public string MinLabel - { - set - { - m_bMinLabelSet = true; - - if (string.Compare(m_MinLabel, value) != 0) - { - m_MinLabel = value; - m_MaxCoords = -1; // Recalculate - Refresh(); - } - } - get { return m_MinLabel; } - } - - // =================================================================== - - /// - /// Gets or sets the width/height (in pixels) of each square in - /// the graph's grid. - /// - - public ushort GridSize - { - set - { - if (m_GridSize != (int)value) - { - m_GridSize = (int)value; - Refresh(); - - } - } - get { return (ushort)m_GridSize; } - } - - // =================================================================== - - /// - /// Gets or sets the maximum peek magnitude of the graph, which should be - /// the largest value you could potentially push to the graph. NOTE: If you - /// have set AutoScale to true, this value will automatically adjust to - /// the highest magnitude pushed to the graph. - /// - - public int MaxPeekMagnitude - { - set - { - m_MaxPeek = value; - RefreshLabels(); - } - get { return m_MaxPeek; } - } - - // =================================================================== - - /// - /// Gets or sets the minimum magnitude of the graph, which should be - /// the smallest value you could potentially push to the graph. - /// NOTE: If you have set AutoScale to true, this value will - /// automatically adjust to the lowest magnitude pushed to the graph. - /// - - public int MinPeekMagnitude - { - set - { - m_MinPeek = value; - RefreshLabels(); - } - get { return m_MinPeek; } - } - - - // =================================================================== - - /// - /// Gets or sets the value indicating whether the graph automatically - /// adjusts MinPeekMagnitude and MaxPeekMagnitude to the lowest and highest - /// values pushed to the graph. - /// - - public bool AutoAdjustPeek - { - set - { - if (m_bAutoScale != value) - { - m_bAutoScale = value; - Refresh(); - } - } - get { return m_bAutoScale; } - } - - // =================================================================== - - /// - /// Gets or sets the value indicating whether the graph is rendered in - /// 'high quality' mode (with antialiasing). It is suggested that this property - /// be set to false if you intend to display your graph using bar graph - /// styles, line thickness greater than two, or if maximum performance - /// is absolutely crucial. - /// - - public bool HighQuality - { - set - { - if (value != m_bHighQuality) - { - m_bHighQuality = value; - Refresh(); // Force redraw - } - } - get { return m_bHighQuality; } - } - - // =================================================================== - - /// - /// Gets or sets the value indicating whether the mimimum and maximum labels - /// are displayed. - /// - - public bool ShowLabels - { - set - { - if (m_bShowMinMax != value) - { - m_bShowMinMax = value; - - /* We're going to need to recalculate our maximum - * coordinates since our graphable width changed */ - m_MaxCoords = -1; - - Refresh(); - } - } - get { return m_bShowMinMax; } - } - - // =================================================================== - - /// - /// Gets or sets the value indicating whether the graph's grid is - /// displayed. - /// - - public bool ShowGrid - { - set - { - if (m_bShowGrid != value) - { - m_bShowGrid = value; - Refresh(); - } - } - get { return m_bShowGrid; } - } - - // =================================================================== - - protected override void OnSizeChanged(EventArgs e) - { - /* We're going to need to recalculate our maximum - * coordinates since our graphable width changed */ - m_MaxCoords = -1; - - Refresh(); - - base.OnSizeChanged(e); - } - - // =================================================================== - - protected override void OnPaint(PaintEventArgs e) - { - Graphics g = e.Graphics;// CreateGraphics(); - - SmoothingMode prevSmoothingMode = g.SmoothingMode; - g.SmoothingMode = (m_bHighQuality ? SmoothingMode.HighQuality - : SmoothingMode.Default); - - /* Reset our offset so we don't continually shift to the right: */ - - m_OffsetX = 0; - - if (m_bShowMinMax) - { - DrawLabels(ref g); - } - - if (m_bShowGrid) - { - DrawGrid(ref g); - } - - if (m_OffsetX != 0) - { - /* This is to avoid crossing the left grid boundary when - * working with lines with great thickness */ - - g.Clip = new Region( - new Rectangle(m_OffsetX, 0, Width - m_OffsetX, Height)); - } - - DrawLines(ref g); - g.ResetClip(); - - g.SmoothingMode = prevSmoothingMode; - } - - // =================================================================== - - /// - /// This function is to be called after you have pushed new magnitude(s) - /// to the graph's lines and want the control re-rendered to take the - /// changes into account. - /// - - public void UpdateGraph() - { - int greatestMCount = 0; - foreach (Line line in m_Lines) - { - if (greatestMCount < line.m_MagnitudeList.Count) - { - greatestMCount = line.m_MagnitudeList.Count; - } - } - - if (greatestMCount >= m_MaxCoords) - { - m_MoveOffset = - (m_MoveOffset - (((greatestMCount - m_MaxCoords) + 1) * m_LineInterval)) - % m_GridSize; - } - - CullAndEqualizeMagnitudeCounts(); - this.Refresh(); - } - - // =================================================================== - - protected void CalculateMaxPushPoints() - { - /* Calculate the maximum of push points (magnitudes) that can be - * drawn for the graphable display width: */ - - m_MaxCoords = ((Width - m_OffsetX) / m_LineInterval) + 2 - + (((Width - m_OffsetX) % m_LineInterval) != 0 ? 1 : 0); - - if (m_MaxCoords <= 0) - { - m_MaxCoords = 1; - } - } - - // =================================================================== - - protected void DrawLabels(ref Graphics g) - { - SizeF maxSize = g.MeasureString(m_MaxLabel, Font); - SizeF minSize = g.MeasureString(m_MinLabel, Font); - - int textWidth = (int)((maxSize.Width > minSize.Width) - ? maxSize.Width - : minSize.Width) + 6; - - SolidBrush textBrush = new SolidBrush(m_TextColor); - - - /* Draw the labels (max: Top) (min: Bottom) */ - - g.DrawString(m_MaxLabel, Font, textBrush, - textWidth / 2 - (maxSize.Width / 2), - 2); - - g.DrawString(m_MinLabel, Font, textBrush, - textWidth / 2 - (minSize.Width / 2), - Height - minSize.Height - 2); - - textBrush.Dispose(); - - - /* Draw the bordering line */ - - Pen borderPen = new Pen(m_GridColor, 1); - g.DrawLine(borderPen, textWidth + 6, 0, textWidth + 6, Height); - - borderPen.Dispose(); - - /* Update the offset so we don't draw the graph over the labels */ - m_OffsetX = textWidth + 6; - } - - // =================================================================== - - protected void RefreshLabels() - { - /* Within this function we ensure our labels are up to date - * if the user isn't using custom labels. It is called whenever - * the graph's range changes. */ - - if (!m_bMinLabelSet) - { - /* Use the minimum magnitude as the label since the - * user has not yet assigned a custom label: */ - - m_MinLabel = m_MinPeek.ToString(); - } - - if (!m_bMaxLabelSet) - { - /* Use the maximum magnitude as the label since the - * user has not yet assigned a custom label: */ - - m_MaxLabel = m_MaxPeek.ToString(); - } - } - - // =================================================================== - - protected void DrawGrid(ref Graphics g) - { - Pen gridPen = new Pen(m_GridColor, 1); - for (int n = Height - 1; n >= 0; n -= m_GridSize) - { - g.DrawLine(gridPen, m_OffsetX, n, Width, n); - } - - for (int n = m_OffsetX + m_MoveOffset; n < Width; n += m_GridSize) - { - if (n < m_OffsetX) - { - continue; - } - - g.DrawLine(gridPen, n, 0, n, Height); - } - - gridPen.Dispose(); - } - - // =================================================================== - - private void CullAndEqualizeMagnitudeCounts() - { - if (m_MaxCoords == -1) - { - /* Maximum push points not yet calculated */ - CalculateMaxPushPoints(); - } - - int greatestMCount = 0; - foreach (Line line in m_Lines) - { - if (greatestMCount < line.m_MagnitudeList.Count) - { - greatestMCount = line.m_MagnitudeList.Count; - } - } - - if (greatestMCount == 0) - { - return; // No magnitudes - } - - foreach (Line line in m_Lines) - { - /* If the line has less push points than the line with the greatest - number of push points, new push points are appended with - the same magnitude as the previous push point. If no push points - exist for the line, one is added with the least magnitude possible. */ - - if (line.m_MagnitudeList.Count == 0) - { - line.m_MagnitudeList.Add(m_MinPeek); - } - - while (line.m_MagnitudeList.Count < greatestMCount) - { - line.m_MagnitudeList.Add( - line.m_MagnitudeList[line.m_MagnitudeList.Count - 1]); - } - - int cullsRequired = (line.m_MagnitudeList.Count - m_MaxCoords) + 1; - if (cullsRequired > 0) - { - line.m_MagnitudeList.RemoveRange(0, cullsRequired); - } - } - } - - // =================================================================== - - protected void DrawLines(ref Graphics g) - { - foreach (Line line in m_Lines) - { - if (line.m_MagnitudeList.Count == 0) - { - //TODO: This may not be nescessary, so look into it. - /* No push points to draw */ - return; - } - - if (!line.m_bVisible) - { - continue; - } - - /* Now prepare to draw the line or bar */ - - Pen linePen = new Pen(line.m_Color, line.m_Thickness); - - Point lastPoint = new Point(); - lastPoint.X = m_OffsetX; - lastPoint.Y = Height - ((line.m_MagnitudeList[0] * - Height) / (m_MaxPeek - m_MinPeek)); - - for (int n = 0; n < line.m_MagnitudeList.Count; ++n) - { - if (line.m_bShowAsBar) - { - /* The line is set to be shown as a bar graph, so - first we get the bars rectangle, then draw the bar */ - - Rectangle barRect = new Rectangle(); - - // Weird hack because BarRect.Location.* causes error - Point p = barRect.Location; - p.X = m_OffsetX + (n * m_LineInterval) + 1; - p.Y = Height - ((line.m_MagnitudeList[n] * Height) / - (m_MaxPeek - m_MinPeek)); - barRect.Location = p; - - barRect.Width = m_LineInterval - 1; - barRect.Height = Height; - - DrawBar(barRect, line, ref g); - } - else - { - /* Draw a line */ - - int newX = m_OffsetX + (n * m_LineInterval); - int newY = Height - ((line.m_MagnitudeList[n] * Height) / - (m_MaxPeek - m_MinPeek)); - - g.DrawLine(linePen, lastPoint.X, lastPoint.Y, newX, newY); - - lastPoint.X = newX; - lastPoint.Y = newY; - } - } - - linePen.Dispose(); - } - } - - // =================================================================== - - private void DrawBar(Rectangle rect, Line line, ref Graphics g) - { - SolidBrush barBrush = new SolidBrush(line.m_Color); - g.FillRectangle(barBrush, rect); - barBrush.Dispose(); - } - - // =================================================================== - - /// - /// Returns a new line handle (LineHandle object) to the line - /// with the matching numerical ID. Returns NULL if a line with a - /// matching ID is not found. - /// - /// - /// The numerical ID of the line you wish to get a handle to. - /// - - public LineHandle GetLineHandle(int numID) - { - Object line = (Object)GetLine(numID); - return (line != null ? new LineHandle(ref line, this) : null); - } - - // =================================================================== - - /// - /// Returns a new line handle (LineHandle object) to the line - /// with the matching name (case insensitive). Returns NULL if a - /// line with a matching name is not found. - /// - /// - /// The case insensitive name of the line you wish to get a handle to. - /// - - public LineHandle GetLineHandle(string nameID) - { - Object line = (Object)GetLine(nameID); - return (line != null ? new LineHandle(ref line, this) : null); - } - - // =================================================================== - - private Line GetLine(int numID) - { - foreach (Line line in m_Lines) - { - if (numID == line.m_NumID) - { - return line; - } - } - return null; - } - - // =================================================================== - - private Line GetLine(string nameID) - { - foreach (Line line in m_Lines) - { - if (string.Compare(nameID, line.m_NameID, true) == 0) - { - return line; - } - } - return null; - } - - // =================================================================== - - /// - /// Returns true if a line exists with an identification number mathing - /// the passed value. Returns false if no match is found. - /// - /// - /// The case numerical ID of the line you wish to check the existence - /// of. - /// - - public bool LineExists(int numID) - { - return GetLine(numID) != null; - } - - // =================================================================== - - /// - /// Returns true if a line exists with a name that case insensitively - /// matches the passes name. Returns false if no match is found. - /// - /// - /// The case insensitive name of the line you wish to check the existence - /// of. - /// - - public bool LineExists(string nameID) - { - return GetLine(nameID) != null; - } - - // =================================================================== - - /// - /// Adds a new line using the passed name as an identifier and sets - /// the line's initial color to the passed color. If successful, returns - /// a handle to the new line. - /// - /// - /// A case insensitive name for the line you wish to create. - /// - /// - /// The line's initial color. - /// - - public LineHandle AddLine(string nameID, Color clr) - { - if (LineExists(nameID)) - { - return null; - } - - Line line = new Line(nameID); - line.m_Color = clr; - - m_Lines.Add(line); - - Object objLine = (Object)line; - return (new LineHandle(ref objLine, this)); - } - - // =================================================================== - // I strongly suggest that you use this method when performance is critical - - /// - /// Adds a new line using the passed numeric ID as an identifier and sets - /// the line's initial color to the passed color. If successful, returns - /// a handle to the new line. - /// - /// - /// A unique numerical for the line you wish to create. - /// - /// - /// The line's initial color. - /// - - public LineHandle AddLine(int numID, Color clr) - { - if (LineExists(numID)) - { - return null; - } - - Line line = new Line(numID); - line.m_Color = clr; - - m_Lines.Add(line); - Object objLine = (Object)line; - return (new LineHandle(ref objLine, this)); - } - - // =================================================================== - - /// - /// Removes a line by its name. - /// - /// - /// The line's case-insensitive name. - /// - - public bool RemoveLine(string nameID) - { - Line line = GetLine(nameID); - if (line == null) - { - return false; - } - - return m_Lines.Remove(line); - } - - // =================================================================== - - /// - /// Removes a line by its numerical ID. - /// - /// - /// The line's numerical ID. - /// - - public bool RemoveLine(int numID) - { - Line line = GetLine(numID); - if (line == null) - { - return false; - } - - return m_Lines.Remove(line); - } - - // =================================================================== - - /// - /// Pushes a new magnitude (point) to the line with the passed name. - /// - /// - /// The magnitude of the new point. - /// - /// - /// The line's case-insensitive name. - /// - - public bool Push(int magnitude, string nameID) - { - Line line = GetLine(nameID); - if (line == null) - { - return false; - } - - return PushDirect(magnitude, line); - } - - // =================================================================== - - /// - /// Pushes a new magnitude (point) to the line with the passed - /// numerical ID. - /// - /// - /// The magnitude of the new point. - /// - /// - /// The line's numerical ID. - /// - - public bool Push(int magnitude, int numID) - { - Line line = GetLine(numID); - if (line == null) - { - return false; - } - - return PushDirect(magnitude, line); - } - - // =================================================================== - - private bool PushDirect(int magnitude, Line line) - { - /* Now add the magnitude (push point) to the array of push points, but - first restrict it to the peek bounds */ - - if (!m_bAutoScale && magnitude > m_MaxPeek) - { - magnitude = m_MaxPeek; - } - else if (m_bAutoScale && magnitude > m_MaxPeek) - { - m_MaxPeek = magnitude; - RefreshLabels(); - } - else if (!m_bAutoScale && magnitude < m_MinPeek) - { - magnitude = m_MinPeek; - } - else if (m_bAutoScale && magnitude < m_MinPeek) - { - m_MinPeek = magnitude; - RefreshLabels(); - } - - magnitude -= m_MinPeek; - - line.m_MagnitudeList.Add(magnitude); - return true; - } - - } - } -} diff --git a/cpumon/ProcessorUsage/PushGraph/C2DPushGraph.csproj b/cpumon/ProcessorUsage/PushGraph/C2DPushGraph.csproj deleted file mode 100644 index 3355204..0000000 --- a/cpumon/ProcessorUsage/PushGraph/C2DPushGraph.csproj +++ /dev/null @@ -1,57 +0,0 @@ - - - Debug - AnyCPU - 8.0.50727 - 2.0 - {290BF7F1-91BB-4AE0-A89B-9320EC1B2619} - Library - Properties - C2DPushGraph - C2DPushGraph - - - - - 2.0 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - Component - - - - - - - \ No newline at end of file diff --git a/cpumon/ProcessorUsage/PushGraph/Properties/AssemblyInfo.cs b/cpumon/ProcessorUsage/PushGraph/Properties/AssemblyInfo.cs deleted file mode 100644 index a1f7d18..0000000 --- a/cpumon/ProcessorUsage/PushGraph/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("C2DPushGraph")] -[assembly: AssemblyDescription("C# Windows Form Control")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Stuart Konen")] -[assembly: AssemblyProduct("C2DPushGraph")] -[assembly: AssemblyCopyright("Copyright © 2006")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("a9ff733b-31a5-4083-87e4-336bd5e8b27b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/disableTouch/disabletouch2/disableTouchCS/Form1.Designer.cs b/disableTouch/disabletouch2/disableTouchCS/Form1.Designer.cs deleted file mode 100644 index a633d7f..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/Form1.Designer.cs +++ /dev/null @@ -1,92 +0,0 @@ -namespace disableTouchCS -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.Windows.Forms.Label label1; - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.btnLockTouch = new System.Windows.Forms.Button(); - this.lblStatus = new System.Windows.Forms.Label(); - label1 = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // label1 - // - label1.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold); - label1.Location = new System.Drawing.Point(22, 145); - label1.Name = "label1"; - label1.Size = new System.Drawing.Size(192, 88); - label1.Text = "When touch screen is locked, press any key to unlock!"; - label1.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // btnLockTouch - // - this.btnLockTouch.Location = new System.Drawing.Point(41, 31); - this.btnLockTouch.Name = "btnLockTouch"; - this.btnLockTouch.Size = new System.Drawing.Size(157, 39); - this.btnLockTouch.TabIndex = 0; - this.btnLockTouch.Text = "Lock Touch Input"; - this.btnLockTouch.Click += new System.EventHandler(this.btnLockTouch_Click); - // - // lblStatus - // - this.lblStatus.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); - this.lblStatus.Location = new System.Drawing.Point(57, 91); - this.lblStatus.Name = "lblStatus"; - this.lblStatus.Size = new System.Drawing.Size(125, 29); - this.lblStatus.Text = "unlocked?"; - this.lblStatus.TextAlign = System.Drawing.ContentAlignment.TopCenter; - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.Controls.Add(this.lblStatus); - this.Controls.Add(label1); - this.Controls.Add(this.btnLockTouch); - this.KeyPreview = true; - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "Form1"; - this.Text = "disableTouchCS"; - this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown); - this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Button btnLockTouch; - private System.Windows.Forms.Label lblStatus; - } -} - diff --git a/disableTouch/disabletouch2/disableTouchCS/Form1.cs b/disableTouch/disabletouch2/disableTouchCS/Form1.cs deleted file mode 100644 index f0dbe7c..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/Form1.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace disableTouchCS -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - - private void Form1_KeyDown(object sender, KeyEventArgs e) - { - disableTouch.UnLock(); - lblStatus.Text = "unlocked?"; - } - - private void btnLockTouch_Click(object sender, EventArgs e) - { - if (disableTouch.Lock()) - lblStatus.Text = "locked?"; - else - lblStatus.Text = "unknown error"; - } - - private void Form1_MouseDown(object sender, MouseEventArgs e) - { - MessageBeeps.MessageBeep(MessageBeeps.beepType.OK); - } - } -} \ No newline at end of file diff --git a/disableTouch/disabletouch2/disableTouchCS/Form1.resx b/disableTouch/disabletouch2/disableTouchCS/Form1.resx deleted file mode 100644 index 53efc21..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/Form1.resx +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - False - - - 17, 17 - - - Pocket_PC_Phone - - - True - - \ No newline at end of file diff --git a/disableTouch/disabletouch2/disableTouchCS/MessageBeep.cs b/disableTouch/disabletouch2/disableTouchCS/MessageBeep.cs deleted file mode 100644 index 285922c..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/MessageBeep.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; - -namespace disableTouchCS -{ - public static class MessageBeeps - { - //credits to http://www.pinvoke.net/default.aspx/user32.messagebeep - [DllImport("coredll.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool MessageBeep(beepType uType); - /// - /// Enum type that enables intellisense on the private method. - /// - /// - /// Used by the public Beep - public enum beepType : uint - { - /// - /// A simple windows beep - /// - SimpleBeep = 0xFFFFFFFF, - /// - /// A standard windows OK beep - /// - OK = 0x00, - /// - /// A standard windows Question beep - /// - Question = 0x20, - /// - /// A standard windows Exclamation beep - /// - Exclamation = 0x30, - /// - /// A standard windows Asterisk beep - /// - Asterisk = 0x40, - } - } -} diff --git a/disableTouch/disabletouch2/disableTouchCS/Program.cs b/disableTouch/disabletouch2/disableTouchCS/Program.cs deleted file mode 100644 index 021ac0f..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace disableTouchCS -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/disableTouch/disabletouch2/disableTouchCS/Properties/AssemblyInfo.cs b/disableTouch/disabletouch2/disableTouchCS/Properties/AssemblyInfo.cs deleted file mode 100644 index 9b36e14..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("disableTouchCS")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("disableTouchCS")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("3ec9ec8c-af17-41d2-8d2e-0f6e2499a330")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/disableTouch/disabletouch2/disableTouchCS/Properties/Resources.Designer.cs b/disableTouch/disabletouch2/disableTouchCS/Properties/Resources.Designer.cs deleted file mode 100644 index 50d8945..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5456 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace disableTouchCS.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("disableTouchCS.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/disableTouch/disabletouch2/disableTouchCS/Properties/Resources.resx b/disableTouch/disabletouch2/disableTouchCS/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/disableTouch/disabletouch2/disableTouchCS/disableTouch.cs b/disableTouch/disabletouch2/disableTouchCS/disableTouch.cs deleted file mode 100644 index 8762c72..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/disableTouch.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; - -namespace disableTouchCS -{ - public static class disableTouch - { - [DllImport("coredll.dll", SetLastError = true)] - private static extern IntPtr GetDesktopWindow(); - - [DllImport("touch.dll", SetLastError = true)] - private static extern bool TouchRegisterWindow(IntPtr hwnd); - - [DllImport("touch.dll", SetLastError = true)] - private static extern void TouchUnregisterWindow(IntPtr hwnd); - - private static IntPtr DesktopHandle = new IntPtr(0); - - public static Boolean Lock() - { - return TouchRegisterWindow(GetDesktopWindow());// do not use (DesktopHandle), will not work! - } - - public static void UnLock() - { - TouchUnregisterWindow(GetDesktopWindow()); - } - } -} diff --git a/disableTouch/disabletouch2/disableTouchCS/disableTouchCS.csproj b/disableTouch/disabletouch2/disableTouchCS/disableTouchCS.csproj deleted file mode 100644 index 73c0a5e..0000000 --- a/disableTouch/disabletouch2/disableTouchCS/disableTouchCS.csproj +++ /dev/null @@ -1,94 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {42BB9AFB-89F4-4A62-9DBF-8347207989ED} - WinExe - Properties - disableTouchCS - disableTouchCS - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - b2c48bd2-963d-4549-9169-1fa021dce484 - 5.2 - disableTouchCS - v2.0 - Windows Mobile 6 Professional SDK - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - Form - - - Form1.cs - - - - - - Form1.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - \ No newline at end of file diff --git a/disableTouch/disabletouch2/disableTouchDll/disableTouchDll.cpp b/disableTouch/disabletouch2/disableTouchDll/disableTouchDll.cpp deleted file mode 100644 index 0eb3da0..0000000 --- a/disableTouch/disabletouch2/disableTouchDll/disableTouchDll.cpp +++ /dev/null @@ -1,62 +0,0 @@ -//disableTouchDll.cpp - -#include -#include "hooks.h" - -//forward declarations -void TouchUnregisterWindow(HWND hwnd); -BOOL TouchRegisterWindow(HWND hwnd); - -BOOL WINAPI DllMainCRTStartup(HANDLE hDLL, DWORD dwReason, LPVOID lpReserved) -{ - switch (dwReason){ - case DLL_PROCESS_ATTACH: - case DLL_THREAD_ATTACH: - DEBUGMSG(1,(L"DLL attached...\n")); - return TRUE; - break; - case DLL_PROCESS_DETACH: - case DLL_THREAD_DETACH: - DEBUGMSG(1,(L"...DLL detached\n")); - return TRUE; - break; - default: - break; - } - return TRUE; -} - -void __declspec( dllexport ) __stdcall disableTouch(BOOL bDisable){ - if(bDisable) - TouchRegisterWindow(GetDesktopWindow()); - else - TouchUnregisterWindow(GetDesktopWindow()); -} - -BOOL TouchRegisterWindow(HWND hwnd) -{ - TCHAR szText1[MAX_PATH]; - TCHAR szText2[MAX_PATH]; - GetWindowText(hwnd, szText1, MAX_PATH); - GetClassName(hwnd, szText2, MAX_PATH); - DEBUGMSG(1, (L"TouchRegisterWindow called with '0x%08x', '%s', '%s'\n", hwnd, szText1, szText2)); - - InitializeTouchDll(); - BOOL bRes = m_fpTouchRegisterWindow(hwnd); - DEBUGMSG(1, (L"real TouchRegisterWindow call returned %i, '%i'\n", bRes, GetLastError())); - return TRUE; -} - -void TouchUnregisterWindow(HWND hwnd) -{ - TCHAR szText1[MAX_PATH]; - TCHAR szText2[MAX_PATH]; - GetWindowText(hwnd, szText1, MAX_PATH); - GetClassName(hwnd, szText2, MAX_PATH); - DEBUGMSG(1, (L"TouchUnregisterWindow called with '0x%80x', '%s', '%s'\n", hwnd, szText1, szText2)); - - InitializeTouchDll(); - m_fpTouchUnregisterWindow(hwnd); - DEBUGMSG(1, (L"real TouchUnregisterWindow called\n")); - return; -} diff --git a/disableTouch/disabletouch2/disableTouchDll/disableTouchDll.def b/disableTouch/disabletouch2/disableTouchDll/disableTouchDll.def deleted file mode 100644 index a8af746..0000000 --- a/disableTouch/disabletouch2/disableTouchDll/disableTouchDll.def +++ /dev/null @@ -1,4 +0,0 @@ -LIBRARY "disableTouchDll" - -EXPORTS - disableTouch diff --git a/disableTouch/disabletouch2/disableTouchDll/disableTouchDll.vcproj b/disableTouch/disabletouch2/disableTouchDll/disableTouchDll.vcproj deleted file mode 100644 index bd59dd1..0000000 --- a/disableTouch/disabletouch2/disableTouchDll/disableTouchDll.vcproj +++ /dev/null @@ -1,242 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/disableTouch/disabletouch2/disableTouchDll/hooks.cpp b/disableTouch/disabletouch2/disableTouchDll/hooks.cpp deleted file mode 100644 index e0f1e25..0000000 --- a/disableTouch/disabletouch2/disableTouchDll/hooks.cpp +++ /dev/null @@ -1,188 +0,0 @@ -//hooks.cpp -/* -usage: - hookInit() - unloadHook() -*/ - -#include "hooks.h" - -#define LOGDEBUG(msg) DEBUGMSG(1, (msg)) -#define LOGERROR(msg) DEBUGMSG(1, (msg)) - -#define WNDCLASSNAME L"TOUCHLOCKPRO/LOCKEDWINDOW" - -#define TOUCH_SEND_TO_SYSTEM 2 -#define TOUCH_SEND_TO_WINDOW 1 - -bool HookTouchPanelStatus = false; - -static bool hooksInitialized = false; // only initialize once. so we have singleton behaviour -bool touchPanelDisabled = false; // keep track of current status, so we do not apply twice - -//from hooks.h -bool touchPanelWindowRegistered=false; -HINSTANCE m_hInstance; -HWND m_LockedWindow; -bool lazyInitialized; - -HMODULE m_TouchDLL; -TouchRegisterWindow_t m_fpTouchRegisterWindow; -TouchUnregisterWindow_t m_fpTouchUnregisterWindow; -//end hooks.h - -TouchPanelPowerHandler_t m_fpTouchPanelPowerHandler; - -LRESULT TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (touchPanelDisabled) { - return 0; - } - return DefWindowProc(hWnd, message, wParam, lParam); -} - -/// Create a new child window in the context of hInstance -void hookInit(HINSTANCE hInstance) { - if (hooksInitialized) - return; - lazyInitialized=false; - hooksInitialized = true; - touchPanelWindowRegistered = false; - m_TouchDLL = NULL; - - LOGDEBUG(L"hookInit"); - - m_hInstance = hInstance; - - WNDCLASS wc; - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = (WNDPROC) TouchPanelHookWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = sizeof(LONG); - wc.hInstance = hInstance; - wc.hIcon = NULL; - wc.hCursor = 0; - wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; - wc.lpszClassName = WNDCLASSNAME; - RegisterClass(&wc); - - m_LockedWindow = CreateWindowEx(0, WNDCLASSNAME, L"TouchLockPro Panel locked", 0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL); - if (m_LockedWindow == NULL) { - LOGERROR(L"Could not create Locked window"); - MessageBox(NULL, _T("Could not create Locked window"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } else { - if (!InitializeTouchDll()) { - LOGERROR(L"Could not create TouchPanel Hook"); - MessageBox(NULL, _T("Could not create TouchPanel Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } - } - - //if (!ActivateKBHook()) { - // LOGERROR(L"Could not create Keyboard Hook"); - // MessageBox(NULL, _T("Could not create Keyboard Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - //} - - //CSettings settingsClass; - // pHooksSettingsClass = &settingsClass; -} - -bool InitializeTouchDll() { - LOGDEBUG(L"InitializeTouchDll()"); - if (m_TouchDLL == NULL) { - m_TouchDLL = LoadLibrary(L"touch.dll"); - if(m_TouchDLL != NULL) { - m_fpTouchPanelPowerHandler = (TouchPanelPowerHandler_t)GetProcAddress(m_TouchDLL, L"TouchPanelPowerHandler"); - m_fpTouchRegisterWindow = (TouchRegisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchRegisterWindow")); - m_fpTouchUnregisterWindow = (TouchUnregisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchUnregisterWindow")); - if ((m_fpTouchPanelPowerHandler != NULL) && (m_fpTouchRegisterWindow != NULL) && (m_fpTouchUnregisterWindow != NULL)) { - return true; // everything Ok - } - } - } else { - LOGERROR(L"Error in initializing Touch dll"); - return false; - } - LOGERROR(L"Error in finding Touch dll register/unregister functions"); - return false; // something wrong -} - -void ShutdownTouchDll() { - LOGDEBUG(L"ShutdownTouchDll()"); - HookTouchPanel(false); - - if (m_TouchDLL != NULL) { - FreeLibrary(m_TouchDLL); - m_TouchDLL = NULL; - } - - m_fpTouchRegisterWindow = NULL; - m_fpTouchUnregisterWindow = NULL; -} - -/// register zero size window with TouchPanelRegisterWindow -/// set zero size window extra memory with TOUCH_SEND_TO_SYSTEM -/// using SetWindowLong(hWnd, 0, x) sets the DWL_MSGRESULT of the window -/// DWL_MSGRESULT: Sets the return value of a message processed in the dialog box procedure -void HookTouchPanel(bool bHook) { - if (HookTouchPanelStatus == bHook) { - LOGDEBUG(L"HookTouchPanel nothing to do"); - return; - } - LOGDEBUG(L"HookTouchPanel"); - HookTouchPanelStatus = bHook; - - if (!lazyInitialized) { - lazyInitialized = true; - SetWindowLong(m_LockedWindow, 0, TOUCH_SEND_TO_SYSTEM); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - - if (bHook && !touchPanelWindowRegistered) { - touchPanelWindowRegistered = true; - BOOL result = m_fpTouchRegisterWindow(m_LockedWindow); - if (!result) { - LOGERROR(L"Error in registering m_LockedWindow"); - } else { - LOGDEBUG(L"TouchRegisterWindow Ok"); - } - } - - SetLastError(0); - LONG nNew; - if(bHook) - nNew = TOUCH_SEND_TO_WINDOW; - else - nNew = TOUCH_SEND_TO_SYSTEM; - ///LONG nNew = bHook ? TOUCH_SEND_TO_WINDOW : TOUCH_SEND_TO_SYSTEM; - LONG prevNew = GetWindowLong(m_LockedWindow, 0); //read DLG_MSG_RESULT - if (prevNew != nNew) { ///if not equal, try a second time to register window - LONG setResult = SetWindowLong(m_LockedWindow, 0, nNew); - if (setResult == 0) { - LOGERROR(L"Error in SetWindowLong"); - } else { - LOGDEBUG(L"SetWindowLong result"); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - } - - //unregister wanted? - if (!bHook && touchPanelWindowRegistered) { - touchPanelWindowRegistered = false; - m_fpTouchUnregisterWindow(m_LockedWindow); - LOGDEBUG(L"TouchUnregisterWindow done"); - } -} - -void unloadHook() { - LOGDEBUG(L"unloadHook"); - ShutdownTouchDll(); - - if (m_LockedWindow != NULL) { - DestroyWindow(m_LockedWindow); - m_LockedWindow = NULL; - } - UnregisterClass(WNDCLASSNAME, m_hInstance); - - //DeactivateKBHook(); // we are done with the hook. now uninstall it. -} - diff --git a/disableTouch/disabletouch2/disableTouchDll/hooks.h b/disableTouch/disabletouch2/disableTouchDll/hooks.h deleted file mode 100644 index ff71b17..0000000 --- a/disableTouch/disabletouch2/disableTouchDll/hooks.h +++ /dev/null @@ -1,32 +0,0 @@ -//hooks.h - -#pragma once -#if !defined(TOUCHLOCKPRO_HOOKS_H_INCLUDED_) -#define TOUCHLOCKPRO_HOOKS_H_INCLUDED_ - -#include - static LRESULT CALLBACK TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - - typedef BOOL (*TouchRegisterWindow_t)(HWND hWnd); - - typedef void (*TouchUnregisterWindow_t)(HWND hWnd); - - typedef VOID (*TouchPanelPowerHandler_t)(BOOL bOff); - - typedef BOOL (*SetKMode_t)(BOOL fMode); - void HookTouchPanel(bool bHook); - bool InitializeTouchDll(); - - void hookInit(HINSTANCE hInstance); - void unloadHook(); - - extern bool touchPanelWindowRegistered; - extern HINSTANCE m_hInstance; - extern HWND m_LockedWindow; - extern bool lazyInitialized; - extern HMODULE m_TouchDLL; - extern TouchRegisterWindow_t m_fpTouchRegisterWindow; - extern TouchUnregisterWindow_t m_fpTouchUnregisterWindow; - - -#endif \ No newline at end of file diff --git a/disableTouch/disabletouch2/disabletouch1/ReadMe.txt b/disableTouch/disabletouch2/disabletouch1/ReadMe.txt deleted file mode 100644 index 762ce7e..0000000 --- a/disableTouch/disabletouch2/disabletouch1/ReadMe.txt +++ /dev/null @@ -1,33 +0,0 @@ -======================================================================== - CONSOLE APPLICATION : disabletouch1 Project Overview -======================================================================== - -AppWizard has created this disabletouch1 application for you. - -This file contains a summary of what you will find in each of the files that -make up your disabletouch1 application. - - -disabletouch1.vcproj - This is the main project file for VC++ projects generated using an Application Wizard. - It contains information about the version of Visual C++ that generated the file, and - information about the platforms, configurations, and project features selected with the - Application Wizard. - -disabletouch1.cpp - This is the main application source file. - -///////////////////////////////////////////////////////////////////////////// -Other standard files: - -StdAfx.h, StdAfx.cpp - These files are used to build a precompiled header (PCH) file - named disabletouch1.pch and a precompiled types file named StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Other notes: - -AppWizard uses "TODO:" comments to indicate parts of the source code you -should add to or customize. - -/////////////////////////////////////////////////////////////////////////////s \ No newline at end of file diff --git a/disableTouch/disabletouch2/disabletouch1/disabletouch1.vcproj b/disableTouch/disabletouch2/disabletouch1/disabletouch1.vcproj deleted file mode 100644 index 35e1537..0000000 --- a/disableTouch/disabletouch2/disabletouch1/disabletouch1.vcproj +++ /dev/null @@ -1,463 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/disableTouch/disabletouch2/disabletouch1/disabletouchCMD.cpp b/disableTouch/disabletouch2/disabletouch1/disabletouchCMD.cpp deleted file mode 100644 index 9296b5d..0000000 --- a/disableTouch/disabletouch2/disabletouch1/disabletouchCMD.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// disabletouch1.cpp : Defines the entry point for the console application. -// - -#include "stdafx.h" - -#include "hooks.h" - -int _tmain(int argc, _TCHAR* argv[]) -{ - if(argc==2){ - InitializeTouchDll(); - HWND hwnd = GetDesktopWindow(); - DEBUGMSG(1,(L"GetDesktopWindow() = 0x%08x", hwnd)); - long lCmd; - lCmd = _wtol(argv[1]); - - if(lCmd==1){ //disable touch - DEBUGMSG(1, (L"+++ TouchRegisterWindow called\n")); - return m_fpTouchRegisterWindow(hwnd); - } - else if (lCmd==0){ //enable touch - SetLastError(0); - DEBUGMSG(1, (L"--- TouchUnregisterWindow called\n")); - m_fpTouchUnregisterWindow(hwnd); - return GetLastError(); - } - else - return -2;//wrong arg - } - else - return -1; //no args no fun - return 0; -} - diff --git a/disableTouch/disabletouch2/disabletouch1/hooks.cpp b/disableTouch/disabletouch2/disabletouch1/hooks.cpp deleted file mode 100644 index e0f1e25..0000000 --- a/disableTouch/disabletouch2/disabletouch1/hooks.cpp +++ /dev/null @@ -1,188 +0,0 @@ -//hooks.cpp -/* -usage: - hookInit() - unloadHook() -*/ - -#include "hooks.h" - -#define LOGDEBUG(msg) DEBUGMSG(1, (msg)) -#define LOGERROR(msg) DEBUGMSG(1, (msg)) - -#define WNDCLASSNAME L"TOUCHLOCKPRO/LOCKEDWINDOW" - -#define TOUCH_SEND_TO_SYSTEM 2 -#define TOUCH_SEND_TO_WINDOW 1 - -bool HookTouchPanelStatus = false; - -static bool hooksInitialized = false; // only initialize once. so we have singleton behaviour -bool touchPanelDisabled = false; // keep track of current status, so we do not apply twice - -//from hooks.h -bool touchPanelWindowRegistered=false; -HINSTANCE m_hInstance; -HWND m_LockedWindow; -bool lazyInitialized; - -HMODULE m_TouchDLL; -TouchRegisterWindow_t m_fpTouchRegisterWindow; -TouchUnregisterWindow_t m_fpTouchUnregisterWindow; -//end hooks.h - -TouchPanelPowerHandler_t m_fpTouchPanelPowerHandler; - -LRESULT TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (touchPanelDisabled) { - return 0; - } - return DefWindowProc(hWnd, message, wParam, lParam); -} - -/// Create a new child window in the context of hInstance -void hookInit(HINSTANCE hInstance) { - if (hooksInitialized) - return; - lazyInitialized=false; - hooksInitialized = true; - touchPanelWindowRegistered = false; - m_TouchDLL = NULL; - - LOGDEBUG(L"hookInit"); - - m_hInstance = hInstance; - - WNDCLASS wc; - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = (WNDPROC) TouchPanelHookWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = sizeof(LONG); - wc.hInstance = hInstance; - wc.hIcon = NULL; - wc.hCursor = 0; - wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; - wc.lpszClassName = WNDCLASSNAME; - RegisterClass(&wc); - - m_LockedWindow = CreateWindowEx(0, WNDCLASSNAME, L"TouchLockPro Panel locked", 0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL); - if (m_LockedWindow == NULL) { - LOGERROR(L"Could not create Locked window"); - MessageBox(NULL, _T("Could not create Locked window"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } else { - if (!InitializeTouchDll()) { - LOGERROR(L"Could not create TouchPanel Hook"); - MessageBox(NULL, _T("Could not create TouchPanel Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } - } - - //if (!ActivateKBHook()) { - // LOGERROR(L"Could not create Keyboard Hook"); - // MessageBox(NULL, _T("Could not create Keyboard Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - //} - - //CSettings settingsClass; - // pHooksSettingsClass = &settingsClass; -} - -bool InitializeTouchDll() { - LOGDEBUG(L"InitializeTouchDll()"); - if (m_TouchDLL == NULL) { - m_TouchDLL = LoadLibrary(L"touch.dll"); - if(m_TouchDLL != NULL) { - m_fpTouchPanelPowerHandler = (TouchPanelPowerHandler_t)GetProcAddress(m_TouchDLL, L"TouchPanelPowerHandler"); - m_fpTouchRegisterWindow = (TouchRegisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchRegisterWindow")); - m_fpTouchUnregisterWindow = (TouchUnregisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchUnregisterWindow")); - if ((m_fpTouchPanelPowerHandler != NULL) && (m_fpTouchRegisterWindow != NULL) && (m_fpTouchUnregisterWindow != NULL)) { - return true; // everything Ok - } - } - } else { - LOGERROR(L"Error in initializing Touch dll"); - return false; - } - LOGERROR(L"Error in finding Touch dll register/unregister functions"); - return false; // something wrong -} - -void ShutdownTouchDll() { - LOGDEBUG(L"ShutdownTouchDll()"); - HookTouchPanel(false); - - if (m_TouchDLL != NULL) { - FreeLibrary(m_TouchDLL); - m_TouchDLL = NULL; - } - - m_fpTouchRegisterWindow = NULL; - m_fpTouchUnregisterWindow = NULL; -} - -/// register zero size window with TouchPanelRegisterWindow -/// set zero size window extra memory with TOUCH_SEND_TO_SYSTEM -/// using SetWindowLong(hWnd, 0, x) sets the DWL_MSGRESULT of the window -/// DWL_MSGRESULT: Sets the return value of a message processed in the dialog box procedure -void HookTouchPanel(bool bHook) { - if (HookTouchPanelStatus == bHook) { - LOGDEBUG(L"HookTouchPanel nothing to do"); - return; - } - LOGDEBUG(L"HookTouchPanel"); - HookTouchPanelStatus = bHook; - - if (!lazyInitialized) { - lazyInitialized = true; - SetWindowLong(m_LockedWindow, 0, TOUCH_SEND_TO_SYSTEM); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - - if (bHook && !touchPanelWindowRegistered) { - touchPanelWindowRegistered = true; - BOOL result = m_fpTouchRegisterWindow(m_LockedWindow); - if (!result) { - LOGERROR(L"Error in registering m_LockedWindow"); - } else { - LOGDEBUG(L"TouchRegisterWindow Ok"); - } - } - - SetLastError(0); - LONG nNew; - if(bHook) - nNew = TOUCH_SEND_TO_WINDOW; - else - nNew = TOUCH_SEND_TO_SYSTEM; - ///LONG nNew = bHook ? TOUCH_SEND_TO_WINDOW : TOUCH_SEND_TO_SYSTEM; - LONG prevNew = GetWindowLong(m_LockedWindow, 0); //read DLG_MSG_RESULT - if (prevNew != nNew) { ///if not equal, try a second time to register window - LONG setResult = SetWindowLong(m_LockedWindow, 0, nNew); - if (setResult == 0) { - LOGERROR(L"Error in SetWindowLong"); - } else { - LOGDEBUG(L"SetWindowLong result"); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - } - - //unregister wanted? - if (!bHook && touchPanelWindowRegistered) { - touchPanelWindowRegistered = false; - m_fpTouchUnregisterWindow(m_LockedWindow); - LOGDEBUG(L"TouchUnregisterWindow done"); - } -} - -void unloadHook() { - LOGDEBUG(L"unloadHook"); - ShutdownTouchDll(); - - if (m_LockedWindow != NULL) { - DestroyWindow(m_LockedWindow); - m_LockedWindow = NULL; - } - UnregisterClass(WNDCLASSNAME, m_hInstance); - - //DeactivateKBHook(); // we are done with the hook. now uninstall it. -} - diff --git a/disableTouch/disabletouch2/disabletouch1/hooks.h b/disableTouch/disabletouch2/disabletouch1/hooks.h deleted file mode 100644 index ff71b17..0000000 --- a/disableTouch/disabletouch2/disabletouch1/hooks.h +++ /dev/null @@ -1,32 +0,0 @@ -//hooks.h - -#pragma once -#if !defined(TOUCHLOCKPRO_HOOKS_H_INCLUDED_) -#define TOUCHLOCKPRO_HOOKS_H_INCLUDED_ - -#include - static LRESULT CALLBACK TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - - typedef BOOL (*TouchRegisterWindow_t)(HWND hWnd); - - typedef void (*TouchUnregisterWindow_t)(HWND hWnd); - - typedef VOID (*TouchPanelPowerHandler_t)(BOOL bOff); - - typedef BOOL (*SetKMode_t)(BOOL fMode); - void HookTouchPanel(bool bHook); - bool InitializeTouchDll(); - - void hookInit(HINSTANCE hInstance); - void unloadHook(); - - extern bool touchPanelWindowRegistered; - extern HINSTANCE m_hInstance; - extern HWND m_LockedWindow; - extern bool lazyInitialized; - extern HMODULE m_TouchDLL; - extern TouchRegisterWindow_t m_fpTouchRegisterWindow; - extern TouchUnregisterWindow_t m_fpTouchUnregisterWindow; - - -#endif \ No newline at end of file diff --git a/disableTouch/disabletouch2/disabletouch1/stdafx.cpp b/disableTouch/disabletouch2/disabletouch1/stdafx.cpp deleted file mode 100644 index d15d44a..0000000 --- a/disableTouch/disabletouch2/disabletouch1/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// disabletouch1.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/disableTouch/disabletouch2/disabletouch1/stdafx.h b/disableTouch/disabletouch2/disabletouch1/stdafx.h deleted file mode 100644 index 2c3dc08..0000000 --- a/disableTouch/disabletouch2/disabletouch1/stdafx.h +++ /dev/null @@ -1,56 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include - -#include -#pragma comment(lib, "aygshell.lib") - - - -#include -#include - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here diff --git a/disableTouch/disabletouch2/disabletouch2.sln b/disableTouch/disabletouch2/disabletouch2.sln deleted file mode 100644 index 42dcaa6..0000000 --- a/disableTouch/disabletouch2/disabletouch2.sln +++ /dev/null @@ -1,166 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "disabletouchWIN", "disabletouch2.vcproj", "{E3B715E2-3903-44D9-8973-BDE079598935}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "touchEnable", "touchEnable\touchEnable.vcproj", "{CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "touchDisable", "touchDisable\touchDisable.vcproj", "{BE470CC4-2E20-4063-806F-EFC837344847}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "disableTouchDLLsimple", "touc1\touc1.vcproj", "{653128C2-6A0A-4BBC-9745-F6F6034CBE42}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "disabletouchCMD", "disabletouch1\disabletouch1.vcproj", "{9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "disableTouchDll", "disableTouchDll\disableTouchDll.vcproj", "{D0F31D5A-FA10-4983-BDCC-CF167F22DC83}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "disableTouchCS", "disableTouchCS\disableTouchCS.csproj", "{42BB9AFB-89F4-4A62-9DBF-8347207989ED}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Debug|Windows Mobile 6 Professional SDK (ARMV4I) = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - Debug|Windows Mobile 6 Standard SDK (ARMV4I) = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 6 Professional SDK (ARMV4I) = Release|Windows Mobile 6 Professional SDK (ARMV4I) - Release|Windows Mobile 6 Standard SDK (ARMV4I) = Release|Windows Mobile 6 Standard SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E3B715E2-3903-44D9-8973-BDE079598935}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Debug|Mixed Platforms.Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Debug|Mixed Platforms.Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Release|Mixed Platforms.Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Release|Mixed Platforms.Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {E3B715E2-3903-44D9-8973-BDE079598935}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Debug|Mixed Platforms.Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Debug|Mixed Platforms.Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Release|Mixed Platforms.Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Release|Mixed Platforms.Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {CEA78CC4-13C1-4A2A-A8FA-1F91928D2C0C}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Debug|Mixed Platforms.Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Debug|Mixed Platforms.Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Release|Mixed Platforms.Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Release|Mixed Platforms.Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {BE470CC4-2E20-4063-806F-EFC837344847}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Debug|Mixed Platforms.Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Debug|Mixed Platforms.Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Release|Mixed Platforms.Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Release|Mixed Platforms.Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {653128C2-6A0A-4BBC-9745-F6F6034CBE42}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Debug|Mixed Platforms.Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Debug|Mixed Platforms.Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Standard SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Release|Mixed Platforms.Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Release|Mixed Platforms.Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {9282EC8E-CAD8-48FB-B41B-F0A6C44AE257}.Release|Windows Mobile 6 Standard SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Standard SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Debug|Any CPU.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Debug|Mixed Platforms.ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Debug|Mixed Platforms.Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Debug|Mixed Platforms.Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Release|Any CPU.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Release|Mixed Platforms.ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Release|Mixed Platforms.Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Release|Mixed Platforms.Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Build.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Release|Windows Mobile 6 Professional SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {D0F31D5A-FA10-4983-BDCC-CF167F22DC83}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 6 Professional SDK (ARMV4I) - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Debug|Any CPU.Build.0 = Debug|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Debug|Mixed Platforms.Deploy.0 = Debug|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Debug|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Debug|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Debug|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Release|Any CPU.ActiveCfg = Release|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Release|Any CPU.Build.0 = Release|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Release|Any CPU.Deploy.0 = Release|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Release|Mixed Platforms.Deploy.0 = Release|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Release|Windows Mobile 6 Professional SDK (ARMV4I).ActiveCfg = Release|Any CPU - {42BB9AFB-89F4-4A62-9DBF-8347207989ED}.Release|Windows Mobile 6 Standard SDK (ARMV4I).ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/disableTouch/disabletouch2/disabletouch2.vcproj b/disableTouch/disabletouch2/disabletouch2.vcproj deleted file mode 100644 index 0399d96..0000000 --- a/disableTouch/disabletouch2/disabletouch2.vcproj +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/disableTouch/disabletouch2/disabletouchWIN.cpp b/disableTouch/disabletouch2/disabletouchWIN.cpp deleted file mode 100644 index a2e47e4..0000000 --- a/disableTouch/disabletouch2/disabletouchWIN.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include -#include "hooks.h" - -#define WM_ENABLETOUCH WM_USER + 5240 - -HINSTANCE g_hInst; - -#define TOUCHWINDOWNAME L"DisableTouch" - -LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - -int WINAPI WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - DEBUGMSG(1, (L"cmd line: '%s'\n", lpCmdLine)); - HWND hwndPrev = FindWindow(TOUCHWINDOWNAME, TOUCHWINDOWNAME); - if(hwndPrev!=NULL && wcsicmp(lpCmdLine, L"0")==0) - { - PostMessage(hwndPrev, WM_ENABLETOUCH, 0, 0); - return 1; - } - - //previous instance running - if(hwndPrev!=NULL) - return 2; - - MSG msg = {0}; - WNDCLASS wc = {0}; - wc.lpfnWndProc = WndProc; - wc.hInstance = hInstance; - wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND); - wc.lpszClassName = TOUCHWINDOWNAME; - - if( !RegisterClass(&wc) ) - return 1; - - HWND hWnd = CreateWindow( - wc.lpszClassName, //class - wc.lpszClassName, //title - WS_VISIBLE, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - 0,0, - hInstance, - NULL); - if(hWnd==NULL) - return 2; - - g_hInst=hInstance; - - ShowWindow(hWnd, SW_MINIMIZE);// nCmdShow); - UpdateWindow(hWnd); - - while( GetMessage( &msg, NULL, 0, 0 ) > 0 ){ - TranslateMessage( &msg ); - DispatchMessage( &msg ); - } - - return 0; -} - -LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - HDC hdc; - PAINTSTRUCT ps; - switch(message) - { - case WM_ENABLETOUCH: - PostQuitMessage(2); - break; - case WM_CREATE: - hookInit(g_hInst); - HookTouchPanel(true); - break; - case WM_DESTROY: - unloadHook(); - case WM_SHOWWINDOW: - if(wParam==FALSE) //hide minimize - PostQuitMessage(0); - break; - case WM_QUIT: - DestroyWindow(hWnd); - case WM_CLOSE: - PostQuitMessage(0); - break; - case WM_PAINT: - hdc = BeginPaint(hWnd, &ps); - // TODO: Add any drawing code here... - - EndPaint(hWnd, &ps); - break; - case WM_KEYUP: - switch(wParam) - { - case VK_ESCAPE: - { - PostQuitMessage(0); - } - break; - } - break; - case WM_MOUSEMOVE: - DEBUGMSG(1, (L"X:%d Y:%d\n", HIWORD(lParam), LOWORD(lParam))); - break; - case WM_LBUTTONUP: - DEBUGMSG(1, (L"Mouse Click: X:%d Y:%d\n", HIWORD(lParam), LOWORD(lParam))); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - return 0; - -} diff --git a/disableTouch/disabletouch2/hooks.cpp b/disableTouch/disabletouch2/hooks.cpp deleted file mode 100644 index e0f1e25..0000000 --- a/disableTouch/disabletouch2/hooks.cpp +++ /dev/null @@ -1,188 +0,0 @@ -//hooks.cpp -/* -usage: - hookInit() - unloadHook() -*/ - -#include "hooks.h" - -#define LOGDEBUG(msg) DEBUGMSG(1, (msg)) -#define LOGERROR(msg) DEBUGMSG(1, (msg)) - -#define WNDCLASSNAME L"TOUCHLOCKPRO/LOCKEDWINDOW" - -#define TOUCH_SEND_TO_SYSTEM 2 -#define TOUCH_SEND_TO_WINDOW 1 - -bool HookTouchPanelStatus = false; - -static bool hooksInitialized = false; // only initialize once. so we have singleton behaviour -bool touchPanelDisabled = false; // keep track of current status, so we do not apply twice - -//from hooks.h -bool touchPanelWindowRegistered=false; -HINSTANCE m_hInstance; -HWND m_LockedWindow; -bool lazyInitialized; - -HMODULE m_TouchDLL; -TouchRegisterWindow_t m_fpTouchRegisterWindow; -TouchUnregisterWindow_t m_fpTouchUnregisterWindow; -//end hooks.h - -TouchPanelPowerHandler_t m_fpTouchPanelPowerHandler; - -LRESULT TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (touchPanelDisabled) { - return 0; - } - return DefWindowProc(hWnd, message, wParam, lParam); -} - -/// Create a new child window in the context of hInstance -void hookInit(HINSTANCE hInstance) { - if (hooksInitialized) - return; - lazyInitialized=false; - hooksInitialized = true; - touchPanelWindowRegistered = false; - m_TouchDLL = NULL; - - LOGDEBUG(L"hookInit"); - - m_hInstance = hInstance; - - WNDCLASS wc; - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = (WNDPROC) TouchPanelHookWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = sizeof(LONG); - wc.hInstance = hInstance; - wc.hIcon = NULL; - wc.hCursor = 0; - wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; - wc.lpszClassName = WNDCLASSNAME; - RegisterClass(&wc); - - m_LockedWindow = CreateWindowEx(0, WNDCLASSNAME, L"TouchLockPro Panel locked", 0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL); - if (m_LockedWindow == NULL) { - LOGERROR(L"Could not create Locked window"); - MessageBox(NULL, _T("Could not create Locked window"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } else { - if (!InitializeTouchDll()) { - LOGERROR(L"Could not create TouchPanel Hook"); - MessageBox(NULL, _T("Could not create TouchPanel Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } - } - - //if (!ActivateKBHook()) { - // LOGERROR(L"Could not create Keyboard Hook"); - // MessageBox(NULL, _T("Could not create Keyboard Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - //} - - //CSettings settingsClass; - // pHooksSettingsClass = &settingsClass; -} - -bool InitializeTouchDll() { - LOGDEBUG(L"InitializeTouchDll()"); - if (m_TouchDLL == NULL) { - m_TouchDLL = LoadLibrary(L"touch.dll"); - if(m_TouchDLL != NULL) { - m_fpTouchPanelPowerHandler = (TouchPanelPowerHandler_t)GetProcAddress(m_TouchDLL, L"TouchPanelPowerHandler"); - m_fpTouchRegisterWindow = (TouchRegisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchRegisterWindow")); - m_fpTouchUnregisterWindow = (TouchUnregisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchUnregisterWindow")); - if ((m_fpTouchPanelPowerHandler != NULL) && (m_fpTouchRegisterWindow != NULL) && (m_fpTouchUnregisterWindow != NULL)) { - return true; // everything Ok - } - } - } else { - LOGERROR(L"Error in initializing Touch dll"); - return false; - } - LOGERROR(L"Error in finding Touch dll register/unregister functions"); - return false; // something wrong -} - -void ShutdownTouchDll() { - LOGDEBUG(L"ShutdownTouchDll()"); - HookTouchPanel(false); - - if (m_TouchDLL != NULL) { - FreeLibrary(m_TouchDLL); - m_TouchDLL = NULL; - } - - m_fpTouchRegisterWindow = NULL; - m_fpTouchUnregisterWindow = NULL; -} - -/// register zero size window with TouchPanelRegisterWindow -/// set zero size window extra memory with TOUCH_SEND_TO_SYSTEM -/// using SetWindowLong(hWnd, 0, x) sets the DWL_MSGRESULT of the window -/// DWL_MSGRESULT: Sets the return value of a message processed in the dialog box procedure -void HookTouchPanel(bool bHook) { - if (HookTouchPanelStatus == bHook) { - LOGDEBUG(L"HookTouchPanel nothing to do"); - return; - } - LOGDEBUG(L"HookTouchPanel"); - HookTouchPanelStatus = bHook; - - if (!lazyInitialized) { - lazyInitialized = true; - SetWindowLong(m_LockedWindow, 0, TOUCH_SEND_TO_SYSTEM); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - - if (bHook && !touchPanelWindowRegistered) { - touchPanelWindowRegistered = true; - BOOL result = m_fpTouchRegisterWindow(m_LockedWindow); - if (!result) { - LOGERROR(L"Error in registering m_LockedWindow"); - } else { - LOGDEBUG(L"TouchRegisterWindow Ok"); - } - } - - SetLastError(0); - LONG nNew; - if(bHook) - nNew = TOUCH_SEND_TO_WINDOW; - else - nNew = TOUCH_SEND_TO_SYSTEM; - ///LONG nNew = bHook ? TOUCH_SEND_TO_WINDOW : TOUCH_SEND_TO_SYSTEM; - LONG prevNew = GetWindowLong(m_LockedWindow, 0); //read DLG_MSG_RESULT - if (prevNew != nNew) { ///if not equal, try a second time to register window - LONG setResult = SetWindowLong(m_LockedWindow, 0, nNew); - if (setResult == 0) { - LOGERROR(L"Error in SetWindowLong"); - } else { - LOGDEBUG(L"SetWindowLong result"); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - } - - //unregister wanted? - if (!bHook && touchPanelWindowRegistered) { - touchPanelWindowRegistered = false; - m_fpTouchUnregisterWindow(m_LockedWindow); - LOGDEBUG(L"TouchUnregisterWindow done"); - } -} - -void unloadHook() { - LOGDEBUG(L"unloadHook"); - ShutdownTouchDll(); - - if (m_LockedWindow != NULL) { - DestroyWindow(m_LockedWindow); - m_LockedWindow = NULL; - } - UnregisterClass(WNDCLASSNAME, m_hInstance); - - //DeactivateKBHook(); // we are done with the hook. now uninstall it. -} - diff --git a/disableTouch/disabletouch2/hooks.h b/disableTouch/disabletouch2/hooks.h deleted file mode 100644 index ff71b17..0000000 --- a/disableTouch/disabletouch2/hooks.h +++ /dev/null @@ -1,32 +0,0 @@ -//hooks.h - -#pragma once -#if !defined(TOUCHLOCKPRO_HOOKS_H_INCLUDED_) -#define TOUCHLOCKPRO_HOOKS_H_INCLUDED_ - -#include - static LRESULT CALLBACK TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - - typedef BOOL (*TouchRegisterWindow_t)(HWND hWnd); - - typedef void (*TouchUnregisterWindow_t)(HWND hWnd); - - typedef VOID (*TouchPanelPowerHandler_t)(BOOL bOff); - - typedef BOOL (*SetKMode_t)(BOOL fMode); - void HookTouchPanel(bool bHook); - bool InitializeTouchDll(); - - void hookInit(HINSTANCE hInstance); - void unloadHook(); - - extern bool touchPanelWindowRegistered; - extern HINSTANCE m_hInstance; - extern HWND m_LockedWindow; - extern bool lazyInitialized; - extern HMODULE m_TouchDLL; - extern TouchRegisterWindow_t m_fpTouchRegisterWindow; - extern TouchUnregisterWindow_t m_fpTouchUnregisterWindow; - - -#endif \ No newline at end of file diff --git a/disableTouch/disabletouch2/touc1/disableTouchDLLsimple.cpp b/disableTouch/disabletouch2/touc1/disableTouchDLLsimple.cpp deleted file mode 100644 index e707b65..0000000 --- a/disableTouch/disabletouch2/touc1/disableTouchDLLsimple.cpp +++ /dev/null @@ -1,53 +0,0 @@ -//touc1.cpp - -//dll to catch touch.dll calls - -#include -#include "hooks.h" - -BOOL WINAPI DllMainCRTStartup(HANDLE hDLL, DWORD dwReason, LPVOID lpReserved) -{ - switch (dwReason){ - case DLL_PROCESS_ATTACH: - case DLL_THREAD_ATTACH: - DEBUGMSG(1,(L"DLL attached...\n")); - return TRUE; - break; - case DLL_PROCESS_DETACH: - case DLL_THREAD_DETACH: - DEBUGMSG(1,(L"...DLL detached\n")); - return TRUE; - break; - default: - break; - } - return TRUE; -} - -BOOL __declspec( dllexport ) __stdcall TouchRegisterWindow(HWND hwnd) -{ - TCHAR szText1[MAX_PATH]; - TCHAR szText2[MAX_PATH]; - GetWindowText(hwnd, szText1, MAX_PATH); - GetClassName(hwnd, szText2, MAX_PATH); - DEBUGMSG(1, (L"TouchRegisterWindow called with '0x%08x', '%s', '%s'\n", hwnd, szText1, szText2)); - - InitializeTouchDll(); - BOOL bRes = m_fpTouchRegisterWindow(hwnd); - DEBUGMSG(1, (L"real TouchRegisterWindow call returned %i, '%i'\n", bRes, GetLastError())); - return TRUE; -} - -void __declspec( dllexport ) __stdcall TouchUnregisterWindow(HWND hwnd) -{ - TCHAR szText1[MAX_PATH]; - TCHAR szText2[MAX_PATH]; - GetWindowText(hwnd, szText1, MAX_PATH); - GetClassName(hwnd, szText2, MAX_PATH); - DEBUGMSG(1, (L"TouchUnregisterWindow called with '0x%80x', '%s', '%s'\n", hwnd, szText1, szText2)); - - InitializeTouchDll(); - m_fpTouchUnregisterWindow(hwnd); - DEBUGMSG(1, (L"real TouchUnregisterWindow called\n")); - return; -} diff --git a/disableTouch/disabletouch2/touc1/disableTouchDLLsimple.def b/disableTouch/disabletouch2/touc1/disableTouchDLLsimple.def deleted file mode 100644 index 6303d36..0000000 --- a/disableTouch/disabletouch2/touc1/disableTouchDLLsimple.def +++ /dev/null @@ -1,6 +0,0 @@ -LIBRARY "disableTouchDLLsimple" - -EXPORTS - TouchRegisterWindow - TouchUnregisterWindow - \ No newline at end of file diff --git a/disableTouch/disabletouch2/touc1/hooks.cpp b/disableTouch/disabletouch2/touc1/hooks.cpp deleted file mode 100644 index e0f1e25..0000000 --- a/disableTouch/disabletouch2/touc1/hooks.cpp +++ /dev/null @@ -1,188 +0,0 @@ -//hooks.cpp -/* -usage: - hookInit() - unloadHook() -*/ - -#include "hooks.h" - -#define LOGDEBUG(msg) DEBUGMSG(1, (msg)) -#define LOGERROR(msg) DEBUGMSG(1, (msg)) - -#define WNDCLASSNAME L"TOUCHLOCKPRO/LOCKEDWINDOW" - -#define TOUCH_SEND_TO_SYSTEM 2 -#define TOUCH_SEND_TO_WINDOW 1 - -bool HookTouchPanelStatus = false; - -static bool hooksInitialized = false; // only initialize once. so we have singleton behaviour -bool touchPanelDisabled = false; // keep track of current status, so we do not apply twice - -//from hooks.h -bool touchPanelWindowRegistered=false; -HINSTANCE m_hInstance; -HWND m_LockedWindow; -bool lazyInitialized; - -HMODULE m_TouchDLL; -TouchRegisterWindow_t m_fpTouchRegisterWindow; -TouchUnregisterWindow_t m_fpTouchUnregisterWindow; -//end hooks.h - -TouchPanelPowerHandler_t m_fpTouchPanelPowerHandler; - -LRESULT TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (touchPanelDisabled) { - return 0; - } - return DefWindowProc(hWnd, message, wParam, lParam); -} - -/// Create a new child window in the context of hInstance -void hookInit(HINSTANCE hInstance) { - if (hooksInitialized) - return; - lazyInitialized=false; - hooksInitialized = true; - touchPanelWindowRegistered = false; - m_TouchDLL = NULL; - - LOGDEBUG(L"hookInit"); - - m_hInstance = hInstance; - - WNDCLASS wc; - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = (WNDPROC) TouchPanelHookWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = sizeof(LONG); - wc.hInstance = hInstance; - wc.hIcon = NULL; - wc.hCursor = 0; - wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; - wc.lpszClassName = WNDCLASSNAME; - RegisterClass(&wc); - - m_LockedWindow = CreateWindowEx(0, WNDCLASSNAME, L"TouchLockPro Panel locked", 0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL); - if (m_LockedWindow == NULL) { - LOGERROR(L"Could not create Locked window"); - MessageBox(NULL, _T("Could not create Locked window"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } else { - if (!InitializeTouchDll()) { - LOGERROR(L"Could not create TouchPanel Hook"); - MessageBox(NULL, _T("Could not create TouchPanel Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } - } - - //if (!ActivateKBHook()) { - // LOGERROR(L"Could not create Keyboard Hook"); - // MessageBox(NULL, _T("Could not create Keyboard Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - //} - - //CSettings settingsClass; - // pHooksSettingsClass = &settingsClass; -} - -bool InitializeTouchDll() { - LOGDEBUG(L"InitializeTouchDll()"); - if (m_TouchDLL == NULL) { - m_TouchDLL = LoadLibrary(L"touch.dll"); - if(m_TouchDLL != NULL) { - m_fpTouchPanelPowerHandler = (TouchPanelPowerHandler_t)GetProcAddress(m_TouchDLL, L"TouchPanelPowerHandler"); - m_fpTouchRegisterWindow = (TouchRegisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchRegisterWindow")); - m_fpTouchUnregisterWindow = (TouchUnregisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchUnregisterWindow")); - if ((m_fpTouchPanelPowerHandler != NULL) && (m_fpTouchRegisterWindow != NULL) && (m_fpTouchUnregisterWindow != NULL)) { - return true; // everything Ok - } - } - } else { - LOGERROR(L"Error in initializing Touch dll"); - return false; - } - LOGERROR(L"Error in finding Touch dll register/unregister functions"); - return false; // something wrong -} - -void ShutdownTouchDll() { - LOGDEBUG(L"ShutdownTouchDll()"); - HookTouchPanel(false); - - if (m_TouchDLL != NULL) { - FreeLibrary(m_TouchDLL); - m_TouchDLL = NULL; - } - - m_fpTouchRegisterWindow = NULL; - m_fpTouchUnregisterWindow = NULL; -} - -/// register zero size window with TouchPanelRegisterWindow -/// set zero size window extra memory with TOUCH_SEND_TO_SYSTEM -/// using SetWindowLong(hWnd, 0, x) sets the DWL_MSGRESULT of the window -/// DWL_MSGRESULT: Sets the return value of a message processed in the dialog box procedure -void HookTouchPanel(bool bHook) { - if (HookTouchPanelStatus == bHook) { - LOGDEBUG(L"HookTouchPanel nothing to do"); - return; - } - LOGDEBUG(L"HookTouchPanel"); - HookTouchPanelStatus = bHook; - - if (!lazyInitialized) { - lazyInitialized = true; - SetWindowLong(m_LockedWindow, 0, TOUCH_SEND_TO_SYSTEM); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - - if (bHook && !touchPanelWindowRegistered) { - touchPanelWindowRegistered = true; - BOOL result = m_fpTouchRegisterWindow(m_LockedWindow); - if (!result) { - LOGERROR(L"Error in registering m_LockedWindow"); - } else { - LOGDEBUG(L"TouchRegisterWindow Ok"); - } - } - - SetLastError(0); - LONG nNew; - if(bHook) - nNew = TOUCH_SEND_TO_WINDOW; - else - nNew = TOUCH_SEND_TO_SYSTEM; - ///LONG nNew = bHook ? TOUCH_SEND_TO_WINDOW : TOUCH_SEND_TO_SYSTEM; - LONG prevNew = GetWindowLong(m_LockedWindow, 0); //read DLG_MSG_RESULT - if (prevNew != nNew) { ///if not equal, try a second time to register window - LONG setResult = SetWindowLong(m_LockedWindow, 0, nNew); - if (setResult == 0) { - LOGERROR(L"Error in SetWindowLong"); - } else { - LOGDEBUG(L"SetWindowLong result"); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - } - - //unregister wanted? - if (!bHook && touchPanelWindowRegistered) { - touchPanelWindowRegistered = false; - m_fpTouchUnregisterWindow(m_LockedWindow); - LOGDEBUG(L"TouchUnregisterWindow done"); - } -} - -void unloadHook() { - LOGDEBUG(L"unloadHook"); - ShutdownTouchDll(); - - if (m_LockedWindow != NULL) { - DestroyWindow(m_LockedWindow); - m_LockedWindow = NULL; - } - UnregisterClass(WNDCLASSNAME, m_hInstance); - - //DeactivateKBHook(); // we are done with the hook. now uninstall it. -} - diff --git a/disableTouch/disabletouch2/touc1/hooks.h b/disableTouch/disabletouch2/touc1/hooks.h deleted file mode 100644 index ff71b17..0000000 --- a/disableTouch/disabletouch2/touc1/hooks.h +++ /dev/null @@ -1,32 +0,0 @@ -//hooks.h - -#pragma once -#if !defined(TOUCHLOCKPRO_HOOKS_H_INCLUDED_) -#define TOUCHLOCKPRO_HOOKS_H_INCLUDED_ - -#include - static LRESULT CALLBACK TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - - typedef BOOL (*TouchRegisterWindow_t)(HWND hWnd); - - typedef void (*TouchUnregisterWindow_t)(HWND hWnd); - - typedef VOID (*TouchPanelPowerHandler_t)(BOOL bOff); - - typedef BOOL (*SetKMode_t)(BOOL fMode); - void HookTouchPanel(bool bHook); - bool InitializeTouchDll(); - - void hookInit(HINSTANCE hInstance); - void unloadHook(); - - extern bool touchPanelWindowRegistered; - extern HINSTANCE m_hInstance; - extern HWND m_LockedWindow; - extern bool lazyInitialized; - extern HMODULE m_TouchDLL; - extern TouchRegisterWindow_t m_fpTouchRegisterWindow; - extern TouchUnregisterWindow_t m_fpTouchUnregisterWindow; - - -#endif \ No newline at end of file diff --git a/disableTouch/disabletouch2/touc1/touc1.vcproj b/disableTouch/disabletouch2/touc1/touc1.vcproj deleted file mode 100644 index 06dfb14..0000000 --- a/disableTouch/disabletouch2/touc1/touc1.vcproj +++ /dev/null @@ -1,242 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/disableTouch/disabletouch2/touchDisable/hooks.cpp b/disableTouch/disabletouch2/touchDisable/hooks.cpp deleted file mode 100644 index e0f1e25..0000000 --- a/disableTouch/disabletouch2/touchDisable/hooks.cpp +++ /dev/null @@ -1,188 +0,0 @@ -//hooks.cpp -/* -usage: - hookInit() - unloadHook() -*/ - -#include "hooks.h" - -#define LOGDEBUG(msg) DEBUGMSG(1, (msg)) -#define LOGERROR(msg) DEBUGMSG(1, (msg)) - -#define WNDCLASSNAME L"TOUCHLOCKPRO/LOCKEDWINDOW" - -#define TOUCH_SEND_TO_SYSTEM 2 -#define TOUCH_SEND_TO_WINDOW 1 - -bool HookTouchPanelStatus = false; - -static bool hooksInitialized = false; // only initialize once. so we have singleton behaviour -bool touchPanelDisabled = false; // keep track of current status, so we do not apply twice - -//from hooks.h -bool touchPanelWindowRegistered=false; -HINSTANCE m_hInstance; -HWND m_LockedWindow; -bool lazyInitialized; - -HMODULE m_TouchDLL; -TouchRegisterWindow_t m_fpTouchRegisterWindow; -TouchUnregisterWindow_t m_fpTouchUnregisterWindow; -//end hooks.h - -TouchPanelPowerHandler_t m_fpTouchPanelPowerHandler; - -LRESULT TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (touchPanelDisabled) { - return 0; - } - return DefWindowProc(hWnd, message, wParam, lParam); -} - -/// Create a new child window in the context of hInstance -void hookInit(HINSTANCE hInstance) { - if (hooksInitialized) - return; - lazyInitialized=false; - hooksInitialized = true; - touchPanelWindowRegistered = false; - m_TouchDLL = NULL; - - LOGDEBUG(L"hookInit"); - - m_hInstance = hInstance; - - WNDCLASS wc; - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = (WNDPROC) TouchPanelHookWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = sizeof(LONG); - wc.hInstance = hInstance; - wc.hIcon = NULL; - wc.hCursor = 0; - wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; - wc.lpszClassName = WNDCLASSNAME; - RegisterClass(&wc); - - m_LockedWindow = CreateWindowEx(0, WNDCLASSNAME, L"TouchLockPro Panel locked", 0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL); - if (m_LockedWindow == NULL) { - LOGERROR(L"Could not create Locked window"); - MessageBox(NULL, _T("Could not create Locked window"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } else { - if (!InitializeTouchDll()) { - LOGERROR(L"Could not create TouchPanel Hook"); - MessageBox(NULL, _T("Could not create TouchPanel Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } - } - - //if (!ActivateKBHook()) { - // LOGERROR(L"Could not create Keyboard Hook"); - // MessageBox(NULL, _T("Could not create Keyboard Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - //} - - //CSettings settingsClass; - // pHooksSettingsClass = &settingsClass; -} - -bool InitializeTouchDll() { - LOGDEBUG(L"InitializeTouchDll()"); - if (m_TouchDLL == NULL) { - m_TouchDLL = LoadLibrary(L"touch.dll"); - if(m_TouchDLL != NULL) { - m_fpTouchPanelPowerHandler = (TouchPanelPowerHandler_t)GetProcAddress(m_TouchDLL, L"TouchPanelPowerHandler"); - m_fpTouchRegisterWindow = (TouchRegisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchRegisterWindow")); - m_fpTouchUnregisterWindow = (TouchUnregisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchUnregisterWindow")); - if ((m_fpTouchPanelPowerHandler != NULL) && (m_fpTouchRegisterWindow != NULL) && (m_fpTouchUnregisterWindow != NULL)) { - return true; // everything Ok - } - } - } else { - LOGERROR(L"Error in initializing Touch dll"); - return false; - } - LOGERROR(L"Error in finding Touch dll register/unregister functions"); - return false; // something wrong -} - -void ShutdownTouchDll() { - LOGDEBUG(L"ShutdownTouchDll()"); - HookTouchPanel(false); - - if (m_TouchDLL != NULL) { - FreeLibrary(m_TouchDLL); - m_TouchDLL = NULL; - } - - m_fpTouchRegisterWindow = NULL; - m_fpTouchUnregisterWindow = NULL; -} - -/// register zero size window with TouchPanelRegisterWindow -/// set zero size window extra memory with TOUCH_SEND_TO_SYSTEM -/// using SetWindowLong(hWnd, 0, x) sets the DWL_MSGRESULT of the window -/// DWL_MSGRESULT: Sets the return value of a message processed in the dialog box procedure -void HookTouchPanel(bool bHook) { - if (HookTouchPanelStatus == bHook) { - LOGDEBUG(L"HookTouchPanel nothing to do"); - return; - } - LOGDEBUG(L"HookTouchPanel"); - HookTouchPanelStatus = bHook; - - if (!lazyInitialized) { - lazyInitialized = true; - SetWindowLong(m_LockedWindow, 0, TOUCH_SEND_TO_SYSTEM); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - - if (bHook && !touchPanelWindowRegistered) { - touchPanelWindowRegistered = true; - BOOL result = m_fpTouchRegisterWindow(m_LockedWindow); - if (!result) { - LOGERROR(L"Error in registering m_LockedWindow"); - } else { - LOGDEBUG(L"TouchRegisterWindow Ok"); - } - } - - SetLastError(0); - LONG nNew; - if(bHook) - nNew = TOUCH_SEND_TO_WINDOW; - else - nNew = TOUCH_SEND_TO_SYSTEM; - ///LONG nNew = bHook ? TOUCH_SEND_TO_WINDOW : TOUCH_SEND_TO_SYSTEM; - LONG prevNew = GetWindowLong(m_LockedWindow, 0); //read DLG_MSG_RESULT - if (prevNew != nNew) { ///if not equal, try a second time to register window - LONG setResult = SetWindowLong(m_LockedWindow, 0, nNew); - if (setResult == 0) { - LOGERROR(L"Error in SetWindowLong"); - } else { - LOGDEBUG(L"SetWindowLong result"); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - } - - //unregister wanted? - if (!bHook && touchPanelWindowRegistered) { - touchPanelWindowRegistered = false; - m_fpTouchUnregisterWindow(m_LockedWindow); - LOGDEBUG(L"TouchUnregisterWindow done"); - } -} - -void unloadHook() { - LOGDEBUG(L"unloadHook"); - ShutdownTouchDll(); - - if (m_LockedWindow != NULL) { - DestroyWindow(m_LockedWindow); - m_LockedWindow = NULL; - } - UnregisterClass(WNDCLASSNAME, m_hInstance); - - //DeactivateKBHook(); // we are done with the hook. now uninstall it. -} - diff --git a/disableTouch/disabletouch2/touchDisable/hooks.h b/disableTouch/disabletouch2/touchDisable/hooks.h deleted file mode 100644 index ff71b17..0000000 --- a/disableTouch/disabletouch2/touchDisable/hooks.h +++ /dev/null @@ -1,32 +0,0 @@ -//hooks.h - -#pragma once -#if !defined(TOUCHLOCKPRO_HOOKS_H_INCLUDED_) -#define TOUCHLOCKPRO_HOOKS_H_INCLUDED_ - -#include - static LRESULT CALLBACK TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - - typedef BOOL (*TouchRegisterWindow_t)(HWND hWnd); - - typedef void (*TouchUnregisterWindow_t)(HWND hWnd); - - typedef VOID (*TouchPanelPowerHandler_t)(BOOL bOff); - - typedef BOOL (*SetKMode_t)(BOOL fMode); - void HookTouchPanel(bool bHook); - bool InitializeTouchDll(); - - void hookInit(HINSTANCE hInstance); - void unloadHook(); - - extern bool touchPanelWindowRegistered; - extern HINSTANCE m_hInstance; - extern HWND m_LockedWindow; - extern bool lazyInitialized; - extern HMODULE m_TouchDLL; - extern TouchRegisterWindow_t m_fpTouchRegisterWindow; - extern TouchUnregisterWindow_t m_fpTouchUnregisterWindow; - - -#endif \ No newline at end of file diff --git a/disableTouch/disabletouch2/touchDisable/touchDisable.cpp b/disableTouch/disabletouch2/touchDisable/touchDisable.cpp deleted file mode 100644 index d727df2..0000000 --- a/disableTouch/disabletouch2/touchDisable/touchDisable.cpp +++ /dev/null @@ -1,111 +0,0 @@ -//touchDisable.cpp - -#include -#include "hooks.h" - -#define WM_ENABLETOUCH WM_USER + 5240 - -HINSTANCE g_hInst; - -#define TOUCHWINDOWNAME L"DisableTouch" - -LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - -int WINAPI WinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - //previous instance running - HWND hwndPrev = FindWindow(TOUCHWINDOWNAME, TOUCHWINDOWNAME); - if(hwndPrev!=NULL) - return 2; - - MSG msg = {0}; - WNDCLASS wc = {0}; - wc.lpfnWndProc = WndProc; - wc.hInstance = hInstance; - wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND); - wc.lpszClassName = TOUCHWINDOWNAME; - - if( !RegisterClass(&wc) ) - return 1; - - HWND hWnd = CreateWindow( - wc.lpszClassName, //class - wc.lpszClassName, //title - WS_VISIBLE, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - 0,0, - hInstance, - NULL); - if(hWnd==NULL) - return 2; - - g_hInst=hInstance; - - ShowWindow(hWnd, SW_MINIMIZE);// nCmdShow); - UpdateWindow(hWnd); - - while( GetMessage( &msg, NULL, 0, 0 ) > 0 ){ - TranslateMessage( &msg ); - DispatchMessage( &msg ); - } - - return 0; -} - -LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - HDC hdc; - PAINTSTRUCT ps; - switch(message) - { - case WM_ENABLETOUCH: - PostQuitMessage(2); - break; - case WM_CREATE: - - hookInit(g_hInst); - HookTouchPanel(true); - - break; - case WM_DESTROY: - unloadHook(); - case WM_SHOWWINDOW: - if(wParam==FALSE) //hide minimize - PostQuitMessage(0); - break; - case WM_QUIT: - DestroyWindow(hWnd); - case WM_CLOSE: - PostQuitMessage(0); - break; - case WM_PAINT: - hdc = BeginPaint(hWnd, &ps); - // TODO: Add any drawing code here... - - EndPaint(hWnd, &ps); - break; - case WM_KEYUP: - switch(wParam) - { - case VK_ESCAPE: - { - PostQuitMessage(0); - } - break; - } - break; - case WM_MOUSEMOVE: - DEBUGMSG(1, (L"X:%d Y:%d\n", HIWORD(lParam), LOWORD(lParam))); - break; - case WM_LBUTTONUP: - DEBUGMSG(1, (L"Mouse Click: X:%d Y:%d\n", HIWORD(lParam), LOWORD(lParam))); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - return 0; - -} diff --git a/disableTouch/disabletouch2/touchDisable/touchDisable.vcproj b/disableTouch/disabletouch2/touchDisable/touchDisable.vcproj deleted file mode 100644 index 91dee47..0000000 --- a/disableTouch/disabletouch2/touchDisable/touchDisable.vcproj +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/disableTouch/disabletouch2/touchEnable/hooks.cpp b/disableTouch/disabletouch2/touchEnable/hooks.cpp deleted file mode 100644 index e0f1e25..0000000 --- a/disableTouch/disabletouch2/touchEnable/hooks.cpp +++ /dev/null @@ -1,188 +0,0 @@ -//hooks.cpp -/* -usage: - hookInit() - unloadHook() -*/ - -#include "hooks.h" - -#define LOGDEBUG(msg) DEBUGMSG(1, (msg)) -#define LOGERROR(msg) DEBUGMSG(1, (msg)) - -#define WNDCLASSNAME L"TOUCHLOCKPRO/LOCKEDWINDOW" - -#define TOUCH_SEND_TO_SYSTEM 2 -#define TOUCH_SEND_TO_WINDOW 1 - -bool HookTouchPanelStatus = false; - -static bool hooksInitialized = false; // only initialize once. so we have singleton behaviour -bool touchPanelDisabled = false; // keep track of current status, so we do not apply twice - -//from hooks.h -bool touchPanelWindowRegistered=false; -HINSTANCE m_hInstance; -HWND m_LockedWindow; -bool lazyInitialized; - -HMODULE m_TouchDLL; -TouchRegisterWindow_t m_fpTouchRegisterWindow; -TouchUnregisterWindow_t m_fpTouchUnregisterWindow; -//end hooks.h - -TouchPanelPowerHandler_t m_fpTouchPanelPowerHandler; - -LRESULT TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - if (touchPanelDisabled) { - return 0; - } - return DefWindowProc(hWnd, message, wParam, lParam); -} - -/// Create a new child window in the context of hInstance -void hookInit(HINSTANCE hInstance) { - if (hooksInitialized) - return; - lazyInitialized=false; - hooksInitialized = true; - touchPanelWindowRegistered = false; - m_TouchDLL = NULL; - - LOGDEBUG(L"hookInit"); - - m_hInstance = hInstance; - - WNDCLASS wc; - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = (WNDPROC) TouchPanelHookWndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = sizeof(LONG); - wc.hInstance = hInstance; - wc.hIcon = NULL; - wc.hCursor = 0; - wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; - wc.lpszClassName = WNDCLASSNAME; - RegisterClass(&wc); - - m_LockedWindow = CreateWindowEx(0, WNDCLASSNAME, L"TouchLockPro Panel locked", 0, 0, 0, 0, 0, NULL, NULL, hInstance, NULL); - if (m_LockedWindow == NULL) { - LOGERROR(L"Could not create Locked window"); - MessageBox(NULL, _T("Could not create Locked window"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } else { - if (!InitializeTouchDll()) { - LOGERROR(L"Could not create TouchPanel Hook"); - MessageBox(NULL, _T("Could not create TouchPanel Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - } - } - - //if (!ActivateKBHook()) { - // LOGERROR(L"Could not create Keyboard Hook"); - // MessageBox(NULL, _T("Could not create Keyboard Hook"), _T("Information"), MB_OK | MB_ICONINFORMATION | MB_TOPMOST); - //} - - //CSettings settingsClass; - // pHooksSettingsClass = &settingsClass; -} - -bool InitializeTouchDll() { - LOGDEBUG(L"InitializeTouchDll()"); - if (m_TouchDLL == NULL) { - m_TouchDLL = LoadLibrary(L"touch.dll"); - if(m_TouchDLL != NULL) { - m_fpTouchPanelPowerHandler = (TouchPanelPowerHandler_t)GetProcAddress(m_TouchDLL, L"TouchPanelPowerHandler"); - m_fpTouchRegisterWindow = (TouchRegisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchRegisterWindow")); - m_fpTouchUnregisterWindow = (TouchUnregisterWindow_t)GetProcAddress(m_TouchDLL, _T("TouchUnregisterWindow")); - if ((m_fpTouchPanelPowerHandler != NULL) && (m_fpTouchRegisterWindow != NULL) && (m_fpTouchUnregisterWindow != NULL)) { - return true; // everything Ok - } - } - } else { - LOGERROR(L"Error in initializing Touch dll"); - return false; - } - LOGERROR(L"Error in finding Touch dll register/unregister functions"); - return false; // something wrong -} - -void ShutdownTouchDll() { - LOGDEBUG(L"ShutdownTouchDll()"); - HookTouchPanel(false); - - if (m_TouchDLL != NULL) { - FreeLibrary(m_TouchDLL); - m_TouchDLL = NULL; - } - - m_fpTouchRegisterWindow = NULL; - m_fpTouchUnregisterWindow = NULL; -} - -/// register zero size window with TouchPanelRegisterWindow -/// set zero size window extra memory with TOUCH_SEND_TO_SYSTEM -/// using SetWindowLong(hWnd, 0, x) sets the DWL_MSGRESULT of the window -/// DWL_MSGRESULT: Sets the return value of a message processed in the dialog box procedure -void HookTouchPanel(bool bHook) { - if (HookTouchPanelStatus == bHook) { - LOGDEBUG(L"HookTouchPanel nothing to do"); - return; - } - LOGDEBUG(L"HookTouchPanel"); - HookTouchPanelStatus = bHook; - - if (!lazyInitialized) { - lazyInitialized = true; - SetWindowLong(m_LockedWindow, 0, TOUCH_SEND_TO_SYSTEM); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - - if (bHook && !touchPanelWindowRegistered) { - touchPanelWindowRegistered = true; - BOOL result = m_fpTouchRegisterWindow(m_LockedWindow); - if (!result) { - LOGERROR(L"Error in registering m_LockedWindow"); - } else { - LOGDEBUG(L"TouchRegisterWindow Ok"); - } - } - - SetLastError(0); - LONG nNew; - if(bHook) - nNew = TOUCH_SEND_TO_WINDOW; - else - nNew = TOUCH_SEND_TO_SYSTEM; - ///LONG nNew = bHook ? TOUCH_SEND_TO_WINDOW : TOUCH_SEND_TO_SYSTEM; - LONG prevNew = GetWindowLong(m_LockedWindow, 0); //read DLG_MSG_RESULT - if (prevNew != nNew) { ///if not equal, try a second time to register window - LONG setResult = SetWindowLong(m_LockedWindow, 0, nNew); - if (setResult == 0) { - LOGERROR(L"Error in SetWindowLong"); - } else { - LOGDEBUG(L"SetWindowLong result"); - //SetWindowPos(m_LockedWindow, HWND_BOTTOM, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW); - } - } - - //unregister wanted? - if (!bHook && touchPanelWindowRegistered) { - touchPanelWindowRegistered = false; - m_fpTouchUnregisterWindow(m_LockedWindow); - LOGDEBUG(L"TouchUnregisterWindow done"); - } -} - -void unloadHook() { - LOGDEBUG(L"unloadHook"); - ShutdownTouchDll(); - - if (m_LockedWindow != NULL) { - DestroyWindow(m_LockedWindow); - m_LockedWindow = NULL; - } - UnregisterClass(WNDCLASSNAME, m_hInstance); - - //DeactivateKBHook(); // we are done with the hook. now uninstall it. -} - diff --git a/disableTouch/disabletouch2/touchEnable/hooks.h b/disableTouch/disabletouch2/touchEnable/hooks.h deleted file mode 100644 index ff71b17..0000000 --- a/disableTouch/disabletouch2/touchEnable/hooks.h +++ /dev/null @@ -1,32 +0,0 @@ -//hooks.h - -#pragma once -#if !defined(TOUCHLOCKPRO_HOOKS_H_INCLUDED_) -#define TOUCHLOCKPRO_HOOKS_H_INCLUDED_ - -#include - static LRESULT CALLBACK TouchPanelHookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - - typedef BOOL (*TouchRegisterWindow_t)(HWND hWnd); - - typedef void (*TouchUnregisterWindow_t)(HWND hWnd); - - typedef VOID (*TouchPanelPowerHandler_t)(BOOL bOff); - - typedef BOOL (*SetKMode_t)(BOOL fMode); - void HookTouchPanel(bool bHook); - bool InitializeTouchDll(); - - void hookInit(HINSTANCE hInstance); - void unloadHook(); - - extern bool touchPanelWindowRegistered; - extern HINSTANCE m_hInstance; - extern HWND m_LockedWindow; - extern bool lazyInitialized; - extern HMODULE m_TouchDLL; - extern TouchRegisterWindow_t m_fpTouchRegisterWindow; - extern TouchUnregisterWindow_t m_fpTouchUnregisterWindow; - - -#endif \ No newline at end of file diff --git a/disableTouch/disabletouch2/touchEnable/touchEnable.cpp b/disableTouch/disabletouch2/touchEnable/touchEnable.cpp deleted file mode 100644 index 6cac6b6..0000000 --- a/disableTouch/disabletouch2/touchEnable/touchEnable.cpp +++ /dev/null @@ -1,25 +0,0 @@ -//touchEnable.cpp - -//shutdown existing DisableTouch window - -#include -#include "hooks.h" - -#define WM_ENABLETOUCH WM_USER + 5240 -#define TOUCHWINDOWNAME L"DisableTouch" - -int _tmain(int argc, _TCHAR* argv[]) -{ - HWND hwndTouchDisable = FindWindow(TOUCHWINDOWNAME, TOUCHWINDOWNAME); - if(hwndTouchDisable!=NULL){ - DEBUGMSG(1, (L"Posting quit to '%s'\n", TOUCHWINDOWNAME)); - PostMessage(hwndTouchDisable, WM_ENABLETOUCH, 0, 0); - return 1; - } - else{ - DEBUGMSG(1, (L"No window found: '%s'\n", TOUCHWINDOWNAME)); - return -1; - } - - return 0; -} \ No newline at end of file diff --git a/disableTouch/disabletouch2/touchEnable/touchEnable.vcproj b/disableTouch/disabletouch2/touchEnable/touchEnable.vcproj deleted file mode 100644 index 440aaca..0000000 --- a/disableTouch/disabletouch2/touchEnable/touchEnable.vcproj +++ /dev/null @@ -1,236 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gps8/Gps8/GPS_Sample8/CommAPI.cs b/gps8/Gps8/GPS_Sample8/CommAPI.cs deleted file mode 100644 index 2da4445..0000000 --- a/gps8/Gps8/GPS_Sample8/CommAPI.cs +++ /dev/null @@ -1,765 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.IO.Serial.CommAPI -// Copyright (c) 2003-2005, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Runtime.InteropServices; -using System.Collections.Specialized; - -namespace OpenNETCF.IO.Serial -{ - #region API structs and enums - - [StructLayout(LayoutKind.Sequential)] - internal class CommTimeouts - { - public UInt32 ReadIntervalTimeout; - public UInt32 ReadTotalTimeoutMultiplier; - public UInt32 ReadTotalTimeoutConstant; - public UInt32 WriteTotalTimeoutMultiplier; - public UInt32 WriteTotalTimeoutConstant; - } - - [StructLayout( LayoutKind.Sequential )] - internal struct OVERLAPPED - { - internal UIntPtr Internal; - internal UIntPtr InternalHigh; - internal UInt32 Offset; - internal UInt32 OffsetHigh; - internal IntPtr hEvent; - } - - /// - /// Event Flags - /// - [Flags] - public enum CommEventFlags : int - { - /// - /// No flags - /// - NONE = 0x0000, // - /// - /// Event on receive - /// - RXCHAR = 0x0001, // Any Character received - /// - /// Event when specific character is received - /// - RXFLAG = 0x0002, // Received specified flag character - /// - /// Event when the transmit buffer is empty - /// - TXEMPTY = 0x0004, // Tx buffer Empty - /// - /// Event on CTS state change - /// - CTS = 0x0008, // CTS changed - /// - /// Event on DSR state change - /// - DSR = 0x0010, // DSR changed - /// - /// Event on RLSD state change - /// - RLSD = 0x0020, // RLSD changed - /// - /// Event on BREAK - /// - BREAK = 0x0040, // BREAK received - /// - /// Event on line error - /// - ERR = 0x0080, // Line status error - /// - /// Event on ring detect - /// - RING = 0x0100, // ring detected - /// - /// Event on printer error - /// - PERR = 0x0200, // printer error - /// - /// Event on 80% high-water - /// - RX80FULL = 0x0400, // rx buffer is at 80% - /// - /// Provider event 1 - /// - EVENT1 = 0x0800, // provider event - /// - /// Provider event 2 - /// - EVENT2 = 0x1000, // provider event - /// - /// Event on CE power notification - /// - POWER = 0x2000, // wince power notification - /// - /// Mask for all flags under CE - /// - ALLCE = 0x3FFF, // mask of all flags for CE - ALLCE_2 = BREAK | CTS | DSR | ERR | RING | RLSD | RXCHAR | RXFLAG, - /// - /// Mask for all flags under desktop Windows - /// - ALLPC = BREAK | CTS | DSR | ERR | RING | RLSD | RXCHAR | RXFLAG | TXEMPTY - } - - internal enum EventFlags - { - EVENT_PULSE = 1, - EVENT_RESET = 2, - EVENT_SET = 3 - } - - /// - /// Error flags - /// - [Flags] - public enum CommErrorFlags : int - { - /// - /// Receive overrun - /// - RXOVER = 0x0001, - /// - /// Overrun - /// - OVERRUN = 0x0002, - /// - /// Parity error - /// - RXPARITY = 0x0004, - /// - /// Frame error - /// - FRAME = 0x0008, - /// - /// BREAK received - /// - BREAK = 0x0010, - /// - /// Transmit buffer full - /// - TXFULL = 0x0100, - /// - /// IO Error - /// - IOE = 0x0400, - /// - /// Requested mode not supported - /// - MODE = 0x8000 - } - - /// - /// Modem status flags - /// - [Flags] - public enum CommModemStatusFlags : int - { - /// - /// The CTS (Clear To Send) signal is on. - /// - MS_CTS_ON = 0x0010, - /// - /// The DSR (Data Set Ready) signal is on. - /// - MS_DSR_ON = 0x0020, - /// - /// The ring indicator signal is on. - /// - MS_RING_ON = 0x0040, - /// - /// The RLSD (Receive Line Signal Detect) signal is on. - /// - MS_RLSD_ON = 0x0080 - } - - /// - /// Communication escapes - /// - internal enum CommEscapes : uint - { - /// - /// Causes transmission to act as if an XOFF character has been received. - /// - SETXOFF = 1, - /// - /// Causes transmission to act as if an XON character has been received. - /// - SETXON = 2, - /// - /// Sends the RTS (Request To Send) signal. - /// - SETRTS = 3, - /// - /// Clears the RTS (Request To Send) signal - /// - CLRRTS = 4, - /// - /// Sends the DTR (Data Terminal Ready) signal. - /// - SETDTR = 5, - /// - /// Clears the DTR (Data Terminal Ready) signal. - /// - CLRDTR = 6, - /// - /// Suspends character transmission and places the transmission line in a break state until the ClearCommBreak function is called (or EscapeCommFunction is called with the CLRBREAK extended function code). The SETBREAK extended function code is identical to the SetCommBreak function. This extended function does not flush data that has not been transmitted. - /// - SETBREAK = 8, - /// - /// Restores character transmission and places the transmission line in a nonbreak state. The CLRBREAK extended function code is identical to the ClearCommBreak function - /// - CLRBREAK = 9, - ///Set the port to IR mode. - SETIR = 10, - /// - /// Set the port to non-IR mode. - /// - CLRIR = 11 - } - - /// - /// Error values from serial API calls - /// - internal enum APIErrors : int - { - /// - /// Port not found - /// - ERROR_FILE_NOT_FOUND = 2, - /// - /// Invalid port name - /// - ERROR_INVALID_NAME = 123, - /// - /// Access denied - /// - ERROR_ACCESS_DENIED = 5, - /// - /// invalid handle - /// - ERROR_INVALID_HANDLE = 6, - /// - /// IO pending - /// - ERROR_IO_PENDING = 997 - } - - internal enum APIConstants : uint - { - WAIT_OBJECT_0 = 0x00000000, - WAIT_ABANDONED = 0x00000080, - WAIT_ABANDONED_0 = 0x00000080, - WAIT_FAILED = 0xffffffff, - INFINITE = 0xffffffff - } - #endregion - - - [StructLayout(LayoutKind.Sequential)] - internal class CommStat - { - // - // typedef struct _COMSTAT { - // DWORD fCtsHold : 1; - // DWORD fDsrHold : 1; - // DWORD fRlsdHold : 1; - // DWORD fXoffHold : 1; - // DWORD fXoffSent : 1; - // DWORD fEof : 1; - // DWORD fTxim : 1; - // DWORD fReserved : 25; - // DWORD cbInQue; - // DWORD cbOutQue; - // } COMSTAT, *LPCOMSTAT; - // - private BitVector32 bitfield = new BitVector32(0); // UKI added for CLR bitfield support - public UInt32 cbInQue = 0; - public UInt32 cbOutQue = 0; - - // Helper constants for manipulating the bit fields. - - [Flags] - private enum commFlags - { - fCtsHoldMask = 0x01, - fDsrHoldMask = 0x02, - fRlsdHoldMask = 0x04, - fXoffHoldMask = 0x08, - fXoffSentMask = 0x10, - fEofMask = 0x20, - fTximMask = 0x40 - - }; - - public bool fCtsHold - { - get { return bitfield[(int)commFlags.fCtsHoldMask]; } - set { bitfield[(int)commFlags.fCtsHoldMask]=value; } - } - public bool fDsrHold - { - get { return bitfield[(int)commFlags.fDsrHoldMask]; } - set { bitfield[(int)commFlags.fDsrHoldMask] = value; } - } - public bool fRlsdHold - { - get { return bitfield[(int)commFlags.fRlsdHoldMask]; } - set { bitfield[(int)commFlags.fRlsdHoldMask]= value; } - } - public bool fXoffHold - { - get { return bitfield[(int)commFlags.fXoffHoldMask]; } - set { bitfield[(int)commFlags.fXoffHoldMask]=value; } - } - public bool fXoffSent - { - get { return bitfield[(int)commFlags.fXoffSentMask]; } - set { bitfield[(int)commFlags.fXoffSentMask]= value; } - } - public bool fEof - { - get { return bitfield[(int)commFlags.fEofMask]; } - set { bitfield[(int)commFlags.fEofMask] = value; } - } - public bool fTxim - { - get { return bitfield[(int)commFlags.fTximMask]; } - set { bitfield[(int)commFlags.fTximMask] = value; } - } - } - - #region CommAPI base class - internal abstract class CommAPI - { - // These functions wrap the P/Invoked API calls and: - // - make the correct call based on whether we're running under the full or compact framework - // - eliminate empty parameters and defaults - // - static internal bool bFullFramework; - - static CommAPI() - { - bFullFramework=System.Environment.OSVersion.Platform != PlatformID.WinCE; - } - - #region ----- virtual function declarations ----- - internal virtual IntPtr CreateFile(string FileName){return (IntPtr)0L;} - internal virtual IntPtr QueryFile(string FileName){return (IntPtr)0L;} - internal virtual bool WaitCommEvent(IntPtr hPort, ref CommEventFlags flags){return false;} - internal virtual bool ClearCommError(IntPtr hPort, ref CommErrorFlags flags, CommStat stat){return false;} - internal virtual bool GetCommModemStatus(IntPtr hPort, ref uint lpModemStat){return false;} - internal virtual bool SetCommMask(IntPtr hPort, CommEventFlags dwEvtMask) {return false;} - internal virtual bool ReadFile(IntPtr hPort, byte[] buffer, int cbToRead, ref Int32 cbRead, IntPtr lpOverlapped) {return false;} - internal virtual bool WriteFile(IntPtr hPort, byte[] buffer, Int32 cbToWrite, ref Int32 cbWritten, IntPtr lpOverlapped) {return false;} - internal virtual bool CloseHandle(IntPtr hPort) {return false;} - internal virtual bool SetupComm(IntPtr hPort, Int32 dwInQueue, Int32 dwOutQueue) {return false;} - internal virtual bool SetCommState(IntPtr hPort, DCB dcb){return false;} - internal virtual bool GetCommState(IntPtr hPort, DCB dcb){return false;} - internal virtual bool SetCommTimeouts(IntPtr hPort, CommTimeouts timeouts) {return false;} - internal virtual bool EscapeCommFunction(IntPtr hPort, CommEscapes escape){return false;} - internal virtual IntPtr CreateEvent(bool bManualReset, bool bInitialState, string lpName) {return (IntPtr)0L;} - internal virtual bool SetEvent(IntPtr hEvent) {return false;} - internal virtual bool ResetEvent(IntPtr hEvent) {return false;} - internal virtual bool PulseEvent(IntPtr hEvent) {return false;} - internal virtual int WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds) {return 0;} - internal virtual int PurgeComm(IntPtr hPort, int dwFlags){return 0;} - internal virtual bool GetCommProperties(IntPtr hPort, CommCapabilities commcap) {return false;} - internal virtual bool GetOverlappedResult(IntPtr hPort, IntPtr lpOverlapped, out Int32 lpNumberOfBytesTransferred, bool bWait) {lpNumberOfBytesTransferred = 0; return false;} - #endregion - - #region Helper Property - - static internal bool FullFramework - { - get{return bFullFramework;} - } - #endregion - - #region API Constants - internal const Int32 INVALID_HANDLE_VALUE = -1; - internal const UInt32 OPEN_EXISTING = 3; - internal const UInt32 GENERIC_READ = 0x80000000; - internal const UInt32 GENERIC_WRITE = 0x40000000; - internal const UInt32 FILE_FLAG_OVERLAPPED = 0x40000000; - internal const UInt32 CreateAccess = GENERIC_WRITE | GENERIC_READ; - /// - /// Overlapped I/O operation is in progress. - /// - internal const UInt32 ERROR_IO_PENDING = 997; - #endregion - - } - #endregion - - #region CE CompactFramework (cf) implementation for CommAPI - internal class CECommAPI : CommAPI - { - override internal IntPtr CreateFile(string FileName) - { - return CECreateFileW(FileName, CreateAccess, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); - } - - // setting AccessMask to 0 returns a handle we can use to query the device without accessing it - override internal IntPtr QueryFile(string FileName) - { - return CECreateFileW(FileName, 0, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); - } - - override internal bool WaitCommEvent(IntPtr hPort, ref CommEventFlags flags) - { - return Convert.ToBoolean(CEWaitCommEvent(hPort, ref flags, IntPtr.Zero)); - } - - override internal bool ClearCommError(IntPtr hPort, ref CommErrorFlags flags, CommStat stat) - { - return Convert.ToBoolean(CEClearCommError(hPort, ref flags, stat)); - } - - override internal bool GetCommModemStatus(IntPtr hPort, ref uint lpModemStat) - { - return Convert.ToBoolean(CEGetCommModemStatus(hPort, ref lpModemStat)); - } - - override internal bool SetCommMask(IntPtr hPort, CommEventFlags dwEvtMask) - { - return Convert.ToBoolean(CESetCommMask(hPort, dwEvtMask)); - } - - override internal bool ReadFile(IntPtr hPort, byte[] buffer, int cbToRead, ref Int32 cbRead, IntPtr lpOverlapped) - { - return Convert.ToBoolean(CEReadFile(hPort, buffer, cbToRead, ref cbRead, IntPtr.Zero)); - } - - override internal bool WriteFile(IntPtr hPort, byte[] buffer, Int32 cbToWrite, ref Int32 cbWritten, IntPtr lpOverlapped) - { - return Convert.ToBoolean(CEWriteFile(hPort, buffer, cbToWrite, out cbWritten, IntPtr.Zero)); - } - - override internal bool CloseHandle(IntPtr hPort) - { - return Convert.ToBoolean(CECloseHandle(hPort)); - } - - override internal bool SetupComm(IntPtr hPort, Int32 dwInQueue, Int32 dwOutQueue) - { - return Convert.ToBoolean(CESetupComm(hPort, dwInQueue, dwOutQueue)); - } - - override internal bool SetCommState(IntPtr hPort, DCB dcb) - { - return Convert.ToBoolean(CESetCommState(hPort, dcb)); - } - - override internal bool GetCommState(IntPtr hPort, DCB dcb) - { - return Convert.ToBoolean(CEGetCommState(hPort, dcb)); - } - - override internal bool SetCommTimeouts(IntPtr hPort, CommTimeouts timeouts) - { - return Convert.ToBoolean(CESetCommTimeouts(hPort, timeouts)); - } - - override internal bool EscapeCommFunction(IntPtr hPort, CommEscapes escape) - { - return Convert.ToBoolean(CEEscapeCommFunction(hPort, (uint)escape)); - } - - override internal IntPtr CreateEvent(bool bManualReset, bool bInitialState, string lpName) - { - return CECreateEvent(IntPtr.Zero, Convert.ToInt32(bManualReset), Convert.ToInt32(bInitialState), lpName); - } - - override internal bool SetEvent(IntPtr hEvent) - { - return Convert.ToBoolean(CEEventModify(hEvent, (uint)EventFlags.EVENT_SET)); - } - - override internal bool ResetEvent(IntPtr hEvent) - { - return Convert.ToBoolean(CEEventModify(hEvent, (uint)EventFlags.EVENT_RESET)); - } - - override internal bool PulseEvent(IntPtr hEvent) - { - return Convert.ToBoolean(CEEventModify(hEvent, (uint)EventFlags.EVENT_PULSE)); - } - - override internal int WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds) - { - return CEWaitForSingleObject(hHandle, dwMilliseconds); - } - internal override int PurgeComm(IntPtr hPort, int dwFlags) { - return CEPurgeComm (hPort, dwFlags); - } - - override internal bool GetCommProperties(IntPtr hPort, CommCapabilities commcap) - { - return Convert.ToBoolean(CEGetCommProperties(hPort, commcap)); - } - #region Windows CE API imports - [DllImport("coredll.dll", EntryPoint="PurgeComm", SetLastError = true)] - private static extern int CEPurgeComm(IntPtr hPort, int dwFlags); - - [DllImport("coredll.dll", EntryPoint="WaitForSingleObject", SetLastError = true)] - private static extern int CEWaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); - - [DllImport("coredll.dll", EntryPoint="EventModify", SetLastError = true)] - private static extern int CEEventModify(IntPtr hEvent, uint function); - - [DllImport("coredll.dll", EntryPoint="CreateEvent", SetLastError = true)] - private static extern IntPtr CECreateEvent(IntPtr lpEventAttributes, int bManualReset, int bInitialState, string lpName); - - [DllImport("coredll.dll", EntryPoint="EscapeCommFunction", SetLastError = true)] - private static extern int CEEscapeCommFunction(IntPtr hFile, UInt32 dwFunc); - - [DllImport("coredll.dll", EntryPoint="SetCommTimeouts", SetLastError = true)] - private static extern int CESetCommTimeouts(IntPtr hFile, CommTimeouts timeouts); - - [DllImport("coredll.dll", EntryPoint="GetCommState", SetLastError = true)] - private static extern int CEGetCommState(IntPtr hFile, DCB dcb); - - [DllImport("coredll.dll", EntryPoint="SetCommState", SetLastError = true)] - private static extern int CESetCommState(IntPtr hFile, DCB dcb); - - [DllImport("coredll.dll", EntryPoint="SetupComm", SetLastError = true)] - private static extern int CESetupComm(IntPtr hFile, Int32 dwInQueue, Int32 dwOutQueue); - - [DllImport("coredll.dll", EntryPoint="CloseHandle", SetLastError = true)] - private static extern int CECloseHandle(IntPtr hObject); - - [DllImport("coredll.dll", EntryPoint="WriteFile", SetLastError = true)] - private static extern int CEWriteFile(IntPtr hFile, byte[] lpBuffer, Int32 nNumberOfBytesToRead, out Int32 lpNumberOfBytesRead, IntPtr lpOverlapped); - - [DllImport("coredll.dll", EntryPoint="ReadFile", SetLastError = true)] - private static extern int CEReadFile(IntPtr hFile, byte[] lpBuffer, Int32 nNumberOfBytesToRead, ref Int32 lpNumberOfBytesRead, IntPtr lpOverlapped); - - [DllImport("coredll.dll", EntryPoint="SetCommMask", SetLastError = true)] - private static extern int CESetCommMask(IntPtr handle, CommEventFlags dwEvtMask); - - [DllImport("coredll.dll", EntryPoint="GetCommModemStatus", SetLastError = true)] - private static extern int CEGetCommModemStatus(IntPtr hFile, ref uint lpModemStat); - - [DllImport("coredll.dll", EntryPoint="ClearCommError", SetLastError = true)] - private static extern int CEClearCommError(IntPtr hFile, ref CommErrorFlags lpErrors, CommStat lpStat); - - [DllImport("coredll.dll", EntryPoint="WaitCommEvent", SetLastError = true)] - private static extern int CEWaitCommEvent(IntPtr hFile, ref CommEventFlags lpEvtMask, IntPtr lpOverlapped); - - [DllImport("coredll.dll", EntryPoint="CreateFileW", SetLastError = true)] - private static extern IntPtr CECreateFileW( - String lpFileName, UInt32 dwDesiredAccess, UInt32 dwShareMode, - IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition, UInt32 dwFlagsAndAttributes, - IntPtr hTemplateFile); - - [DllImport("coredll.dll", EntryPoint="GetCommProperties", SetLastError=true)] - private static extern int CEGetCommProperties(IntPtr hFile, CommCapabilities commcap); - #endregion - - } - # endregion - - #region Full Framework (aka Win) implementation for CommAPI - internal class WinCommAPI:CommAPI - { - override internal IntPtr CreateFile(string FileName) - { - return WinCreateFileW(FileName, CreateAccess, 0, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero); - } - - // setting AccessMask to 0 returns a handle we can use to query the device without accessing it - override internal IntPtr QueryFile(string FileName) - { - return WinCreateFileW(FileName, 0, 0, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero); - } - - override internal bool WaitCommEvent(IntPtr hPort, ref CommEventFlags flags) - { - return Convert.ToBoolean(WinWaitCommEvent(hPort, ref flags, IntPtr.Zero)); - } - - override internal bool ClearCommError(IntPtr hPort, ref CommErrorFlags flags, CommStat stat) - { - return Convert.ToBoolean(WinClearCommError(hPort, ref flags, stat)); - } - - override internal bool GetCommModemStatus(IntPtr hPort, ref uint lpModemStat) - { - return Convert.ToBoolean(WinGetCommModemStatus(hPort, ref lpModemStat)); - } - - override internal bool SetCommMask(IntPtr hPort, CommEventFlags dwEvtMask) - { - return Convert.ToBoolean(WinSetCommMask(hPort, dwEvtMask)); - } - - override internal bool ReadFile(IntPtr hPort, byte[] buffer, int cbToRead, ref Int32 cbRead, IntPtr lpOverlapped) - { - return Convert.ToBoolean(WinReadFile(hPort, buffer, cbToRead, ref cbRead, lpOverlapped)); - } - - override internal bool WriteFile(IntPtr hPort, byte[] buffer, Int32 cbToWrite, ref Int32 cbWritten, IntPtr lpOverlapped) - { - return Convert.ToBoolean(WinWriteFile(hPort, buffer, cbToWrite, ref cbWritten, lpOverlapped)); - } - - override internal bool CloseHandle(IntPtr hPort) - { - return Convert.ToBoolean(WinCloseHandle(hPort)); - } - - override internal bool SetupComm(IntPtr hPort, Int32 dwInQueue, Int32 dwOutQueue) - { - return Convert.ToBoolean(WinSetupComm(hPort, dwInQueue, dwOutQueue)); - } - - override internal bool SetCommState(IntPtr hPort, DCB dcb) - { - return Convert.ToBoolean(WinSetCommState(hPort, dcb)); - } - - override internal bool GetCommState(IntPtr hPort, DCB dcb) - { - return Convert.ToBoolean(WinGetCommState(hPort, dcb)); - } - - override internal bool SetCommTimeouts(IntPtr hPort, CommTimeouts timeouts) - { - return Convert.ToBoolean(WinSetCommTimeouts(hPort, timeouts)); - } - - override internal bool EscapeCommFunction(IntPtr hPort, CommEscapes escape) - { - return Convert.ToBoolean(WinEscapeCommFunction(hPort, (uint)escape)); - } - - override internal IntPtr CreateEvent(bool bManualReset, bool bInitialState, string lpName) - { - return WinCreateEvent(IntPtr.Zero, Convert.ToInt32(bManualReset), Convert.ToInt32(bInitialState), lpName); - } - - override internal bool SetEvent(IntPtr hEvent) - { - return Convert.ToBoolean(WinSetEvent(hEvent)); - } - - override internal bool ResetEvent(IntPtr hEvent) - { - return Convert.ToBoolean(WinResetEvent(hEvent)); - } - - override internal bool PulseEvent(IntPtr hEvent) - { - return Convert.ToBoolean(WinPulseEvent(hEvent)); - } - - override internal int WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds) - { - return WinWaitForSingleObject(hHandle, dwMilliseconds); - } - - override internal bool GetCommProperties(IntPtr hPort, CommCapabilities commcap) - { - return Convert.ToBoolean(WinGetCommProperties(hPort, commcap)); - } - - override internal bool GetOverlappedResult(IntPtr hPort, IntPtr lpOverlapped, out Int32 lpNumberOfBytesTransferred, bool bWait) - { - return WinGetOverlappedResult(hPort, lpOverlapped, out lpNumberOfBytesTransferred, bWait); - } - - #region Desktop Windows API imports - - [DllImport("kernel32.dll", EntryPoint="WaitForSingleObject", SetLastError = true)] - private static extern int WinWaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); - - [DllImport("kernel32.dll", EntryPoint="SetEvent", SetLastError = true)] - private static extern int WinSetEvent(IntPtr hEvent); - - [DllImport("kernel32.dll", EntryPoint="ResetEvent", SetLastError = true)] - private static extern int WinResetEvent(IntPtr hEvent); - - [DllImport("kernel32.dll", EntryPoint="PulseEvent", SetLastError = true)] - private static extern int WinPulseEvent(IntPtr hEvent); - - [DllImport("kernel32.dll", EntryPoint="CreateEvent", SetLastError = true)] - private static extern IntPtr WinCreateEvent(IntPtr lpEventAttributes, int bManualReset, int bInitialState, string lpName); - - [DllImport("kernel32.dll", EntryPoint="EscapeCommFunction", SetLastError = true)] - private static extern int WinEscapeCommFunction(IntPtr hFile, UInt32 dwFunc); - - [DllImport("kernel32.dll", EntryPoint="SetCommTimeouts", SetLastError = true)] - private static extern int WinSetCommTimeouts(IntPtr hFile, CommTimeouts timeouts); - - [DllImport("kernel32.dll", EntryPoint="GetCommState", SetLastError = true)] - private static extern int WinGetCommState(IntPtr hFile, DCB dcb); - - [DllImport("kernel32.dll", EntryPoint="SetCommState", SetLastError = true)] - private static extern int WinSetCommState(IntPtr hFile, DCB dcb); - - [DllImport("kernel32.dll", EntryPoint="SetupComm", SetLastError = true)] - private static extern int WinSetupComm(IntPtr hFile, Int32 dwInQueue, Int32 dwOutQueue); - - [DllImport("kernel32.dll", EntryPoint="CloseHandle", SetLastError = true)] - private static extern int WinCloseHandle(IntPtr hObject); - - [DllImport("kernel32.dll", EntryPoint="WriteFile", SetLastError = true)] - private static extern int WinWriteFile(IntPtr hFile, byte[] lpBuffer, Int32 nNumberOfBytesToRead, ref Int32 lpNumberOfBytesRead, IntPtr lpOverlapped); - - [DllImport("kernel32.dll", EntryPoint="ReadFile", SetLastError = true)] - private static extern int WinReadFile(IntPtr hFile, byte[] lpBuffer, Int32 nNumberOfBytesToRead, ref Int32 lpNumberOfBytesRead, IntPtr lpOverlapped); - - [DllImport("kernel32.dll", EntryPoint="SetCommMask", SetLastError = true)] - private static extern int WinSetCommMask(IntPtr handle, CommEventFlags dwEvtMask); - - [DllImport("kernel32.dll", EntryPoint="GetCommModemStatus", SetLastError = true)] - private static extern int WinGetCommModemStatus(IntPtr hFile, ref uint lpModemStat); - - [DllImport("kernel32.dll", EntryPoint="ClearCommError", SetLastError = true)] - private static extern int WinClearCommError(IntPtr hFile, ref CommErrorFlags lpErrors, CommStat lpStat); - - [DllImport("kernel32.dll", EntryPoint="CreateFileW", SetLastError = true, CharSet = CharSet.Unicode)] - private static extern IntPtr WinCreateFileW(String lpFileName, UInt32 dwDesiredAccess, UInt32 dwShareMode, - IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition, UInt32 dwFlagsAndAttributes, - IntPtr hTemplateFile); - - [DllImport("kernel32.dll", EntryPoint="WaitCommEvent", SetLastError = true)] - private static extern int WinWaitCommEvent(IntPtr hFile, ref CommEventFlags lpEvtMask, IntPtr lpOverlapped); - - [DllImport("kernel32.dll", EntryPoint="GetCommProperties", SetLastError=true)] - private static extern int WinGetCommProperties(IntPtr hFile, CommCapabilities commcap); - - [DllImport("kernel32.dll", EntryPoint="GetOverlappedResult", SetLastError=true)] - private static extern bool WinGetOverlappedResult(IntPtr hFile, IntPtr lpOverlapped, out Int32 lpNumberOfBytesTransferred, bool bWait); - - #endregion - } - #endregion -} - - diff --git a/gps8/Gps8/GPS_Sample8/DCB.cs b/gps8/Gps8/GPS_Sample8/DCB.cs deleted file mode 100644 index 454b588..0000000 --- a/gps8/Gps8/GPS_Sample8/DCB.cs +++ /dev/null @@ -1,250 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.IO.Serial.DCB -// Copyright (c) 2003, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== - -using System; -using System.Text; -using System.IO; -using System.Runtime.InteropServices; -using System.Collections.Specialized; - -namespace OpenNETCF.IO.Serial -{ - - // - // The Win32 DCB structure is implemented below in a C# class. - // - - [StructLayout(LayoutKind.Sequential)] - internal class DCB - { - private UInt32 DCBlength; - public UInt32 BaudRate; - BitVector32 Control; - internal UInt16 wReserved; - public UInt16 XonLim; - public UInt16 XoffLim; - public byte ByteSize; - public byte Parity; - public byte StopBits; - public sbyte XonChar; - public sbyte XoffChar; - public sbyte ErrorChar; - public sbyte EofChar; - public sbyte EvtChar; - internal UInt16 wReserved1; - - private readonly BitVector32.Section sect1; - private readonly BitVector32.Section DTRsect; - private readonly BitVector32.Section sect2; - private readonly BitVector32.Section RTSsect; - - public DCB() - { - // - // Initialize the length of the structure. Marshal.SizeOf returns - // the size of the unmanaged object (basically the object that - // gets marshalled). - // - this.DCBlength = (uint)Marshal.SizeOf(this); - - // initialize BitVector32 - Control=new BitVector32(0); - - // of the following 4 sections only 2 are needed - sect1=BitVector32.CreateSection(0x0f); - DTRsect=BitVector32.CreateSection(3,sect1); // this is where the DTR setting is stored - sect2=BitVector32.CreateSection(0x3f,DTRsect); - RTSsect=BitVector32.CreateSection(3,sect2); // this is where the RTS setting is stored - } - - - - // - // We need to have to define reserved fields in the DCB class definition - // to preserve the size of the - // underlying structure to match the Win32 structure when it is - // marshaled. Use these fields to suppress compiler warnings. - // - internal void _SuppressCompilerWarnings() - { - wReserved +=0; - wReserved1 +=0; - } - - // - // Enumeration for fDtrControl bit field. - // - public enum DtrControlFlags - { - Disable = 0, - Enable =1 , - Handshake = 2 - } - - // - // Enumeration for fRtsControl bit field. - // - public enum RtsControlFlags - { - Disable = 0, - Enable = 1, - Handshake = 2, - Toggle = 3 - } - - // Helper constants for manipulating the bit fields. - // these are defined as an enum in order to preserve memory - [Flags] - enum ctrlBit { - fBinaryMask = 0x001, - fParityMask = 0x0002, - fOutxCtsFlowMask = 0x0004, - fOutxDsrFlowMask = 0x0008, - fDtrControlMask = 0x0030, - fDsrSensitivityMask = 0x0040, - fTXContinueOnXoffMask = 0x0080, - fOutXMask = 0x0100, - fInXMask = 0x0200, - fErrorCharMask = 0x0400, - fNullMask = 0x0800, - fRtsControlMask = 0x3000, - fAbortOnErrorMask = 0x4000 - } - - // get and set of bool works with the underlying BitVector32 - // by using a mask for each bit field we can let the compiler - // and JIT do the work - // - - public bool fBinary - { - get { return (Control[(int)ctrlBit.fBinaryMask]); } - set { Control[(int)ctrlBit.fBinaryMask]=value; } - } - public bool fParity - { - get { return (Control[(int)ctrlBit.fParityMask]); } - set { Control[(int)ctrlBit.fParityMask]=value; } - } - public bool fOutxCtsFlow - { - get { return (Control[(int)ctrlBit.fOutxCtsFlowMask]); } - set { Control[(int)ctrlBit.fOutxCtsFlowMask] = value; } - } - public bool fOutxDsrFlow - { - get { return (Control[(int)ctrlBit.fOutxDsrFlowMask]); } - set { Control[(int)ctrlBit.fOutxDsrFlowMask]=value; } - } - - // we have to use a segment because the width of the underlying information - // is wider than just one bit - public byte fDtrControl - { - get {return (byte)Control[DTRsect]; } - set { Control[DTRsect]=(int)value; } - } - - public bool fDsrSensitivity - { - get { return Control[(int)ctrlBit.fDsrSensitivityMask];} - set { Control[(int)ctrlBit.fDsrSensitivityMask] = value; } - } - public bool fTXContinueOnXoff - { - get { return Control[(int)ctrlBit.fTXContinueOnXoffMask]; } - set { Control[(int)ctrlBit.fTXContinueOnXoffMask]=value; } - } - public bool fOutX - { - get { return Control [(int)ctrlBit.fOutXMask]; } - set { Control[(int)ctrlBit.fOutXMask]=value; } - } - public bool fInX - { - get { return Control[(int)ctrlBit.fInXMask]; } - set { Control[(int)ctrlBit.fInXMask]=value; } - } - public bool fErrorChar - { - get { return Control[(int)ctrlBit.fErrorCharMask]; } - set { Control[(int)ctrlBit.fErrorCharMask]=value; } - } - public bool fNull - { - get { return Control[(int)ctrlBit.fNullMask]; } - set { Control[(int)ctrlBit.fNullMask]=value; } - } - - // we have to use a segment because the width of the underlying information - // is wider than just one bit - public byte fRtsControl - { - get { return (byte)Control[RTSsect]; } - set { Control[RTSsect]=(int)value; } - } - - public bool fAbortOnError - { - get { return Control[(int)ctrlBit.fAbortOnErrorMask]; } - set { Control[(int)ctrlBit.fAbortOnErrorMask]=value; } - } - - // - // Method to dump the DCB to take a look and help debug issues. - // - public override String ToString() - { - StringBuilder sb = new StringBuilder(); - - sb.Append("DCB:\r\n"); - sb.AppendFormat(null, " BaudRate: {0}\r\n", BaudRate); - sb.AppendFormat(null, " Control: 0x{0:x}\r\n", Control.Data); - sb.AppendFormat(null, " fBinary: {0}\r\n", fBinary); - sb.AppendFormat(null, " fParity: {0}\r\n", fParity); - sb.AppendFormat(null, " fOutxCtsFlow: {0}\r\n", fOutxCtsFlow); - sb.AppendFormat(null, " fOutxDsrFlow: {0}\r\n", fOutxDsrFlow); - sb.AppendFormat(null, " fDtrControl: {0}\r\n", fDtrControl); - sb.AppendFormat(null, " fDsrSensitivity: {0}\r\n", fDsrSensitivity); - sb.AppendFormat(null, " fTXContinueOnXoff: {0}\r\n", fTXContinueOnXoff); - sb.AppendFormat(null, " fOutX: {0}\r\n", fOutX); - sb.AppendFormat(null, " fInX: {0}\r\n", fInX); - sb.AppendFormat(null, " fNull: {0}\r\n", fNull); - sb.AppendFormat(null, " fRtsControl: {0}\r\n", fRtsControl); - sb.AppendFormat(null, " fAbortOnError: {0}\r\n", fAbortOnError); - sb.AppendFormat(null, " XonLim: {0}\r\n", XonLim); - sb.AppendFormat(null, " XoffLim: {0}\r\n", XoffLim); - sb.AppendFormat(null, " ByteSize: {0}\r\n", ByteSize); - sb.AppendFormat(null, " Parity: {0}\r\n", Parity); - sb.AppendFormat(null, " StopBits: {0}\r\n", StopBits); - sb.AppendFormat(null, " XonChar: {0}\r\n", XonChar); - sb.AppendFormat(null, " XoffChar: {0}\r\n", XoffChar); - sb.AppendFormat(null, " ErrorChar: {0}\r\n", ErrorChar); - sb.AppendFormat(null, " EofChar: {0}\r\n", EofChar); - sb.AppendFormat(null, " EvtChar: {0}\r\n", EvtChar); - - return sb.ToString(); - } - } -} diff --git a/gps8/Gps8/GPS_Sample8/EnumEx.cs b/gps8/Gps8/GPS_Sample8/EnumEx.cs deleted file mode 100644 index a77d523..0000000 --- a/gps8/Gps8/GPS_Sample8/EnumEx.cs +++ /dev/null @@ -1,483 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.EnumEx -// Copyright (c) 2003-2006, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Globalization; -using System.Collections; -using System.Reflection; - -// Peter Foot -// Sergey Bogdanov - -namespace OpenNETCF -{ - /// - /// Provides helper functions for Enumerations. - /// - /// Extends the System.Enum Class. - /// System.Enum Class - public sealed class EnumEx - { - private EnumEx(){} - - #region Get Name - /// - /// Retrieves the name of the constant in the specified enumeration that has the specified value. - /// - /// An enumeration type. - /// The value of a particular enumerated constant in terms of its underlying type. - /// A string containing the name of the enumerated constant in enumType whose value is value, or null if no such constant is found. - /// enumType is not an System.Enum. -or- value is neither of type enumType nor does it have the same underlying type as enumType. - /// The following code sample illustrates the use of GetName (Based on the example provided with desktop .NET Framework): - /// [Visual Basic] - /// Imports System - /// - /// Public Class GetNameTest - /// - /// Enum Colors - /// Red - /// Green - /// Blue - /// Yellow - /// End Enum 'Colors - /// - /// Enum Styles - /// Plaid - /// Striped - /// Tartan - /// Corduroy - /// End Enum 'Styles - /// - /// Public Shared Sub Main() - /// MessageBox.Show("The 4th value of the Colors Enum is " + [OpenNETCF.Enum].GetName(GetType(Colors), 3)) - /// MessageBox.Show("The 4th value of the Styles Enum is " + [OpenNETCF.Enum].GetName(GetType(Styles), 3)) - /// End Sub 'Main - /// - /// End Class 'GetNameTest - /// [C#] - /// using System; - /// - /// public class GetNameTest - /// { - /// enum Colors { Red, Green, Blue, Yellow }; - /// enum Styles { Plaid, Striped, Tartan, Corduroy }; - /// - /// public static void Main() - /// { - /// MessageBox.Show("The 4th value of the Colors Enum is " + OpenNETCF.Enum.GetName(typeof(Colors), 3)); - /// MessageBox.Show("The 4th value of the Styles Enum is " + OpenNETCF.Enum.GetName(typeof(Styles), 3)); - /// } - /// } - /// - /// System.Enum.GetName Method - public static string GetName(Type enumType, object value) - { - //check that the type supplied inherits from System.Enum - if(enumType.BaseType==Type.GetType("System.Enum")) - { - //get details of all the public static fields (enum items) - FieldInfo[] fi = enumType.GetFields(BindingFlags.Static | BindingFlags.Public); - - //cycle through the enum values - foreach(FieldInfo thisField in fi) - { - object numericValue = 0; - - try - { - //convert the enum value to the numeric type supplied - numericValue = Convert.ChangeType(thisField.GetValue(null), value.GetType(), null); - } - catch - { - throw new ArgumentException(); - } - - //if value matches return the name - if(numericValue.Equals(value)) - { - return thisField.Name; - } - } - //if there is no match return null - return null; - } - else - { - //the type supplied does not derive from enum - throw new ArgumentException("enumType parameter is not an System.Enum"); - } - } - #endregion - - #region Get Names - /// - /// Retrieves an array of the names of the constants in a specified enumeration. - /// - /// An enumeration type. - /// A string array of the names of the constants in enumType. The elements of the array are sorted by the values of the enumerated constants. - /// enumType parameter is not an System.Enum - /// The follow example shows how to enumerate the members of the System.DayOfWeek enumeration by adding them to a ComboBox:- - /// [Visual Basic] - /// Dim thisDOW As New DayOfWeek - /// For Each thisDOW In OpenNETCF.Enum.GetValues(Type.GetType("System.DayOfWeek")) - /// ComboBox1.Items.Add(thisDOW) - /// Next - /// [C#] - /// foreach(DayOfWeek thisdow in OpenNETCF.Enum.GetValues(typeof(DayOfWeek))) - /// { - /// comboBox1.Items.Add(thisdow); - /// } - /// System.Enum.GetNames Method - public static string[] GetNames(Type enumType) - { - if(enumType.BaseType==Type.GetType("System.Enum")) - { - //get the public static fields (members of the enum) - System.Reflection.FieldInfo[] fi = enumType.GetFields(BindingFlags.Static | BindingFlags.Public); - - //create a new enum array - string[] names = new string[fi.Length]; - - //populate with the values - for(int iEnum = 0; iEnum < fi.Length; iEnum++) - { - names[iEnum] = fi[iEnum].Name; - } - - //return the array - return names; - } - else - { - //the type supplied does not derive from enum - throw new ArgumentException("enumType parameter is not an System.Enum"); - } - } - #endregion - - #region Get Underlying Type - /// - /// Returns the underlying type of the specified enumeration. - /// New in v1.1 - /// - /// An enumeration type. - /// The underlying of enumType. - /// System.Enum.GetUnderlyingType Method - public static Type GetUnderlyingType(Type enumType) - { - return System.Enum.GetUnderlyingType(enumType); - } - #endregion - - #region Get Values - /// - /// Retrieves an array of the values of the constants in a specified enumeration. - /// - /// An enumeration type. - /// An System.Array of the values of the constants in enumType. The elements of the array are sorted by the values of the enumeration constants. - /// enumType parameter is not an System.Enum - /// System.Enum.GetValues Method - public static System.Enum[] GetValues(Type enumType) - { - if(enumType.BaseType==Type.GetType("System.Enum")) - { - //get the public static fields (members of the enum) - System.Reflection.FieldInfo[] fi = enumType.GetFields(BindingFlags.Static | BindingFlags.Public); - - //create a new enum array - System.Enum[] values = new System.Enum[fi.Length]; - - //populate with the values - for(int iEnum = 0; iEnum < fi.Length; iEnum++) - { - values[iEnum] = (System.Enum)fi[iEnum].GetValue(null); - } - - //return the array - return values; - } - else - { - //the type supplied does not derive from enum - throw new ArgumentException("enumType parameter is not an System.Enum"); - } - } - #endregion - - #region Is Defined - /// - /// Returns an indication whether a constant with a specified value exists in a specified enumeration. - /// New in v1.1 - /// - /// An enumeration type. - /// The value or name of a constant in enumType. - /// true if a constant in enumType has a value equal to value; otherwise, false. - /// System.Enum.IsDefined Method - public static bool IsDefined(Type enumType, object value) - { - return System.Enum.IsDefined(enumType, value); - } - #endregion - - #region Parse - /// - /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. - /// - /// The of the enumeration. - /// A string containing the name or value to convert. - /// An object of type enumType whose value is represented by value. - public static object Parse(System.Type enumType, string value) - { - //do case sensitive parse - return Parse(enumType, value, false); - } - /// - /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. - /// A parameter specifies whether the operation is case-sensitive. - /// - /// The of the enumeration. - /// A string containing the name or value to convert. - /// If true, ignore case; otherwise, regard case. - /// An object of type enumType whose value is represented by value. - /// enumType is not an . - /// -or- value is either an empty string ("") or only contains white space. - /// -or- value is a name, but not one of the named constants defined for the enumeration. - /// System.Enum.Parse Method - public static object Parse(System.Type enumType, string value, bool ignoreCase) - { -#if NETCF2 - //use intrinsic functionality in v2 - return Enum.Parse(enumType,value,ignoreCase); -#else - //throw an exception on null value - if(value.TrimEnd(' ')=="") - { - throw new ArgumentException("value is either an empty string (\"\") or only contains white space."); - } - else - { - //type must be a derivative of enum - if(enumType.BaseType==Type.GetType("System.Enum")) - { - //remove all spaces - string[] memberNames = value.Replace(" ","").Split(','); - - //collect the results - //we are cheating and using a long regardless of the underlying type of the enum - //this is so we can use ordinary operators to add up each value - //I suspect there is a more efficient way of doing this - I will update the code if there is - long returnVal = 0; - - //for each of the members, add numerical value to returnVal - foreach(string thisMember in memberNames) - { - //skip this string segment if blank - if(thisMember!="") - { - try - { - if(ignoreCase) - { - returnVal += (long)Convert.ChangeType(enumType.GetField(thisMember, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null),returnVal.GetType(), null); - } - else - { - returnVal += (long)Convert.ChangeType(enumType.GetField(thisMember, BindingFlags.Public | BindingFlags.Static).GetValue(null),returnVal.GetType(), null); - } - } - catch - { - try - { - //try getting the numeric value supplied and converting it - returnVal += (long)Convert.ChangeType(System.Enum.ToObject(enumType, Convert.ChangeType(thisMember, System.Enum.GetUnderlyingType(enumType), null)),typeof(long),null); - } - catch - { - throw new ArgumentException("value is a name, but not one of the named constants defined for the enumeration."); - } - // - } - } - } - - - //return the total converted back to the correct enum type - return System.Enum.ToObject(enumType, returnVal); - } - else - { - //the type supplied does not derive from enum - throw new ArgumentException("enumType parameter is not an System.Enum"); - } - } -#endif - } - #endregion - - #region To Object - /// - /// Returns an instance of the specified enumeration set to the specified value. - /// New in v1.1 - /// - /// An enumeration. - /// The value. - /// An enumeration object whose value is value. - /// System.Enum.ToObject Method - public static object ToObject(System.Type enumType, object value) - { - return System.Enum.ToObject(enumType, value); - } - #endregion - - #region Format - private static string InternalFormat(Type enumType, object value) - { - if (enumType.IsDefined(typeof(FlagsAttribute), false)) - return InternalFlagsFormat(enumType, value); - - string t = GetName(enumType, value); - if (t == null) - return value.ToString(); - - return t; - } - - private static string InternalFlagsFormat(Type enumType, object value) - { - string t = GetName(enumType, value); - if (t == null) - return value.ToString(); - - return t; - } - - private static string InternalValuesFormat(Type enumType, object value, bool showValues) - { - string [] names = null; - if (!showValues) names = GetNames(enumType); - ulong v = Convert.ToUInt64(value); - Enum [] e = GetValues(enumType); - ArrayList al = new ArrayList(); - for(int i = 0; i < e.Length; i++) - { - ulong ev = (ulong)Convert.ChangeType(e[i], typeof(ulong), null); - if (i == 0 && ev == 0) continue; - if ((v & ev) == ev) - { - v -= ev; - if (showValues) - al.Add(ev.ToString()); - else - al.Add(names[i]); - } - } - - if (v != 0) - return value.ToString(); - - - string [] t = (string [])al.ToArray(typeof(string)); - return string.Join(", ", t); - } - - /// - /// Converts the specified value of a specified enumerated type to its equivalent string representation according to the specified format. - /// - /// - /// The valid format values are: - /// "G" or "g" - If value is equal to a named enumerated constant, the name of that constant is returned; otherwise, the decimal equivalent of value is returned. - /// For example, suppose the only enumerated constant is named, Red, and its value is 1. If value is specified as 1, then this format returns "Red". However, if value is specified as 2, this format returns "2". - /// "X" or "x" - Represents value in hexadecimal without a leading "0x". - /// "D" or "d" - Represents value in decimal form. - /// "F" or "f" - Behaves identically to "G" or "g", except the FlagsAttribute is not required to be present on the Enum declaration. - /// "V" or "v" - If value is equal to a named enumerated constant, the value of that constant is returned; otherwise, the decimal equivalent of value is returned. - /// - /// The enumeration type of the value to convert. - /// The value to convert. - /// The output format to use. - /// A string representation of value. - public static string Format(Type enumType, object value, string format) - { - if (enumType == null) throw new ArgumentNullException("enumType"); - if (value == null) throw new ArgumentNullException("value"); - if (format == null) throw new ArgumentNullException("format"); - if (!enumType.IsEnum) throw new ArgumentException("The argument enumType must be an System.Enum."); - - if (string.Compare(format, "G", true, CultureInfo.InvariantCulture) == 0) - return InternalFormat(enumType, value); - if (string.Compare(format, "F", true, CultureInfo.InvariantCulture) == 0) - return InternalValuesFormat(enumType, value, false); - if (string.Compare(format, "V", true, CultureInfo.InvariantCulture) == 0) - return InternalValuesFormat(enumType, value, true); - if (string.Compare(format, "X", true, CultureInfo.InvariantCulture) == 0) - return InternalFormattedHexString(value); - if (string.Compare(format, "D", true, CultureInfo.InvariantCulture) == 0) - return Convert.ToUInt64(value).ToString(); - - throw new FormatException("Invalid format."); - } - - private static string InternalFormattedHexString(object value) - { - switch (Convert.GetTypeCode(value)) - { - case TypeCode.SByte: - { - sbyte n = (sbyte) value; - return n.ToString("X2", null); - } - case TypeCode.Byte: - { - byte n = (byte) value; - return n.ToString("X2", null); - } - case TypeCode.Int16: - { - short n = (short) value; - return n.ToString("X4", null); - } - case TypeCode.UInt16: - { - ushort n = (ushort) value; - return n.ToString("X4", null); - } - case TypeCode.Int32: - { - int n = (int) value; - return n.ToString("X8", null); - } - case TypeCode.UInt32: - { - uint n = (uint) value; - return n.ToString("X8", null); - } - - } - - throw new InvalidOperationException("Unknown enum type."); - } - #endregion - } -} diff --git a/gps8/Gps8/GPS_Sample8/GPSForm1.cs b/gps8/Gps8/GPS_Sample8/GPSForm1.cs deleted file mode 100644 index bc5e338..0000000 --- a/gps8/Gps8/GPS_Sample8/GPSForm1.cs +++ /dev/null @@ -1,1188 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -// Use of this source code is subject to the terms of the Microsoft end-user -// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. -// If you did not accept the terms of the EULA, you are not authorized to use -// this source code. For a copy of the EULA, please see the LICENSE.RTF on your -// install media. -using System; -using System.Drawing; -using System.Windows.Forms; -using Microsoft.WindowsMobile.Samples.Location; -using System.IO; -using System.Text; -using OpenNETCF.IO.Serial; -using PInvokeLibrary2; - -namespace GpsTest -{ - /// - /// Summary description for Form1. - /// - public class Form1 : System.Windows.Forms.Form - { - private System.Windows.Forms.MenuItem exitMenuItem; - private System.Windows.Forms.MainMenu mainMenu1; - private MenuItem menuItem2; - - - private EventHandler updateDataHandler; - GpsDeviceState device = null; - GpsPosition position = null; - private Microsoft.WindowsCE.Forms.InputPanel inputPanel1; - - Gps gps = new Gps(); - private Timer timer1; - - Port serialPort; - private ListBox lbl_RawData; - private TextBox status; - private MenuItem GPSID_submenu; - private MenuItem mnuGPSStart; - private MenuItem mnuGPSStop; - private MenuItem mnuGPSRestart; - private MenuItem mnusubGPSRaw; - private MenuItem mnuRAWStop; - private MenuItem mnuRAWStart; - private MenuItem mnuRAWRestart; - private MenuItem mnusubLogFiles; - private MenuItem mnuGPSLogOnOff; - private MenuItem mnuGPSLogClear; - private MenuItem mnuXMLLogOnOff; - - bool m_FixValid=false; - bool m_AutoRestart = true; - bool m_XMLLogging = true; - bool m_RAWLogging = true; - string RAWLoggingPath = @"\GPSraw.log.txt"; - private MenuItem mnuSetTime2GPS; - private MenuItem mnusubSpecial; - private MenuItem mnuNavInit; - private Panel panel1; - - bool m_SetTime = false; - /// - /// used to store and retrieve SN values - /// - private Satellite[] sats; - private MenuItem mnuAutoRestartGPS; - private MenuItem subGPSdevice; - private MenuItem mnuRestartGPSdevice; - private MenuItem mnuStartRAW2; - /// - /// used to store 'Sat is used in Solution' - /// - private Satellite[] satSol; - - public Form1() - { - // - // Required for Windows Form Designer support - // - InitializeComponent(); - inputPanel1.Enabled = false; - // - // TODO: Add any constructor code after InitializeComponent call - // - } - /// - /// Clean up any resources being used. - /// - protected override void Dispose( bool disposing ) - { - base.Dispose( disposing ); - } - #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.exitMenuItem = new System.Windows.Forms.MenuItem(); - this.menuItem2 = new System.Windows.Forms.MenuItem(); - this.GPSID_submenu = new System.Windows.Forms.MenuItem(); - this.mnuGPSStart = new System.Windows.Forms.MenuItem(); - this.mnuGPSStop = new System.Windows.Forms.MenuItem(); - this.mnuGPSRestart = new System.Windows.Forms.MenuItem(); - this.mnuAutoRestartGPS = new System.Windows.Forms.MenuItem(); - this.mnusubGPSRaw = new System.Windows.Forms.MenuItem(); - this.mnuRAWStop = new System.Windows.Forms.MenuItem(); - this.mnuRAWStart = new System.Windows.Forms.MenuItem(); - this.mnuRAWRestart = new System.Windows.Forms.MenuItem(); - this.mnusubLogFiles = new System.Windows.Forms.MenuItem(); - this.mnuGPSLogOnOff = new System.Windows.Forms.MenuItem(); - this.mnuGPSLogClear = new System.Windows.Forms.MenuItem(); - this.mnuXMLLogOnOff = new System.Windows.Forms.MenuItem(); - this.mnuSetTime2GPS = new System.Windows.Forms.MenuItem(); - this.mnusubSpecial = new System.Windows.Forms.MenuItem(); - this.mnuNavInit = new System.Windows.Forms.MenuItem(); - this.subGPSdevice = new System.Windows.Forms.MenuItem(); - this.mnuRestartGPSdevice = new System.Windows.Forms.MenuItem(); - this.inputPanel1 = new Microsoft.WindowsCE.Forms.InputPanel(); - this.timer1 = new System.Windows.Forms.Timer(); - this.lbl_RawData = new System.Windows.Forms.ListBox(); - this.status = new System.Windows.Forms.TextBox(); - this.panel1 = new System.Windows.Forms.Panel(); - this.mnuStartRAW2 = new System.Windows.Forms.MenuItem(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.exitMenuItem); - this.mainMenu1.MenuItems.Add(this.menuItem2); - // - // exitMenuItem - // - this.exitMenuItem.Text = "Exit"; - this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click); - // - // menuItem2 - // - this.menuItem2.MenuItems.Add(this.GPSID_submenu); - this.menuItem2.MenuItems.Add(this.mnusubGPSRaw); - this.menuItem2.MenuItems.Add(this.mnusubLogFiles); - this.menuItem2.MenuItems.Add(this.mnuSetTime2GPS); - this.menuItem2.MenuItems.Add(this.mnusubSpecial); - this.menuItem2.MenuItems.Add(this.subGPSdevice); - this.menuItem2.Text = "Extras"; - // - // GPSID_submenu - // - this.GPSID_submenu.MenuItems.Add(this.mnuGPSStart); - this.GPSID_submenu.MenuItems.Add(this.mnuGPSStop); - this.GPSID_submenu.MenuItems.Add(this.mnuGPSRestart); - this.GPSID_submenu.MenuItems.Add(this.mnuAutoRestartGPS); - this.GPSID_submenu.Text = "GPSID driver"; - // - // mnuGPSStart - // - this.mnuGPSStart.Text = "Start GPS"; - this.mnuGPSStart.Click += new System.EventHandler(this.startGpsMenuItem_Click); - // - // mnuGPSStop - // - this.mnuGPSStop.Text = "Stop GPS"; - this.mnuGPSStop.Click += new System.EventHandler(this.stopGpsMenuItem_Click); - // - // mnuGPSRestart - // - this.mnuGPSRestart.Text = "Restart GPS"; - this.mnuGPSRestart.Click += new System.EventHandler(this.mnu_RestartGPS_Click); - // - // mnuAutoRestartGPS - // - this.mnuAutoRestartGPS.Checked = true; - this.mnuAutoRestartGPS.Text = "Auto Restart"; - this.mnuAutoRestartGPS.Click += new System.EventHandler(this.mnuAutoRestartGPS_Click); - // - // mnusubGPSRaw - // - this.mnusubGPSRaw.MenuItems.Add(this.mnuRAWStop); - this.mnusubGPSRaw.MenuItems.Add(this.mnuRAWStart); - this.mnusubGPSRaw.MenuItems.Add(this.mnuRAWRestart); - this.mnusubGPSRaw.MenuItems.Add(this.mnuStartRAW2); - this.mnusubGPSRaw.Text = "GPS Raw"; - // - // mnuRAWStop - // - this.mnuRAWStop.Enabled = false; - this.mnuRAWStop.Text = "Stop RAW"; - this.mnuRAWStop.Click += new System.EventHandler(this.mnuRAWStop_Click); - // - // mnuRAWStart - // - this.mnuRAWStart.Text = "Start RAW"; - this.mnuRAWStart.Click += new System.EventHandler(this.mnuRAWStart_Click); - // - // mnuRAWRestart - // - this.mnuRAWRestart.Text = "Restart RAW"; - this.mnuRAWRestart.Click += new System.EventHandler(this.mnuRAWRestart_Click); - // - // mnusubLogFiles - // - this.mnusubLogFiles.MenuItems.Add(this.mnuGPSLogOnOff); - this.mnusubLogFiles.MenuItems.Add(this.mnuGPSLogClear); - this.mnusubLogFiles.MenuItems.Add(this.mnuXMLLogOnOff); - this.mnusubLogFiles.Text = "Log Files"; - // - // mnuGPSLogOnOff - // - this.mnuGPSLogOnOff.Text = "GPS logging off"; - this.mnuGPSLogOnOff.Click += new System.EventHandler(this.mnuGPSLogOnOff_Click); - // - // mnuGPSLogClear - // - this.mnuGPSLogClear.Text = "GPS clear log file"; - this.mnuGPSLogClear.Click += new System.EventHandler(this.mnuGPSLogClear_Click); - // - // mnuXMLLogOnOff - // - this.mnuXMLLogOnOff.Text = "XML logging off"; - this.mnuXMLLogOnOff.Click += new System.EventHandler(this.mnuXMLLogOnOff_Click); - // - // mnuSetTime2GPS - // - this.mnuSetTime2GPS.Checked = true; - this.mnuSetTime2GPS.Text = "Set Time to GPS"; - this.mnuSetTime2GPS.Click += new System.EventHandler(this.mnuSetTime2GPS_Click); - // - // mnusubSpecial - // - this.mnusubSpecial.MenuItems.Add(this.mnuNavInit); - this.mnusubSpecial.Text = "Special"; - // - // mnuNavInit - // - this.mnuNavInit.Text = "NavigationInit"; - this.mnuNavInit.Click += new System.EventHandler(this.mnuNavInit_Click); - // - // subGPSdevice - // - this.subGPSdevice.MenuItems.Add(this.mnuRestartGPSdevice); - this.subGPSdevice.Text = "GPS Device"; - // - // mnuRestartGPSdevice - // - this.mnuRestartGPSdevice.Text = "Restart Device"; - this.mnuRestartGPSdevice.Click += new System.EventHandler(this.mnuRestartGPSdevice_Click); - // - // timer1 - // - this.timer1.Interval = 1000; - this.timer1.Tick += new System.EventHandler(this.timer1_Tick); - // - // lbl_RawData - // - this.lbl_RawData.Location = new System.Drawing.Point(3, 193); - this.lbl_RawData.Name = "lbl_RawData"; - this.lbl_RawData.Size = new System.Drawing.Size(234, 72); - this.lbl_RawData.TabIndex = 2; - // - // status - // - this.status.AcceptsReturn = true; - this.status.BackColor = System.Drawing.SystemColors.InactiveBorder; - this.status.Font = new System.Drawing.Font("Courier New", 8F, System.Drawing.FontStyle.Regular); - this.status.Location = new System.Drawing.Point(3, 4); - this.status.Multiline = true; - this.status.Name = "status"; - this.status.ReadOnly = true; - this.status.Size = new System.Drawing.Size(233, 133); - this.status.TabIndex = 1; - this.status.Text = "status"; - this.status.WordWrap = false; - // - // panel1 - // - this.panel1.Location = new System.Drawing.Point(3, 138); - this.panel1.Name = "panel1"; - this.panel1.Size = new System.Drawing.Size(234, 55); - this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint); - // - // mnuStartRAW2 - // - this.mnuStartRAW2.Text = "Start Direct RAW"; - this.mnuStartRAW2.Click += new System.EventHandler(this.mnuStartRAW2_Click); - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.BackColor = System.Drawing.SystemColors.ScrollBar; - this.ClientSize = new System.Drawing.Size(240, 268); - this.Controls.Add(this.panel1); - this.Controls.Add(this.status); - this.Controls.Add(this.lbl_RawData); - this.Menu = this.mainMenu1; - this.Name = "Form1"; - this.Text = "GpsSample (logger)"; - this.Load += new System.EventHandler(this.Form1_Load); - this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint); - this.Closed += new System.EventHandler(this.Form1_Closed); - this.ResumeLayout(false); - - } - #endregion - - /// - /// The main entry point for the application. - /// - - static void Main() - { - Application.Run(new Form1()); - } - - //http://www.highoncoding.com/Articles/532_How%20to%20access%20GPS%20in%20Windows%20Mobile%20devices.aspx - private delegate void MessageHandler(ListBox control, string message); - - private void UpdateListBoxControl(ListBox control, string message) - { - //avoid overrun - if (control.Items.Count > 200) - control.Items.Clear(); - control.Items.Add(message); - control.SelectedIndex = control.Items.Count - 1; - } - //================================================================== - private void AddRawText(string s) - { - if (s.Length != 0) - { - DateTime dt = DateTime.Now; - SetTimeToGPS(dt); - MessageHandler lb = UpdateListBoxControl; - Invoke(lb, lbl_RawData, s); - //lbl_RawData.Items.Add(s); - //lbl_RawData.SelectedIndex = lbl_RawData.Items.Count - 1; - if (m_RAWLogging) - { - try - { - StreamWriter sw = System.IO.File.AppendText(RAWLoggingPath); - sw.Write("{0:00}.{1:00}.{2:0000} {3:00}:{4:00}:{5:00}\t", dt.Day, dt.Month, dt.Year, dt.Hour, dt.Minute, dt.Second); - sw.WriteLine(s); - sw.Flush(); - sw.Close(); - } - catch (SystemException) - { - lbl_RawData.Items.Add("exception in appendText"); - } - } - } - } - - #region CN50raw - bgThread2 myStreamReaderThread; - private void OpenStream() - { - //background thread already running? - if (myStreamReaderThread == null) - { - string szPort=""; - szPort = GetGPSPort(); - if (szPort != "") - { - AddRawText("Start reading stream at '" + szPort +"'"); - //start a new thread - myStreamReaderThread = new bgThread2(szPort); - myStreamReaderThread.bgThread2Event += new bgThread2.bgThread2EventHandler(myStreamReaderThread_bgThread2Event); - } - else - AddRawText("No raw GPS port found"); - } - } - - private void OpenStream(string szPort) - { - //background thread already running? - if (myStreamReaderThread == null) - { - if (szPort != "") - { - AddRawText("Start reading stream at '" + szPort + "'"); - //start a new thread - myStreamReaderThread = new bgThread2(szPort); - myStreamReaderThread.bgThread2Event += new bgThread2.bgThread2EventHandler(myStreamReaderThread_bgThread2Event); - } - else - AddRawText("No raw GPS port found"); - } - } - void myStreamReaderThread_bgThread2Event(object sender, bgThread2.BgThreadEventArgs bte) - { - AddRawText(bte.sString); - } - private void CloseStream() - { - if (myStreamReaderThread != null) - { - myStreamReaderThread.Dispose(); - Application.DoEvents(); - myStreamReaderThread = null; - } - Application.DoEvents(); - mnuRAWStart.Enabled = true; - mnuRAWStop.Enabled = false; - } - #endregion - #region Serial - private void OpenCOM(string szPort) - { - try - { - serialPort = new Port(szPort, new HandshakeNone()); - AddRawText("Trying to open " + szPort + ":..."); - serialPort.Settings.BaudRate = BaudRates.CBR_57600; - serialPort.RThreshold = 1; - serialPort.InputLen = 1; - serialPort.DataReceived += - new OpenNETCF.IO.Serial.Port.CommEvent(serialPort_DataReceived); - serialPort.Open(); - AddRawText("port opened..."); - } - catch (OpenNETCF.IO.Serial.CommPortException sx) - { - AddRawText("Exception in OpenCOM " + szPort); - AddRawText(sx.Message); - mnuRAWStart.Enabled = true; - mnuRAWStop.Enabled = false; - } - } - - private void OpenCOM() - { - string szPort=""; - try - { - szPort = GetGPSPort(); - if (szPort == "") - szPort = "GPD1:"; - - serialPort = new Port(szPort, new HandshakeNone()); - AddRawText("Trying to open " + szPort + ":..."); - serialPort.Settings.BaudRate = BaudRates.CBR_57600; - serialPort.RThreshold = 1; - serialPort.InputLen = 1; - serialPort.DataReceived += - new OpenNETCF.IO.Serial.Port.CommEvent(serialPort_DataReceived); - serialPort.Open(); - AddRawText("port opened..."); - } - catch(OpenNETCF.IO.Serial.CommPortException sx) - { - AddRawText("Exception in OpenCOM " + szPort); - AddRawText(sx.Message); - mnuRAWStart.Enabled = true; - mnuRAWStop.Enabled = false; - } - } - private void CloseCOM() - { - if (serialPort != null) - serialPort.Close(); - } - - private void serialPort_DataReceived() - { - byte[] inputData = new byte[1]; - string s = String.Empty; - while (serialPort.InBufferCount > 0) - { - inputData = serialPort.Input; - if ((inputData[0] != '\n') && (inputData[0] != '\r')) - s += Encoding.ASCII.GetString(inputData, 0, inputData.Length); - else - { - //parseNmeaSentence(s); - AddRawText(s); - s = string.Empty; - } - } - } -#endregion - - private void exitMenuItem_Click(object sender, EventArgs e) - { - if (gps.Opened) - { - gps.Close(); - } - CloseCOM(); - CloseStream(); - Application.Exit(); - } - - private void Form1_Load(object sender, System.EventArgs e) - { - updateDataHandler = new EventHandler(UpdateData); - - status.Text = ""; - - //status.Width = Screen.PrimaryScreen.WorkingArea.Width; - //status.Height = (Screen.PrimaryScreen.WorkingArea.Height - btn_Restart.Height)/2; - - //lbl_RawData.Height=(Screen.PrimaryScreen.WorkingArea.Height - btn_Restart.Height)/2; - - gps.DeviceStateChanged += new DeviceStateChangedEventHandler(gps_DeviceStateChanged); - gps.LocationChanged += new LocationChangedEventHandler(gps_LocationChanged); - if (!this.gps.Opened) - { - this.gps.Open(); - status.Text += "gps.Open()\r\n"; - } - if (this.gps.Opened) - { - gps.DeviceStateChanged += new DeviceStateChangedEventHandler(gps_DeviceStateChanged); - gps.LocationChanged += new LocationChangedEventHandler(gps_LocationChanged); - } - else - { - status.Text += "gps.open() FAILED\r\n"; - } - if (isCN50orCK70()) - mnuNavInit.Enabled = false; - - mnuGPSStart.Enabled = false; - mnuGPSStop.Enabled = true; - timer1.Interval = 30000; - timer1.Enabled=true; - BeginInvoke(updateDataHandler); - //OpenCOM(); - } - - protected void gps_LocationChanged(object sender, LocationChangedEventArgs args) - { - position = args.Position; - - // call the UpdateData method via the updateDataHandler so that we - // update the UI on the UI thread - try - { - BeginInvoke(updateDataHandler); - - } - catch (NullReferenceException ) - { - - } - } - ////http://www.highoncoding.com/Articles/532_How%20to%20access%20GPS%20in%20Windows%20Mobile%20devices.aspx - //private delegate void MessageHandler(object sender, DeviceStateChangedEventArgs args); - - //private void UpdateControl(object sender, DeviceStateChangedEventArgs args) - //{ - // UpdateData(sender, args); - // //control.Text = message; - //} - //========================================================================== - void gps_DeviceStateChanged(object sender, DeviceStateChangedEventArgs args) - { - ////http://www.highoncoding.com/Articles/532_How%20to%20access%20GPS%20in%20Windows%20Mobile%20devices.aspx - //MessageHandler dev_change = UpdateControl; - - //device = args.DeviceState; - //Invoke(dev_change, status, device); - //Invoke(cu, tbGPSDeviceState, device.DeviceState.ToString()); - //Invoke(cu, tbGPSServiceState, device.ServiceState.ToString()); - - // call the UpdateData method via the updateDataHandler so that we - // update the UI on the UI thread - try - { - BeginInvoke(updateDataHandler); - } - catch (NullReferenceException) - { - } - } - void UpdateData(object sender, System.EventArgs args) - { - try - { - if (gps.Opened) - { - string str = ""; - if (device != null) - { - str = "Name: '" + device.FriendlyName + "' Svc: '" + device.ServiceState + "', Dvc: '" + device.DeviceState + "'\r\n"; - } - else - str = "Name: '' Svc:''\r\n"; - - if (position != null) - { - //if all valid - if ((((((this.position.LatitudeValid && this.position.LongitudeValid) && this.position.SatellitesInSolutionValid) && this.position.SatellitesInViewValid) && this.position.SatelliteCountValid) && this.position.TimeValid) && (this.position.SatelliteCount > 2)) - { - m_FixValid = true; - if (m_XMLLogging) - this.position2XMLFile(this.position); - } - else - m_FixValid = false; - - //Latitude - if (position.LatitudeValid) - { - str += "Lat: " + position.Latitude.ToString("00.000") + " "; - //str += "Lat (D,M,S): " + position.LatitudeInDegreesMinutesSeconds + "\r\n"; - } - else - str += "Lat: --.--- "; - - //Longitude - if (position.LongitudeValid) - { - str += "Lon: " + position.Longitude.ToString("00.000") + "\r\n"; - //str += "Lon (D,M,S): " + position.LongitudeInDegreesMinutesSeconds + "\r\n"; - } - else - str += "Lon: --.---\r\n"; - - //sat in view and in solution - if (position.SatellitesInSolutionValid && - position.SatellitesInViewValid && - position.SatelliteCountValid) - { - str += "Sat. Count: " + position.GetSatellitesInSolution().Length + "/" + - position.GetSatellitesInView().Length + " (" + - position.SatelliteCount + ")\r\n"; - } - //list sats in solution - if (position.SatellitesInSolutionValid) - { - satSol = position.GetSatellitesInSolution(); - } - //list sats in view and there signal - if (position.SatellitesInViewValid) - { - /* Satellite[] */ - sats = position.GetSatellitesInView(); - str += "SV:"; - foreach (Satellite sat in sats) - { - str += sat.Id.ToString("00") + " "; - } - str += "\r\nSN:"; - foreach (Satellite sat in sats) - { - str += sat.SignalStrength.ToString("00") + " "; - } - str += "\r\n"; - panel1.Invalidate(); - } - else - { - //panel1.Invalidate(); - } - //time - if (position.TimeValid) - { - str += "Time: " + position.Time.ToString() + "\r\n"; - if (m_FixValid) - { - SetTimeToGPS(position.Time); - } - } - - //fixtype - FixType fx = position.eFixType; - switch (fx) - { - case FixType.Unknown: str += "FixType: Unknown\r\n"; - break; - case FixType.XyD: str += "FixType: 2D\r\n"; - break; - case FixType.XyzD: str += "FixType: 3D\r\n"; - break; - } - //fix quality - FixQuality fq = position.eFixQuality; - switch (fq) - { - case FixQuality.Unknown: str += "FixQuality: Unknown\r\n"; - break; - case FixQuality.Gps: str += "FixQuality: GPS\r\n"; - break; - case FixQuality.DGps: str += "FixQuality: DGPS\r\n"; - break; - } - - } - panel1.Invalidate(); - - status.Text = str; - - } - } - catch (NullReferenceException) - { - - } - } - - private void Form1_Closed(object sender, System.EventArgs e) - { - if (gps.Opened) - { - gps.Close(); - } - } - private void StopGPS() - { - if (gps.Opened) - { - gps.Close(); - } - - mnuGPSStart.Enabled = true; - mnuGPSStop.Enabled = false; - } - private void stopGpsMenuItem_Click(object sender, EventArgs e) - { - StopGPS(); - } - private void StartGPS() - { - if (!gps.Opened) - { - gps.Open(); - status.Text += "StartGPS()...\r\n"; - } - - mnuGPSStart.Enabled = false; - mnuGPSStop.Enabled = true; - } - private void startGpsMenuItem_Click(object sender, EventArgs e) - { - StartGPS(); - } - private void position2XMLFile(GpsPosition position) - { - DateTime dateTime1; - using (StreamWriter streamWriter1 = new StreamWriter("bcPosition.xml")) - { - streamWriter1.WriteLine(""); - streamWriter1.WriteLine(""); - streamWriter1.Write(""); - streamWriter1.Write(position.Latitude); - streamWriter1.WriteLine(""); - streamWriter1.Write(""); - streamWriter1.Write(position.Longitude); - streamWriter1.WriteLine(""); - streamWriter1.Write(""); - streamWriter1.Write(position.Speed); - streamWriter1.WriteLine(""); - streamWriter1.Write(""); - streamWriter1.Write(position.Heading); - streamWriter1.WriteLine(""); - streamWriter1.Write(""); - streamWriter1.Write(position.SeaLevelAltitude); - streamWriter1.WriteLine(""); - streamWriter1.Write(""); - streamWriter1.Write(position.SatelliteCount); - streamWriter1.WriteLine(""); - streamWriter1.Write(""); - dateTime1 = position.Time; - streamWriter1.Write(dateTime1.Ticks); - streamWriter1.WriteLine(""); - streamWriter1.Write(""); - streamWriter1.Write(((dateTime1 = position.Time).ToString("MM\'/\'dd\'/\'yyyy hh:mm:ss") + " UTC+0000")); - streamWriter1.WriteLine(""); - streamWriter1.Write(""); - streamWriter1.Write(((dateTime1 = position.Time).ToString("s") + "Z")); - streamWriter1.WriteLine(""); - streamWriter1.WriteLine(""); - } - } - private void GPSRestart() - { - m_FixValid = false; - status.Text = "Restarting GPS ...\r\n"; - Application.DoEvents(); - StopGPS(); - System.Threading.Thread.Sleep(1000); - StartGPS(); - status.Text = "GPS has been restarted\r\n"; - Application.DoEvents(); - } - private void btn_Restart_Click(object sender, EventArgs e) - { - } - - private void timer1_Tick(object sender, EventArgs e) - { - if (!m_FixValid) - btn_Restart_Click(sender, e); - } - - private string GetGPSPort() - { - string szStr=""; - if (Registry.GetStringValue(Registry.HKLM, - "System\\CurrentControlSet\\GPS Intermediate Driver\\Multiplexer", - "DriverInterface", - ref szStr) - == 0) - { - return szStr; - } - else - { - if (Registry.GetStringValue(Registry.HKLM, - "System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers", - "CurrentDriver", - ref szStr) == 0) - { - string szPath = "System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers\\" + szStr; - if (Registry.GetStringValue(Registry.HKLM, szPath, "CommPort", ref szStr) == 0) - { - return szStr; - } - } - } - return ""; - } - private string GetGPSRAWdirectPort() - { - string szStr = ""; - if (Registry.GetStringValue(Registry.HKLM, - "System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers\\SWIGPSModem", - "CommPort", - ref szStr) - == 0) - { - return szStr; - } - return ""; - } - - private void SetTimeToGPS(DateTime UTCtime) - { - if (m_SetTime) - { - // Get the local time zone and a base Coordinated Universal - // Time (UTC). - TimeZone localZone = TimeZone.CurrentTimeZone; - DateTime baseUTC = UTCtime; // new DateTime(2000, 1, 1); - - System.Diagnostics.Debug.WriteLine("\nLocal time: {0}\n", - localZone.StandardName); - - // Calculate the local time and UTC offset. - DateTime localTime = localZone.ToLocalTime(baseUTC); - TimeSpan localOffset = - localZone.GetUtcOffset(localTime); - - System.Diagnostics.Debug.WriteLine(string.Format("{0,-20:yyyy-MM-dd HH:mm}" + - "{1,-20:yyyy-MM-dd HH:mm}{2,-12}{3}", - baseUTC, localTime, localOffset, - localZone.IsDaylightSavingTime(localTime))); - //adjust the clock - //localTime += localOffset; - PInvokeLibrary.SystemTimeLib.SetTime(localTime); - m_SetTime = false; - } - } - - private void mnu_RestartGPS_Click(object sender, EventArgs e) - { - GPSRestart(); - } - - private void mnuRAWStop_Click(object sender, EventArgs e) - { - if (isCN50orCK70()) - CloseStream(); - else - CloseCOM(); - mnuRAWStop.Enabled = false; - mnuRAWStart.Enabled = true; - mnuStartRAW2.Enabled = true; - - } - - private bool isCN50orCK70() - { - string sResult = "nn"; - try - { - Registry.GetStringValue(Registry.HKLM, "Platform", "Model", ref sResult); - if (sResult.Substring(0, 4) == "CN50" || - sResult.Substring(0, 4) == "CK70" || - sResult.Substring(0, 4) == "CN70") - return true; - else - return false; - } - catch { - } - return false; - } - private void mnuRAWStart_Click(object sender, EventArgs e) - { - if (isCN50orCK70()) - OpenStream(); - else - OpenCOM(); - mnuRAWStart.Enabled = false; - mnuRAWStop.Enabled = true; - } - - private void mnuRAWRestart_Click(object sender, EventArgs e) - { - if (isCN50orCK70()) - CloseStream(); - else - CloseCOM(); - Application.DoEvents(); - System.Threading.Thread.Sleep(1000); - if (isCN50orCK70()) - OpenStream(); - else - OpenCOM(); - Application.DoEvents(); - } - - private void mnuGPSLogOnOff_Click(object sender, EventArgs e) - { - if (m_RAWLogging) - { - m_RAWLogging = false; - mnuGPSLogOnOff.Text = "GPS logging On"; - } - else - { - m_RAWLogging = true; - mnuGPSLogOnOff.Text = "GPS logging Off"; - } - } - - private void mnuGPSLogClear_Click(object sender, EventArgs e) - { - bool oldval = m_RAWLogging; - m_RAWLogging = false; - Application.DoEvents(); - try - { - System.IO.File.Delete(RAWLoggingPath); - } - catch(SystemException x){ - AddRawText("Exception in LogClear() " + x.Message); - } - m_RAWLogging = oldval; - } - - private void mnuXMLLogOnOff_Click(object sender, EventArgs e) - { - if (m_XMLLogging) - { - m_XMLLogging = false; - mnuXMLLogOnOff.Text = "XML logging on"; - } - else - { - m_XMLLogging = true; - mnuXMLLogOnOff.Text = "XML logging off"; - } - } - - private void mnuSetTime2GPS_Click(object sender, EventArgs e) - { - if (m_SetTime) - { - m_SetTime = false; - mnuSetTime2GPS.Checked = false; - } - else - { - m_SetTime = true; - mnuSetTime2GPS.Checked = true; - } - } - - // Calculates the checksum for a sentence - private static string getChecksum(string sentence) - { - //Start with first Item - int checksum = Convert.ToByte(sentence[sentence.IndexOf('$') + 1]); - - //first cheksum starts with first char after $ - checksum = Convert.ToByte(sentence[sentence.IndexOf('$') + 1]); - // Loop through all chars to get a checksum - for (int i = sentence.IndexOf('$') + 2; i < sentence.IndexOf('*'); i++) - { - // No. XOR the checksum with this character's value - - checksum ^= Convert.ToByte(sentence[i]); - } - // Return the checksum formatted as a two-character hexadecimal - return checksum.ToString("X2"); - } - - private void SendRAWData(string s) - { - if (serialPort.IsOpen) - { - // Create an ASCII encoding. - Encoding ascii = Encoding.ASCII; - - //add Cr/Lf - s+="\r\n"; - Byte[] encodedBytes = ascii.GetBytes(s); - try - { - serialPort.Output = encodedBytes; - AddRawText("Send: " + s); - } - catch (OpenNETCF.IO.Serial.CommPortException cx) - { - System.Diagnostics.Debug.WriteLine("Exception in SerialOutput: " + cx.Message + "\r\n"); - } - } - } - - //NavigationInitialization - private void SendNavigationInitialization() - { - //string NavigationInitialization="$PSRF101,-2686700,-4304200,3851624,96000,497260,921,12,3*";//1C"; - string ColdStart = "$PSRF101,0,0,0,0,0,0,12,6*"; - /* - 1. COLD START : $PSRF101,0,0,0,000,0,0,12,6*12 - 2. WARM START : $PSRF101,0,0,0,000,0,0,12,2*16 - 3. HOT START : $PSRF101,0,0,0,000,0,0,12,1*15 - 4. FACTORY RESET : $PSRF101,0,0,0,000,0,0,12,8*1C - */ - string s=ColdStart; - string strChk = getChecksum(s); - s += strChk; - SendRAWData(s); - } - - private void mnuNavInit_Click(object sender, EventArgs e) - { - StopGPS(); - Application.DoEvents(); - SendNavigationInitialization(); - Application.DoEvents(); - StartGPS(); - } - - private void Form1_Paint(object sender, PaintEventArgs e) - { - - } - - private void panel1_Paint(object sender, PaintEventArgs e) - { - try - { - int h = panel1.Height; //39 - int w = panel1.Width; //234 - int count = 0; - //System.Diagnostics.Debug.WriteLine(string.Format("h={0} / w={1}", h, w)); - if(sats!=null) - count = sats.Length; - if (count == 0) - return; - int[] SNs = new int[count]; //to store signal - bool[] inSolution= new bool[count]; //to store sat is in solution - int i,j; - - for (i = 0; i < sats.Length; i++) - { - inSolution[i] = false; - if (satSol != null) - { - for (j = 0; j < satSol.Length; j++) - { - if (sats[i].Id == satSol[j].Id) - inSolution[i] = true; - } - } - } - - for (i=0; i < count ; i++) //foreach (Satellite sat in sats) - { - SNs[i] = sats[i].SignalStrength; // is about 15 to 40 - } - - System.Drawing.SolidBrush b; - System.Drawing.Rectangle r; - - int rx, ry, rw, rh; - if (count > 0) - { - for (i = 0; i < count; i++) //foreach (Satellite sat in sats) - { - //adjust the color - b = new System.Drawing.SolidBrush(Color.LightGray); - if (SNs[i] == 0) - { - b = new System.Drawing.SolidBrush(Color.Red); - if (System.Diagnostics.Debugger.IsAttached) - SNs[i] = 3 * i + 1; - else - SNs[i] = 1; - } - else if (SNs[i] > 1 && SNs[i] < 28) - b = new System.Drawing.SolidBrush(Color.Yellow); - else if (SNs[i] >= 28) - b = new System.Drawing.SolidBrush(Color.Magenta); - - if (inSolution[i]) - b = new System.Drawing.SolidBrush(Color.LightGreen); - - rx = (i * 18); // +15; - ry = h - 1; - rw = 15; - rh = -SNs[i]; - r = new System.Drawing.Rectangle(rx, ry, rw, rh);// (mLeftMargin + (1 * mThick) + (bar * 20), mMaxHeihgt - height, 5, height); - //System.Diagnostics.Debug.WriteLine(string.Format("i={4} x={0} y={1} w={2} h={3}", rx, ry, rw, rh, i)); - e.Graphics.FillRectangle(b, r); - } - } - else - { - b = new System.Drawing.SolidBrush(Color.LightGray); - e.Graphics.DrawString("no data", new Font("Arial", 8, FontStyle.Regular), b, 6, 6); - - } - } - catch (Exception ee) - { - System.Diagnostics.Debug.WriteLine(ee.ToString()); - } - } - - private void mnuAutoRestartGPS_Click(object sender, EventArgs e) - { - m_AutoRestart = !m_AutoRestart; - mnuAutoRestartGPS.Checked = m_AutoRestart; - - } - private void RestartGPSdevice() - { - if (GpsDeviceControl.SendIoctl(GpsDeviceControl.IOCTL_SERVICE_STOP)==0) - { - AddRawText("Service stopped"); - if (GpsDeviceControl.SendIoctl(GpsDeviceControl.IOCTL_SERVICE_START) == 0) - AddRawText("Service started"); - else - AddRawText("Start Service failed"); - } - else - AddRawText("Stop Service failed"); - } - - private void mnuRestartGPSdevice_Click(object sender, EventArgs e) - { - RestartGPSdevice(); - } - - private void mnuStartRAW2_Click(object sender, EventArgs e) - { - - //OpenCOM("WMP6:"); // WMP6: SWI6: //both failed - //OpenCOM("SWI6:"); - //OpenStream("SWI6:"); //OK but no DATA -// OpenStream("WMP6:"); //OK but no DATA -// return; - - string directPort = GetGPSRAWdirectPort(); - if (directPort != "") - OpenCOM(directPort); - mnuRAWStart.Enabled = false; - mnuStartRAW2.Enabled = false; - mnuRAWStop.Enabled = true; - - } - } -} diff --git a/gps8/Gps8/GPS_Sample8/GPSForm1.resx b/gps8/Gps8/GPS_Sample8/GPSForm1.resx deleted file mode 100644 index a2dce11..0000000 --- a/gps8/Gps8/GPS_Sample8/GPSForm1.resx +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 210, 17 - - - 100, 17 - - - 17, 17 - - - Pocket_PC_Phone - - - True - - \ No newline at end of file diff --git a/gps8/Gps8/GPS_Sample8/GPS_Sample8.csproj b/gps8/Gps8/GPS_Sample8/GPS_Sample8.csproj deleted file mode 100644 index e343b79..0000000 --- a/gps8/Gps8/GPS_Sample8/GPS_Sample8.csproj +++ /dev/null @@ -1,123 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {188228FC-E19A-4D2D-9FA2-4F2544B20CAD} - WinExe - Properties - GPS_Sample8 - GPS_Sample8 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 2AC76CE7-3E8C-402d-85E7-AE9C98D7B6BA - 5.02 - GPS_Sample8 - v2.0 - Windows Mobile 6.5.3 Professional DTK - - - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - prompt - 512 - 4 - true - true - Off - true - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - prompt - 512 - 4 - true - true - Off - true - - - true - true - Off - true - bin\Debug Sample8\ - DEBUG;TRACE;PocketPC - true - full - AnyCPU - prompt - - - - - - - - - - - - - - - - - - - - - - - Component - - - - - - Form - - - - - - - - - - - - {E575252D-45C4-4BA8-A9A4-FA1579045E2F} - gps.parser - - - {DB77C1EE-A383-4CD5-A107-1C7C26A9E6B8} - Microsoft.WindowsMobile.Samples.Location - - - - - GPSForm1.cs - Designer - - - \ No newline at end of file diff --git a/gps8/Gps8/GPS_Sample8/Port.cs b/gps8/Gps8/GPS_Sample8/Port.cs deleted file mode 100644 index 1af2f7d..0000000 --- a/gps8/Gps8/GPS_Sample8/Port.cs +++ /dev/null @@ -1,1155 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.IO.Serial.Port -// Copyright (c) 2003, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== - -using System; -using System.Runtime.InteropServices; -using System.Threading; -using System.Text; -using System.Collections; - -namespace OpenNETCF.IO.Serial -{ - /// - /// Exceptions throw by the OpenNETCF.IO.Serial class - /// - public class CommPortException : Exception - { - /// - /// Default CommPortException - /// - /// - public CommPortException(string desc) : base(desc) {} - } - - /// - /// A class wrapper for serial port communications - /// - public class Port : IDisposable - { - [DllImport("kernel32", EntryPoint="LocalAlloc", SetLastError=true)] - internal static extern IntPtr LocalAlloc(int uFlags, int uBytes); - - [DllImport("kernel32", EntryPoint="LocalFree", SetLastError=true)] - internal static extern IntPtr LocalFree(IntPtr hMem); - - #region delegates and events - /// - /// Raised on all enabled communication events - /// - public delegate void CommEvent(); - /// - /// Raised when the communication state changes - /// - public delegate void CommChangeEvent(bool NewState); - /// - /// Raised during any communication error - /// - public delegate void CommErrorEvent(string Description); - /// - /// A communication error has occurred - /// - public event CommErrorEvent OnError; - /// - /// Serial data has been received - /// - public event CommEvent DataReceived; -// /// -// /// Overrun of the transmit buffer -// /// -// public event CommEvent RxOverrun; - /// - /// Transmit complete - /// - public event CommEvent TxDone; - /// - /// Set flag character was in the receive stream - /// - public event CommEvent FlagCharReceived; - /// - /// Power change event has occurred - /// - public event CommEvent PowerEvent; - /// - /// Serial buffer's high-water level has been exceeded - /// - public event CommEvent HighWater; - /// - /// DSR state has changed - /// - public event CommChangeEvent DSRChange; - /// - /// Ring signal has been detected - /// - public event CommChangeEvent RingChange; - /// - /// CTS state has changed - /// - public event CommChangeEvent CTSChange; - /// - /// RLSD state has changed - /// - public event CommChangeEvent RLSDChange; - #endregion - - #region ##### variable declarations ##### - private string portName; - private IntPtr hPort = (IntPtr)CommAPI.INVALID_HANDLE_VALUE; - - // default Rx buffer is 1024 bytes - private int rxBufferSize = 1024; - private Queue rxFIFO; - private int rthreshold = 1; - - // default Tx buffer is 1024 bytes - private int txBufferSize = 1024; - private byte[] txBuffer; - private int ptxBuffer = 0; - private int sthreshold = 1; - - private Mutex rxBufferBusy = new Mutex(); - private int inputLength; - - private DCB dcb = new DCB(); - private DetailedPortSettings portSettings; - - private Thread eventThread; - private ManualResetEvent threadStarted = new ManualResetEvent(false); - - private IntPtr closeEvent; - private string closeEventName = "CloseEvent"; - - private int rts = 0; - private bool rtsavail = false; - private int dtr = 0; - private bool dtravail = false; - private int brk = 0; - private int setir = 0; - private bool isOpen = false; - - private IntPtr txOverlapped = IntPtr.Zero; - private IntPtr rxOverlapped = IntPtr.Zero; - - private CommAPI m_CommAPI; - /// - /// stores port's capabilities - capabilities can only be retreived not set - /// - public readonly CommCapabilities Capabilities = new CommCapabilities(); - - #endregion - - private void Init() - { - // create the API class based on the target - if (System.Environment.OSVersion.Platform != PlatformID.WinCE) - m_CommAPI=new IO.Serial.WinCommAPI(); - else - m_CommAPI=new IO.Serial.CECommAPI(); - - // create a system event for synchronizing Closing - closeEvent = m_CommAPI.CreateEvent(true, false, closeEventName); - - rxFIFO = new Queue(rxBufferSize); - txBuffer = new byte[txBufferSize]; - portSettings = new DetailedPortSettings(); - } - - #region constructors - /// - /// Create a serial port class. The port will be created with defualt settings. - /// - /// The port to open (i.e. "COM1:") - public Port(string PortName) - { - this.PortName = PortName; - Init(); - } - - /// - /// Create a serial port class. - /// - /// The port to open (i.e. "COM1:") - /// BasicPortSettings to apply to the new Port - public Port(string PortName, BasicPortSettings InitialSettings) - { - this.PortName = PortName; - Init(); - - //override default ettings - portSettings.BasicSettings = InitialSettings; - } - - /// - /// Create a serial port class. - /// - /// The port to open (i.e. "COM1:") - /// DetailedPortSettings to apply to the new Port - public Port(string PortName, DetailedPortSettings InitialSettings) - { - this.PortName = PortName; - Init(); - - //override default ettings - portSettings = InitialSettings; - } - - /// - /// Create a serial port class. - /// - /// The port to open (i.e. "COM1:") - /// Receive buffer size, in bytes - /// Transmit buffer size, in bytes - public Port(string PortName, int RxBufferSize, int TxBufferSize) - { - rxBufferSize = RxBufferSize; - txBufferSize = TxBufferSize; - this.PortName = PortName; - Init(); - } - - /// - /// Create a serial port class. - /// - /// The port to open (i.e. "COM1:") - /// BasicPortSettings to apply to the new Port - /// Receive buffer size, in bytes - /// Transmit buffer size, in bytes - public Port(string PortName, BasicPortSettings InitialSettings, int RxBufferSize, int TxBufferSize) - { - rxBufferSize = RxBufferSize; - txBufferSize = TxBufferSize; - this.PortName = PortName; - Init(); - - //override default ettings - portSettings.BasicSettings = InitialSettings; - } - - /// - /// Create a serial port class. - /// - /// The port to open (i.e. "COM1:") - /// DetailedPortSettings to apply to the new Port - /// Receive buffer size, in bytes - /// Transmit buffer size, in bytes - public Port(string PortName, DetailedPortSettings InitialSettings, int RxBufferSize, int TxBufferSize) - { - rxBufferSize = RxBufferSize; - txBufferSize = TxBufferSize; - this.PortName = PortName; - Init(); - - //override default ettings - portSettings = InitialSettings; - } - #endregion - - // since the event thread blocks until the port handle is closed - // implement both a Dispose and destrucor to make sure that we - // clean up as soon as possible - /// - /// Dispose the object's resources - /// - public void Dispose() - { - if(isOpen) - this.Close(); - } - - /// - /// Class destructor - /// - ~Port() - { - if(isOpen) - this.Close(); - } - - /// - /// The name of the Port (i.e. "COM1:") - /// - public string PortName - { - get - { - return portName; - } - set - { - if(! CommAPI.FullFramework) - { - // for CE, ensure the port name is colon terminated "COMx:" - if(! value.EndsWith(":")) - { - portName = value + ":"; - return; - } - } - - portName = value; - } - } - - /// - /// Returns whether or not the port is currently open - /// - public bool IsOpen - { - get - { - return isOpen; - } - } - - /// - /// Open the current port - /// - /// true if successful, false if it fails - public bool Open() - { - if(isOpen) return false; - - if(CommAPI.FullFramework) - { - // set up the overlapped tx IO - // AutoResetEvent are = new AutoResetEvent(false); - OVERLAPPED o = new OVERLAPPED(); - txOverlapped = LocalAlloc(0x40, Marshal.SizeOf(o)); - o.Offset = 0; - o.OffsetHigh = 0; - o.hEvent = IntPtr.Zero; - Marshal.StructureToPtr(o, txOverlapped, true); - } - - hPort = m_CommAPI.CreateFile(portName); - - if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) - { - int e = Marshal.GetLastWin32Error(); - - if(e == (int)APIErrors.ERROR_ACCESS_DENIED) - { - // port is unavailable - return false; - } - - // ClearCommError failed! - string error = String.Format("CreateFile Failed: {0}", e); - throw new CommPortException(error); - } - - - isOpen = true; - - // set queue sizes - m_CommAPI.SetupComm(hPort, rxBufferSize, txBufferSize); - - // transfer the port settings to a DCB structure - dcb.BaudRate = (uint)portSettings.BasicSettings.BaudRate; - dcb.ByteSize = portSettings.BasicSettings.ByteSize; - dcb.EofChar = (sbyte)portSettings.EOFChar; - dcb.ErrorChar = (sbyte)portSettings.ErrorChar; - dcb.EvtChar = (sbyte)portSettings.EVTChar; - dcb.fAbortOnError = portSettings.AbortOnError; - dcb.fBinary = true; - dcb.fDsrSensitivity = portSettings.DSRSensitive; - dcb.fDtrControl = (byte)portSettings.DTRControl; - dcb.fErrorChar = portSettings.ReplaceErrorChar; - dcb.fInX = portSettings.InX; - dcb.fNull = portSettings.DiscardNulls; - dcb.fOutX = portSettings.OutX; - dcb.fOutxCtsFlow = portSettings.OutCTS; - dcb.fOutxDsrFlow = portSettings.OutDSR; - dcb.fParity = (portSettings.BasicSettings.Parity == Parity.none) ? false : true; - dcb.fRtsControl = (byte)portSettings.RTSControl; - dcb.fTXContinueOnXoff = portSettings.TxContinueOnXOff; - dcb.Parity = (byte)portSettings.BasicSettings.Parity; - - dcb.StopBits = (byte)portSettings.BasicSettings.StopBits; - dcb.XoffChar = (sbyte)portSettings.XoffChar; - dcb.XonChar = (sbyte)portSettings.XonChar; - - dcb.XonLim = dcb.XoffLim = (ushort)(rxBufferSize / 10); - - m_CommAPI.SetCommState(hPort, dcb); - - // store some state values - brk = 0; - dtr = dcb.fDtrControl == (byte)DCB.DtrControlFlags.Enable ? 1 : 0; - rts = dcb.fRtsControl == (byte)DCB.RtsControlFlags.Enable ? 1 : 0; - - // set the Comm timeouts - CommTimeouts ct = new CommTimeouts(); - - // reading we'll return immediately - // this doesn't seem to work as documented - ct.ReadIntervalTimeout = uint.MaxValue; // this = 0xffffffff - ct.ReadTotalTimeoutConstant = 0; - ct.ReadTotalTimeoutMultiplier = 0; - - // writing we'll give 5 seconds - ct.WriteTotalTimeoutConstant = 5000; - ct.WriteTotalTimeoutMultiplier = 0; - - m_CommAPI.SetCommTimeouts(hPort, ct); - - // read the ports capabilities - bool status=GetPortProperties(); - - // start the receive thread - eventThread = new Thread(new ThreadStart(CommEventThread)); - eventThread.Priority = ThreadPriority.Highest; - eventThread.Start(); - - // wait for the thread to actually get spun up - threadStarted.WaitOne(); - - return true; - } - - /// - /// Query the current port's capabilities without accessing it. You can only call the Close() - /// method after reading the capabilities. This method does neither initialize nor Open() the - /// port. - /// - /// - /// - /// - /// - public bool Query() - { - if(isOpen) return false; - - hPort = m_CommAPI.QueryFile(portName); - - if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) - { - int e = Marshal.GetLastWin32Error(); - - if(e == (int)APIErrors.ERROR_ACCESS_DENIED) - { - // port is unavailable - return false; - } - - // ClearCommError failed! - string error = String.Format("CreateFile Failed: {0}", e); - throw new CommPortException(error); - } - - - // read the port's capabilities - bool status=GetPortProperties(); - - return true; - } - - // parameters without closing and reopening the port - /// - /// Updates communication settings of the port - /// - /// true if successful, false if it fails - private bool UpdateSettings() - { - if(!isOpen) return false; - - // transfer the port settings to a DCB structure - dcb.BaudRate = (uint)portSettings.BasicSettings.BaudRate; - dcb.ByteSize = portSettings.BasicSettings.ByteSize; - dcb.EofChar = (sbyte)portSettings.EOFChar; - dcb.ErrorChar = (sbyte)portSettings.ErrorChar; - dcb.EvtChar = (sbyte)portSettings.EVTChar; - dcb.fAbortOnError = portSettings.AbortOnError; - dcb.fBinary = true; - dcb.fDsrSensitivity = portSettings.DSRSensitive; - dcb.fDtrControl = (byte)portSettings.DTRControl; - dcb.fErrorChar = portSettings.ReplaceErrorChar; - dcb.fInX = portSettings.InX; - dcb.fNull = portSettings.DiscardNulls; - dcb.fOutX = portSettings.OutX; - dcb.fOutxCtsFlow = portSettings.OutCTS; - dcb.fOutxDsrFlow = portSettings.OutDSR; - dcb.fParity = (portSettings.BasicSettings.Parity == Parity.none) ? false : true; - dcb.fRtsControl = (byte)portSettings.RTSControl; - dcb.fTXContinueOnXoff = portSettings.TxContinueOnXOff; - dcb.Parity = (byte)portSettings.BasicSettings.Parity; - dcb.StopBits = (byte)portSettings.BasicSettings.StopBits; - dcb.XoffChar = (sbyte)portSettings.XoffChar; - dcb.XonChar = (sbyte)portSettings.XonChar; - - dcb.XonLim = dcb.XoffLim = (ushort)(rxBufferSize / 10); - - return m_CommAPI.SetCommState(hPort, dcb); - - } - - /// - /// Close the current serial port - /// - /// true indicates success, false indicated failure - public bool Close() - { - - if(txOverlapped != IntPtr.Zero) - { - LocalFree(txOverlapped); - txOverlapped = IntPtr.Zero; - } - - if(!isOpen) return false; - - isOpen = false; // to help catch intentional close - - if(m_CommAPI.CloseHandle(hPort)) - { - m_CommAPI.SetEvent(closeEvent); - - isOpen = false; - - hPort = (IntPtr)CommAPI.INVALID_HANDLE_VALUE; - - m_CommAPI.SetEvent(closeEvent); - - return true; - } - - return false; - } - - /// - /// The Port's output buffer. Set this property to send data. - /// - public byte[] Output - { - set - { - if(!isOpen) - throw new CommPortException("Port not open"); - - int written = 0; - - // more than threshold amount so send without buffering - if(value.GetLength(0) > sthreshold) - { - // first send anything already in the buffer - if(ptxBuffer > 0) - { - m_CommAPI.WriteFile(hPort, txBuffer, ptxBuffer, ref written, txOverlapped); - ptxBuffer = 0; - } - - m_CommAPI.WriteFile(hPort, value, (int)value.GetLength(0), ref written, txOverlapped); - } - else - { - // copy it to the tx buffer - value.CopyTo(txBuffer, (int)ptxBuffer); - ptxBuffer += (int)value.Length; - - // now if the buffer is above sthreshold, send it - if(ptxBuffer >= sthreshold) - { - m_CommAPI.WriteFile(hPort, txBuffer, ptxBuffer, ref written, txOverlapped); - ptxBuffer = 0; - } - } - } - } - - /// - /// The Port's input buffer. Incoming data is read from here and a read will pull InputLen bytes from the buffer - /// - /// - public byte[] Input - { - get - { - if(!isOpen) return null; - - int dequeueLength = 0; - - // lock the rx FIFO while reading - rxBufferBusy.WaitOne(); - - // how much data are we *actually* going to return from the call? - if(inputLength == 0) - dequeueLength = rxFIFO.Count; // pull the entire buffer - else - dequeueLength = (inputLength < rxFIFO.Count) ? inputLength : rxFIFO.Count; - - byte[] data = new byte[dequeueLength]; - - // dequeue the data - for(int p = 0 ; p < dequeueLength ; p++) - data[p] = (byte)rxFIFO.Dequeue(); - - // release the mutex so the Rx thread can continue - rxBufferBusy.ReleaseMutex(); - - return data; - } - } - - /// - /// The length of the input buffer - /// - public int InputLen - { - get - { - return inputLength; - } - set - { - inputLength = value; - } - } - - /// - /// The actual amount of data in the input buffer - /// - public int InBufferCount - { - get - { - if(!isOpen) return 0; - - return rxFIFO.Count; - } - } - - /// - /// The actual amount of data in the output buffer - /// - public int OutBufferCount - { - get - { - if(!isOpen) return 0; - - return ptxBuffer; - } - } - - /// - /// The number of bytes that the receive buffer must exceed to trigger a Receive event - /// - public int RThreshold - { - get - { - return rthreshold; - } - set - { - rthreshold = value; - } - } - - /// - /// The number of bytes that the transmit buffer must exceed to trigger a Transmit event - /// - public int SThreshold - { - get - { - return sthreshold; - } - set - { - sthreshold = value; - } - } - - /// - /// Send or check for a communications BREAK event - /// - public bool Break - { - get - { - if(!isOpen) return false; - - return (brk == 1); - } - set - { - if(!isOpen) return; - if(brk < 0) return; - if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) return; - - if (value) - { - if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.SETBREAK)) - brk = 1; - else - throw new CommPortException("Failed to set break!"); - } - else - { - if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.CLRBREAK)) - brk = 0; - else - throw new CommPortException("Failed to clear break!"); - } - } - } - - /// - /// Returns whether or not the current port support a DTR signal - /// - public bool DTRAvailable - { - get - { - return dtravail; - } - } - - /// - /// Gets or sets the current DTR line state (true = 1, false = 0) - /// - public bool DTREnable - { - get - { - return (dtr == 1); - } - set - { - if(dtr < 0) return; - if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) return; - - if (value) - { - if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.SETDTR)) - dtr = 1; - else - throw new CommPortException("Failed to set DTR!"); - } - else - { - if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.CLRDTR)) - dtr = 0; - else - throw new CommPortException("Failed to clear DTR!"); - } - } - } - - /// - /// Returns whether or not the current port support an RTS signal - /// - public bool RTSAvailable - { - get - { - return rtsavail; - } - } - - /// - /// Gets or sets the current RTS line state (true = 1, false = 0) - /// - public bool RTSEnable - { - get - { - return (rts == 1); - } - set - { - if(rts < 0) return; - if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) return; - - if (value) - { - if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.SETRTS)) - rts = 1; - else - throw new CommPortException("Failed to set RTS!"); - } - else - { - if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.CLRRTS)) - rts = 0; - else - throw new CommPortException("Failed to clear RTS!"); - } - } - } - /// - /// Gets or sets the com port for IR use (true = 1, false = 0) - /// - - public bool IREnable - { - get - { - return (setir == 1); - } - set - { - if(setir < 0) return; - if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) return; - - if (value) - { - if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.SETIR)) - setir = 1; - else - throw new CommPortException("Failed to set IR!"); - } - else - { - if (m_CommAPI.EscapeCommFunction(hPort, CommEscapes.CLRIR)) - setir = 0; - else - throw new CommPortException("Failed to clear IR!"); - } - } - } - - /// - /// Get or Set the Port's DetailedPortSettings - /// - public DetailedPortSettings DetailedSettings - { - get - { - return portSettings; - } - set - { - portSettings = value; - UpdateSettings(); - } - } - - /// - /// Get or Set the Port's BasicPortSettings - /// - public BasicPortSettings Settings - { - get - { - return portSettings.BasicSettings; - } - set - { - portSettings.BasicSettings = value; - UpdateSettings(); - } - } - - /// - /// GetPortProperties initializes the commprop member of the port object - /// - /// - private bool GetPortProperties() - { - bool success; - - success=m_CommAPI.GetCommProperties(hPort,Capabilities); - - return (success); - } - - private void CommEventThread() - { - CommEventFlags eventFlags = new CommEventFlags(); - byte[] readbuffer = new Byte[rxBufferSize]; - int bytesread = 0; - AutoResetEvent rxevent = new AutoResetEvent(false); - - // specify the set of events to be monitored for the port. - if(CommAPI.FullFramework) - { - m_CommAPI.SetCommMask(hPort, CommEventFlags.ALLPC); - - // set up the overlapped IO - OVERLAPPED o = new OVERLAPPED(); - rxOverlapped = LocalAlloc(0x40, Marshal.SizeOf(o)); - o.Offset = 0; - o.OffsetHigh = 0; - o.hEvent = rxevent.Handle; - Marshal.StructureToPtr(o, rxOverlapped, true); - } - else - { - m_CommAPI.SetCommMask(hPort, CommEventFlags.ALLCE); - } - - - try - { - // let Open() know we're started - threadStarted.Set(); - - #region >>>> thread loop <<<< - while(hPort != (IntPtr)CommAPI.INVALID_HANDLE_VALUE) - { - // wait for a Comm event - if(!m_CommAPI.WaitCommEvent(hPort, ref eventFlags)) - { - int e = Marshal.GetLastWin32Error(); - - if(e == (int)APIErrors.ERROR_IO_PENDING) - { - // IO pending so just wait and try again - rxevent.WaitOne(); - Thread.Sleep(0); - continue; - } - - if(e == (int)APIErrors.ERROR_INVALID_HANDLE) - { - // Calling Port.Close() causes hPort to become invalid - // Since Thread.Abort() is unsupported in the CF, we must - // accept that calling Close will throw an error here. - - // Close signals the closeEvent, so wait on it - // We wait 1 second, though Close should happen much sooner - int eventResult = m_CommAPI.WaitForSingleObject(closeEvent, 1000); - - if(eventResult == (int)APIConstants.WAIT_OBJECT_0) - { - // the event was set so close was called - hPort = (IntPtr)CommAPI.INVALID_HANDLE_VALUE; - - // reset our ResetEvent for the next call to Open - threadStarted.Reset(); - - if(isOpen) // this should not be the case...if so, throw an exception for the owner - { - string error = String.Format("Wait Failed: {0}", e); - throw new CommPortException(error); - } - - return; - } - } - - // WaitCommEvent failed - // 995 means an exit was requested (thread killed) - if(e == 995) - { - return; - } - else - { - string error = String.Format("Wait Failed: {0}", e); - throw new CommPortException(error); - } - } - - // Re-specify the set of events to be monitored for the port. - if(CommAPI.FullFramework) - { - m_CommAPI.SetCommMask(hPort, CommEventFlags.ALLPC); - } - else - { - m_CommAPI.SetCommMask(hPort, CommEventFlags.ALLCE); - } - - // check the event for errors - #region >>>> error checking <<<< - if(((uint)eventFlags & (uint)CommEventFlags.ERR) != 0) - { - CommErrorFlags errorFlags = new CommErrorFlags(); - CommStat commStat = new CommStat(); - - // get the error status - if(!m_CommAPI.ClearCommError(hPort, ref errorFlags, commStat)) - { - // ClearCommError failed! - string error = String.Format("ClearCommError Failed: {0}", Marshal.GetLastWin32Error()); - throw new CommPortException(error); - } - - if(((uint)errorFlags & (uint)CommErrorFlags.BREAK) != 0) - { - // BREAK can set an error, so make sure the BREAK bit is set an continue - eventFlags |= CommEventFlags.BREAK; - } - else - { - // we have an error. Build a meaningful string and throw an exception - StringBuilder s = new StringBuilder("UART Error: ", 80); - if ((errorFlags & CommErrorFlags.FRAME) != 0) - { s = s.Append("Framing,"); } - if ((errorFlags & CommErrorFlags.IOE) != 0) - { s = s.Append("IO,"); } - if ((errorFlags & CommErrorFlags.OVERRUN) != 0) - { s = s.Append("Overrun,"); } - if ((errorFlags & CommErrorFlags.RXOVER) != 0) - { s = s.Append("Receive Overflow,"); } - if ((errorFlags & CommErrorFlags.RXPARITY) != 0) - { s = s.Append("Parity,"); } - if ((errorFlags & CommErrorFlags.TXFULL) != 0) - { s = s.Append("Transmit Overflow,"); } - - // no known bits are set - if(s.Length == 12) - { s = s.Append("Unknown"); } - - // raise an error event - if(OnError != null) - OnError(s.ToString()); - - continue; - } - } // if(((uint)eventFlags & (uint)CommEventFlags.ERR) != 0) - #endregion - - #region >>>> Receive data subsection <<<< - // check for RXCHAR - if((eventFlags & CommEventFlags.RXCHAR) != 0) - { - do - { - // make sure the port handle is valid - if(hPort == (IntPtr)CommAPI.INVALID_HANDLE_VALUE) - { - bytesread = 0; - break; - } - - // data came in, put it in the buffer and set the event - if (!m_CommAPI.ReadFile(hPort, readbuffer, rxBufferSize, ref bytesread, rxOverlapped)) - { - if (Marshal.GetLastWin32Error() == CommAPI.ERROR_IO_PENDING) - { - // Thanks to Geoff McIlraith: - // Read operation was not completed on ReadFile call...block until - // complete, and grab result. - if (!m_CommAPI.GetOverlappedResult(hPort, rxOverlapped, out bytesread, true)) - { - string errString = String.Format("GetOverlappedResult Failed: {0}", Marshal.GetLastWin32Error()); - if(OnError != null) - OnError(errString); - - return; - } - } - else - { - string errString = String.Format("ReadFile Failed: {0}", Marshal.GetLastWin32Error()); - if(OnError != null) - OnError(errString); - - return; - } - } - if (bytesread >= 1) - { - // take the mutex - rxBufferBusy.WaitOne(); - - // put the data into the fifo - // this *may* be a perf problem and needs testing - for(int b = 0 ; b < bytesread ; b++) - rxFIFO.Enqueue(readbuffer[b]); - - // get the FIFO length - int fifoLength = rxFIFO.Count; - - // release the mutex - rxBufferBusy.ReleaseMutex(); - - // fire the DataReceived event every RThreshold bytes - if((DataReceived != null) && (rthreshold != 0) && (fifoLength >= rthreshold)) - { - DataReceived(); - } - } - } while (bytesread > 0); - } // if((eventFlags & CommEventFlags.RXCHAR) != 0) - #endregion - - #region >>>> line status checking <<<< - // check for status changes - uint status = 0; - m_CommAPI.GetCommModemStatus(hPort, ref status); - - // check the CTS - if(((uint)eventFlags & (uint)CommEventFlags.CTS) != 0) - { - if(CTSChange != null) - CTSChange((status & (uint)CommModemStatusFlags.MS_CTS_ON) != 0); - } - - // check the DSR - if(((uint)eventFlags & (uint)CommEventFlags.DSR) != 0) - { - if(DSRChange != null) - DSRChange((status & (uint)CommModemStatusFlags.MS_DSR_ON) != 0); - } - - // check for a RING - if(((uint)eventFlags & (uint)CommEventFlags.RING) != 0) - { - if(RingChange != null) - RingChange((status & (uint)CommModemStatusFlags.MS_RING_ON) != 0); - } - - // check for a RLSD - if(((uint)eventFlags & (uint)CommEventFlags.RLSD) != 0) - { - if(RLSDChange != null) - RLSDChange((status & (uint)CommModemStatusFlags.MS_RLSD_ON) != 0); - } - - // check for TXEMPTY - if(((uint)eventFlags & (uint)CommEventFlags.TXEMPTY) != 0) - if(TxDone != null) { TxDone(); } - - // check for RXFLAG - if(((uint)eventFlags & (uint)CommEventFlags.RXFLAG) != 0) - if(FlagCharReceived != null) { FlagCharReceived(); } - - // check for POWER - if(((uint)eventFlags & (uint)CommEventFlags.POWER) != 0) - if(PowerEvent != null) { PowerEvent(); } - - // check for high-water state - if((eventFlags & CommEventFlags.RX80FULL) != 0) - if(HighWater != null) { HighWater(); } - #endregion - } // while(true) - #endregion - } // try - catch(Exception e) - { - if(rxOverlapped != IntPtr.Zero) - LocalFree(rxOverlapped); - - if(OnError != null) - OnError(e.Message); - - return; - } - } - } -} diff --git a/gps8/Gps8/GPS_Sample8/PortCapabilities.cs b/gps8/Gps8/GPS_Sample8/PortCapabilities.cs deleted file mode 100644 index 31870bf..0000000 --- a/gps8/Gps8/GPS_Sample8/PortCapabilities.cs +++ /dev/null @@ -1,760 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.IO.Serial.PortCapabilities -// Copyright (c) 2004, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== -using System; -using System.Runtime.InteropServices; -using System.Collections.Specialized; -namespace OpenNETCF.IO.Serial -{ - // - // Serial provider type. - // -/// -/// SEP enumerates known serial provider types. Currently SERIALCOMM is the only -/// provider in this enumeration. -/// - [Flags] - public enum SEP - { - /// - /// SERIALCOMM is the only service provider supported by serial APIs. - /// - SEP_SERIALCOMM = 0x00000001 - }; - // - // Provider SubTypes - // - /// - /// PST enumerates the provider subtypes supported by the WIN32 serial APIs. PST indicates which - /// Port is used for serial communication. Ports can either be physical or logical devices. - /// - public enum PST - { - /// - /// no provider subtype specified - /// - PST_UNSPECIFIED = 0x00000000, - /// - /// RS232 Port - /// - PST_RS232 = 0x00000001, - /// - /// parallel port - /// - PST_PARALLELPORT = 0x00000002, - /// - /// RS422 Port - /// - PST_RS422 = 0x00000003, - /// - /// RS423 Port - /// - PST_RS423 = 0x00000004, - /// - /// RS449 Port - /// - PST_RS449 = 0x00000005, - /// - /// Modem - /// - PST_MODEM = 0x00000006, - /// - /// Fax - /// - PST_FAX = 0x00000021, - /// - /// Scanner - /// - PST_SCANNER = 0x00000022, - /// - /// unspecified network bridge - /// - PST_NETWORK_BRIDGE = 0x00000100, - /// - /// DEC's LAT Port - /// - PST_LAT = 0x00000101, - /// - /// Telnet connection - /// - PST_TCPIP_TELNET = 0x00000102, - /// - /// X.25 standard - /// - PST_X25 = 0x00000103 - }; - - // - // Provider capabilities flags. - // -/// -/// PCF enumerates the provider capabilites supported by the specified COMx: Port. This enumeration -/// is used internaly only. Access to this bitfield information is provided through attributes of the -/// CommProp class. -/// - [Flags] - internal enum PCF - { - PCF_DTRDSR = 0x0001, - PCF_RTSCTS = 0x0002, - PCF_RLSD = 0x0004, - PCF_PARITY_CHECK = 0x0008, - PCF_XONXOFF = 0x0010, - PCF_SETXCHAR = 0x0020, - PCF_TOTALTIMEOUTS= 0x0040, - PCF_INTTIMEOUTS = 0x0080, - PCF_SPECIALCHARS = 0x0100, - PCF_16BITMODE = 0x0200 - }; - - // - // Comm provider settable parameters. - // -/// -/// SP -/// - [Flags] - internal enum SP - { - SP_PARITY = 0x0001, - SP_BAUD = 0x0002, - SP_DATABITS = 0x0004, - SP_STOPBITS = 0x0008, - SP_HANDSHAKING = 0x0010, - SP_PARITY_CHECK = 0x0020, - SP_RLSD = 0x0040 - }; - - // - // Settable baud rates in the provider. - // - /// - /// baud rates settable by Comm API - /// - [Flags] - public enum BAUD - { - /// - /// 75 bits per second - /// - BAUD_075 = 0x00000001, - /// - /// 110 bits per second - /// - BAUD_110 = 0x00000002, - /// - /// 134.5 bits per second - /// - BAUD_134_5 = 0x00000004, - /// - /// 150 bits per second - /// - BAUD_150 = 0x00000008, - /// - /// 300 bits per second - /// - BAUD_300 = 0x00000010, - /// - /// 600 bits per second - /// - BAUD_600 = 0x00000020, - /// - /// 1,200 bits per second - /// - BAUD_1200 = 0x00000040, - /// - /// 1,800 bits per second - /// - BAUD_1800 = 0x00000080, - /// - /// 2,400 bits per second - /// - BAUD_2400 = 0x00000100, - /// - /// 4,800 bits per second - /// - BAUD_4800 = 0x00000200, - /// - /// 7,200 bits per second - /// - BAUD_7200 = 0x00000400, - /// - /// 9,600 bits per second - /// - BAUD_9600 = 0x00000800, - /// - /// 14,400 bits per second - /// - BAUD_14400 = 0x00001000, - /// - /// 19,200 bits per second - /// - BAUD_19200 = 0x00002000, - /// - /// 38,400 bits per second - /// - BAUD_38400 = 0x00004000, - /// - /// 56 Kbits per second - /// - BAUD_56K = 0x00008000, - /// - /// 129 Kbits per second - /// - BAUD_128K = 0x00010000, - /// - /// 115,200 bits per second - /// - BAUD_115200 = 0x00020000, - /// - /// 57,600 bits per second - /// - BAUD_57600 = 0x00040000, - /// - /// User defined bitrates - /// - BAUD_USER = 0x10000000 - }; - // - // Settable Data Bits - // - - [Flags] - internal enum DB - { - DATABITS_5 = 0x0001, - DATABITS_6 = 0x0002, - DATABITS_7 = 0x0004, - DATABITS_8 = 0x0008, - DATABITS_16 = 0x0010, - DATABITS_16X = 0x0020 - }; - // - // Settable Stop and Parity bits. - // - [Flags] - internal enum SB - { - STOPBITS_10 = 0x00010000, - STOPBITS_15 = 0x00020000, - STOPBITS_20 = 0x00040000, - PARITY_NONE = 0x01000000, - PARITY_ODD = 0x02000000, - PARITY_EVEN = 0x04000000, - PARITY_MARK = 0x08000000, - PARITY_SPACE = 0x10000000 - }; - // - // Set dwProvSpec1 to COMMPROP_INITIALIZED to indicate that wPacketLength - // is valid when calling GetCommProperties(). - // - [Flags] - internal enum CPS:uint - { - COMMPROP_INITIALIZED= 0xE73CF52E - }; - /// - /// Container for all available information on port's capabilties - /// - [StructLayout(LayoutKind.Sequential)] - public class CommCapabilities - { - private UInt16 wPacketLength; - private UInt16 wPacketVersion; - /// - /// Indicates which services are supported by the port. SP_SERIALCOMM is specified for communication - /// providers, including modem providers. - /// - public IO.Serial.SEP dwServiceMask; - private UInt32 dwReserved1; - /// - /// Specifies the maximum size, in bytes, of the driver's internal output buffer. A value of zero - /// indicates that no maximum value is imposed by the driver. - /// - //HGO [CLSCompliant(false)] - public UInt32 dwMaxTxQueue; - /// - /// Specifies the maximum size, in bytes, of the driver's internal input buffer. A value of zero - /// indicates that no maximum value is imposed by the driver. - /// - //HGO [CLSCompliant(false)] - public UInt32 dwMaxRxQueue; - /// - /// Specifies the maximum baud rate, in bits per second (bps). - /// - public IO.Serial.BAUD dwMaxBaud; - /// - /// Specifies the communication provider type. - /// - public IO.Serial.PST dwProvSubType; - private BitVector32 dwProvCapabilities; - private BitVector32 dwSettableParams; - private BitVector32 dwSettableBaud; - private BitVector32 dwSettableStopParityData; - /// - /// Specifies the size, in bytes, of the driver's internal output buffer. A value of zero indicates - /// that the value is unavailable. - /// - //HGO [CLSCompliant(false)] - public UInt32 dwCurrentTxQueue; - /// - /// Specifies the size, in bytes, of the driver's internal input buffer. A value of zero indicates - /// that the value is unavailable. - /// - //HGO [CLSCompliant(false)] - public UInt32 dwCurrentRxQueue; - private IO.Serial.CPS dwProvSpec1; - private UInt32 dwProvSpec2; - private UInt16 wcProvChar; - - internal CommCapabilities() - { - this.wPacketLength=(ushort)Marshal.SizeOf(this); - this.dwProvSpec1=CPS.COMMPROP_INITIALIZED; - - dwProvCapabilities=new BitVector32(0); - dwSettableParams=new BitVector32(0); - dwSettableBaud=new BitVector32(0); - dwSettableStopParityData=new BitVector32(0); - } - - // - // We need to have to define reserved fields in the CommCapabilties class definition - // to preserve the size of the - // underlying structure to match the Win32 structure when it is - // marshaled. Use these fields to suppress compiler warnings. - // - internal void _SuppressCompilerWarnings() - { - wPacketVersion +=0; - dwReserved1 +=0; - dwProvSpec1 +=0; - dwProvSpec2 +=0; - wcProvChar +=0; - } - - // Provider Capabilties - /// - /// Port supports special 16-bit mode - /// - public bool Supports16BitMode - { - get { return dwProvCapabilities[(int)PCF.PCF_16BITMODE]; } - } - - /// - /// Port supports DTR (Data Terminal ready) and DSR (Data Set Ready) flow control - /// - public bool SupportsDtrDts - { - get { return dwProvCapabilities[(int)PCF.PCF_DTRDSR]; } - } - - /// - /// Port supports interval timeouts - /// - public bool SupportsIntTimeouts - { - get { return dwProvCapabilities[(int)PCF.PCF_INTTIMEOUTS]; } - } - - /// - /// Port supports parity checking - /// - public bool SupportsParityCheck - { - get { return dwProvCapabilities[(int)PCF.PCF_PARITY_CHECK]; } - } - - /// - /// Port supports RLSD (Receive Line Signal Detect) - /// - public bool SupportsRlsd - { - get { return dwProvCapabilities[(int)PCF.PCF_RLSD]; } - } - - /// - /// Port supports RTS (Request To Send) and CTS (Clear To Send) flowcontrol - /// - public bool SupportsRtsCts - { - get { return dwProvCapabilities[(int)PCF.PCF_RTSCTS]; } - } - - /// - /// Port supports user definded characters for XON and XOFF - /// - public bool SupportsSetXChar - { - get { return dwProvCapabilities[(int)PCF.PCF_SETXCHAR]; } - } - - /// - /// Port supports special characters - /// - public bool SupportsSpecialChars - { - get { return dwProvCapabilities[(int)PCF.PCF_SPECIALCHARS]; } - } - - /// - /// Port supports total and elapsed time-outs - /// - public bool SupportsTotalTimeouts - { - get { return dwProvCapabilities[(int)PCF.PCF_TOTALTIMEOUTS]; } - } - - /// - /// Port supports XON/XOFF flow control - /// - public bool SupportsXonXoff - { - get { return dwProvCapabilities[(int)PCF.PCF_XONXOFF]; } - } - - // Settable Params - /// - /// Baud rate can be set - /// - public bool SettableBaud - { - get { return dwSettableParams[(int)SP.SP_BAUD]; } - } - - /// - /// Number of data bits can be set - /// - public bool SettableDataBits - { - get { return dwSettableParams[(int)SP.SP_DATABITS]; } - } - - /// - /// Handshake protocol can be set - /// - public bool SettableHandShaking - { - get { return dwSettableParams[(int)SP.SP_HANDSHAKING]; } - } - - /// - /// Number of parity bits can be set - /// - public bool SettableParity - { - get { return dwSettableParams[(int)SP.SP_PARITY]; } - } - - /// - /// Parity check can be enabled/disabled - /// - public bool SettableParityCheck - { - get { return dwSettableParams[(int)SP.SP_PARITY_CHECK]; } - } - /// - /// Receive Line Signal detect can be enabled/disabled - /// - public bool SettableRlsd - { - get { return dwSettableParams[(int)SP.SP_RLSD]; } - } - /// - /// Number of stop bits can be set - /// - public bool SettableStopBits - { - get { return dwSettableParams[(int)SP.SP_STOPBITS]; } - } - - // Settable Databits - /// - /// Port supports 5 data bits - /// - public bool Supports5DataBits - { - get { return dwSettableStopParityData[(int)DB.DATABITS_5]; } - } - - /// - /// Port supports 6 data bits - /// - public bool Supports6DataBits - { - get { return dwSettableStopParityData[(int)DB.DATABITS_6]; } - } - - /// - /// Port supports 7 data bits - /// - public bool Supports7DataBits - { - get { return dwSettableStopParityData[(int)DB.DATABITS_7]; } - } - - /// - /// Port supports 8 data bits - /// - public bool Supports8DataBits - { - get { return dwSettableStopParityData[(int)DB.DATABITS_8]; } - } - - /// - /// Port supports 16 data bits - /// - public bool Supports16DataBits - { - get { return dwSettableStopParityData[(int)DB.DATABITS_16]; } - } - - /// - /// Port supports special wide data path through serial hardware lines - /// - public bool Supports16XDataBits - { - get { return dwSettableStopParityData[(int)DB.DATABITS_16X]; } - } - - // Settable Stop - - /// - /// Port supports even parity - /// - public bool SupportsParityEven - { - get { return dwSettableStopParityData[(int)SB.PARITY_EVEN]; } - } - - /// - /// Port supports mark parity - /// - public bool SupportsParityMark - { - get { return dwSettableStopParityData[(int)SB.PARITY_MARK]; } - } - - /// - /// Port supports none parity - /// - public bool SupportsParityNone - { - get { return dwSettableStopParityData[(int)SB.PARITY_NONE]; } - } - - /// - /// Port supports odd parity - /// - public bool SupportsParityOdd - { - get { return dwSettableStopParityData[(int)SB.PARITY_ODD]; } - } - - /// - /// Port supports space parity - /// - public bool SupportsParitySpace - { - get { return dwSettableStopParityData[(int)SB.PARITY_SPACE]; } - } - - /// - /// Port supports 1 stop bit - /// - public bool SupportsStopBits10 - { - get { return dwSettableStopParityData[(int)SB.STOPBITS_10]; } - } - - /// - /// Port supports 1.5 stop bits - /// - public bool SupportsStopBits15 - { - get { return dwSettableStopParityData[(int)SB.STOPBITS_15]; } - } - - /// - /// Port supports 2 stop bits - /// - public bool SupportsStopBits20 - { - get { return dwSettableStopParityData[(int)SB.STOPBITS_20]; } - } - - // settable Baud Rates - /// - /// Port can be set to 75 bits per second - /// - public bool HasBaud75 - { - get { return dwSettableBaud[(int)BAUD.BAUD_075];} - } - /// - /// Port can be set to 110 bits per second - /// - public bool HasBaud110 - { - get { return dwSettableBaud[(int)BAUD.BAUD_110];} - } - /// - /// Port can be set to 134.5 bits per second - /// - public bool HasBaud134_5 - { - get { return dwSettableBaud[(int)BAUD.BAUD_134_5];} - } - /// - /// Port can be set to 150 bits per second - /// - public bool HasBaud150 - { - get { return dwSettableBaud[(int)BAUD.BAUD_150];} - } - - /// - /// Port can be set to 300 bits per second - /// - public bool HasBaud300 - { - get { return dwSettableBaud[(int)BAUD.BAUD_300];} - } - - /// - /// Port can be set to 600 bits per second - /// - public bool HasBaud600 - { - get { return dwSettableBaud[(int)BAUD.BAUD_600];} - } - - /// - /// Port can be set to 1,200 bits per second - /// - public bool HasBaud1200 - { - get { return dwSettableBaud[(int)BAUD.BAUD_1200];} - } - - /// - /// Port can be set to 2,400 bits per second - /// - public bool HasBaud2400 - { - get { return dwSettableBaud[(int)BAUD.BAUD_2400];} - } - - /// - /// Port can be set to 4,800 bits per second - /// - public bool HasBaud4800 - { - get { return dwSettableBaud[(int)BAUD.BAUD_4800];} - } - - /// - /// Port can be set to 7,200 bits per second - /// - public bool HasBaud7200 - { - get { return dwSettableBaud[(int)BAUD.BAUD_7200];} - } - - /// - /// Port can be set to 9,600 bits per second - /// - public bool HasBaud9600 - { - get { return dwSettableBaud[(int)BAUD.BAUD_9600];} - } - - /// - /// Port can be set to 14,400 bits per second - /// - public bool HasBaud14400 - { - get { return dwSettableBaud[(int)BAUD.BAUD_14400];} - } - - /// - /// Port can be set to 19,200 bits per second - /// - public bool HasBaud19200 - { - get { return dwSettableBaud[(int)BAUD.BAUD_19200];} - } - - /// - /// Port can be set to 38,400 bits per second - /// - public bool HasBaud38400 - { - get { return dwSettableBaud[(int)BAUD.BAUD_38400];} - } - - /// - /// Port can be set to 56 Kbits per second - /// - public bool HasBaud56K - { - get { return dwSettableBaud[(int)BAUD.BAUD_56K];} - } - - /// - /// Port can be set to 128 Kbits per second - /// - public bool HasBaud128K - { - get { return dwSettableBaud[(int)BAUD.BAUD_128K];} - } - - /// - /// Port can be set to 115,200 bits per second - /// - public bool HasBaud115200 - { - get { return dwSettableBaud[(int)BAUD.BAUD_115200];} - } - - /// - /// Port can be set to 57,600 bits per second - /// - public bool HasBaud57600 - { - get { return dwSettableBaud[(int)BAUD.BAUD_57600];} - } - - /// - /// Port can be set to user defined bit rate - /// - public bool HasBaudUser - { - get { return dwSettableBaud[(int)BAUD.BAUD_USER];} - } - - }; - - -} \ No newline at end of file diff --git a/gps8/Gps8/GPS_Sample8/PortSettings.cs b/gps8/Gps8/GPS_Sample8/PortSettings.cs deleted file mode 100644 index 3a7dae5..0000000 --- a/gps8/Gps8/GPS_Sample8/PortSettings.cs +++ /dev/null @@ -1,592 +0,0 @@ -//========================================================================================== -// -// OpenNETCF.IO.Serial.PortSettings -// Copyright (c) 2003, OpenNETCF.org -// -// This library is free software; you can redistribute it and/or modify it under -// the terms of the OpenNETCF.org Shared Source License. -// -// This library is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License -// for more details. -// -// You should have received a copy of the OpenNETCF.org Shared Source License -// along with this library; if not, email licensing@opennetcf.org to request a copy. -// -// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please -// email licensing@opennetcf.org. -// -// For general enquiries, email enquiries@opennetcf.org or visit our website at: -// http://www.opennetcf.org -// -//========================================================================================== - -using System; -using System.Runtime.InteropServices; - -namespace OpenNETCF.IO.Serial -{ - #region namespace enumerations - /// - /// Common ASCII Control Codes - /// - public enum ASCII : byte - { - /// - /// NULL - /// - NULL = 0x00, - /// - /// Start of Heading - /// - SOH = 0x01, - /// - /// Start of Text - /// - STX = 0x02, - /// - /// End of Text - /// - ETX = 0x03, - /// - /// End of Transmission - /// - EOT = 0x04, - /// - /// Enquiry - /// - ENQ = 0x05, - /// - /// Acknowledge - /// - ACK = 0x06, - /// - /// Bell - /// - BELL = 0x07, - /// - /// Backspace - /// - BS = 0x08, - /// - /// Horizontal tab - /// - HT = 0x09, - /// - /// Line Feed - /// - LF = 0x0A, - /// - /// Vertical tab - /// - VT = 0x0B, - /// - /// Form Feed - /// - FF = 0x0C, - /// - /// Carriage Return - /// - CR = 0x0D, - /// - /// Shift out - /// - SO = 0x0E, - /// - /// Shift in - /// - SI = 0x0F, - /// - /// Device Control 1 - /// - DC1 = 0x11, - /// - /// Device Control 2 - /// - DC2 = 0x12, - /// - /// Device Control 3 - /// - DC3 = 0x13, - /// - /// Device Control 4 - /// - DC4 = 0x14, - /// - /// No Acknowledge - /// - NAK = 0x15, - /// - /// Synchronization - /// - SYN = 0x16, - /// - /// End of Transmission Block - /// - ETB = 0x17, - /// - /// Cancel - /// - CAN = 0x18, - /// - /// End of Medium - /// - EM = 0x19, - /// - /// Substitute Character - /// - SUB = 0x1A, - /// - /// Escape - /// - ESC = 0x1B, - /// - /// Field Separator - /// - FS = 0x1C, - /// - /// Group Separator - /// - GS = 0x1D, - /// - /// Record Separator - /// - RS = 0x1E, - /// - /// Unit Separator - /// - US = 0x1F, - /// - /// Spare - /// - SP = 0x20, - /// - /// Delete - /// - DEL = 0x7F - } - - /// - /// Common serial handshaking protocols - /// - public enum Handshake - { - /// - /// No handshaking - /// - none, - /// - /// XOn/XOff handshaking - /// - XonXoff, - /// - /// CTS/RTS - /// - CtsRts, - /// - /// DSR/DTR - /// - DsrDtr - } - - /// - /// Parity - /// - public enum Parity - { - /// - /// No parity - /// - none = 0, - /// - /// Odd parity - /// - odd = 1, - /// - /// Even parity - /// - even = 2, - /// - /// Mark parity - /// - mark = 3, - /// - /// Space parity - /// - space = 4 - }; - - /// - /// Stop bits - /// - public enum StopBits - { - /// - /// One stop bit - /// - one = 0, - /// - /// 1.5 stop bits - /// - onePointFive = 1, - /// - /// Two stop bits - /// - two = 2 - }; - - /// - /// DTR Flow Control - /// - public enum DTRControlFlows - { - /// - /// Disabled - /// - disable = 0x00, - /// - /// Enabled - /// - enable = 0x01, - /// - /// Determined by handshaking - /// - handshake = 0x02 - } - - /// - /// RTS Flow Control - /// - public enum RTSControlFlows - { - /// - /// Disabled - /// - disable = 0x00, - /// - /// Enabled - /// - enable = 0x01, - /// - /// Determined by handshaking - /// - handshake = 0x02, - /// - /// Toggle - /// - toggle = 0x03 - } - - /// - /// CE-supported baud rates (check your hardware for actual availability) - /// - public enum BaudRates : int - { - /// - /// 110bpb - /// - CBR_110 = 110, - /// - /// 300bps - /// - CBR_300 = 300, - /// - /// 600bps - /// - CBR_600 = 600, - /// - /// 1200bps - /// - CBR_1200 = 1200, - /// - /// 2400bps - /// - CBR_2400 = 2400, - /// - /// 4800bps - /// - CBR_4800 = 4800, - /// - /// 9600bps - /// - CBR_9600 = 9600, - /// - /// 14.4kbps - /// - CBR_14400 = 14400, - /// - /// 19.2kbps - /// - CBR_19200 = 19200, - /// - /// 38.4kbps - /// - CBR_38400 = 38400, - /// - /// 56kbps - /// - CBR_56000 = 56000, - /// - /// 57.6kbps - /// - CBR_57600 = 57600, - /// - /// 115kbps - /// - CBR_115200 = 115200, - /// - /// 128kbps - /// - CBR_128000 = 128000, - /// - /// 225kbps - /// - CBR_230400 = 230400, - /// - /// 256kbps - /// - CBR_256000 = 256000, - /// - /// 450kbps - /// - CBR_460800= 460800, - /// - /// 900kbps - /// - CBR_921600 = 921600, - } - #endregion - - /// - /// Used for manipulating several basic Port settings of a Port class - /// - [StructLayout(LayoutKind.Sequential)] - public class BasicPortSettings - { - /// - /// Baud rate (default = 19200bps) - /// - public BaudRates BaudRate = BaudRates.CBR_19200; - /// - /// Byte Size of data (default = 8) - /// - public byte ByteSize = 8; - /// - /// Data Parity (default = none) - /// - public Parity Parity = Parity.none; - /// - /// Number of stop bits (default = 1) - /// - public StopBits StopBits = StopBits.one; - } - - /// - /// Used for manipulating all settings of a Port class - /// - [StructLayout(LayoutKind.Sequential)] - public class DetailedPortSettings - { - /// - /// Create a DetailedPortSettings class - /// - public DetailedPortSettings() - { - BasicSettings = new BasicPortSettings(); - Init(); - } - - /// - /// These are the default port settings - /// override Init() to create new defaults (i.e. common handshaking) - /// - protected virtual void Init() - { - BasicSettings.BaudRate = BaudRates.CBR_19200; - BasicSettings.ByteSize = 8; - BasicSettings.Parity = Parity.none; - BasicSettings.StopBits = StopBits.one; - - OutCTS = false; - OutDSR = false; - DTRControl = DTRControlFlows.disable; - DSRSensitive = false; - TxContinueOnXOff = true; - OutX = false; - InX = false; - ReplaceErrorChar = false; - RTSControl = RTSControlFlows.disable; - DiscardNulls = false; - AbortOnError = false; - XonChar = (char)ASCII.DC1; - XoffChar = (char)ASCII.DC3; - ErrorChar = (char)ASCII.NAK; - EOFChar = (char)ASCII.EOT; - EVTChar = (char)ASCII.NULL; - } - - /// - /// Basic port settings - /// - public BasicPortSettings BasicSettings; - /// - /// Specifies if the CTS (clear-to-send) signal is monitored for output flow control. If this member is TRUE and CTS is turned off, output is suspended until CTS is sent again. - /// - public bool OutCTS = false; - /// - /// Specifies if the DSR (data-set-ready) signal is monitored for output flow control. If this member is TRUE and DSR is turned off, output is suspended until DSR is sent again. - /// - public bool OutDSR = false; - /// - /// Specifies the DTR (data-terminal-ready) flow control. - /// - public DTRControlFlows DTRControl = DTRControlFlows.disable; - /// - /// Specifies if the communications driver is sensitive to the state of the DSR signal. If this member is TRUE, the driver ignores any bytes received, unless the DSR modem input line is high. - /// - public bool DSRSensitive = false; - /// - /// Specifies if transmission stops when the input buffer is full and the driver has transmitted the XoffChar character. If this member is TRUE, transmission continues after the input buffer has come within XoffLim bytes of being full and the driver has transmitted the XoffChar character to stop receiving bytes. If this member is FALSE, transmission does not continue until the input buffer is within XonLim bytes of being empty and the driver has transmitted the XonChar character to resume reception. - /// - public bool TxContinueOnXOff = true; - /// - /// Specifies if XON/XOFF flow control is used during transmission. If this member is TRUE, transmission stops when the XoffChar character is received and starts again when the XonChar character is received. - /// - public bool OutX = false; - /// - /// Specifies if XON/XOFF flow control is used during reception. If this member is TRUE, the XoffChar character is sent when the input buffer comes within XoffLim bytes of being full, and the XonChar character is sent when the input buffer comes within XonLim bytes of being empty - /// - public bool InX = false; - /// - /// Specifies if bytes received with parity errors are replaced with the character specified by the ErrorChar member. If this member is TRUE and the fParity member is TRUE, replacement occurs. - /// - public bool ReplaceErrorChar = false; - /// - /// Specifies the RTS (request-to-send) flow control. If this value is zero, the default is RTS_CONTROL_HANDSHAKE. The following table shows possible values for this member. - /// - public RTSControlFlows RTSControl = RTSControlFlows.disable; - /// - /// Specifies if null bytes are discarded. If this member is TRUE, null bytes are discarded when received. - /// - public bool DiscardNulls = false; - /// - /// Specifies if read and write operations are terminated if an error occurs. If this member is TRUE, the driver terminates all read and write operations with an error status if an error occurs. The driver will not accept any further communications operations until the application has acknowledged the error by calling the ClearError function. - /// - public bool AbortOnError = false; - /// - /// Specifies the value of the XON character for both transmission and reception - /// - public char XonChar = (char)ASCII.DC1; - /// - /// Specifies the value of the XOFF character for both transmission and reception. - /// - public char XoffChar = (char)ASCII.DC3; - /// - /// Specifies the value of the character used to replace bytes received with a parity error. - /// - public char ErrorChar = (char)ASCII.NAK; - /// - /// Specifies the value of the character used to signal the end of data. - /// - public char EOFChar = (char)ASCII.EOT; - /// - /// Specifies the value of the character used to signal an event. - /// - public char EVTChar = (char)ASCII.NULL; - } - - /// - /// A common implementation of DetailedPortSettings for non handshaking - /// - public class HandshakeNone : DetailedPortSettings - { - /// - /// Initialize the port - /// - protected override void Init() - { - base.Init (); - - OutCTS = false; - OutDSR = false; - OutX = false; - InX = false; - RTSControl = RTSControlFlows.enable; - DTRControl = DTRControlFlows.enable; - TxContinueOnXOff = true; - DSRSensitive = false; - } - } - - /// - /// A common implementation of DetailedPortSettings for XON/XOFF handshaking - /// - public class HandshakeXonXoff : DetailedPortSettings - { - /// - /// Initialize the port - /// - protected override void Init() - { - base.Init (); - - OutCTS = false; - OutDSR = false; - OutX = true; - InX = true; - RTSControl = RTSControlFlows.enable; - DTRControl = DTRControlFlows.enable; - TxContinueOnXOff = true; - DSRSensitive = false; - XonChar = (char)ASCII.DC1; - XoffChar = (char)ASCII.DC3; - } - } - - /// - /// A common implementation of DetailedPortSettings for CTS/RTS handshaking - /// - public class HandshakeCtsRts : DetailedPortSettings - { - /// - /// Initialize the port - /// - protected override void Init() - { - base.Init (); - - OutCTS = true; - OutDSR = false; - OutX = false; - InX = false; - RTSControl = RTSControlFlows.handshake; - DTRControl = DTRControlFlows.enable; - TxContinueOnXOff = true; - DSRSensitive = false; - } - } - - /// - /// A common implementation of DetailedPortSettings for DSR/DTR handshaking - /// - public class HandshakeDsrDtr : DetailedPortSettings - { - /// - /// Initialize the port - /// - protected override void Init() - { - base.Init (); - - OutCTS = false; - OutDSR = true; - OutX = false; - InX = false; - RTSControl = RTSControlFlows.enable; - DTRControl = DTRControlFlows.handshake; - TxContinueOnXOff = true; - DSRSensitive = false; - } - } -} diff --git a/gps8/Gps8/GPS_Sample8/ReadFile.cs b/gps8/Gps8/GPS_Sample8/ReadFile.cs deleted file mode 100644 index 1be9bd9..0000000 --- a/gps8/Gps8/GPS_Sample8/ReadFile.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; -using System.Runtime.InteropServices; - -namespace GPS_Sample8 -{ - public static class ReadFileClass - { - [DllImport("coredll.dll", SetLastError = true)] - private unsafe static extern bool ReadFile( - int hFile, // handle to file - byte[] lpBuffer, // data buffer - int nNumberOfBytesToRead, // number of bytes to read - ref int lpNumberOfBytesRead, // number of bytes read - IntPtr ptr - // - // ref OVERLAPPED lpOverlapped // overlapped buffer - ); - public const uint GENERIC_READ = 0x80000000; - public const uint GENERIC_WRITE = 0x40000000; - public const uint CREATE_NEW = 1; - public const uint CREATE_ALWAYS = 2; - public const uint OPEN_EXISTING = 3; - public const uint OPEN_ALWAYS = 4; - public const int INVALID_HANDLE_VALUE = -1; - - [DllImport("coredll.dll", SetLastError = true)] - static extern IntPtr CreateFile( - String lpFileName, - UInt32 dwDesiredAccess, - UInt32 dwShareMode, - IntPtr lpSecurityAttributes, - UInt32 dwCreationDisposition, - UInt32 dwFlagsAndAttributes, - IntPtr hTemplateFile); - - public static int readFile(string sFile, ref string sOut) - { - IntPtr handle; - int rc; - handle = CreateFile(sFile, - GENERIC_READ | GENERIC_WRITE, - 0, - IntPtr.Zero, - OPEN_EXISTING, 0, IntPtr.Zero); - if (handle.ToInt32() == INVALID_HANDLE_VALUE) - { - rc = Marshal.GetLastWin32Error(); - return rc; - } - int rxBufferSize = 500; - byte[] readbuffer = new Byte[rxBufferSize]; - int bytesread = 0; - int iHandle = handle.ToInt32(); - if (ReadFile(iHandle, readbuffer, rxBufferSize, ref bytesread, IntPtr.Zero)) - { - sOut = System.Text.ASCIIEncoding.ASCII.GetString(readbuffer, 0, bytesread); - return 0; - } - else - { - sOut = ""; - return -1; - } - } - } -} diff --git a/gps8/Gps8/GPS_Sample8/Registry.cs b/gps8/Gps8/GPS_Sample8/Registry.cs deleted file mode 100644 index 703c045..0000000 --- a/gps8/Gps8/GPS_Sample8/Registry.cs +++ /dev/null @@ -1,548 +0,0 @@ -using System; -using System.Windows.Forms; -using System.Runtime.InteropServices; -using System.Text; - -namespace PInvokeLibrary2 -{ - /// - /// Provides access to the device's registry. - /// - public class Registry - { - /// - /// Creates a registry key. - /// - /// Name of the key to be created. - /// ERROR_SUCCESS if successful - public static int CreateKey(string keyName) - { - UIntPtr hkey = UIntPtr.Zero; - uint disposition = 0; - - try - { - return RegCreateKeyEx(HKCU, keyName, 0, null, 0, - KeyAccess.None, IntPtr.Zero, ref hkey, ref disposition); - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Deletes a registry key. - /// - /// Name of key - /// ERROR_SUCCESS if successful - public static int DeleteKey(string keyName) - { - return RegDeleteKey(HKCU, keyName); - } - - /// - /// Create a string value in the specified registry key - /// - /// Name of key - /// Name of value - /// Value data - /// ERROR_SUCCESS if successful - public static int CreateValueString(string keyName, string valueName, string stringData) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = Encoding.Unicode.GetBytes(stringData); - - return RegSetValueEx(hkey, valueName, 0, KeyType.String, - bytes, (uint)bytes.Length); - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Create a DWORD value in the specified registry key - /// - /// Name of key - /// Name of value - /// Value data - /// ERROR_SUCCESS if successful - public static int CreateValueDWORD(string keyName, string valueName, uint dwordData) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = BitConverter.GetBytes(dwordData); - return RegSetValueEx(hkey, valueName, 0, KeyType.Dword, - bytes, (uint)bytes.Length); - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - public static int GetStringValue(UIntPtr tree, string keyName, string valueName, ref string stringResult) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(tree, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = null; - uint length = 0; - KeyType keyType = KeyType.None; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - null, ref length); - - if (ERROR_SUCCESS != result) - return result; - - keyType = KeyType.None; - bytes = new byte[length]; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - bytes, ref length); - - if (ERROR_SUCCESS != result) - return result; - - stringResult = Encoding.Unicode.GetString(bytes, 0, bytes.Length-1); - - return ERROR_SUCCESS; - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - /// - /// Get the specified string value registry entry - /// - /// Key name - /// Value name - /// string data - /// ERROR_SUCCESS if successful - public static int GetStringValue(string keyName, string valueName, ref string stringResult) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = null; - uint length = 0; - KeyType keyType = KeyType.None; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - null, ref length); - - if (ERROR_SUCCESS != result) - return result; - - keyType = KeyType.None; - bytes = new byte[length]; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - bytes, ref length); - - if (ERROR_SUCCESS != result) - return result; - - stringResult = Encoding.Unicode.GetString(bytes, 0, bytes.Length); - - return ERROR_SUCCESS; - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Get the specified DWORD value registry entry. - /// - /// Key name - /// Value name - /// Value data - /// ERROR_SUCCESS if successful - public static int GetDWORDValue(string keyName, string valueName, ref uint dwordResult) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = null; - uint length = 0; - KeyType keyType = KeyType.None; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - null, ref length); - - bytes = new byte[Marshal.SizeOf(typeof(uint))]; - length = (uint)bytes.Length; - keyType = KeyType.None; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - bytes, ref length); - - if (ERROR_SUCCESS != result) - return result; - - dwordResult = BitConverter.ToUInt32(bytes, 0); - - return ERROR_SUCCESS; - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Delete the specified value form the registry key. - /// - /// Key name - /// Value name - /// ERROR_SUCCESS if successful - public static int DeleteValue(string keyName, string valueName) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - return RegDeleteValue(hkey, valueName); - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Key value types - /// - public enum KeyType : uint - { - None = 0, - String = 1, - Dword = 4, - } - - /// - /// Key access types - /// - public enum KeyAccess : uint - { - None = 0x0000, - QueryValue = 0x0001, - SetValue = 0x0002, - CreateSubKey = 0x0004, - EnumerateSubKeys = 0x0008, - Notify = 0x0010, - CreateLink = 0x0020 - } - - /// - /// HKEY_CLASSES_ROOT - /// - public static UIntPtr HKCR = new UIntPtr(0x80000000); - /// - /// HKEY_CURRENT_USER - /// - public static UIntPtr HKCU = new UIntPtr(0x80000001); - /// - /// HKEY_LOCAL_MACHINE - /// - public static UIntPtr HKLM = new UIntPtr(0x80000002); - - /// - /// HKEY_USERS - /// - public static UIntPtr HKU = new UIntPtr(0x80000003); - - /// - /// Successful return value from Registry API - /// - public const int ERROR_SUCCESS = 0; - - /// - /// This function creates the specified key. If the key already exists in - /// the registry, the function opens it. A remote application interface - /// (RAPI) version of this function exists, and it is called - /// CeRegCreateKeyEx. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a null-terminated string specifying - /// the name of a subkey that this function opens or creates. The subkey - /// specified must be a subkey of the key identified by the hKey parameter. - /// This subkey must not begin with the backslash character (\). This - /// parameter cannot be NULL. In Windows CE, the maximum length of a key - /// name is 255 characters, not including the terminating NULL character. - /// You can also only nest 16 levels of sub-keys in Windows CE. - /// [in] Reserved; set to 0. - /// [in] Pointer to a null-terminated string that - /// specifies the class (object type) of this key. This parameter is ignored - /// if the key already exists. In Windows CE, the maximum length of a class - /// string is 255 characters, not including the terminating NULL - /// character. - /// [in] Ignored; set to 0 to ensure compatibility - /// with future versions of Windows CE. - /// [in] Ignored; set to 0 to ensure compatibility - /// with future versions of Windows CE. - /// [in] Set to NULL. Windows CE - /// automatically assigns the key a default security descriptor. - /// [out] Pointer to a variable that receives a - /// handle to the opened or created key. When you no longer need the - /// returned handle, call the RegCloseKey function to close it. - /// out] Pointer to a variable that receives - /// one of the following disposition values: REG_CREATED_NEW_KEY or - /// REG_OPENED_EXISTING_KEY - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the error, - /// call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. The - /// message resource is optional; therefore, if you call FormatMessage it - /// could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegCreateKeyEx - ( - UIntPtr hkey, - String lpSubKey, - uint Reserved, - StringBuilder lpClass, - uint dwOptions, - KeyAccess samDesired, - IntPtr lpSecurityAttributes, - ref UIntPtr phkResult, - ref uint lpdwDisposition - ); - - /// - /// This function deletes a named subkey from the specified registry key. - /// A remote application interface (RAPI) version of this function exists, - /// and it is called CeRegDeleteKey. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a null-terminated string - /// specifying the name of the key to delete. This parameter cannot - /// be NULL. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. - /// The message resource is optional; therefore, if you call FormatMessage - /// it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegDeleteKey - ( - UIntPtr hkey, - string subkeyName - ); - - /// - /// This function opens the specified key. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a null-terminated string - /// containing the name of the subkey to open. If this parameter is NULL - /// or a pointer to an empty string, the function will open a new handle - /// to the key identified by the hKey parameter. In this case, the function - /// will not close the handles previously opened. - /// [in] Reserved; set to 0. - /// [in] Not supported; set to 0. - /// [out] Pointer to a variable that receives - /// a handle to the opened key. When you no longer need the returned - /// handle, call the RegCloseKey function to close it. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag - /// set. The message resource is optional; therefore, if you call - /// FormatMessage it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegOpenKeyEx - ( - UIntPtr hkey, - String lpSubKey, - uint ulOptions, - KeyAccess samDesired, - ref UIntPtr phkResult - ); - - /// - /// This function retrieves the type and data for a specified value - /// name associated with an open registry key. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a string containing the - /// name of the value to query. If this parameter is NULL or an empty - /// string, the function retrieves the type and data for the keys - /// unnamed value. A registry key does not automatically have an unnamed - /// or default value. Unnamed values can be of any type. - /// [in] Reserved; set to NULL. - /// [out] Pointer to a variable that receives the - /// type of data associated with the specified value. - /// [out] Pointer to a buffer that receives the values - /// data. This parameter can be NULL if the data is not required. - /// [in/out] Pointer to a variable that specifies the - /// size, in bytes, of the buffer pointed to by the lpData parameter. When - /// the function returns, this variable contains the size of the data copied - /// to lpData. If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, - /// then lpcbData will also include the size of the terminating null character. - /// The lpcbData parameter can be NULL only if lpData is NULL. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. - /// The message resource is optional; therefore, if you call FormatMessage - /// it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegQueryValueEx - ( - UIntPtr hkey, - String lpValueName, - IntPtr lpReserved, - ref KeyType lpType, - byte[] lpData, - ref uint lpcbData - ); - - /// - /// This function stores data in the value field of an open registry key. - /// It can also set additional value and type information for the - /// specified key. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a string containing the - /// name of the value to set. If a value with this name is not already - /// present in the key, the function adds it to the key. If this parameter - /// is NULL or an empty string, the function sets the type and data for the - /// keys unnamed value. Registry keys do not have default values, but they - /// can have one unnamed value, which can be of any type. The maximum length - /// of a value name is 255, not including the terminating NULL - /// character. - /// [in] Reserved; must be zero. - /// [in] Specifies the type of information to be stored - /// as the values data. - /// [in] Pointer to a buffer containing the data to - /// be stored with the specified value name. - /// [in] Specifies the size, in bytes, of the - /// information pointed to by the lpData parameter. If the data is of - /// type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the - /// size of the terminating null character. The maximum size of data allowed - /// in Windows CE is 4 KB. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. - /// The message resource is optional; therefore, if you call FormatMessage - /// it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegSetValueEx - ( - UIntPtr hkey, - String lpValueName, - uint Reserved, - KeyType dwType, - byte[] lpData, - uint cbData - ); - - /// - /// This function removes a named value from the specified registry key. - /// A remote application interface (RAPI) version of this function exists, - /// and it is called CeRegDeleteValue. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a null-terminated string - /// that names the value to remove. If this parameter is NULL or points - /// to an empty string, the default value of the key is removed. A default - /// value is create by calling RegSetValueEx with a NULL or empty string - /// value name. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. - /// The message resource is optional; therefore, if you call FormatMessage - /// it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegDeleteValue - ( - UIntPtr hkey, - string valueName - ); - - /// - /// This function releases the handle of the specified key. A remote - /// application interface (RAPI) version of this function exists, and - /// it is called CeRegCloseKey. - /// - /// [in] Handle to the open key to close. - /// ERROR_SUCCESS indicates success. A nonzero error code - /// defined in Winerror.h indicates failure. To get a generic description - /// of the error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM - /// flag set. The message resource is optional; therefore, if you call - /// FormatMessage it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegCloseKey - ( - UIntPtr hkey - ); - - /// - /// Run a test of the Registry class. - /// - /// Delegate called to show debug information - } -} diff --git a/gps8/Gps8/GPS_Sample8/SystemTime.cs b/gps8/Gps8/GPS_Sample8/SystemTime.cs deleted file mode 100644 index b94ce91..0000000 --- a/gps8/Gps8/GPS_Sample8/SystemTime.cs +++ /dev/null @@ -1,83 +0,0 @@ -#region Using directives - -using System; -using System.Runtime.InteropServices; - -#endregion - -namespace PInvokeLibrary -{ - /// - /// Summary description for SystemTime. - /// - public class SystemTimeLib - { - [DllImport("coredll.dll")] - private extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime); - - [DllImport("coredll.dll")] - private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime); - - private struct SYSTEMTIME - { - public ushort wYear; - public ushort wMonth; - public ushort wDayOfWeek; - public ushort wDay; - public ushort wHour; - public ushort wMinute; - public ushort wSecond; - public ushort wMilliseconds; - } - // - // TODO: Add constructor logic here - // - public SystemTimeLib() - { - } - - public static DateTime GetTime() - { - // Call the native GetSystemTime method - // with the defined structure. - SYSTEMTIME stime = new SYSTEMTIME(); - GetSystemTime(ref stime); - - // Show the current time. - string strDateTime=( - stime.wDay.ToString() + "." + stime.wMonth.ToString() + "." + stime.wYear.ToString() + " "+ - stime.wHour.ToString() + ":"+ stime.wMinute.ToString()+":"+stime.wSecond.ToString() - ); - DateTime dt; - try - { - dt = DateTime.Parse(strDateTime); - } - catch (SystemException sx) - { - System.Diagnostics.Debug.WriteLine("Exception in GetTime(): " + sx.Message + "\r\n"); - dt=DateTime.Now; - } - return dt; - } - public static void SetTime(DateTime dt) - { - // Call the native GetSystemTime method - // with the defined structure. - SYSTEMTIME systime = new SYSTEMTIME(); - //GetSystemTime(ref systime); - systime.wDay = (ushort)dt.Day; - systime.wMonth = (ushort)dt.Month; - systime.wYear = (ushort)dt.Year; - systime.wHour = (ushort)dt.Hour; - systime.wMinute = (ushort)dt.Minute; - systime.wSecond = (ushort)dt.Second; - // Set the system clock ahead one hour. - //systime.wHour = (ushort)(systime.wHour + 1 % 24); - SetSystemTime(ref systime); - System.Diagnostics.Debug.WriteLine(string.Format("New time: " + systime.wHour.ToString() + ":" - + systime.wMinute.ToString()+"\r\n")); - } - } -} - diff --git a/gps8/Gps8/GPS_Sample8/bgThread2.cs b/gps8/Gps8/GPS_Sample8/bgThread2.cs deleted file mode 100644 index aab424e..0000000 --- a/gps8/Gps8/GPS_Sample8/bgThread2.cs +++ /dev/null @@ -1,269 +0,0 @@ -// a background thread class enabled to do direct calls to GUI thread -// this variant uses WM_COPY DATA to exchange data -using System; -using System.Text; -using System.Windows.Forms; -using Microsoft.WindowsCE.Forms; -using System.ComponentModel; -using System.Threading; -using System.Runtime.InteropServices; - -using gps.parser; - - public class bgThread2 : Component - { - /// - /// the bgThread2EventHandler is the protoype of the eventhandler - /// - /// - /// - public delegate void bgThread2EventHandler(object sender, BgThreadEventArgs bte); - /// - /// this event function is the 'link' back to the subscriber of the event handler - /// and will be used to fire the event in the other thread - /// - public event bgThread2EventHandler bgThread2Event; - private Container components; - /// - /// we will run a background thread. this is the thread object we use - /// - private Thread myThread; - /// - /// a var to let the thread stop - /// in reality the thread will be mostly aborted by using thread.Abort() - /// - private bool bRunThread; - /// - /// we will store the derived window handle for communication - /// - internal bgThread2WndProc bgWnd; - private string _sCOM = "COM4"; - /// - /// we use a user window message ID, not any of the predefined WM_ constants - /// - internal const int msgID = 1025; - internal const int WM_COPYDATA = 0x004A; - #region WM_COPYDATA_code - internal struct COPYDATASTRUCT - { - public int dwData; - public int cbData; //size of following string - public IntPtr lpData; //pointer to string - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct UserData - { - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)] - public string msg; - } - #endregion - #region Nested Class - - /// This is the message window we use to communicate back to the thread - /// where the bgThread2 object is created - /// so we avoid cross-threading updates problems especially with the GUI thread - /// - internal class bgThread2WndProc : MessageWindow - { - #region Fields - private bgThread2 _bgThread2; - public IntPtr hwndControl; - #endregion - #region Constructors - public bgThread2WndProc(bgThread2 Parent) - { - System.Diagnostics.Debug.WriteLine("Creating ThreadWnd..."); - this._bgThread2 = Parent; - hwndControl = Hwnd; - System.Diagnostics.Debug.WriteLine("bgThread2WndProc hWnd is 0x: "+hwndControl.ToInt32().ToString("x")); - } - #endregion - #region Methods - protected override void WndProc(ref Message m) - { - int iMsg = m.Msg; - System.Diagnostics.Debug.WriteLine("WndProc called..."); - switch (iMsg) - { - case WM_COPYDATA: - System.Diagnostics.Debug.WriteLine("WndProc sending notification ..."); - // extract the own data from the Windows Message m - COPYDATASTRUCT data = (COPYDATASTRUCT)Marshal.PtrToStructure - (m.LParam, typeof(COPYDATASTRUCT)); - UserData userData = - (UserData)Marshal.PtrToStructure(data.lpData, typeof(UserData)); - this._bgThread2.NotifyData(data.dwData, userData.msg); - m.Result = IntPtr.Zero; - break; - default: - base.WndProc(ref m); - break; - } - } - #endregion //Methods - - }//MsgWnd - #endregion - #region theClass - public bgThread2() - { - bgWnd = new bgThread2WndProc(this); - myThread = new Thread(myThreadStart); - bRunThread = true; - myThread.Start(); - } - //for the ping here is a second constuctor to enable you to specify the IP - public bgThread2(string sCOM) - { - bgWnd = new bgThread2WndProc(this); - myThread = new Thread(myThreadStart); - bRunThread = true; - _sCOM = sCOM; - myThread.Start(); - } - #region TheTHREAD - public gps.parser.Nmea parser = new gps.parser.Nmea(); - private void myThreadStart() - { - System.Diagnostics.Debug.WriteLine("Entering thread proc"); - int _i=0; - try - { - parser.NewMessage += new Nmea.NewMessageEventHandler(parser_NewMessage); - do - { - //The blocking function... - char[] cSep = new char[] { '\r', '\n' }; - int iRes = 0; - do - { - string sRes = ""; - iRes = GPS_Sample8.ReadFileClass.readFile(_sCOM, ref sRes); - string[] sAll = sRes.Split(cSep); - foreach (string s1 in sAll) - { - if (s1.Length > 0) - { - SendData(bgWnd.Hwnd, iRes, s1); - if (s1.StartsWith("$GPGSV")) - { - parser.parseString(s1); - System.Diagnostics.Debug.WriteLine("### GPS sat data: '" + s1 + "'"); - } - } - } - //Application.DoEvents(); - Thread.Sleep(100); - } while (iRes == 0); - - System.Diagnostics.Debug.WriteLine("Thread sleeps..."); - _i++; - Thread.Sleep(100); - } while (bRunThread); - } - catch (ThreadAbortException) - { - System.Diagnostics.Debug.WriteLine("Thread will abort"); - bRunThread = false; - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in ThreadStart: " + ex.Message); - } - System.Diagnostics.Debug.WriteLine("ThreadProc ended"); - } - - void parser_NewMessage(NmeaMsg msg) - { - SendData(bgWnd.Hwnd, 0, msg.ToString()); - System.Diagnostics.Debug.WriteLine("### GPS sat data: '" + msg.ToString() + "'"); - } - #endregion - private void SendData(IntPtr hWnd, int id, string sMsg) - { - COPYDATASTRUCT data = new COPYDATASTRUCT(); - - data.dwData = id;// 3; // whatever value (have to match receiver end) - data.cbData = 512;// size of UserData struct (I have two 200 bytes long ANSI array) - - UserData userData = new UserData(); - if (sMsg.Length > 500) - userData.msg = sMsg.Substring(0, 500); - else - userData.msg = sMsg; - - //copy data to unmanaged pointers - data.lpData = Marshal.AllocCoTaskMem(data.cbData); - Marshal.StructureToPtr( userData, data.lpData, false); - - IntPtr lpData = Marshal.AllocCoTaskMem(Marshal.SizeOf(data)); - Marshal.StructureToPtr(data, lpData, false); - - Message msg1 = Message.Create(hWnd, WM_COPYDATA, lpData, lpData); - MessageWindow.SendMessage(ref msg1); - - Marshal.FreeCoTaskMem(data.lpData); - Marshal.FreeCoTaskMem(lpData); - } - protected override void Dispose (bool disposing) - { - if (disposing) - { - if (this.components != null) - { - this.components.Dispose (); - } - } - this.myThread.Abort(); - base.Dispose (disposing); - } - ~bgThread2() - { - myThread.Abort(); - this.Dispose (false); - } - #region theNotifyHandlers - - private void NotifyData(int i1, string s) - { - BgThreadEventArgs _bgThread2EventArgs; - //is there any subscriber - if (this.bgThread2Event == null) - { - return; - } - try - { - _bgThread2EventArgs = new BgThreadEventArgs(i1, s); - this.bgThread2Event(this, _bgThread2EventArgs); - } - catch (MissingMethodException) - { - } - } - - #endregion - //============================================================================== - #region EventArgs - /// - /// the GUI eventhandler will get an instance of this EventArgs class - /// the instance is generated inside the bgThread2 class - /// - public class BgThreadEventArgs : EventArgs - { - #region Fields - public int iStatus; - public string sString; - #endregion - #region Constructors - public BgThreadEventArgs(int i1, string s) - { - this.iStatus = i1; - this.sString = s; - } - #endregion - } - #endregion - } - #endregion diff --git a/gps8/Gps8/GPS_Sample8/bin/Release/GPS_Sample8.exe b/gps8/Gps8/GPS_Sample8/bin/Release/GPS_Sample8.exe deleted file mode 100644 index ae5218b..0000000 Binary files a/gps8/Gps8/GPS_Sample8/bin/Release/GPS_Sample8.exe and /dev/null differ diff --git a/gps8/Gps8/GPS_Sample8/bin/Release/Microsoft.WindowsMobile.Samples.Location.dll b/gps8/Gps8/GPS_Sample8/bin/Release/Microsoft.WindowsMobile.Samples.Location.dll deleted file mode 100644 index e2827e4..0000000 Binary files a/gps8/Gps8/GPS_Sample8/bin/Release/Microsoft.WindowsMobile.Samples.Location.dll and /dev/null differ diff --git a/gps8/Gps8/GPS_Sample8/bin/Release/Microsoft.WindowsMobile.dll b/gps8/Gps8/GPS_Sample8/bin/Release/Microsoft.WindowsMobile.dll deleted file mode 100644 index 92dbb0d..0000000 Binary files a/gps8/Gps8/GPS_Sample8/bin/Release/Microsoft.WindowsMobile.dll and /dev/null differ diff --git a/gps8/Gps8/Gps/DegreesMinutesSeconds.cs b/gps8/Gps8/Gps/DegreesMinutesSeconds.cs deleted file mode 100644 index 14949ad..0000000 --- a/gps8/Gps8/Gps/DegreesMinutesSeconds.cs +++ /dev/null @@ -1,105 +0,0 @@ -#region Using directives - -using System; - -#endregion - -namespace Microsoft.WindowsMobile.Samples.Location -{ - /// - /// class that represents a gps coordinate in degrees, minutes, and seconds. - /// - public class DegreesMinutesSeconds - { - int degrees; - /// - /// The degrees unit of the coordinate - /// - public int Degrees - { - get { return degrees; } - } - - int minutes; - /// - /// The minutes unit of the coordinate - /// - public int Minutes - { - get { return minutes; } - } - - double seconds; - /// - /// The seconds unit of the coordinate - /// - public double Seconds - { - get { return seconds; } - } - - /// - /// Constructs a new instance of DegreesMinutesSeconds converting - /// from decimal degrees - /// - /// Initial value as decimal degrees - public DegreesMinutesSeconds(double decimalDegrees) - { - degrees = (int)decimalDegrees; - - double doubleMinutes = (Math.Abs(decimalDegrees) - Math.Abs((double)degrees)) * 60.0; - - minutes = (int)doubleMinutes; - seconds = (doubleMinutes - (double)minutes) * 60.0; - } - - /// - /// Constructs a new instance of DegreesMinutesSeconds - /// - /// Degrees unit of the coordinate - /// Minutes unit of the coordinate - /// Seconds unit of the coordinate - public DegreesMinutesSeconds(int degrees, int minutes, double seconds) - { - this.degrees = degrees; - this.minutes = minutes; - this.seconds = seconds; - } - - /// - /// Converts the decimal, minutes, seconds coordinate to - /// decimal degrees - /// - /// - public double ToDecimalDegrees() - { // see http://peterfoot.net/PermaLink.aspx?guid=1d7952f3-3741-4233-bae7-b36a282db99b - if (degrees == 0) - { - return 0.0; - } - - int absDegrees = Math.Abs(degrees); - - double val = (double)absDegrees + ((double)minutes / 60.0) + ((double)seconds / 3600.0); - - return val * (absDegrees / degrees); - - //int absDegrees = Math.Abs(degrees); - - //double val = (double)absDegrees + ((double)minutes / 60.0) + ((double)seconds / 3600.0); - //if ( degrees != 0) //avoid DivideByZero - // return val * (absDegrees / degrees); - //else - // return 0; - } - - /// - /// Converts the instance to a string in format: D M' S" - /// - /// string representation of degrees, minutes, seconds - public override string ToString() - { - return degrees + "d " + minutes + "' " + seconds + "\""; - } - } -} diff --git a/gps8/Gps8/Gps/DeviceStateChangedEventArgs.cs b/gps8/Gps8/Gps/DeviceStateChangedEventArgs.cs deleted file mode 100644 index 0a81177..0000000 --- a/gps8/Gps8/Gps/DeviceStateChangedEventArgs.cs +++ /dev/null @@ -1,32 +0,0 @@ -#region Using directives - -using System; - -#endregion - -namespace Microsoft.WindowsMobile.Samples.Location -{ - /// - /// Event args used for DeviceStateChanged event. - /// - public class DeviceStateChangedEventArgs: EventArgs - { - public DeviceStateChangedEventArgs(GpsDeviceState deviceState) - { - this.deviceState = deviceState; - } - - /// - /// Gets the new device state when the GPS reports a new device state. - /// - public GpsDeviceState DeviceState - { - get - { - return deviceState; - } - } - - private GpsDeviceState deviceState; - } -} diff --git a/gps8/Gps8/Gps/GPS.cs b/gps8/Gps8/Gps/GPS.cs deleted file mode 100644 index eee23c7..0000000 --- a/gps8/Gps8/Gps/GPS.cs +++ /dev/null @@ -1,360 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -// Use of this source code is subject to the terms of the Microsoft end-user -// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. -// If you did not accept the terms of the EULA, you are not authorized to use -// this source code. For a copy of the EULA, please see the LICENSE.RTF on your -// install media. -// -using System; -using System.Runtime.InteropServices; -using System.Collections; -using System.Text; - - -namespace Microsoft.WindowsMobile.Samples.Location -{ - public delegate void LocationChangedEventHandler(object sender, LocationChangedEventArgs args); - public delegate void DeviceStateChangedEventHandler(object sender, DeviceStateChangedEventArgs args); - - /// - /// Summary description for GPS. - /// - public class Gps - { - // handle to the gps device - IntPtr gpsHandle = IntPtr.Zero; - - // handle to the native event that is signalled when the GPS - // devices gets a new location - IntPtr newLocationHandle = IntPtr.Zero; - - // handle to the native event that is signalled when the GPS - // device state changes - IntPtr deviceStateChangedHandle = IntPtr.Zero; - - // handle to the native event that we use to stop our event - // thread - IntPtr stopHandle = IntPtr.Zero; - - // holds our event thread instance - System.Threading.Thread gpsEventThread = null; - - - event LocationChangedEventHandler locationChanged; - - /// - /// Event that is raised when the GPS locaction data changes - /// - public event LocationChangedEventHandler LocationChanged - { - add - { - locationChanged += value; - - // create our event thread only if the user decides to listen - CreateGpsEventThread(); - } - remove - { - locationChanged -= value; - } - } - - - event DeviceStateChangedEventHandler deviceStateChanged; - - /// - /// Event that is raised when the GPS device state changes - /// - public event DeviceStateChangedEventHandler DeviceStateChanged - { - add - { - deviceStateChanged += value; - - // create our event thread only if the user decides to listen - CreateGpsEventThread(); - } - remove - { - deviceStateChanged -= value; - } - } - - /// - /// True: The GPS device has been opened. False: It has not been opened - /// - public bool Opened - { - get { return gpsHandle != IntPtr.Zero; } - } - - public Gps() - { - } - - ~Gps() - { - // make sure that the GPS was closed. - Close(); - } - - /// - /// Opens the GPS device and prepares to receive data from it. - /// - public void Open() - { - if (!Opened) - { - // create handles for GPS events - newLocationHandle = CreateEvent(IntPtr.Zero, 0, 0, null); - deviceStateChangedHandle = CreateEvent(IntPtr.Zero, 0, 0, null); - stopHandle = CreateEvent(IntPtr.Zero, 0, 0, null); - - gpsHandle = GPSOpenDevice(newLocationHandle, deviceStateChangedHandle, null, 0); - - // if events were hooked up before the device was opened, we'll need - // to create the gps event thread. - if (locationChanged != null || deviceStateChanged != null) - { - CreateGpsEventThread(); - } - } - } - - /// - /// Closes the gps device. - /// - public void Close() - { - if (gpsHandle != IntPtr.Zero) - { - GPSCloseDevice(gpsHandle); - gpsHandle = IntPtr.Zero; - } - - // Set our native stop event so we can exit our event thread. - if (stopHandle != IntPtr.Zero) - { - EventModify(stopHandle, eventSet); - } - - // block until our event thread is finished before - // we close our native event handles - lock (this) - { - if (newLocationHandle != IntPtr.Zero) - { - CloseHandle(newLocationHandle); - newLocationHandle = IntPtr.Zero; - } - - if (deviceStateChangedHandle != IntPtr.Zero) - { - CloseHandle(deviceStateChangedHandle); - deviceStateChangedHandle = IntPtr.Zero; - } - - if (stopHandle != IntPtr.Zero) - { - CloseHandle(stopHandle); - stopHandle = IntPtr.Zero; - } - } - } - - /// - /// Get the position reported by the GPS receiver - /// - /// GpsPosition class with all the position details - public GpsPosition GetPosition() - { - return GetPosition(TimeSpan.Zero); - } - - - /// - /// Get the position reported by the GPS receiver that is no older than - /// the maxAge passed in - /// - /// Max age of the gps position data that you want back. - /// If there is no data within the required age, null is returned. - /// if maxAge == TimeSpan.Zero, then the age of the data is ignored - /// GpsPosition class with all the position details - public GpsPosition GetPosition(TimeSpan maxAge) - { - GpsPosition gpsPosition = null; - if (Opened) - { - // allocate the necessary memory on the native side. We have a class (GpsPosition) that - // has the same memory layout as its native counterpart - IntPtr ptr = Utils.LocalAlloc(Marshal.SizeOf(typeof(GpsPosition))); - - // fill in the required fields - gpsPosition = new GpsPosition(); - gpsPosition.dwVersion = 1; - gpsPosition.dwSize = Marshal.SizeOf(typeof(GpsPosition)); - - // Marshal our data to the native pointer we allocated. - Marshal.StructureToPtr(gpsPosition, ptr, false); - - // call native method passing in our native buffer - int result = GPSGetPosition(gpsHandle, ptr, 500000, 0); - if (result == 0) - { - // native call succeeded, marshal native data to our managed data - gpsPosition = (GpsPosition)Marshal.PtrToStructure(ptr, typeof(GpsPosition)); - - if (maxAge != TimeSpan.Zero) - { - // check to see if the data is recent enough. - if (!gpsPosition.TimeValid || DateTime.Now - maxAge > gpsPosition.Time) - { - gpsPosition = null; - } - } - } - - // free our native memory - Utils.LocalFree(ptr); - } - - return gpsPosition; - } - /// - /// Queries the device state. - /// - /// Device state information - public GpsDeviceState GetDeviceState() - { - GpsDeviceState device = null; - - // allocate a buffer on the native side. Since the - IntPtr pGpsDevice = Utils.LocalAlloc(GpsDeviceState.GpsDeviceStructureSize); - - // GPS_DEVICE structure has arrays of characters, it's easier to just - // write directly into memory rather than create a managed structure with - // the same layout. - Marshal.WriteInt32(pGpsDevice, 1); // write out GPS version of 1 - Marshal.WriteInt32(pGpsDevice, 4, GpsDeviceState.GpsDeviceStructureSize); // write out dwSize of structure - - int result = GPSGetDeviceState(pGpsDevice); - - if (result == 0) - { - // instantiate the GpsDeviceState class passing in the native pointer - device = new GpsDeviceState(pGpsDevice); - } - - // free our native memory - Utils.LocalFree(pGpsDevice); - - return device; - } - - /// - /// Creates our event thread that will receive native events - /// - private void CreateGpsEventThread() - { - // we only want to create the thread if we don't have one created already - // and we have opened the gps device - if (gpsEventThread == null && gpsHandle != IntPtr.Zero) - { - // Create and start thread to listen for GPS events - gpsEventThread = new System.Threading.Thread(new System.Threading.ThreadStart(WaitForGpsEvents)); - gpsEventThread.Start(); - } - } - - /// - /// Method used to listen for native events from the GPS. - /// - private void WaitForGpsEvents() - { - lock (this) - { - bool listening = true; - // allocate 3 handles worth of memory to pass to WaitForMultipleObjects - IntPtr handles = Utils.LocalAlloc(12); - - // write the three handles we are listening for. - Marshal.WriteInt32(handles, 0, stopHandle.ToInt32()); - Marshal.WriteInt32(handles, 4, deviceStateChangedHandle.ToInt32()); - Marshal.WriteInt32(handles, 8, newLocationHandle.ToInt32()); - - while (listening) - { - int obj = WaitForMultipleObjects(3, handles, 0, -1); - if (obj != waitFailed) - { - switch (obj) - { - case 0: - // we've been signalled to stop - listening = false; - break; - case 1: - // device state has changed - if (deviceStateChanged != null) - { - deviceStateChanged(this, new DeviceStateChangedEventArgs(GetDeviceState())); - } - break; - case 2: - // location has changed - if (locationChanged != null) - { - locationChanged(this, new LocationChangedEventArgs(GetPosition())); - } - break; - } - } - else - System.Diagnostics.Debug.WriteLine("wait failed"); - } - - // free the memory we allocated for the native handles - Utils.LocalFree(handles); - - // clear our gpsEventThread so that we can recreate this thread again - // if the events are hooked up again. - gpsEventThread = null; - } - } - - #region PInvokes to gpsapi.dll - [DllImport("gpsapi.dll")] - static extern IntPtr GPSOpenDevice(IntPtr hNewLocationData, IntPtr hDeviceStateChange, string szDeviceName, int dwFlags); - - [DllImport("gpsapi.dll")] - static extern int GPSCloseDevice(IntPtr hGPSDevice); - - [DllImport("gpsapi.dll")] - static extern int GPSGetPosition(IntPtr hGPSDevice, IntPtr pGPSPosition, int dwMaximumAge, int dwFlags); - - [DllImport("gpsapi.dll")] - static extern int GPSGetDeviceState(IntPtr pGPSDevice); - #endregion - #region PInvokes to coredll.dll - [DllImport("coredll.dll")] - static extern IntPtr CreateEvent(IntPtr lpEventAttributes, int bManualReset, int bInitialState, StringBuilder lpName); - - [DllImport("coredll.dll")] - static extern int CloseHandle(IntPtr hObject); - - const int waitFailed = -1; - [DllImport("coredll.dll")] - static extern int WaitForMultipleObjects(int nCount, IntPtr lpHandles, int fWaitAll, int dwMilliseconds); - - const int eventSet = 3; - [DllImport("coredll.dll")] - static extern int EventModify(IntPtr hHandle, int dwFunc); - -#endregion - - } -} diff --git a/gps8/Gps8/Gps/GPSdevice.cs b/gps8/Gps8/Gps/GPSdevice.cs deleted file mode 100644 index 9060347..0000000 --- a/gps8/Gps8/Gps/GPSdevice.cs +++ /dev/null @@ -1,137 +0,0 @@ -#region Using directives - -using System; -using System.Runtime.InteropServices; -using PInvokeLibrary; - -#endregion -namespace Microsoft.WindowsMobile.Samples.Location -{ - [StructLayout(LayoutKind.Sequential)] - public class GpsDeviceControl - { - [DllImport("coredll.dll", SetLastError = true)] - //public static extern int DeviceIoControl( - // IntPtr hDevice, - // uint dwIoControlCode, - // IntPtr lpInBuffer, - // int nInBufferSize, - // IntPtr lpOutBuffer, - // int nOutBufferSize, - // ref int lpBytesReturned, - // IntPtr lpOverlapped - //); - public static extern int DeviceIoControl( - IntPtr hDevice, - uint dwIoControlCode, - IntPtr lpInBuffer, - int nInBufferSize, - IntPtr lpOutBuffer, - int nOutBufferSize, - IntPtr lpBytesReturned, - IntPtr lpOverlapped - ); - - [DllImport("coredll.dll", SetLastError = true)] - public static extern IntPtr CreateFile( - String lpFileName, // file name - uint dwDesiredAccess, // access mode - uint dwShareMode, // share mode - IntPtr pAttr, //SecurityAttributes attr, // SD - uint dwCreationDisposition, // how to create - uint dwFlagsAndAttributes, // file attributes - uint hTemplateFile); // handle to template file - - public const uint IOCTL_SERVICE_START = 0x41000004; - public const uint IOCTL_SERVICE_STOP = 0x41000008; - public const uint IOCTL_SERVICE_REFRESH = 0x4100000C; - public const uint IOCTL_SERVICE_STATUS = 0x41000020; - public const uint GENERIC_READ = 0x80000000; - public const uint GENERIC_WRITE = 0x40000000; - public const uint CREATE_NEW =1; - public const uint CREATE_ALWAYS =2; - public const uint OPEN_EXISTING =3; - public const uint OPEN_ALWAYS = 4; - public const int INVALID_HANDLE_VALUE = -1; - - private static string GetGPSPort() - { - string szStr = ""; - if (Registry.GetStringValue(Registry.HKLM, - "System\\CurrentControlSet\\GPS Intermediate Driver\\Multiplexer", - "DriverInterface", - ref szStr) - == 0) - { - return szStr; - } - else - { - if (Registry.GetStringValue(Registry.HKLM, - "System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers", - "CurrentDriver", - ref szStr) == 0) - { - string szPath = "System\\CurrentControlSet\\GPS Intermediate Driver\\Drivers\\" + szStr; - if (Registry.GetStringValue(Registry.HKLM, szPath, "CommPort", ref szStr) == 0) - { - return szStr; - } - } - } - return ""; - } - - public static int SendIoctl(uint code) - { - int rc; - IntPtr handle; - string gpsPort = GetGPSPort(); - if (gpsPort == "") - return -1; - - handle = CreateFile("GPD0:", - GENERIC_READ | GENERIC_WRITE, - 0, - IntPtr.Zero, - OPEN_EXISTING, 0, 0); - if (handle.ToInt32() == INVALID_HANDLE_VALUE) - { - rc = Marshal.GetLastWin32Error(); - return rc; - } - - int numBytesReturned = 0; - rc = DeviceIoControl( //GPSID.NativeFile. - handle, - IOCTL_SERVICE_REFRESH, //code, //IOCTL_SERVICE_STOP, - IntPtr.Zero, - 0, - IntPtr.Zero, - 0, - IntPtr.Zero, //ref numBytesReturned, - IntPtr.Zero); - int error = Marshal.GetLastWin32Error(); - - CloseHandle(handle); - - if (rc == 0) - { - return error; - } - else - { - return 0; - } - } - //internal virtual bool CloseHandle(IntPtr hPort) { return false; } - [DllImport("coredll.dll", EntryPoint = "CloseHandle", SetLastError = true)] - private static extern int CECloseHandle(IntPtr hObject); - - private static bool CloseHandle(IntPtr hPort) - { - return Convert.ToBoolean(CECloseHandle(hPort)); - } - - } -} \ No newline at end of file diff --git a/gps8/Gps8/Gps/GpsDeviceState.cs b/gps8/Gps8/Gps/GpsDeviceState.cs deleted file mode 100644 index 4a164e9..0000000 --- a/gps8/Gps8/Gps/GpsDeviceState.cs +++ /dev/null @@ -1,144 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -// Use of this source code is subject to the terms of the Microsoft end-user -// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. -// If you did not accept the terms of the EULA, you are not authorized to use -// this source code. For a copy of the EULA, please see the LICENSE.RTF on your -// install media. -// -#region Using directives - -using System; -using System.Runtime.InteropServices; - -#endregion - -public enum GpsServiceState : int -{ - Off = 0, - On = 1, - StartingUp = 2, - ShuttingDown = 3, - Unloading = 4, - Uninitialized = 5, - Unknown = -1 -} - -namespace Microsoft.WindowsMobile.Samples.Location -{ - - [StructLayout(LayoutKind.Sequential)] - internal struct FileTime - { - int dwLowDateTime; - int dwHighDateTime; - } - - /// - /// GpsDeviceState holds the state of the gps device and the friendly name if the - /// gps supports them. - /// - [StructLayout(LayoutKind.Sequential)] - public class GpsDeviceState - { - public static int GpsMaxFriendlyName = 64; - public static int GpsDeviceStructureSize = 216; - - int serviceState = 0; - /// - /// State of the GPS Intermediate Driver service - /// - public GpsServiceState ServiceState - { - get {return (GpsServiceState)serviceState;} - } - - int deviceState = 0; - /// - /// Status of the actual GPS device driver. - /// - public GpsServiceState DeviceState - { - get {return (GpsServiceState)deviceState;} - } - - string friendlyName = ""; - /// - /// Friendly name of the real GPS device we are currently using. - /// - public string FriendlyName - { - get {return friendlyName;} - } - /// - /// String with GPSDriverPrefix - /// - string m_GPSDriverPrefix = ""; - public string GPSDriverPrefix - { - get { return m_GPSDriverPrefix; } - } - /// - /// String with GPSDriverPrefix; - /// - string m_GPSMultiplexPrefix = ""; - public string GPSMultiplexPrefix - { - get { return m_GPSMultiplexPrefix ; } - } - /// - /// Constructor of GpsDeviceState. It copies values from the native pointer - /// passed in. - /// - /// Native pointer to memory that contains - /// the GPS_DEVICE data - public GpsDeviceState(IntPtr pGpsDevice) - { - // make sure our pointer is valid - if (pGpsDevice == IntPtr.Zero) - { - throw new ArgumentException(); - } - - // read in the service state which starts at offset 8 - serviceState = Marshal.ReadInt32(pGpsDevice, 8); - // read in the device state which starts at offset 12 - deviceState = Marshal.ReadInt32(pGpsDevice, 12); - -#region GPS_DEVICE struct - // - // GPS_DEVICE contains information about the device driver and the - // service itself and is returned on a call to GPSGetDeviceState(). - // States are indicated with SERVICE_STATE_XXX flags defined in service.h - // - //#define GPS_MAX_SATELLITES 12 - //#define GPS_MAX_PREFIX_NAME 16 - //#define GPS_MAX_FRIENDLY_NAME 64 - //typedef struct _GPS_DEVICE { - // DWORD dwVersion; 0-3 // Current version of GPSID client is using. - // DWORD dwSize; 4-7 // sizeof this structure - // DWORD dwServiceState; 8-11 // State of the GPS Intermediate Driver service. - // DWORD dwDeviceState; 12-15 // Status of the actual GPS device driver. - // FILETIME ftLastDataReceived; 16-19,20-23 // Last time that the actual GPS device sent information to the intermediate driver. - // WCHAR szGPSDriverPrefix[GPS_MAX_PREFIX_NAME]; 24-55 (16x2byte)// Prefix name we are using to communicate to the base GPS driver - // WCHAR szGPSMultiplexPrefix[GPS_MAX_PREFIX_NAME]; 56-87 // Prefix name that GPS Intermediate Driver Multiplexer is running on - // WCHAR szGPSFriendlyName[GPS_MAX_FRIENDLY_NAME]; 88-215 (62x2) // Friendly name real GPS device we are currently using - //} *PGPS_DEVICE, GPS_DEVICE; -#endregion - - // the friendly name starts at offset 88 - IntPtr pFriendlyName = (IntPtr)(pGpsDevice.ToInt32() + 88); - // marshal the native string into our gpsFriendlyName - friendlyName = Marshal.PtrToStringUni(pFriendlyName); - - // - IntPtr pGPSDriverPrefix = (IntPtr)(pGpsDevice.ToInt32() + 24); - m_GPSDriverPrefix = Marshal.PtrToStringUni(pGPSDriverPrefix); - - IntPtr pGPSMultiplexPrefix = (IntPtr)(pGpsDevice.ToInt32() + 56); - m_GPSMultiplexPrefix = Marshal.PtrToStringUni(pGPSMultiplexPrefix); ; - } - } -} diff --git a/gps8/Gps8/Gps/GpsPosition.cs b/gps8/Gps8/Gps/GpsPosition.cs deleted file mode 100644 index f867e40..0000000 --- a/gps8/Gps8/Gps/GpsPosition.cs +++ /dev/null @@ -1,609 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -// Use of this source code is subject to the terms of the Microsoft end-user -// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. -// If you did not accept the terms of the EULA, you are not authorized to use -// this source code. For a copy of the EULA, please see the LICENSE.RTF on your -// install media. -// -#region Using directives - -using System; -using System.Runtime.InteropServices; -using System.Collections; - -#endregion - -namespace Microsoft.WindowsMobile.Samples.Location -{ - #region Internal Native Structures - [StructLayout(LayoutKind.Sequential)] - internal struct SystemTime - { - internal short year; - internal short month; - internal short dayOfWeek; - internal short day; - internal short hour; - internal short minute; - internal short second; - internal short millisecond; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SatelliteArray - { - int a, b, c, d, e, f, g, h, i, j, k, l; - - public int Count - { - get { return 12; } - } - - public int this[int value] - { - get - { - if (value == 0) return a; - else if (value == 1) return b; - else if (value == 2) return c; - else if (value == 3) return d; - else if (value == 4) return e; - else if (value == 5) return f; - else if (value == 6) return g; - else if (value == 7) return h; - else if (value == 8) return i; - else if (value == 9) return j; - else if (value == 10) return k; - else if (value == 11) return l; - else throw new ArgumentOutOfRangeException("value must be 0 - 11"); - } - } - } - #endregion - - public enum FixQuality : int - { - Unknown = 0, - Gps, - DGps - } - public enum FixType : int - { - Unknown = 0, - XyD, - XyzD - } - - public enum FixSelection : int - { - Unknown = 0, - Auto, - Manual - } - - public class Satellite - { - public Satellite() { } - public Satellite(int id, int elevation, int azimuth, int signalStrength) - { - this.id = id; - this.elevation = elevation; - this.azimuth = azimuth; - this.signalStrength = signalStrength; - } - - int id; - /// - /// Id of the satellite - /// - public int Id - { - get - { - return id; - } - set - { - id = value; - } - } - - - int elevation; - /// - /// Elevation of the satellite - /// - public int Elevation - { - get - { - return elevation; - } - set - { - elevation = value; - } - } - - - int azimuth; - /// - /// Azimuth of the satellite - /// - public int Azimuth - { - get - { - return azimuth; - } - set - { - azimuth = value; - } - } - - - int signalStrength; - /// - /// SignalStrenth of the satellite - /// - public int SignalStrength - { - get - { - return signalStrength; - } - set - { - signalStrength = value; - } - } - - } - - [StructLayout(LayoutKind.Sequential)] - public class GpsPosition - { - internal GpsPosition() { } - internal static int GPS_VALID_UTC_TIME = 0x00000001; - internal static int GPS_VALID_LATITUDE = 0x00000002; - internal static int GPS_VALID_LONGITUDE = 0x00000004; - internal static int GPS_VALID_SPEED = 0x00000008; - internal static int GPS_VALID_HEADING = 0x00000010; - internal static int GPS_VALID_MAGNETIC_VARIATION = 0x00000020; - internal static int GPS_VALID_ALTITUDE_WRT_SEA_LEVEL = 0x00000040; - internal static int GPS_VALID_ALTITUDE_WRT_ELLIPSOID = 0x00000080; - internal static int GPS_VALID_POSITION_DILUTION_OF_PRECISION = 0x00000100; - internal static int GPS_VALID_HORIZONTAL_DILUTION_OF_PRECISION = 0x00000200; - internal static int GPS_VALID_VERTICAL_DILUTION_OF_PRECISION = 0x00000400; - internal static int GPS_VALID_SATELLITE_COUNT = 0x00000800; - internal static int GPS_VALID_SATELLITES_USED_PRNS = 0x00001000; - internal static int GPS_VALID_SATELLITES_IN_VIEW = 0x00002000; - internal static int GPS_VALID_SATELLITES_IN_VIEW_PRNS = 0x00004000; - internal static int GPS_VALID_SATELLITES_IN_VIEW_ELEVATION = 0x00008000; - internal static int GPS_VALID_SATELLITES_IN_VIEW_AZIMUTH = 0x00010000; - internal static int GPS_VALID_SATELLITES_IN_VIEW_SIGNAL_TO_NOISE_RATIO = 0x00020000; - - - internal int dwVersion = 1; // Current version of GPSID client is using. - internal int dwSize = 0; // sizeof(_GPS_POSITION) - - // Not all fields in the structure below are guaranteed to be valid. - // Which fields are valid depend on GPS device being used, how stale the API allows - // the data to be, and current signal. - // Valid fields are specified in dwValidFields, based on GPS_VALID_XXX flags. - internal int dwValidFields = 0; - - // Additional information about this location structure (GPS_DATA_FLAGS_XXX) - internal int dwFlags = 0; - - //** Time related - internal SystemTime stUTCTime = new SystemTime(); // UTC according to GPS clock. - - //** Position + heading related - internal double dblLatitude = 0.0; // Degrees latitude. North is positive - internal double dblLongitude = 0.0; // Degrees longitude. East is positive - internal float flSpeed = 0.0f; // Speed in knots - internal float flHeading = 0.0f; // Degrees heading (course made good). True North=0 - internal double dblMagneticVariation = 0.0; // Magnetic variation. East is positive - internal float flAltitudeWRTSeaLevel = 0.0f; // Altitute with regards to sea level, in meters - internal float flAltitudeWRTEllipsoid = 0.0f; // Altitude with regards to ellipsoid, in meters - - //** Quality of this fix - // Where did we get fix from? - internal FixQuality fixQuality = FixQuality.Unknown; - // Is this 2d or 3d fix? - internal FixType fixType = FixType.Unknown; - // Auto or manual selection between 2d or 3d mode - internal FixSelection selectionType = FixSelection.Unknown; - // Position Dilution Of Precision - internal float flPositionDilutionOfPrecision = 0.0f; - // Horizontal Dilution Of Precision - internal float flHorizontalDilutionOfPrecision = 0.0f; - // Vertical Dilution Of Precision - internal float flVerticalDilutionOfPrecision = 0.0f; - - //** Satellite information - // Number of satellites used in solution - internal int dwSatelliteCount = 0; - // PRN numbers of satellites used in the solution - internal SatelliteArray rgdwSatellitesUsedPRNs = new SatelliteArray(); - // Number of satellites in view. From 0-GPS_MAX_SATELLITES - internal int dwSatellitesInView = 0; - // PRN numbers of satellites in view - internal SatelliteArray rgdwSatellitesInViewPRNs = new SatelliteArray(); - // Elevation of each satellite in view - internal SatelliteArray rgdwSatellitesInViewElevation = new SatelliteArray(); - // Azimuth of each satellite in view - internal SatelliteArray rgdwSatellitesInViewAzimuth = new SatelliteArray(); - // Signal to noise ratio of each satellite in view - internal SatelliteArray rgdwSatellitesInViewSignalToNoiseRatio = new SatelliteArray(); - - public FixType eFixType - { - get { - return fixType; - } - } - - public FixQuality eFixQuality - { - get - { - return fixQuality; - } - } - - public FixSelection eFixSelection - { - get { - return selectionType; - } - } - /// - /// UTC according to GPS clock. - /// - public DateTime Time - { - get - { - DateTime time = new DateTime(stUTCTime.year, stUTCTime.month, stUTCTime.day, stUTCTime.hour, stUTCTime.minute, stUTCTime.second, stUTCTime.millisecond); - return time; - } - - } - /// - /// True if the Time property is valid, false if invalid - /// - public bool TimeValid - { - get { return (dwValidFields & GPS_VALID_UTC_TIME) != 0; } - } - - - /// - /// Satellites used in the solution - /// - /// Array of Satellites - public Satellite[] GetSatellitesInSolution() - { - Satellite[] inViewSatellites = GetSatellitesInView(); - ArrayList list = new ArrayList(); - for (int index = 0; index < dwSatelliteCount; index++) - { - Satellite found = null; - for (int viewIndex = 0; viewIndex < inViewSatellites.Length && found == null; viewIndex++) - { - if (rgdwSatellitesUsedPRNs[index] == inViewSatellites[viewIndex].Id) - { - found = inViewSatellites[viewIndex]; - list.Add(found); - } - } - } - - return (Satellite[])list.ToArray(typeof(Satellite)); - } - /// - /// True if the SatellitesInSolution property is valid, false if invalid - /// - public bool SatellitesInSolutionValid - { - get { return (dwValidFields & GPS_VALID_SATELLITES_USED_PRNS) != 0; } - } - - - - /// - /// Satellites in view - /// - /// Array of Satellites - public Satellite[] GetSatellitesInView() - { - Satellite[] satellites = null; - if (dwSatellitesInView != 0) - { - satellites = new Satellite[dwSatellitesInView]; - for (int index = 0; index < satellites.Length; index++) - { - satellites[index] = new Satellite(); - satellites[index].Azimuth = rgdwSatellitesInViewAzimuth[index]; - satellites[index].Elevation = rgdwSatellitesInViewElevation[index]; - satellites[index].Id = rgdwSatellitesInViewPRNs[index]; - satellites[index].SignalStrength = rgdwSatellitesInViewSignalToNoiseRatio[index]; - } - } - - return satellites; - } - /// - /// True if the SatellitesInView property is valid, false if invalid - /// - public bool SatellitesInViewValid - { - get { return (dwValidFields & GPS_VALID_SATELLITES_IN_VIEW) != 0; } - } - - - /// - /// Number of satellites used in solution - /// - public int SatelliteCount - { - get { return dwSatelliteCount; } - } - /// - /// True if the SatelliteCount property is valid, false if invalid - /// - public bool SatelliteCountValid - { - get { return (dwValidFields & GPS_VALID_SATELLITE_COUNT) != 0; } - } - - /// - /// Number of satellites in view. - /// - public int SatellitesInViewCount - { - get { return dwSatellitesInView; } - } - /// - /// True if the SatellitesInViewCount property is valid, false if invalid - /// - public bool SatellitesInViewCountValid - { - get { return (dwValidFields & GPS_VALID_SATELLITES_IN_VIEW) != 0; } - } - - /// - /// Speed in knots - /// - public float Speed - { - get { return flSpeed; } - } - /// - /// True if the Speed property is valid, false if invalid - /// - public bool SpeedValid - { - get { return (dwValidFields & GPS_VALID_SPEED) != 0; } - } - - /// - /// Altitude with regards to ellipsoid, in meters - /// - public float EllipsoidAltitude - { - get { return flAltitudeWRTEllipsoid; } - } - /// - /// True if the EllipsoidAltitude property is valid, false if invalid - /// - public bool EllipsoidAltitudeValid - { - get { return (dwValidFields & GPS_VALID_ALTITUDE_WRT_ELLIPSOID) != 0; } - } - - /// - /// Altitute with regards to sea level, in meters - /// - public float SeaLevelAltitude - { - get { return flAltitudeWRTSeaLevel; } - } - /// - /// True if the SeaLevelAltitude property is valid, false if invalid - /// - public bool SeaLevelAltitudeValid - { - get { return (dwValidFields & GPS_VALID_ALTITUDE_WRT_SEA_LEVEL) != 0; } - } - - /// - /// Latitude in decimal degrees. North is positive - /// - public double Latitude - { - get { return dblLatitude; } - } - - //public double Latitude - //{ - // get { return ParseDegreesMinutesSeconds(dblLatitude).ToDecimalDegrees(); } - //} - /// - /// Latitude in degrees, minutes, seconds. North is positive - /// - public DegreesMinutesSeconds LatitudeInDegreesMinutesSeconds - { - get { return ParseDegreesMinutesSeconds(dblLatitude); } - } - - /// - /// True if the Latitude property is valid, false if invalid - /// - public bool LatitudeValid - { - get { return (dwValidFields & GPS_VALID_LATITUDE) != 0; } - } - - /// - /// Longitude in decimal degrees. East is positive - /// - public double Longitude - { - get { return dblLongitude; } - } - //public double Longitude - //{ - // get { return ParseDegreesMinutesSeconds(dblLongitude).ToDecimalDegrees(); } - //} - - /// - /// Longitude in degrees, minutes, seconds. East is positive - /// - public DegreesMinutesSeconds LongitudeInDegreesMinutesSeconds - { - get { return ParseDegreesMinutesSeconds(dblLongitude); } - } - /// - /// True if the Longitude property is valid, false if invalid - /// - public bool LongitudeValid - { - get { return (dwValidFields & GPS_VALID_LONGITUDE) != 0; } - } - - /// - /// Degrees heading (course made good). True North=0 - /// - public float Heading - { - get { return flHeading; } - } - /// - /// True if the Heading property is valid, false if invalid - /// - public bool HeadingValid - { - get { return (dwValidFields & GPS_VALID_HEADING) != 0; } - } - - /// - /// Position Dilution Of Precision - /// - public float PositionDilutionOfPrecision - { - get { return flPositionDilutionOfPrecision; } - } - /// - /// True if the PositionDilutionOfPrecision property is valid, false if invalid - /// - public bool PositionDilutionOfPrecisionValid - { - get { return (dwValidFields & GPS_VALID_POSITION_DILUTION_OF_PRECISION) != 0; } - } - - /// - /// Horizontal Dilution Of Precision - /// - public float HorizontalDilutionOfPrecision - { - get { return flHorizontalDilutionOfPrecision; } - } - /// - /// True if the HorizontalDilutionOfPrecision property is valid, false if invalid - /// - public bool HorizontalDilutionOfPrecisionValid - { - get { return (dwValidFields & GPS_VALID_HORIZONTAL_DILUTION_OF_PRECISION) != 0; } - } - - /// - /// Vertical Dilution Of Precision - /// - public float VerticalDilutionOfPrecision - { - get { return flVerticalDilutionOfPrecision; } - } - /// - /// True if the VerticalDilutionOfPrecision property is valid, false if invalid - /// - public bool VerticalDilutionOfPrecisionValid - { - get { return (dwValidFields & GPS_VALID_VERTICAL_DILUTION_OF_PRECISION) != 0; } - } - - /// - /// Parses out the degrees, minutes, seconds from the double format returned by - /// the NMEA GPS device - /// - /// degrees, minutes, seconds as a double - /// DegreesMinutesSeconds structure - private DegreesMinutesSeconds ParseDegreesMinutesSeconds(double val) - { - double degrees; - //DivideByZero ?? - if (val != 0) - degrees = (val / 100.0); - else - degrees = 0; - double minutes = (Math.Abs(degrees) - Math.Abs((double)(int)(degrees))) * 100; - double seconds = (Math.Abs(val) - Math.Abs((double)(int)val)) * 60.0; - - return new DegreesMinutesSeconds((int)degrees, (int)minutes, seconds); - } - } - //// - //// GPS_POSITION contains our latest physical coordinates, the time, - //// and satellites used in determining these coordinates. - //// - //typedef struct _GPS_POSITION { - // DWORD dwVersion; // Current version of GPSID client is using. - // DWORD dwSize; // sizeof(_GPS_POSITION) - - // // Not all fields in the structure below are guaranteed to be valid. - // // Which fields are valid depend on GPS device being used, how stale the API allows - // // the data to be, and current signal. - // // Valid fields are specified in dwValidFields, based on GPS_VALID_XXX flags. - // DWORD dwValidFields; - - // // Additional information about this location structure (GPS_DATA_FLAGS_XXX) - // DWORD dwFlags; - - // //** Time related - // SYSTEMTIME stUTCTime; // UTC according to GPS clock. - - // //** Position + heading related - // double dblLatitude; // Degrees latitude. North is positive - // double dblLongitude; // Degrees longitude. East is positive - // float flSpeed; // Speed in knots - // float flHeading; // Degrees heading (course made good). True North=0 - // double dblMagneticVariation; // Magnetic variation. East is positive - // float flAltitudeWRTSeaLevel; // Altitute with regards to sea level, in meters - // float flAltitudeWRTEllipsoid; // Altitude with regards to ellipsoid, in meters - - // //** Quality of this fix - // GPS_FIX_QUALITY FixQuality; // Where did we get fix from? - // GPS_FIX_TYPE FixType; // Is this 2d or 3d fix? - // GPS_FIX_SELECTION SelectionType; // Auto or manual selection between 2d or 3d mode - // float flPositionDilutionOfPrecision; // Position Dilution Of Precision - // float flHorizontalDilutionOfPrecision; // Horizontal Dilution Of Precision - // float flVerticalDilutionOfPrecision; // Vertical Dilution Of Precision - - // //** Satellite information - // DWORD dwSatelliteCount; // Number of satellites used in solution - // DWORD rgdwSatellitesUsedPRNs[GPS_MAX_SATELLITES]; // PRN numbers of satellites used in the solution - - // DWORD dwSatellitesInView; // Number of satellites in view. From 0-GPS_MAX_SATELLITES - // DWORD rgdwSatellitesInViewPRNs[GPS_MAX_SATELLITES]; // PRN numbers of satellites in view - // DWORD rgdwSatellitesInViewElevation[GPS_MAX_SATELLITES]; // Elevation of each satellite in view - // DWORD rgdwSatellitesInViewAzimuth[GPS_MAX_SATELLITES]; // Azimuth of each satellite in view - // DWORD rgdwSatellitesInViewSignalToNoiseRatio[GPS_MAX_SATELLITES]; // Signal to noise ratio of each satellite in view - // } GPS_POSITION, *PGPS_POSITION; - -} diff --git a/gps8/Gps8/Gps/LocationChangedEventArgs.cs b/gps8/Gps8/Gps/LocationChangedEventArgs.cs deleted file mode 100644 index 9b6418c..0000000 --- a/gps8/Gps8/Gps/LocationChangedEventArgs.cs +++ /dev/null @@ -1,33 +0,0 @@ -#region Using directives - -using System; - -#endregion - -namespace Microsoft.WindowsMobile.Samples.Location -{ - /// - /// Event args used for LocationChanged events. - /// - public class LocationChangedEventArgs: EventArgs - { - public LocationChangedEventArgs(GpsPosition position) - { - this.position = position; - } - - /// - /// Gets the new position when the GPS reports a new position. - /// - public GpsPosition Position - { - get - { - return position; - } - } - - private GpsPosition position; - - } -} diff --git a/gps8/Gps8/Gps/Microsoft.WindowsMobile.Samples.Location.csproj b/gps8/Gps8/Gps/Microsoft.WindowsMobile.Samples.Location.csproj deleted file mode 100644 index 40cc54e..0000000 --- a/gps8/Gps8/Gps/Microsoft.WindowsMobile.Samples.Location.csproj +++ /dev/null @@ -1,77 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {DB77C1EE-A383-4CD5-A107-1C7C26A9E6B8} - Library - Microsoft.WindowsMobile.Samples.Location - Microsoft.WindowsMobile.Samples.Location - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - b2c48bd2-963d-4549-9169-1fa021dce484 - 5.02 - ManagedGPS - v2.0 - - - - - - - 2.0 - Windows Mobile 6 Professional SDK - - - true - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - 512 - 4 - off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - 512 - 4 - off - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/gps8/Gps8/Gps/Properties/AssemblyInfo.cs b/gps8/Gps8/Gps/Properties/AssemblyInfo.cs deleted file mode 100644 index 0ed2fb9..0000000 --- a/gps8/Gps8/Gps/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -// Use of this source code is subject to the terms of the Microsoft end-user -// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. -// If you did not accept the terms of the EULA, you are not authorized to use -// this source code. For a copy of the EULA, please see the LICENSE.RTF on your -// install media. -// -using System.Reflection; -using System.Runtime.CompilerServices; - -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// -[assembly: AssemblyTitle("Microsoft.WindowsMobile.Samples.Location")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Microsoft.WindowsMobile.Samples.Location")] -[assembly: AssemblyCopyright("Copyright Microsoft 2005")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly: AssemblyVersion("1.0.*")] diff --git a/gps8/Gps8/Gps/Registry.cs b/gps8/Gps8/Gps/Registry.cs deleted file mode 100644 index 165c4e2..0000000 --- a/gps8/Gps8/Gps/Registry.cs +++ /dev/null @@ -1,547 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.Text; - -namespace PInvokeLibrary -{ - /// - /// Provides access to the device's registry. - /// - public class Registry - { - /// - /// Creates a registry key. - /// - /// Name of the key to be created. - /// ERROR_SUCCESS if successful - public static int CreateKey(string keyName) - { - UIntPtr hkey = UIntPtr.Zero; - uint disposition = 0; - - try - { - return RegCreateKeyEx(HKCU, keyName, 0, null, 0, - KeyAccess.None, IntPtr.Zero, ref hkey, ref disposition); - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Deletes a registry key. - /// - /// Name of key - /// ERROR_SUCCESS if successful - public static int DeleteKey(string keyName) - { - return RegDeleteKey(HKCU, keyName); - } - - /// - /// Create a string value in the specified registry key - /// - /// Name of key - /// Name of value - /// Value data - /// ERROR_SUCCESS if successful - public static int CreateValueString(string keyName, string valueName, string stringData) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = Encoding.Unicode.GetBytes(stringData); - - return RegSetValueEx(hkey, valueName, 0, KeyType.String, - bytes, (uint)bytes.Length); - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Create a DWORD value in the specified registry key - /// - /// Name of key - /// Name of value - /// Value data - /// ERROR_SUCCESS if successful - public static int CreateValueDWORD(string keyName, string valueName, uint dwordData) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = BitConverter.GetBytes(dwordData); - return RegSetValueEx(hkey, valueName, 0, KeyType.Dword, - bytes, (uint)bytes.Length); - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - public static int GetStringValue(UIntPtr tree, string keyName, string valueName, ref string stringResult) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(tree, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = null; - uint length = 0; - KeyType keyType = KeyType.None; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - null, ref length); - - if (ERROR_SUCCESS != result) - return result; - - keyType = KeyType.None; - bytes = new byte[length]; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - bytes, ref length); - - if (ERROR_SUCCESS != result) - return result; - - stringResult = Encoding.Unicode.GetString(bytes, 0, bytes.Length-1); - - return ERROR_SUCCESS; - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - /// - /// Get the specified string value registry entry - /// - /// Key name - /// Value name - /// string data - /// ERROR_SUCCESS if successful - public static int GetStringValue(string keyName, string valueName, ref string stringResult) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = null; - uint length = 0; - KeyType keyType = KeyType.None; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - null, ref length); - - if (ERROR_SUCCESS != result) - return result; - - keyType = KeyType.None; - bytes = new byte[length]; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - bytes, ref length); - - if (ERROR_SUCCESS != result) - return result; - - stringResult = Encoding.Unicode.GetString(bytes, 0, bytes.Length); - - return ERROR_SUCCESS; - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Get the specified DWORD value registry entry. - /// - /// Key name - /// Value name - /// Value data - /// ERROR_SUCCESS if successful - public static int GetDWORDValue(string keyName, string valueName, ref uint dwordResult) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - byte[] bytes = null; - uint length = 0; - KeyType keyType = KeyType.None; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - null, ref length); - - bytes = new byte[Marshal.SizeOf(typeof(uint))]; - length = (uint)bytes.Length; - keyType = KeyType.None; - - result = RegQueryValueEx(hkey, valueName, IntPtr.Zero, ref keyType, - bytes, ref length); - - if (ERROR_SUCCESS != result) - return result; - - dwordResult = BitConverter.ToUInt32(bytes, 0); - - return ERROR_SUCCESS; - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Delete the specified value form the registry key. - /// - /// Key name - /// Value name - /// ERROR_SUCCESS if successful - public static int DeleteValue(string keyName, string valueName) - { - UIntPtr hkey = UIntPtr.Zero; - - try - { - int result = RegOpenKeyEx(HKCU, keyName, 0, KeyAccess.None, ref hkey); - if (ERROR_SUCCESS != result) - return result; - - return RegDeleteValue(hkey, valueName); - } - finally - { - if (UIntPtr.Zero != hkey) - { - RegCloseKey(hkey); - } - } - } - - /// - /// Key value types - /// - public enum KeyType : uint - { - None = 0, - String = 1, - Dword = 4, - } - - /// - /// Key access types - /// - public enum KeyAccess : uint - { - None = 0x0000, - QueryValue = 0x0001, - SetValue = 0x0002, - CreateSubKey = 0x0004, - EnumerateSubKeys = 0x0008, - Notify = 0x0010, - CreateLink = 0x0020 - } - - /// - /// HKEY_CLASSES_ROOT - /// - public static UIntPtr HKCR = new UIntPtr(0x80000000); - /// - /// HKEY_CURRENT_USER - /// - public static UIntPtr HKCU = new UIntPtr(0x80000001); - /// - /// HKEY_LOCAL_MACHINE - /// - public static UIntPtr HKLM = new UIntPtr(0x80000002); - - /// - /// HKEY_USERS - /// - public static UIntPtr HKU = new UIntPtr(0x80000003); - - /// - /// Successful return value from Registry API - /// - public const int ERROR_SUCCESS = 0; - - /// - /// This function creates the specified key. If the key already exists in - /// the registry, the function opens it. A remote application interface - /// (RAPI) version of this function exists, and it is called - /// CeRegCreateKeyEx. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a null-terminated string specifying - /// the name of a subkey that this function opens or creates. The subkey - /// specified must be a subkey of the key identified by the hKey parameter. - /// This subkey must not begin with the backslash character (\). This - /// parameter cannot be NULL. In Windows CE, the maximum length of a key - /// name is 255 characters, not including the terminating NULL character. - /// You can also only nest 16 levels of sub-keys in Windows CE. - /// [in] Reserved; set to 0. - /// [in] Pointer to a null-terminated string that - /// specifies the class (object type) of this key. This parameter is ignored - /// if the key already exists. In Windows CE, the maximum length of a class - /// string is 255 characters, not including the terminating NULL - /// character. - /// [in] Ignored; set to 0 to ensure compatibility - /// with future versions of Windows CE. - /// [in] Ignored; set to 0 to ensure compatibility - /// with future versions of Windows CE. - /// [in] Set to NULL. Windows CE - /// automatically assigns the key a default security descriptor. - /// [out] Pointer to a variable that receives a - /// handle to the opened or created key. When you no longer need the - /// returned handle, call the RegCloseKey function to close it. - /// out] Pointer to a variable that receives - /// one of the following disposition values: REG_CREATED_NEW_KEY or - /// REG_OPENED_EXISTING_KEY - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the error, - /// call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. The - /// message resource is optional; therefore, if you call FormatMessage it - /// could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegCreateKeyEx - ( - UIntPtr hkey, - String lpSubKey, - uint Reserved, - StringBuilder lpClass, - uint dwOptions, - KeyAccess samDesired, - IntPtr lpSecurityAttributes, - ref UIntPtr phkResult, - ref uint lpdwDisposition - ); - - /// - /// This function deletes a named subkey from the specified registry key. - /// A remote application interface (RAPI) version of this function exists, - /// and it is called CeRegDeleteKey. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a null-terminated string - /// specifying the name of the key to delete. This parameter cannot - /// be NULL. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. - /// The message resource is optional; therefore, if you call FormatMessage - /// it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegDeleteKey - ( - UIntPtr hkey, - string subkeyName - ); - - /// - /// This function opens the specified key. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a null-terminated string - /// containing the name of the subkey to open. If this parameter is NULL - /// or a pointer to an empty string, the function will open a new handle - /// to the key identified by the hKey parameter. In this case, the function - /// will not close the handles previously opened. - /// [in] Reserved; set to 0. - /// [in] Not supported; set to 0. - /// [out] Pointer to a variable that receives - /// a handle to the opened key. When you no longer need the returned - /// handle, call the RegCloseKey function to close it. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag - /// set. The message resource is optional; therefore, if you call - /// FormatMessage it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegOpenKeyEx - ( - UIntPtr hkey, - String lpSubKey, - uint ulOptions, - KeyAccess samDesired, - ref UIntPtr phkResult - ); - - /// - /// This function retrieves the type and data for a specified value - /// name associated with an open registry key. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a string containing the - /// name of the value to query. If this parameter is NULL or an empty - /// string, the function retrieves the type and data for the keys - /// unnamed value. A registry key does not automatically have an unnamed - /// or default value. Unnamed values can be of any type. - /// [in] Reserved; set to NULL. - /// [out] Pointer to a variable that receives the - /// type of data associated with the specified value. - /// [out] Pointer to a buffer that receives the values - /// data. This parameter can be NULL if the data is not required. - /// [in/out] Pointer to a variable that specifies the - /// size, in bytes, of the buffer pointed to by the lpData parameter. When - /// the function returns, this variable contains the size of the data copied - /// to lpData. If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, - /// then lpcbData will also include the size of the terminating null character. - /// The lpcbData parameter can be NULL only if lpData is NULL. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. - /// The message resource is optional; therefore, if you call FormatMessage - /// it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegQueryValueEx - ( - UIntPtr hkey, - String lpValueName, - IntPtr lpReserved, - ref KeyType lpType, - byte[] lpData, - ref uint lpcbData - ); - - /// - /// This function stores data in the value field of an open registry key. - /// It can also set additional value and type information for the - /// specified key. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a string containing the - /// name of the value to set. If a value with this name is not already - /// present in the key, the function adds it to the key. If this parameter - /// is NULL or an empty string, the function sets the type and data for the - /// keys unnamed value. Registry keys do not have default values, but they - /// can have one unnamed value, which can be of any type. The maximum length - /// of a value name is 255, not including the terminating NULL - /// character. - /// [in] Reserved; must be zero. - /// [in] Specifies the type of information to be stored - /// as the values data. - /// [in] Pointer to a buffer containing the data to - /// be stored with the specified value name. - /// [in] Specifies the size, in bytes, of the - /// information pointed to by the lpData parameter. If the data is of - /// type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the - /// size of the terminating null character. The maximum size of data allowed - /// in Windows CE is 4 KB. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. - /// The message resource is optional; therefore, if you call FormatMessage - /// it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegSetValueEx - ( - UIntPtr hkey, - String lpValueName, - uint Reserved, - KeyType dwType, - byte[] lpData, - uint cbData - ); - - /// - /// This function removes a named value from the specified registry key. - /// A remote application interface (RAPI) version of this function exists, - /// and it is called CeRegDeleteValue. - /// - /// [in] Handle to a currently open key or one of: - /// HKCR, HKCU, HKLM. - /// [in] Pointer to a null-terminated string - /// that names the value to remove. If this parameter is NULL or points - /// to an empty string, the default value of the key is removed. A default - /// value is create by calling RegSetValueEx with a NULL or empty string - /// value name. - /// ERROR_SUCCESS indicates success. A nonzero error code defined - /// in Winerror.h indicates failure. To get a generic description of the - /// error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set. - /// The message resource is optional; therefore, if you call FormatMessage - /// it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegDeleteValue - ( - UIntPtr hkey, - string valueName - ); - - /// - /// This function releases the handle of the specified key. A remote - /// application interface (RAPI) version of this function exists, and - /// it is called CeRegCloseKey. - /// - /// [in] Handle to the open key to close. - /// ERROR_SUCCESS indicates success. A nonzero error code - /// defined in Winerror.h indicates failure. To get a generic description - /// of the error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM - /// flag set. The message resource is optional; therefore, if you call - /// FormatMessage it could fail. - [DllImport("coredll.dll", SetLastError=true)] - public static extern int RegCloseKey - ( - UIntPtr hkey - ); - - /// - /// Run a test of the Registry class. - /// - /// Delegate called to show debug information - } -} diff --git a/gps8/Gps8/Gps/Utils.cs b/gps8/Gps8/Gps/Utils.cs deleted file mode 100644 index c395c6d..0000000 --- a/gps8/Gps8/Gps/Utils.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -// Use of this source code is subject to the terms of the Microsoft end-user -// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. -// If you did not accept the terms of the EULA, you are not authorized to use -// this source code. For a copy of the EULA, please see the LICENSE.RTF on your -// install media. -// -#region Using directives - -using System; - -#endregion - -namespace Microsoft.WindowsMobile.Samples.Location -{ - /// - /// Summary description for Utils. - /// - public class Utils - { - public Utils() - { - } - - public static IntPtr LocalAlloc(int byteCount) - { - IntPtr ptr = Win32.LocalAlloc(Win32.LMEM_ZEROINIT, byteCount); - if (ptr == IntPtr.Zero) - { - throw new OutOfMemoryException(); - } - - return ptr; - } - - public static void LocalFree(IntPtr hMem) - { - IntPtr ptr = Win32.LocalFree(hMem); - if (ptr != IntPtr.Zero) - { - throw new ArgumentException(); - } - } - } - - public class Win32 - { - public const int LMEM_ZEROINIT = 0x40; - public const int LMEM_FIXED = 0x0000; - public const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT); - [System.Runtime.InteropServices.DllImport("coredll.dll", EntryPoint = "#33", SetLastError = true)] - public static extern IntPtr LocalAlloc(int flags, int byteCount); - [System.Runtime.InteropServices.DllImport("coredll.dll", EntryPoint = "#33", SetLastError = true)] - public static extern IntPtr LocalAlloc(uint flags, uint byteCount); - - [System.Runtime.InteropServices.DllImport("coredll.dll", EntryPoint = "#36", SetLastError = true)] - public static extern IntPtr LocalFree(IntPtr hMem); - } -} diff --git a/gps8/Gps8/Gps8.sln b/gps8/Gps8/Gps8.sln deleted file mode 100644 index 45bf888..0000000 --- a/gps8/Gps8/Gps8.sln +++ /dev/null @@ -1,38 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.WindowsMobile.Samples.Location", "Gps\Microsoft.WindowsMobile.Samples.Location.csproj", "{DB77C1EE-A383-4CD5-A107-1C7C26A9E6B8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GPS_Sample8", "GPS_Sample8\GPS_Sample8.csproj", "{188228FC-E19A-4D2D-9FA2-4F2544B20CAD}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "gps.parser", "..\..\..\..\C-Source\test\GPSparser\nmeaparser\gps.parser.csproj", "{E575252D-45C4-4BA8-A9A4-FA1579045E2F}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {DB77C1EE-A383-4CD5-A107-1C7C26A9E6B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DB77C1EE-A383-4CD5-A107-1C7C26A9E6B8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DB77C1EE-A383-4CD5-A107-1C7C26A9E6B8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DB77C1EE-A383-4CD5-A107-1C7C26A9E6B8}.Release|Any CPU.Build.0 = Release|Any CPU - {188228FC-E19A-4D2D-9FA2-4F2544B20CAD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {188228FC-E19A-4D2D-9FA2-4F2544B20CAD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {188228FC-E19A-4D2D-9FA2-4F2544B20CAD}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {188228FC-E19A-4D2D-9FA2-4F2544B20CAD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {188228FC-E19A-4D2D-9FA2-4F2544B20CAD}.Release|Any CPU.Build.0 = Release|Any CPU - {188228FC-E19A-4D2D-9FA2-4F2544B20CAD}.Release|Any CPU.Deploy.0 = Release|Any CPU - {E575252D-45C4-4BA8-A9A4-FA1579045E2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E575252D-45C4-4BA8-A9A4-FA1579045E2F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E575252D-45C4-4BA8-A9A4-FA1579045E2F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E575252D-45C4-4BA8-A9A4-FA1579045E2F}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/ilock.md b/ilock.md new file mode 100644 index 0000000..f0c8314 --- /dev/null +++ b/ilock.md @@ -0,0 +1,3 @@ +iLock is a kiosk mode helper app which locks your device as long as the target app is not yet started. This prevents the user from accessing the device until your kiosk mode app is started. + +See http://www.hjgode.de/wp/2010/03/18/ilock-a-tool-to-lock-the-startup-process-of-a-windows-mobile-device/ for details \ No newline at end of file diff --git a/ipconfig/ipconfig.sln b/ipconfig/ipconfig.sln deleted file mode 100644 index 09c9db4..0000000 --- a/ipconfig/ipconfig.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ipconfig", "ipconfig\ipconfig.vcproj", "{88DEC31F-EE37-44C5-99C3-0C47D4930F30}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {88DEC31F-EE37-44C5-99C3-0C47D4930F30}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {88DEC31F-EE37-44C5-99C3-0C47D4930F30}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {88DEC31F-EE37-44C5-99C3-0C47D4930F30}.Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Debug|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {88DEC31F-EE37-44C5-99C3-0C47D4930F30}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).ActiveCfg = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {88DEC31F-EE37-44C5-99C3-0C47D4930F30}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Build.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - {88DEC31F-EE37-44C5-99C3-0C47D4930F30}.Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I).Deploy.0 = Release|Windows Mobile 5.0 Pocket PC SDK (ARMV4I) - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/ipconfig/ipconfig/ReadMe.txt b/ipconfig/ipconfig/ReadMe.txt deleted file mode 100644 index b8daf24..0000000 --- a/ipconfig/ipconfig/ReadMe.txt +++ /dev/null @@ -1,63 +0,0 @@ -======================================================================== - WIN32 APPLICATION : ipconfig Project Overview -======================================================================== - -AppWizard has created this ipconfig application for you. - -This file contains a summary of what you will find in each of the files that -make up your ipconfig application. - - -ipconfig.vcproj - This is the main project file for VC++ projects generated using an Application Wizard. - It contains information about the version of Visual C++ that generated the file, and - information about the platforms, configurations, and project features selected with the - Application Wizard. - -ipconfig.cpp - This is the main application source file. - -///////////////////////////////////////////////////////////////////////////// -AppWizard has created the following resources: - - -ipconfigppc.rc - This is a listing of all of the Microsoft Windows resources that the - program uses when compiling for the Pocket PC 2003 platform, or a platform - that supports the same user interface model. It includes the icons, bitmaps, - and cursors that are stored in the RES subdirectory. This file can be - directly edited in Microsoft Visual C++. When the .rc file is persisted, - the defines in the data section are persisted as the hexadecimal version - of the numeric value they are defined to rather than the friendly name of - the define. - -ipconfigppc.rc2 - This file contains resources that are not edited by Microsoft - Visual C++. You should place all resources not editable by - the resource editor in this file. - -Resourceppc.h - This is the standard header file, which defines new resource IDs. - Microsoft Visual C++ reads and updates this file. - - - - -ipconfig.ico - This is an icon file, which is used as the application's icon (32x32). - This icon is included by the main resource file ipconfig.rc. - -///////////////////////////////////////////////////////////////////////////// -Other standard files: - -StdAfx.h, StdAfx.cpp - These files are used to build a precompiled header (PCH) file - named ipconfig.pch and a precompiled types file named StdAfx.obj. - -///////////////////////////////////////////////////////////////////////////// -Other notes: - -AppWizard uses "TODO:" comments to indicate parts of the source code you -should add to or customize. - -/////////////////////////////////////////////////////////////////////////////s \ No newline at end of file diff --git a/ipconfig/ipconfig/Windows Mobile 5.0 Pocket PC SDK (ARMV4I)/Debug/ipconfig.exe b/ipconfig/ipconfig/Windows Mobile 5.0 Pocket PC SDK (ARMV4I)/Debug/ipconfig.exe deleted file mode 100644 index e70d951..0000000 Binary files a/ipconfig/ipconfig/Windows Mobile 5.0 Pocket PC SDK (ARMV4I)/Debug/ipconfig.exe and /dev/null differ diff --git a/ipconfig/ipconfig/cOutClass.h b/ipconfig/ipconfig/cOutClass.h deleted file mode 100644 index b830e02..0000000 --- a/ipconfig/ipconfig/cOutClass.h +++ /dev/null @@ -1,35 +0,0 @@ - - -class COutput -{ -public: - COutput(HWND hEdit) { m_hEdit = hEdit; }; - COutput() { m_hEdit = NULL; }; - - COutput& operator<<(LPCTSTR); - COutput& operator<<(WORD); - COutput& operator<<(CHAR); - COutput& operator<<(DWORD); - COutput& operator<<(FLOAT); - COutput& operator<<(int); - COutput& operator<<(char* lpcharOutput); - COutput& operator<<(wchar_t* lpwcharOutput); - - void print(const wchar_t *fmt, ...); - - void SetOutputWindow(HWND hEdit) { m_hEdit = hEdit; }; - void COutput::CLS(); - void refresh(); - -private: - HWND m_hEdit; -}; - -extern const TCHAR endl[]; -extern const TCHAR tab[]; - -extern COutput cout; -extern HWND hWndEdit; // Read only edit box for output display -extern HWND hWnd; // Handle to application window -extern HINSTANCE hInst; // The current instance -extern TCHAR szTitle[]; // The title bar text diff --git a/ipconfig/ipconfig/cOutclass.cpp b/ipconfig/ipconfig/cOutclass.cpp deleted file mode 100644 index 1451417..0000000 --- a/ipconfig/ipconfig/cOutclass.cpp +++ /dev/null @@ -1,130 +0,0 @@ -// 'Windows CE 3.0 Programming' Source Code Samples (Prentice Hall, 2000) -// Source Code Author: Nick Grattan (nick@softwarepaths.com) -// Version 1.00 -/* USAGE - - //global - #include "cOutClass.h" - - COutput cout; - HWND hWndEdit; // Read only edit box for output display - - //in wndproc for WM_CREATE: - //#### COutput stuff start #### - GetClientRect(hWnd, &rClient); - nCmdHt = CommandBar_Height(mbi.hwndMB); - hWndEdit = CreateWindow(_T("Edit"), - NULL, WS_CHILD | WS_VISIBLE | ES_READONLY - | ES_MULTILINE | WS_VSCROLL | WS_HSCROLL, - 0, 0, - rClient.right, rClient.bottom - 25, - hWnd, NULL, g_hInst, NULL); - cout.SetOutputWindow(hWndEdit); - //#### COutput stuff END #### - - // in code use cout.CLS() to clear window - // cout << L"sometext"; cout << intVar - // cout.print(L"Hello %s", szText); -*/ -// Input and output routines for sample files - -#include "stdafx.h" -#include "coutclass.h" - -const TCHAR endl[] = _T("\r\n"); -const TCHAR tab[] = _T("\t"); - -void COutput::refresh(){ - ::UpdateWindow(m_hEdit); -} - -void COutput::print(const wchar_t *fmt, ...){ - int nIndex; - va_list vl; - va_start(vl,fmt); - wchar_t buf[1024]; // to bad CE hasn't got wvnsprintf - wvsprintf(buf,fmt,vl); - - nIndex = GetWindowTextLength(m_hEdit); - SendMessage(m_hEdit, EM_SETSEL, nIndex, nIndex); - SendMessage(m_hEdit, EM_REPLACESEL, 0, (LPARAM)buf); -} - -COutput& COutput::operator<<(wchar_t* lpwcharOutput){ - int nIndex; - //LPCWSTR lpOutput=new WCHAR(wcslen(lpwcharOutput)); - wchar_t* lpOutput=new WCHAR(wcslen(lpwcharOutput)); - - memcpy(lpOutput, lpwcharOutput, (wcslen(lpwcharOutput)+1)*sizeof(WCHAR)); - - nIndex = GetWindowTextLength(m_hEdit); - SendMessage(m_hEdit, EM_SETSEL, nIndex, nIndex); - SendMessage(m_hEdit, EM_REPLACESEL, 0, (LPARAM)lpOutput); - delete lpOutput; - return *this; -} - -COutput& COutput::operator<<(LPCTSTR lpOutput) -{ - int nIndex; - - nIndex = GetWindowTextLength(m_hEdit); - SendMessage(m_hEdit, EM_SETSEL, nIndex, nIndex); - SendMessage(m_hEdit, EM_REPLACESEL, 0, (LPARAM)lpOutput); - return *this; -} - -COutput& COutput::operator <<(char* lpcharOutput) -{ - LPTSTR lpBuffer = new TCHAR[strlen(lpcharOutput) + 1]; - mbstowcs(lpBuffer, lpcharOutput, strlen(lpcharOutput)); - lpBuffer[strlen(lpcharOutput)] = '\0'; - *this << lpBuffer; - return *this; -} - -COutput& COutput::operator <<(CHAR cOutput) -{ - TCHAR szBuffer[2]; - szBuffer[0] = cOutput; - szBuffer[1] = '\0'; - *this << szBuffer; - return *this; -} - -COutput& COutput::operator<<(DWORD dwOutput) -{ - TCHAR szBuffer[20]; - wsprintf(szBuffer, _T("%lu"), dwOutput); - *this << szBuffer; - return *this; -} - -COutput& COutput::operator<<(WORD wOutput) -{ - TCHAR szBuffer[20]; - wsprintf(szBuffer, _T("%u"), wOutput); - *this << szBuffer; - return *this; -} - -COutput& COutput::operator<<(FLOAT fOutput) -{ - TCHAR szBuffer[20]; - swprintf(szBuffer, _T("%f"), fOutput); - *this << szBuffer; - return *this; -} - -COutput& COutput::operator<<(int nOutput) -{ - TCHAR szBuffer[20]; - wsprintf(szBuffer, _T("%d"), nOutput); - *this << szBuffer; - return *this; -} -void COutput::CLS() -{ - SetWindowText(m_hEdit, NULL); -} - diff --git a/ipconfig/ipconfig/ipconfig.cpp b/ipconfig/ipconfig/ipconfig.cpp deleted file mode 100644 index 86c518d..0000000 --- a/ipconfig/ipconfig/ipconfig.cpp +++ /dev/null @@ -1,513 +0,0 @@ -// ipconfig.cpp : Defines the entry point for the application. -// -#ifdef _MSC_VER -# pragma comment(linker, "/subsystem:windowsce /ENTRY:WinMain") -#endif - -#include "stdafx.h" -#include "ipconfig.h" - -#include "ipconfig_src.h" -//extern int GetConfigData(); -//extern void FlushDNSCache(void); -//extern void setOutputWindow(HWND hWndEdit); - -#define MAX_LOADSTRING 100 - -// Global Variables: -HINSTANCE g_hInst; // current instance -HWND g_hWndMain; -HWND g_hWndMenuBar; // menu bar handle -HWND g_hWndEdit; // Edit window handle -DWORD g_selectedAdapter=0; // for release and renew -TCHAR g_InfoText[MAX_PATH]; - -// Forward declarations of functions included in this code module: -ATOM MyRegisterClass(HINSTANCE, LPTSTR); -BOOL InitInstance(HINSTANCE, int); -LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); -INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); -INT_PTR CALLBACK InputDialog(HWND, UINT, WPARAM, LPARAM); - -int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPTSTR lpCmdLine,int nCmdShow) -{ - MSG msg; - - //begin arg parsing - LPWSTR *szArgList=__wargv; - int argCount = __argc; -// szArgList = CommandLineToArgvW(GetCommandLine(), &argCount); - for(int i = 0; i < argCount; i++) - { - DEBUGMSG(1, (L"%i: '%s'\n", szArgList[i])); - } - /* - if(argCount>0){ - DWORD Address =0; - BOOL NextParamIsAddress=FALSE, Error=FALSE, Renew=FALSE, Release=FALSE, FlushDNS=FALSE; - - for (int i=1;i0 - */ - //end cmdline parsing - LocalFree(szArgList); - - // Perform application initialization: - if (!InitInstance(hInstance, nCmdShow)) - { - return FALSE; - } - - HACCEL hAccelTable; - hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_IPCONFIG)); - - // Main message loop: - while (GetMessage(&msg, NULL, 0, 0)) - { - if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - return (int) msg.wParam; -} - -// -// FUNCTION: MyRegisterClass() -// -// PURPOSE: Registers the window class. -// -// COMMENTS: -// -ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass) -{ - WNDCLASS wc; - - wc.style = CS_HREDRAW | CS_VREDRAW; - wc.lpfnWndProc = WndProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = hInstance; - wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_IPCONFIG)); - wc.hCursor = 0; - wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); - wc.lpszMenuName = 0; - wc.lpszClassName = szWindowClass; - - return RegisterClass(&wc); -} - -// -// FUNCTION: InitInstance(HINSTANCE, int) -// -// PURPOSE: Saves instance handle and creates main window -// -// COMMENTS: -// -// In this function, we save the instance handle in a global variable and -// create and display the main program window. -// -BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) -{ - HWND hWnd; - TCHAR szTitle[MAX_LOADSTRING]; // title bar text - TCHAR szWindowClass[MAX_LOADSTRING]; // main window class name - - g_hInst = hInstance; // Store instance handle in our global variable - - // SHInitExtraControls should be called once during your application's initialization to initialize any - // of the device specific controls such as CAPEDIT and SIPPREF. - SHInitExtraControls(); - - LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); - LoadString(hInstance, IDC_IPCONFIG, szWindowClass, MAX_LOADSTRING); - - //If it is already running, then focus on the window, and exit - hWnd = FindWindow(szWindowClass, szTitle); - if (hWnd) - { - // set focus to foremost child window - // The "| 0x00000001" is used to bring any owned windows to the foreground and - // activate them. - SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001)); - return 0; - } - - if (!MyRegisterClass(hInstance, szWindowClass)) - { - return FALSE; - } - - hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); - - if (!hWnd) - { - return FALSE; - } - - // When the main window is created using CW_USEDEFAULT the height of the menubar (if one - // is created is not taken into account). So we resize the window after creating it - // if a menubar is present - if (g_hWndMenuBar) - { - RECT rc; - RECT rcMenuBar; - - GetWindowRect(hWnd, &rc); - GetWindowRect(g_hWndMenuBar, &rcMenuBar); - rc.bottom -= (rcMenuBar.bottom - rcMenuBar.top); - - MoveWindow(hWnd, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, FALSE); - } - - g_hWndMain=hWnd; - - ShowWindow(hWnd, nCmdShow); - UpdateWindow(hWnd); - - - return TRUE; -} - -void saveText(){ - TCHAR fileName[MAX_PATH]; - wsprintf(fileName,L"ipconfig.txt"); - OPENFILENAME ofn; - memset(&ofn, 0, sizeof(OPENFILENAME)); - ofn.lStructSize=sizeof(OPENFILENAME); - ofn.hwndOwner=g_hWndMain; - ofn.lpstrFile=fileName; - ofn.nMaxFile=MAX_PATH; - ofn.lpstrInitialDir=L"\\MyDocuments"; - ofn.lpstrTitle =L"Save text to file"; - ofn.Flags=OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST; - - if (GetSaveFileName(&ofn)){ - HANDLE hFile; - BOOL bSuccess = FALSE; - - hFile = CreateFile(ofn.lpstrFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if(hFile != INVALID_HANDLE_VALUE) - { - DWORD dwTextLength; - - dwTextLength = GetWindowTextLength(g_hWndEdit); - // No need to bother if there's no text. - if(dwTextLength > 0) - { - LPTSTR pszText; - DWORD dwBufferSize = (dwTextLength + 1)*sizeof(TCHAR); - - pszText = (LPTSTR)GlobalAlloc(GPTR, dwBufferSize); - if(pszText != NULL) - { - if(GetWindowText(g_hWndEdit, pszText, dwBufferSize)) - { - DWORD dwWritten; - - if(WriteFile(hFile, pszText, dwTextLength*sizeof(TCHAR), &dwWritten, NULL)) - bSuccess = TRUE; - } - GlobalFree(pszText); - } - } - CloseHandle(hFile); - } - } - -} - -// -// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) -// -// PURPOSE: Processes messages for the main window. -// -// WM_COMMAND - process the application menu -// WM_PAINT - Paint the main window -// WM_DESTROY - post a quit message and return -// -// -LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) -{ - int wmId, wmEvent; - PAINTSTRUCT ps; - HDC hdc; - RECT rClient; -// HWND hwndInput; - - static SHACTIVATEINFO s_sai; - - switch (message) - { - case WM_COMMAND: - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - // Parse the menu selections: - switch (wmId) - { - case IDM_HELP_ABOUT: - DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About); - break; - case IDM_COMMANDS_IPINFO: - GetConfigData(); - break; - case ID_COMMANDS_FLUSHDNS: - FlushDNSCache(); - break; - case ID_COMMANDS_RELEASE: - wsprintf(g_InfoText, L"please enter the adapter to release:"); - //hwndInput = CreateDialogParam(g_hInst, (LPCTSTR)IDD_GetInput, hWnd, InputDialog, (LPARAM)L"please enter the adapter to release:"); - //ShowWindow(hwndInput, SW_SHOWNA); - if(DialogBox(g_hInst, (LPCTSTR)IDD_GetInput, hWnd, InputDialog)==IDOK) - ReleaseAddress(g_selectedAdapter); - break; - case ID_COMMANDS_RENEW: - wsprintf(g_InfoText, L"please enter the adapter to renew:"); - //hwndInput = CreateDialogParam(g_hInst, (LPCTSTR)IDD_GetInput, hWnd, InputDialog, (LPARAM)L"please enter the adapter to release:"); - //ShowWindow(hwndInput, SW_SHOWNA); - if(DialogBox(g_hInst, (LPCTSTR)IDD_GetInput, hWnd, InputDialog)==IDOK) - RenewAddress(g_selectedAdapter); - break; - case ID_COMMANDS_SAVETEXT: - saveText(); - break; - case IDM_OK: - SendMessage (hWnd, WM_CLOSE, 0, 0); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - break; - case WM_CREATE: - SHMENUBARINFO mbi; - - memset(&mbi, 0, sizeof(SHMENUBARINFO)); - mbi.cbSize = sizeof(SHMENUBARINFO); - mbi.hwndParent = hWnd; - mbi.nToolBarId = IDR_MENU; - mbi.hInstRes = g_hInst; - - if (!SHCreateMenuBar(&mbi)) - { - g_hWndMenuBar = NULL; - } - else - { - g_hWndMenuBar = mbi.hwndMB; - } - - // Initialize the shell activate info structure - memset(&s_sai, 0, sizeof (s_sai)); - s_sai.cbSize = sizeof (s_sai); - - //#### COutput stuff start #### - GetClientRect(hWnd, &rClient); -// nCmdHt = CommandBar_Height(mbi.hwndMB); - g_hWndEdit = CreateWindow(_T("Edit"), - NULL, - WS_CHILD | WS_VISIBLE | ES_READONLY | ES_MULTILINE | ES_WANTRETURN | - WS_VSCROLL | WS_HSCROLL - //ES_AUTOHSCROLL | ES_AUTOVSCROLL - , - 0, 0, - rClient.right, rClient.bottom - 25, - hWnd, NULL, g_hInst, NULL); - - setOutputWindow(g_hWndEdit); - - - break; - case WM_PAINT: - hdc = BeginPaint(hWnd, &ps); - - // TODO: Add any drawing code here... - - EndPaint(hWnd, &ps); - break; - case WM_DESTROY: - CommandBar_Destroy(g_hWndMenuBar); - PostQuitMessage(0); - break; - - case WM_ACTIVATE: - // Notify shell of our activate message - SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE); - break; - case WM_SETTINGCHANGE: - SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai); - break; - - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - return 0; -} - -// Message handler for about box. -INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - switch (message) - { - case WM_INITDIALOG: - { - // Create a Done button and size it. - SHINITDLGINFO shidi; - shidi.dwMask = SHIDIM_FLAGS; - shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN | SHIDIF_EMPTYMENU; - shidi.hDlg = hDlg; - SHInitDialog(&shidi); - } - return (INT_PTR)TRUE; - - case WM_COMMAND: - if (LOWORD(wParam) == IDOK) - { - EndDialog(hDlg, LOWORD(wParam)); - return TRUE; - } - break; - - case WM_CLOSE: - EndDialog(hDlg, message); - return TRUE; - - } - return (INT_PTR)FALSE; -} - -// Message handler for about box. -INT_PTR CALLBACK InputDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ -// TCHAR* szTxt; - BOOL lpTrans=FALSE; - DWORD dwRes=0; - switch (message) - { - case WM_INITDIALOG: - { - // Create a Done button and size it. - SHINITDLGINFO shidi; - shidi.dwMask = SHIDIM_FLAGS; - shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN | SHIDIF_EMPTYMENU; - shidi.hDlg = hDlg; - SHInitDialog(&shidi); - } - //szTxt=(TCHAR*)lParam; - //SetDlgItemText(hDlg, IDC_EDIT_INFO, szTxt); - SetDlgItemText(hDlg, IDC_EDIT_INFO, g_InfoText); - if(SetDlgItemInt(hDlg, IDC_EDIT_INPUT, g_selectedAdapter, 0)==0) - DEBUGMSG(1, (L"SetDlgItemInt failed with code=%i\n", GetLastError())); - else - DEBUGMSG(1, (L"SetDlgItemInt OK \n")); - return (INT_PTR)TRUE; - - case WM_COMMAND: - if (LOWORD(wParam) == IDOK) - { - dwRes=GetDlgItemInt(hDlg,IDC_EDIT_INPUT, &lpTrans, false); - if(lpTrans!=0) - g_selectedAdapter=dwRes; - EndDialog(hDlg, LOWORD(wParam)); - //DestroyWindow(hDlg); - return TRUE; - } - if (LOWORD(wParam) == IDCANCEL) - { - EndDialog(hDlg, LOWORD(wParam)); - //DestroyWindow(hDlg); - return TRUE; - } - break; - - case WM_CLOSE: - EndDialog(hDlg, message); - DestroyWindow(hDlg); - return TRUE; - - } - return (INT_PTR)FALSE; -} diff --git a/ipconfig/ipconfig/ipconfig.h b/ipconfig/ipconfig/ipconfig.h deleted file mode 100644 index d01e90b..0000000 --- a/ipconfig/ipconfig/ipconfig.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once -#include "resourceppc.h" diff --git a/ipconfig/ipconfig/ipconfig.ico b/ipconfig/ipconfig/ipconfig.ico deleted file mode 100644 index d551aa3..0000000 Binary files a/ipconfig/ipconfig/ipconfig.ico and /dev/null differ diff --git a/ipconfig/ipconfig/ipconfig.vcproj b/ipconfig/ipconfig/ipconfig.vcproj deleted file mode 100644 index e18e593..0000000 --- a/ipconfig/ipconfig/ipconfig.vcproj +++ /dev/null @@ -1,312 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ipconfig/ipconfig/ipconfig.vcproj.CORPNET.E841719.user b/ipconfig/ipconfig/ipconfig.vcproj.CORPNET.E841719.user deleted file mode 100644 index 6e50834..0000000 --- a/ipconfig/ipconfig/ipconfig.vcproj.CORPNET.E841719.user +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/ipconfig/ipconfig/ipconfig_src.cpp b/ipconfig/ipconfig/ipconfig_src.cpp deleted file mode 100644 index f2d9807..0000000 --- a/ipconfig/ipconfig/ipconfig_src.cpp +++ /dev/null @@ -1,1145 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -// Use of this source code is subject to the terms of the Microsoft end-user -// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. -// If you did not accept the terms of the EULA, you are not authorized to use -// this source code. For a copy of the EULA, please see the LICENSE.RTF on your -// install media. -// -//==================================================================== -// -// ipconfig -// -// Displays the configuration Information -// -// -//==================================================================== -#include "stdafx.h" - -#include "coutClass.h" - -#include "ipconfig_src.h" - -#include -#include -#include -#include -#include -#pragma comment (lib, "ws2.lib") -#include -#include -#include "iphlpapi.h" -#pragma comment (lib, "iphlpapi.lib") -#include -#include -#include "ntddip6.h" - - -COutput cout; - -/* -// Function Declarations -void usage(); -int GetConfigData(); -void ReleaseAddress(DWORD); -void RenewAddress(DWORD); -void FlushDNSCache(void); - -void setOutputWindow(HWND hWndEdit); -*/ - -// Global Variables -//int Verbose=FALSE; -BOOL bflagall=TRUE; // This is TRUE if the /all option is specified at the command prompt - -// month[] and dayofweek[] are arrays meant to convert the month and -//dayofweek indices to month and day names respectively -TCHAR *month[]={NULL, _T("January"),_T("February"),_T("March"),_T("April"),_T("May"),_T("June"),_T("July"),_T("August"),_T("September"),_T("October"),_T("November"),_T("December")}; -TCHAR *dayofweek[]={_T("Sunday"),_T("Monday"),_T("Tuesday"),_T("Wednesday"),_T("Thursday"),_T("Friday"),_T("Saturday")}; - -typedef int (__cdecl *PFN_tprintf)(const TCHAR*, ...); -PFN_tprintf v_pfn_tprintf; -HMODULE v_hCoreDLL; -BOOL v_fDebugOut=FALSE; - - -// -// Currently defined privately only. -// - -#define IF_TYPE_OTHER 1 -#define IF_TYPE_ETHERNET 6 -#define IF_TYPE_TOKENRING 9 -#define IF_TYPE_FDDI 15 -#define IF_TYPE_PPP 23 -#define IF_TYPE_LOOPBACK 24 -#define IF_TYPE_SLIP 28 - -void setOutputWindow(HWND hwndEdit){ - cout.SetOutputWindow(hwndEdit); -} - -//============================================================================== - -// Name : OutputMessage -// Description : Outputs to the console or the debug output port -// Parameters : Variable Number -// Returns : integer - -//================================================================================ - -int OutputMessage (TCHAR *pFormat, ...) { - va_list ArgList; - TCHAR Buffer[256]; - int RetVal; - - va_start (ArgList, pFormat); - RetVal = wvsprintf (Buffer, pFormat, ArgList); - if (!v_fDebugOut) { - if (v_pfn_tprintf == NULL) { - // Since not all configs contain the wprintf function we'll - // try to find it. If it's not there we'll default to using - // OutputDebugString. - v_hCoreDLL = LoadLibrary(TEXT("coredll.dll")); - if (v_hCoreDLL) { -#ifdef UNICODE - v_pfn_tprintf = (PFN_tprintf)GetProcAddress(v_hCoreDLL, TEXT("wprintf")); -#else - v_pfn_tprintf = (PFN_tprintf)GetProcAddress(v_hCoreDLL, TEXT("printf")); -#endif - } - - } - if (v_pfn_tprintf != NULL) { - (v_pfn_tprintf) (TEXT("%s"), Buffer); - } - else { - // Couldn't find the entry point, revert to OutputDebugString() - v_fDebugOut = TRUE; - } - } - if (v_fDebugOut) { - OutputDebugString(Buffer); - } - - cout.print(L"%s", Buffer); - cout.refresh(); - - return RetVal; -} - -static const TCHAR* getNodeTypeStr(UINT uiNodeType){ - TCHAR* BROADCAST_NODETYPE_STR = L"Broadcast node"; - TCHAR* PEER_TO_PEER_NODETYPE_STR =L"Peer to Peer node"; - TCHAR* MIXED_NODETYPE_STR = L"mixed node"; - TCHAR* HYBRID_NODETYPE_STR = L"hybrid node"; - switch (uiNodeType){ - case BROADCAST_NODETYPE: - return BROADCAST_NODETYPE_STR; - case PEER_TO_PEER_NODETYPE: - return PEER_TO_PEER_NODETYPE_STR; - case MIXED_NODETYPE: - return MIXED_NODETYPE_STR; - case HYBRID_NODETYPE: - return HYBRID_NODETYPE_STR; - default: - return L"unknown node type"; - } - return L"unknown node type"; -} - -//============================================================== -// -//Name : TimeToFileTime -//Description : Converts time in the structure time_t to FILETIME format -// Parameters : time_t t -// LPFILETIME pft -//Returns : void -// -//========================================================== - - -void TimeToFileTime( time_t t, LPFILETIME pft ) { - unsigned __int64 ui64 = (unsigned __int64)t * 10000000 + 116444736000000000; - *pft = *(FILETIME *)&ui64; - return; -} - - - -//=============================================================================== - -// Name : DisplayErrorMessage -// Description : It displays the error message resulting from an unsuccessful attempt to use an IPhelper API -// Parameters : -// int errorcode The return value of that API -// -// Returns : void -// -//=================================================================================== -void DisplayErrorMessage(int errorcode) { - - LPVOID lpMsgBuf = NULL; - - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - errorcode, //GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) &lpMsgBuf, - 0, - NULL - ); - - if (lpMsgBuf) { - OutputMessage(TEXT("%ls"),lpMsgBuf); - LocalFree( lpMsgBuf ); - } - return; -} - -// =================================================================================== - -// Name : IsAutoConfigEnabled -// Description : Determines whether Autoconfig is enabled for a particular adapter -// Since this information is not returned by the 2 main APIs used to -// get the other information,namely, GetAdaptersInfo and GetNetworkParams, -// this function calls another API, GetPerAdapterInfo -// Parameters : ULONG index The index of the Adapter that has to be tested for Autoconfig Enabled -// Returns: BOOL -// True : AutoConfig is enbled -// False: AutoConfig is NOT enbled - -//====================================================================================== -BOOL IsAutoConfigEnabled( ULONG Index) - -{ - PIP_PER_ADAPTER_INFO ptr=NULL; - ULONG size=0; - DWORD result; - BOOL ReturnValue; - - - result=GetPerAdapterInfo( Index,ptr, &size); - if (result==ERROR_BUFFER_OVERFLOW) { - if (!(ptr=(PIP_PER_ADAPTER_INFO)malloc(size))) { - OutputMessage(TEXT("Insufficient Memory\r\n")); - exit(1); - } - result=GetPerAdapterInfo(Index,ptr,&size); - if (result!=ERROR_SUCCESS) { - DisplayErrorMessage(result); - exit(1); - } - } - else if (result!=ERROR_SUCCESS) { - DisplayErrorMessage(result); - exit(1); - } - - ReturnValue = (ptr && ptr->AutoconfigEnabled ) ? TRUE : FALSE; - if (ptr) - free(ptr); - return(ReturnValue); - -} - -//============================================================================================= -// -// Name : _tmain -// Decription : Entry Point for the program -// Parameters : -// argc : The number of commandline arguments -// argv : Tha array containing the commandline arguments( as Unicode strings) -// Retuns : int - -//============================================================================================= - -int _tmain1(int argc, TCHAR **argv ) { - - - DWORD Address =0; - BOOL NextParamIsAddress=FALSE, Error=FALSE, Renew=FALSE, Release=FALSE, FlushDNS=FALSE; - - for (int i=1;i")); - } - else - { - if (ptcAddressType) - { - wcscat(ptcBuffer, TEXT(" ")); - wcscat(ptcBuffer, ptcAddressType); - } - } - - if (ptcTitle) - { - OutputMessage(TEXT("\t %s %s\r\n"), - ptcTitle, - ptcBuffer); - } - else - { - OutputMessage(TEXT("\t %s\r\n"), - ptcBuffer); - } - - - -} // DisplayV6Address() - - - -/////////////////////////////////////////////////////////////////////////////// -// PrintIPv6Addresses() -// -// Routine Description: -// -// Print the V6 addresses correcponds to the given IP_ADAPTER_INFO. -// -// Arguments: -// -// pAdapterInfo :: [optional] should be from GetAdapterInfo() -// pAdapterAddresses :: should be from GetAdapterAddresses(). -// PrintType :: The V6 address type to be printed. -// bNoLabel :: Don't print label. -// -// Return Value: -// -// None. -// - -typedef enum -{ - PRINT_UNICAST_ADDRESS = 0, - PRINT_ANYCAST_ADDRESS, - PRINT_MULTICAST_ADDRESS, - PRINT_DNSSERVER_ADDRESS, - PRINT_ROUTER_ADDRESS - -} PRINT_TYPE; - -void -PrintIpv6Addresses( - PIP_ADAPTER_INFO pAdapterInfo, - PIP_ADAPTER_ADDRESSES pAdapterAddresses, - PRINT_TYPE PrintType, - BOOL bNoLabel) -{ - PIP_ADAPTER_ADDRESSES pAA; - PIP_ADAPTER_UNICAST_ADDRESS pUnicastAddr; - PIP_ADAPTER_DNS_SERVER_ADDRESS pDnsServerAddr; - BOOL bFirstAddress; - - // - // Find matching entry in IPv6 interface list. - // - - if (pAdapterInfo) - { - for (pAA = pAdapterAddresses ; pAA ; pAA = pAA->Next) - { - if (pAA->IfIndex == pAdapterInfo->Index) - break; - } - } - else - pAA = pAdapterAddresses; - - - if (pAA == NULL || pAA->Ipv6IfIndex == 0) - return; - - // - // Print the Unicast Addresses.. - // - - bNoLabel ? bFirstAddress = FALSE: bFirstAddress = TRUE; - - if (!(pAA->OperStatus & IfOperStatusUp)) - { - // - // Iterface is most likely in media status disconnected. - // IPv6 stack does not remove the addresses to keep idle connections - // alive. - // We'll skip this i/f. - // - - return; - } - - switch(PrintType) - { - /////////////////////////////////////////////////////////////////////// - - case PRINT_UNICAST_ADDRESS: - for (pUnicastAddr = pAA->FirstUnicastAddress; - pUnicastAddr ; - pUnicastAddr = pUnicastAddr->Next) - { - if (pUnicastAddr->Address.lpSockaddr->sa_family == AF_INET6) - { - // - // Following ipv6.exe, wellknown is not printed. - // - - DisplayV6Address( - (PSOCKADDR_IN6)pUnicastAddr->Address.lpSockaddr, - bFirstAddress ? L"IP Address ........ :" : NULL, - (pUnicastAddr->PrefixOrigin == IpPrefixOriginManual && - pUnicastAddr->SuffixOrigin == IpSuffixOriginManual) ? - TEXT("[Manual]"): - (pUnicastAddr->PrefixOrigin == IpPrefixOriginRouterAdvertisement && - pUnicastAddr->SuffixOrigin == IpSuffixOriginLinkLayerAddress) ? - TEXT("[Public]"): - (pUnicastAddr->PrefixOrigin == IpPrefixOriginRouterAdvertisement && - pUnicastAddr->SuffixOrigin == IpSuffixOriginRandom) ? - TEXT("[Temporary]"): - (pUnicastAddr->PrefixOrigin == IpPrefixOriginDhcp && - pUnicastAddr->SuffixOrigin == IpSuffixOriginDhcp) ? - TEXT("[DHCP]"): - NULL); - - bFirstAddress = FALSE; - } - } - break; - - /////////////////////////////////////////////////////////////////////// - - case PRINT_DNSSERVER_ADDRESS: - for (pDnsServerAddr = pAA->FirstDnsServerAddress; - pDnsServerAddr ; - pDnsServerAddr = pDnsServerAddr->Next) - { - if (pDnsServerAddr->Address.lpSockaddr->sa_family == AF_INET6) - { - DisplayV6Address( - (PSOCKADDR_IN6)pDnsServerAddr->Address.lpSockaddr, - bFirstAddress ? L"DNS Servers ...... :" : NULL, - NULL); - - bFirstAddress = FALSE; - } - } - - break; - - /////////////////////////////////////////////////////////////////////// - - case PRINT_ROUTER_ADDRESS: - { -#define IP6_DEVICE_NAME TEXT("IP60:") - - HANDLE hIPv6; - IPV6_QUERY_ROUTE_TABLE QueryRouteTable, NextQueryRouteTable; - IPV6_INFO_ROUTE_TABLE RTE; - ULONG ulBytesReturned; - SOCKADDR_IN6 Addr; - - - hIPv6 = CreateFileW( - IP6_DEVICE_NAME, - GENERIC_WRITE, // access mode - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, // security attributes - OPEN_EXISTING, - 0, // flags & attributes - NULL); // template file - - NextQueryRouteTable.Neighbor.IF.Index = 0; - - for (;;) - { - QueryRouteTable = NextQueryRouteTable; - - if (!DeviceIoControl( - hIPv6, - IOCTL_IPV6_QUERY_ROUTE_TABLE, - &QueryRouteTable, - sizeof(QueryRouteTable), - &RTE, - sizeof(RTE), - &ulBytesReturned, - NULL)) - { - - } - - NextQueryRouteTable = RTE.Next; - -#if 0 - OutputMessage(TEXT("Prefix Length = [%d] --- Index = [%d]\r\n"), - RTE.This.PrefixLength, - RTE.This.Neighbor.IF.Index); -#endif - - if (QueryRouteTable.Neighbor.IF.Index != 0) - { - RTE.This = QueryRouteTable; - - if ((RTE.This.PrefixLength == 0) && - (pAA->Ipv6IfIndex == RTE.This.Neighbor.IF.Index)) - { - // - // We have valid router, display it. - // - - Addr.sin6_family = AF_INET6; - Addr.sin6_addr = RTE.This.Neighbor.Address; - Addr.sin6_port = 0; - - if (IN6_IS_ADDR_LINKLOCAL(&(Addr.sin6_addr))) - { - Addr.sin6_scope_id = pAA->ZoneIndices[ScopeLevelLink]; - } - else - if (IN6_IS_ADDR_SITELOCAL(&(Addr.sin6_addr))) - { - Addr.sin6_scope_id = pAA->ZoneIndices[ScopeLevelSite]; - } - else - { - Addr.sin6_scope_id = 0; - } - - DisplayV6Address( - (PSOCKADDR_IN6)&Addr, - bFirstAddress ? L"Default Gateway ... :" : NULL, - NULL); - - bFirstAddress = FALSE; - - } - - } - - if (NextQueryRouteTable.Neighbor.IF.Index == 0) - break; - - } - - CloseHandle(hIPv6); - break; - } - - /////////////////////////////////////////////////////////////////////// - - case PRINT_ANYCAST_ADDRESS: - case PRINT_MULTICAST_ADDRESS: - default: - pUnicastAddr = NULL; - break; - } - -} // PrintIpv6Addresses() - - - -/////////////////////////////////////////////////////////////////////////////// -// DisplayV6OnlyAddresses() -// -// Routine Description: -// -// Run through the IP_ADAPTER_ADDRESSES list and print out V6 only -// adapters. -// -// Arguments: -// -// pAdapterAddresses :: should be from GetAdapterAddresses(). -// -// Return Value: -// -// None. -// - -void -DisplayV6OnlyAddresses(PIP_ADAPTER_ADDRESSES pAdapterAddresses) -{ - PIP_ADAPTER_ADDRESSES pAA; - - for (pAA = pAdapterAddresses ; pAA ; pAA = pAA->Next) - { - if ((pAA->IfIndex == 0) && - (pAA->Ipv6IfIndex != 0) && - (pAA->IfType != IF_TYPE_SOFTWARE_LOOPBACK) && - (pAA->OperStatus & IfOperStatusUp)) - { - OutputMessage(TEXT("Tunnel adapter [%s]: \r\n"), - pAA->Description); - - OutputMessage(TEXT("\t Interface Number .. : %d\r\n"), pAA->Ipv6IfIndex); - - PrintIpv6Addresses(NULL, pAA, PRINT_UNICAST_ADDRESS, FALSE); - PrintIpv6Addresses(NULL, pAA, PRINT_ROUTER_ADDRESS, FALSE); - OutputMessage(TEXT("\r\n")); - } - } -} // DisplayV6OnlyAddresses() - - - -// ================================================================================ -// Name : GetConfigData -// Description : Gets the ipconfig information by calling 2 APIS, GetAdaptersInfo and getNetworkParams -// Parameters : None -// Returns : integer - -//================================================================================== -int GetConfigData() -{ - // -----------------------GetAdaptersInfo----------------------------------------- - PIP_ADAPTER_INFO pAdapterInfo = NULL; - ULONG ulSizeAdapterInfo = 0; - DWORD dwReturnvalueGetAdapterInfo; - PIP_ADAPTER_INFO pOriginalPtr; - LPTSTR pszNICAddr; - - ULONG ulBufferLength, ulFlags=0; - DWORD dwError; - PIP_ADAPTER_ADDRESSES pAdapterAddresses; - BOOL bFirstAddress; - - OutputMessage(TEXT("Windows IP configuration \r\n\r\n")); - - - // - // Get V6 address list. - // - - ulFlags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST; - - GetAdaptersAddresses(AF_UNSPEC, ulFlags, NULL, NULL, &ulBufferLength); - - //HGO OutputMessage(TEXT("GetAdaptersAddresses ulBufferLength: %d\r\n"), ulBufferLength); - - pAdapterAddresses = (PIP_ADAPTER_ADDRESSES)malloc(ulBufferLength); - - if (NULL == pAdapterAddresses) - { - OutputMessage(TEXT("Insufficient Memory\n")); - return(1); - } - - - dwError = GetAdaptersAddresses(AF_UNSPEC, ulFlags, NULL, pAdapterAddresses, &ulBufferLength); - - if (dwError != NO_ERROR) - { - DisplayErrorMessage(dwError); - return(1); - } - - dwReturnvalueGetAdapterInfo = GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo ); - if ( dwReturnvalueGetAdapterInfo == ERROR_BUFFER_OVERFLOW) { - if (!(pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulSizeAdapterInfo))) { - OutputMessage(TEXT("Insufficient Memory\n")); - return(1); - } - - dwReturnvalueGetAdapterInfo = GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo); - if (dwReturnvalueGetAdapterInfo != ERROR_SUCCESS) { - DisplayErrorMessage(dwReturnvalueGetAdapterInfo); - return(1); - } - } - else if (dwReturnvalueGetAdapterInfo == ERROR_NO_DATA) - { - OutputMessage(TEXT("No IPv4 adapter found.\r\n\r\n")); - return(1); - } - else if (dwReturnvalueGetAdapterInfo != ERROR_SUCCESS) { - DisplayErrorMessage(dwReturnvalueGetAdapterInfo); - return(1); - } - - pOriginalPtr = pAdapterInfo; - - if(ulSizeAdapterInfo == 0) - pAdapterInfo = NULL; - - if (pAdapterInfo == NULL) - OutputMessage(TEXT("No Interfaces Present.\r\n")); - - while (pAdapterInfo != NULL) { - - OutputMessage(TEXT("AdapterInfo->Index : %d\r\n"), pAdapterInfo->Index); - OutputMessage(TEXT("AdapterInfo->Type : %d\r\n"), pAdapterInfo->Type); - - switch (pAdapterInfo->Type) - { - case IF_TYPE_ETHERNET: - if (bflagall) - OutputMessage(TEXT("Ethernet adapter Local Area Connection: \r\n")); - else - OutputMessage(TEXT("Ethernet adapter [%hs]: \r\n"), - pAdapterInfo->AdapterName); - break; - - case IF_TYPE_PPP: - OutputMessage(TEXT("PPP Adapter [%hs]:\r\n"), pAdapterInfo->AdapterName); - break; - - case IF_TYPE_OTHER: - case IF_TYPE_TOKENRING: - case IF_TYPE_FDDI: - case IF_TYPE_LOOPBACK: - case IF_TYPE_SLIP: - OutputMessage(TEXT("IP connection:\r\n\r\n")); - break; - } - - - - PIP_ADDR_STRING pAddressList = &(pAdapterInfo->IpAddressList); - - do { - OutputMessage(TEXT("\t IP Address ........ : %hs\r\n"),pAddressList->IpAddress.String); - OutputMessage(TEXT("\t Subnet Mask ....... : %hs\r\n"), pAddressList->IpMask.String); - pAddressList = pAddressList->Next; - } while (pAddressList != NULL); - - - PrintIpv6Addresses(pAdapterInfo, pAdapterAddresses, PRINT_UNICAST_ADDRESS, FALSE); - - PIP_ADDR_STRING pGatewayList = &(pAdapterInfo->GatewayList); - - if (pGatewayList->IpAddress.String[0] != 0) - { - do { - OutputMessage(TEXT("\t Default Gateway ... : %hs\r\n"), pGatewayList->IpAddress.String); - pGatewayList = pGatewayList->Next; - } while (pGatewayList != NULL); - } - - PrintIpv6Addresses(pAdapterInfo, pAdapterAddresses, PRINT_ROUTER_ADDRESS, TRUE); - - if (bflagall == TRUE) { - OutputMessage(TEXT("\t Adapter Name ...... : %hs\r\n"), pAdapterInfo->AdapterName); - OutputMessage(TEXT("\t Description ....... : %hs\r\n"), pAdapterInfo->Description); - OutputMessage(TEXT("\t Adapter Index ..... : %lu\r\n"), pAdapterInfo->Index); - if (pszNICAddr = FormatNICAddrString(pAdapterInfo->Address, pAdapterInfo->AddressLength)) { - OutputMessage(TEXT("\t Address............ : %s\r\n"), pszNICAddr); - LocalFree(pszNICAddr); - } - - - OutputMessage(TEXT("\t DHCP Enabled....... : %s\r\n"), (pAdapterInfo->DhcpEnabled) ? TEXT("YES") : TEXT("NO")); - - if (pAdapterInfo->DhcpEnabled) { - // - // It does not make sense to display the following information if DHCP is not enabled. - // - PIP_ADDR_STRING pDhcpServer = &(pAdapterInfo->DhcpServer); - do { - OutputMessage(TEXT("\t DHCP Server........ : %hs\r\n"), pDhcpServer->IpAddress.String); - pDhcpServer = pDhcpServer->Next; - } while (pDhcpServer != NULL); - - FILETIME LeaseObtained, LeaseObtainedLocal; - SYSTEMTIME SysLeaseObtained; - - if (pAdapterInfo->LeaseObtained != 0) { - TimeToFileTime(pAdapterInfo->LeaseObtained, &LeaseObtained); - FileTimeToLocalFileTime(&LeaseObtained, &LeaseObtainedLocal); - BOOL bflag = FileTimeToSystemTime(&LeaseObtainedLocal, &SysLeaseObtained); - OutputMessage(TEXT("\t Lease obtained on : %s, %s %lu ,%lu %lu : %lu : %lu \r\n"), dayofweek[SysLeaseObtained.wDayOfWeek], month[SysLeaseObtained.wMonth], SysLeaseObtained.wDay, SysLeaseObtained.wYear, SysLeaseObtained.wHour, SysLeaseObtained.wMinute, SysLeaseObtained.wSecond); - } - else - OutputMessage(TEXT("\t Lease obtained on : Not Available\r\n")); - - FILETIME LeaseExpires, LeaseExpiresLocal; - SYSTEMTIME SysLeaseExpires; - - if (pAdapterInfo->LeaseExpires != 0) { - TimeToFileTime(pAdapterInfo->LeaseExpires, &LeaseExpires); - FileTimeToLocalFileTime(&LeaseExpires, &LeaseExpiresLocal); - FileTimeToSystemTime(&LeaseExpiresLocal, &SysLeaseExpires); - OutputMessage(TEXT("\t Lease expires on : %s, %s %lu ,%lu %lu : %lu : %lu \r\n"), dayofweek[SysLeaseExpires.wDayOfWeek], month[SysLeaseExpires.wMonth], SysLeaseExpires.wDay, SysLeaseExpires.wYear, SysLeaseExpires.wHour, SysLeaseExpires.wMinute, SysLeaseExpires.wSecond ); - } - else - OutputMessage(TEXT("\t Lease expires on : Not Available\r\n")); - } // Dhcp enabled - - //WINS information - PIP_ADDR_STRING pPrimaryWinsServer = &(pAdapterInfo->PrimaryWinsServer) ; - do { - OutputMessage(TEXT("\t Primary WinsServer : %hs\r\n"), pPrimaryWinsServer->IpAddress.String); - pPrimaryWinsServer=pPrimaryWinsServer->Next; - } while (pPrimaryWinsServer != NULL); - - PIP_ADDR_STRING pSecondaryWinsServer =&(pAdapterInfo->SecondaryWinsServer) ; - do { - OutputMessage(TEXT("\t Secondary WinsServer: %hs\r\n"), pSecondaryWinsServer->IpAddress.String); - pSecondaryWinsServer = pSecondaryWinsServer->Next; - } while (pSecondaryWinsServer != NULL); - - PrintIpv6Addresses(pAdapterInfo, pAdapterAddresses, PRINT_DNSSERVER_ADDRESS, FALSE); - - - DWORD Index = (ULONG)(pAdapterInfo->Index); - OutputMessage(TEXT("\t AutoConfig Enabled : %s\r\n"), IsAutoConfigEnabled(Index) ? TEXT("YES") : TEXT("NO")); - } // Matches if(blagall==TRUE) { - - OutputMessage(TEXT("\r\n")); - pAdapterInfo = pAdapterInfo->Next; - } // End of while(pAdapterInfo!=NULL){ - - // - // V6 only addresses.. - // - - DisplayV6OnlyAddresses(pAdapterAddresses); - - - //---------------------End of GetAdaptersInfo------------------- - - // ---------------------GetNetwork Params -------------------------- - - PFIXED_INFO pNetworkParams = NULL; - ULONG uSizeNetworkParams = 0; - DWORD dwReturnvalueGetNetworkParams; - - OutputMessage(L"================\r\nNetwork Parameters:\r\n"); - dwReturnvalueGetNetworkParams = GetNetworkParams(pNetworkParams , &uSizeNetworkParams); - if (dwReturnvalueGetNetworkParams == ERROR_BUFFER_OVERFLOW) { - if (!(pNetworkParams = (PFIXED_INFO) malloc(uSizeNetworkParams))) { - OutputMessage(TEXT("Insufficient Memory\r\n")); - return(1); - } - - dwReturnvalueGetNetworkParams = GetNetworkParams(pNetworkParams, &uSizeNetworkParams); - if (dwReturnvalueGetNetworkParams != ERROR_SUCCESS) { - DisplayErrorMessage(dwReturnvalueGetNetworkParams); - return(1); - } - } - else if (dwReturnvalueGetNetworkParams != ERROR_SUCCESS) { - DisplayErrorMessage(dwReturnvalueGetNetworkParams); - return(1); - } - - if (bflagall == TRUE) - OutputMessage(TEXT("\t Host name.......... : %hs\r\n"), pNetworkParams->HostName); - if (bflagall == TRUE) - OutputMessage(TEXT("\t Domain Name........ : %hs\r\n"), pNetworkParams->DomainName); - - PIP_ADDR_STRING pDnsServer = &(pNetworkParams->DnsServerList); - - // If there is no adapters - there will be no dns server - but there will be - // a pointer - so we much check to see if the address string is empty - if (pDnsServer->IpAddress.String[0] != 0) - { - bFirstAddress = TRUE; - while (pDnsServer != NULL) - { - if (bFirstAddress) - OutputMessage(TEXT("\t DNS Servers........ : %hs\r\n"), pDnsServer->IpAddress.String); - else - OutputMessage(TEXT("\t %hs\r\n"), pDnsServer->IpAddress.String); - - bFirstAddress = FALSE; - pDnsServer = pDnsServer->Next; - } - - } - - if (bflagall == TRUE) { - OutputMessage(TEXT("\t NODETYPE........... : %s\r\n"), getNodeTypeStr(pNetworkParams->NodeType)); //No details in the documentation regarding the correspondence between integer constants and nodetypes - OutputMessage(TEXT("\t Routing Enabled.... : %s\r\n"), pNetworkParams->EnableRouting ? TEXT("YES") : TEXT(" NO")); - OutputMessage(TEXT("\t Proxy Enabled...... : %s\r\n"), pNetworkParams->EnableProxy ? TEXT("YES") : TEXT("NO")); - } - - //----------------End of GetNetwork Params -------------------------- - OutputMessage(TEXT("\r\n")); - - if (pNetworkParams) - free(pNetworkParams); - if (pOriginalPtr) - free(pOriginalPtr); - return(0); - -} - -void RenewAddress(DWORD AdapterIndex) { - ULONG sizeofbuffer=0; - PIP_INTERFACE_INFO pbuffer=NULL; - int returnvalue; - BOOL bfound =FALSE; - - returnvalue= GetInterfaceInfo(pbuffer, &sizeofbuffer); - if (returnvalue==ERROR_INSUFFICIENT_BUFFER) { - pbuffer=(PIP_INTERFACE_INFO) malloc(sizeofbuffer); - if (pbuffer != NULL) { - returnvalue=GetInterfaceInfo(pbuffer, &sizeofbuffer); - } - } - if (returnvalue!=NO_ERROR) { - DisplayErrorMessage(returnvalue); - exit(1); - } - - OutputMessage(TEXT("\tAdapter Name: %s\r\n"), pbuffer->Adapter[0].Name); - OutputMessage(TEXT("\tAdapter Index: %ld\r\n"), pbuffer->Adapter[0].Index); - OutputMessage(TEXT("\tNum Adapters: %ld\r\n"), pbuffer->NumAdapters); - - - for (int index=0;indexNumAdapters; index++) { - if ((pbuffer->Adapter[index].Index==AdapterIndex)||(AdapterIndex==0)) { - bfound =TRUE; - //OutputMessage(TEXT(" Found the adapter")); - returnvalue=IpRenewAddress(&(pbuffer->Adapter[index])); - if (returnvalue==NO_ERROR) - OutputMessage(TEXT("Successfully Renewed Adapter with Index Number %lu\r\n"), pbuffer->Adapter[index].Index); - else { - OutputMessage(TEXT("Failed to renew Adpter with Index Number %lu\r\n"), pbuffer->Adapter[index].Index); - DisplayErrorMessage(returnvalue); - } - } - - } - if (!bfound) - OutputMessage(TEXT("Adapter with given Index Number not found\r\n")); - - if (pbuffer) - free(pbuffer); -} - - -void ReleaseAddress( DWORD AdapterIndex) { - - BOOL bfound =FALSE; - ULONG sizeofbuffer=0; - PIP_INTERFACE_INFO prelease=NULL; - int returnvalue; - - returnvalue= GetInterfaceInfo(prelease, &sizeofbuffer); - if (returnvalue==ERROR_INSUFFICIENT_BUFFER) { - prelease=(PIP_INTERFACE_INFO) malloc(sizeofbuffer); - if (prelease != NULL) { - returnvalue=GetInterfaceInfo(prelease, &sizeofbuffer); - } - } - if (returnvalue!=NO_ERROR) { - DisplayErrorMessage(returnvalue); - exit(1); - } - - for (int index=0;indexNumAdapters; index++) { - if ((AdapterIndex==0) || (prelease->Adapter[index].Index==AdapterIndex)) { - bfound=TRUE; - // OutputMessage(TEXT(" Found the adapter")); - returnvalue=IpReleaseAddress(&(prelease->Adapter[index])); - if (returnvalue==NO_ERROR) - OutputMessage(TEXT("Successfully Released adapter with index Number %lu\r\n"),prelease->Adapter[index].Index); - else { - OutputMessage(TEXT("Failed to release Adapter with index Number %lu\r\n"), prelease->Adapter[index].Index); - DisplayErrorMessage(returnvalue); - } - } - - } - - - if (!bfound) - OutputMessage(TEXT("Adapter with the given index Number not found\r\n")); - - if (prelease) - free(prelease); -} - - -#define WSCNTL_FLUSH_NAME_RESOLVER_CACHE 6 - -extern "C" -DWORD -__cdecl -WSAControl( - DWORD Protocol, - DWORD Action, - LPVOID InputBuffer, - LPDWORD InputBufferLength, - LPVOID OutputBuffer, - LPDWORD OutputBufferLength - ); - -void FlushDNSCache(void) -{ - OutputMessage(L"flushing DNS...\r\n"); - DWORD dwRes = WSAControl(-1, WSCNTL_FLUSH_NAME_RESOLVER_CACHE, NULL, NULL, NULL, NULL); - OutputMessage(L"flushing DNS done: %i\r\n", dwRes); -} diff --git a/ipconfig/ipconfig/ipconfig_src.h b/ipconfig/ipconfig/ipconfig_src.h deleted file mode 100644 index efeed1c..0000000 --- a/ipconfig/ipconfig/ipconfig_src.h +++ /dev/null @@ -1,18 +0,0 @@ - -#pragma once - -#ifndef _IPCONFIG_SRC_H_ -#define _IPCONFIG_SRC_H_ - -#include "stdafx.h" - -// Function Declarations -void usage(); -int GetConfigData(); -void ReleaseAddress(DWORD); -void RenewAddress(DWORD); -void FlushDNSCache(void); - -void setOutputWindow(HWND); - -#endif //_IPCONFIG_SRC_H_ \ No newline at end of file diff --git a/ipconfig/ipconfig/ipconfig_src1.h b/ipconfig/ipconfig/ipconfig_src1.h deleted file mode 100644 index e484d20..0000000 --- a/ipconfig/ipconfig/ipconfig_src1.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -using namespace System; -using namespace System::ComponentModel; -using namespace System::Collections; -using namespace System::Windows::Forms; -using namespace System::Data; -using namespace System::Drawing; - - -namespace ipconfig { - - /// - /// Summary for ipconfig_src - /// - /// WARNING: If you change the name of this class, you will need to change the - /// 'Resource File Name' property for the managed resource compiler tool - /// associated with all .resx files this class depends on. Otherwise, - /// the designers will not be able to interact properly with localized - /// resources associated with this form. - /// - public ref class ipconfig_src : public System::Windows::Forms::Form - { - public: - ipconfig_src(void) - { - InitializeComponent(); - // - //TODO: Add the constructor code here - // - } - - protected: - /// - /// Clean up any resources being used. - /// - ~ipconfig_src() - { - if (components) - { - delete components; - } - } - - private: - /// - /// Required designer variable. - /// - System::ComponentModel::Container ^components; - -#pragma region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - void InitializeComponent(void) - { - this->components = gcnew System::ComponentModel::Container(); - this->Size = System::Drawing::Size(300,300); - this->Text = L"ipconfig_src"; - this->Padding = System::Windows::Forms::Padding(0); - this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; - } -#pragma endregion - }; -} diff --git a/ipconfig/ipconfig/ipconfigppc.aps b/ipconfig/ipconfig/ipconfigppc.aps deleted file mode 100644 index 074ec37..0000000 Binary files a/ipconfig/ipconfig/ipconfigppc.aps and /dev/null differ diff --git a/ipconfig/ipconfig/ipconfigppc.rc b/ipconfig/ipconfig/ipconfigppc.rc deleted file mode 100644 index 82ca546..0000000 --- a/ipconfig/ipconfig/ipconfigppc.rc +++ /dev/null @@ -1,241 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resourceppc.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#define APSTUDIO_HIDDEN_SYMBOLS -#include "windows.h" -#include "resdefce.h" -#undef APSTUDIO_HIDDEN_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// German (Germany) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -#ifdef _WIN32 -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_GetInput DIALOG 0, 0, 125, 133 -STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_CAPTION -CAPTION "Input" -FONT 8, "MS Shell Dlg" -BEGIN - DEFPUSHBUTTON "OK",IDOK,68,112,50,14 - PUSHBUTTON "Cancel",IDCANCEL,7,112,50,14 - EDITTEXT IDC_EDIT_INPUT,7,66,111,13,ES_AUTOHSCROLL | ES_NUMBER - EDITTEXT IDC_EDIT_INFO,7,7,111,41,ES_MULTILINE | ES_AUTOHSCROLL | ES_READONLY -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_GetInput, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 118 - TOPMARGIN, 7 - BOTTOMMARGIN, 126 - END -END -#endif // APSTUDIO_INVOKED - -#endif // German (Germany) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_ABOUTBOX DIALOG 0, 0, 156, 129 -STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_CAPTION -EXSTYLE 0x80000000L -CAPTION "About ipconfig" -FONT 8, "MS Sans Serif" -BEGIN - ICON IDI_IPCONFIG,IDC_STATIC_1,12,12,21,20,SS_REALSIZEIMAGE - LTEXT "ipconfig Version 1.0",IDC_STATIC_2,12,36,70,8,SS_NOPREFIX - LTEXT "Copyright (C) 2014",IDC_STATIC_3,12,48,66,8 -END - -IDD_ABOUTBOX_WIDE DIALOG 0, 0, 210, 129 -STYLE DS_SETFONT | WS_POPUP | WS_CAPTION -EXSTYLE 0x80000000L -CAPTION "About ipconfig" -FONT 8, "MS Sans Serif" -BEGIN - ICON IDI_IPCONFIG,IDC_STATIC_1,12,12,21,20,SS_REALSIZEIMAGE - LTEXT "ipconfig Version 1.0",IDC_STATIC_2,48,12,66,8,SS_NOPREFIX - LTEXT "Copyright (C) 2014",IDC_STATIC_3,48,24,66,8 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_ABOUTBOX, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 149 - TOPMARGIN, 7 - BOTTOMMARGIN, 122 - END - - IDD_ABOUTBOX_WIDE, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 203 - TOPMARGIN, 7 - BOTTOMMARGIN, 122 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_IPCONFIG ICON "ipconfig.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDR_MENU MENU -BEGIN - POPUP "Commands" - BEGIN - MENUITEM "IP Info", IDM_COMMANDS_IPINFO - MENUITEM "Release ...", ID_COMMANDS_RELEASE - MENUITEM "Renew ...", ID_COMMANDS_RENEW - MENUITEM "Flush DNS", ID_COMMANDS_FLUSHDNS - MENUITEM "Save Text", ID_COMMANDS_SAVETEXT - MENUITEM SEPARATOR - MENUITEM "About", IDM_HELP_ABOUT - END -END - - -///////////////////////////////////////////////////////////////////////////// -// -// Accelerator -// - -IDC_IPCONFIG ACCELERATORS -BEGIN - "A", IDM_HELP_ABOUT, VIRTKEY, CONTROL, NOINVERT - "Q", IDM_OK, VIRTKEY, CONTROL, NOINVERT -END - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resourceppc.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#define APSTUDIO_HIDDEN_SYMBOLS\r\n" - "#include ""windows.h""\r\n" - "#include ""resdefce.h""\r\n" - "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" - "LANGUAGE 9, 1\r\n" - "#pragma code_page(1252)\r\n" - "#include ""ipconfigppc.rc2"" // non-Microsoft Visual C++ edited resources\r\n" - "#endif\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// String Table -// - -STRINGTABLE -BEGIN - IDS_APP_TITLE "ipconfig" - IDC_IPCONFIG "IPCONFIG" -END - -STRINGTABLE -BEGIN - IDS_OK "OK" - IDS_HELP "Commands" -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 -#pragma code_page(1252) -#include "ipconfigppc.rc2" // non-Microsoft Visual C++ edited resources -#endif - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/ipconfig/ipconfig/ipconfigppc.rc2 b/ipconfig/ipconfig/ipconfigppc.rc2 deleted file mode 100644 index 0bda846..0000000 --- a/ipconfig/ipconfig/ipconfigppc.rc2 +++ /dev/null @@ -1,35 +0,0 @@ -// -// ipconfigPPC.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED -#error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... - -///////////////////////////////////////////////////////////////////////////// -HI_RES_AWARE CEUX {1} // turn off the emulation layer - // Remove this resource to enable pixel- - // doubling on platforms that support it -///////////////////////////////////////////////////////////////////////////// - -///////////////////////////////////////////////////////////////////////////// -// -// SHMENUBAR -// - -IDR_MENU SHMENUBAR DISCARDABLE -BEGIN - IDR_MENU, - 2, - - I_IMAGENONE, IDM_OK, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE, - IDS_OK, 0, NOMENU, - - I_IMAGENONE, IDM_HELP, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE, - IDS_HELP, 0, 0, -END - diff --git a/ipconfig/ipconfig/ntddip6.h b/ipconfig/ipconfig/ntddip6.h deleted file mode 100644 index 317a657..0000000 --- a/ipconfig/ipconfig/ntddip6.h +++ /dev/null @@ -1,1331 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -// Use of this source code is subject to the terms of the Microsoft end-user -// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. -// If you did not accept the terms of the EULA, you are not authorized to use -// this source code. For a copy of the EULA, please see the LICENSE.RTF on your -// install media. -// -// -// Abstract: -// -// This header file defines constants and types for accessing -// the MSR IPv6 driver via ioctls. -// - - -#ifndef _NTDDIP6_ -#define _NTDDIP6_ - -#include -#include - -// -// We need a definition of CTL_CODE for use below. -// When compiling kernel components in the DDK environment, -// ntddk.h supplies this definition. Otherwise get it -// from devioctl.h in the SDK environment. -// -#ifndef CTL_CODE -#ifdef UNDER_CE -#include -#else -#include -#endif -#endif - -#pragma warning(push) -#pragma warning(disable:4201) // nameless struct/union - -// -// We also need a definition of TDI_ADDRESS_IP6. -// In the DDK environment, tdi.h supplies this. -// We provide a definition here for the SDK environment. -// -#ifndef TDI_ADDRESS_LENGTH_IP6 -#include -typedef struct _TDI_ADDRESS_IP6 { - USHORT sin6_port; - ULONG sin6_flowinfo; - USHORT sin6_addr[8]; - ULONG sin6_scope_id; -} TDI_ADDRESS_IP6, *PTDI_ADDRESS_IP6; -#include - -#define TDI_ADDRESS_LENGTH_IP6 sizeof (TDI_ADDRESS_IP6) -#endif - -// -// This is the key name of the TCP/IPv6 protocol stack in the registry. -// The protocol driver and the winsock helper both use it. -// -#define TCPIPV6_NAME L"Tcpip6" - -// -// Device Name - this string is the name of the device. It is the name -// that should be passed to NtCreateFile when accessing the device. -// -#define DD_TCPV6_DEVICE_NAME L"\\Device\\Tcp6" -#define DD_UDPV6_DEVICE_NAME L"\\Device\\Udp6" -#define DD_RAW_IPV6_DEVICE_NAME L"\\Device\\RawIp6" -#ifndef UNDER_CE -#define DD_IPV6_DEVICE_NAME L"\\Device\\Ip6" -#else -#define DD_IPV6_DEVICE_NAME TEXT("IP60:") -#endif //UNDER_CE -// -// The Windows-accessible device name. It is the name that -// (prepended with "\\\\.\\") should be passed to CreateFile. -// -#ifndef UNDER_CE -#define WIN_IPV6_BASE_DEVICE_NAME L"Ip6" -#define WIN_IPV6_DEVICE_NAME L"\\\\.\\" WIN_IPV6_BASE_DEVICE_NAME -#else -#define WIN_IPV6_BASE_DEVICE_NAME L"IP60:" -#define WIN_IPV6_DEVICE_NAME L"IP60:" -#endif // UNDER_CE - - -// -// When an interface is bound, we are passed a name beginning with -// IPV6_BIND_STRING_PREFIX. However, we register our interfaces with -// TDI using names beginning with IPV6_EXPORT_STRING_PREFIX. -// -#ifdef UNDER_CE -#define IPV6_BIND_STRING_PREFIX L'\0' -#else //UNDER_CE -#define IPV6_BIND_STRING_PREFIX L"\\DEVICE\\" -#endif //UNDER_CE -#define IPV6_EXPORT_STRING_PREFIX L"\\DEVICE\\TCPIP6_" - -// -// For buffer sizing convenience, bound the link-layer address size. -// -#define MAX_LINK_LAYER_ADDRESS_LENGTH 64 - -// -// IPv6 IOCTL code definitions. -// -// The codes that use FILE_ANY_ACCESS are open to all users. -// The codes that use FILE_WRITE_ACCESS require local Administrator privs. -// - -#define FSCTL_IPV6_BASE FILE_DEVICE_NETWORK - -#define _IPV6_CTL_CODE(function, method, access) \ - CTL_CODE(FSCTL_IPV6_BASE, function, method, access) - - -// -// This IOCTL is used to send an ICMPv6 Echo request. -// It returns the reply (unless there was a timeout or TTL expired). -// -#define IOCTL_ICMPV6_ECHO_REQUEST \ - _IPV6_CTL_CODE(0, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct icmpv6_echo_request { - TDI_ADDRESS_IP6 DstAddress; // Destination address. - TDI_ADDRESS_IP6 SrcAddress; // Source address. - unsigned int Timeout; // Request timeout in milliseconds. - unsigned char TTL; // TTL or Hop Count. - unsigned int Flags; - // Request data follows this structure in memory. -} ICMPV6_ECHO_REQUEST, *PICMPV6_ECHO_REQUEST; - -#define ICMPV6_ECHO_REQUEST_FLAG_REVERSE 0x1 // Use routing header. - -typedef struct icmpv6_echo_reply { - TDI_ADDRESS_IP6 Address; // Replying address. - IP_STATUS Status; // Reply IP_STATUS. - unsigned int RoundTripTime; // RTT in milliseconds. - // Reply data follows this structure in memory. -} ICMPV6_ECHO_REPLY, *PICMPV6_ECHO_REPLY; - - -// -// This IOCTL retrieves information about an interface, -// given an interface index or guid. -// It takes as input an IPV6_QUERY_INTERFACE structure -// and returns as output an IPV6_INFO_INTERFACE structure. -// To perform an iteration, start with Index set to -1, in which case -// only an IPV6_QUERY_INTERFACE is returned, for the first interface. -// If there are no more interfaces, then the Index in the returned -// IPV6_QUERY_INTERFACE will be -1. -// -#define IOCTL_IPV6_QUERY_INTERFACE \ - _IPV6_CTL_CODE(1, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_interface { - unsigned int Index; // -1 means start/finish iteration, - // 0 means use the Guid. - GUID Guid; -} IPV6_QUERY_INTERFACE; - -// -// This IOCTL retrieves persisted information about an interface, -// given a registry index or guid. -// It takes as input an IPV6_PERSISTENT_QUERY_INTERFACE structure -// and returns as output an IPV6_INFO_INTERFACE structure. -// -#define IOCTL_IPV6_PERSISTENT_QUERY_INTERFACE \ - _IPV6_CTL_CODE(48, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_persistent_query_interface { - unsigned int RegistryIndex; // -1 means use the Guid. - GUID Guid; -} IPV6_PERSISTENT_QUERY_INTERFACE; - -typedef struct ipv6_info_interface { - IPV6_QUERY_INTERFACE Next; // For non-persistent queries only. - IPV6_QUERY_INTERFACE This; - - // - // Length of this structure in bytes, not including - // any link-layer addresses following in memory. - // - unsigned int Length; - - // - // These fields are ignored for updates. - // - unsigned int LinkLayerAddressLength; - unsigned int LocalLinkLayerAddress; // Offset, zero indicates absence. - unsigned int RemoteLinkLayerAddress; // Offset, zero indicates absence. - - unsigned int Type; // Ignored for updates. - int RouterDiscovers; // Ignored for updates. - int NeighborDiscovers; // Ignored for updates. - int PeriodicMLD; // Ignored for updates. - int Advertises; // -1 means no change, else boolean. - int Forwards; // -1 means no change, else boolean. - unsigned int MediaStatus; // Ignored for updates. - int OtherStatefulConfig; // Ignored for updates. - -#if defined MIPV6 || defined UNDER_CE - unsigned int ReconnectStateFlush; // Milliseconds, 0 means no change. - unsigned int HeuristicStateFlush; // Milliseconds, 0 means no change. -#endif // MIPV6 - - unsigned int ZoneIndices[16]; // 0 means no change. - - unsigned int TrueLinkMTU; // Ignored for updates. - unsigned int LinkMTU; // 0 means no change. - unsigned int CurHopLimit; // -1 means no change. - unsigned int BaseReachableTime; // Milliseconds, 0 means no change. - unsigned int ReachableTime; // Milliseconds, ignored for updates. - unsigned int RetransTimer; // Milliseconds, 0 means no change. - unsigned int DupAddrDetectTransmits; // -1 means no change. - unsigned int Preference; // -1 means no change. - int FirewallEnabled; // -1 means no change, else boolean. - unsigned int DefSitePrefixLength; // -1 means no change, 0 means none. -#if defined MIPV6 || defined UNDER_CE - unsigned int MaxRtrAdvInterval; // Milliseconds, 0 means no change. - unsigned int MinRtrAdvInterval; // Milliseconds, 0 means no change. -#endif // MIPV6 - -#ifdef UNDER_CE - unsigned int AdvCurHopLimit; // -1 means no change. - unsigned int AdvReachableTime; // Milliseconds, -1 means no change. -#endif - - // Link-layer addresses may follow. -} IPV6_INFO_INTERFACE; - -// -// These values should agree with definitions also -// found in llip6if.h and ip6def.h. -// - -#define IPV6_IF_TYPE_LOOPBACK 0 -#define IPV6_IF_TYPE_ETHERNET 1 -#define IPV6_IF_TYPE_FDDI 2 -#define IPV6_IF_TYPE_TUNNEL_AUTO 3 -#define IPV6_IF_TYPE_TUNNEL_6OVER4 4 -#define IPV6_IF_TYPE_TUNNEL_V6V4 5 -#define IPV6_IF_TYPE_TUNNEL_6TO4 6 -#define IPV6_IF_TYPE_TUNNEL_TEREDO 7 -#define IPV6_IF_TYPE_MIPV6 8 - -#define IPV6_IF_MEDIA_STATUS_DISCONNECTED 0 -#define IPV6_IF_MEDIA_STATUS_RECONNECTING 1 -#define IPV6_IF_MEDIA_STATUS_CONNECTED 2 - -// -// Initialize the fields of the IPV6_INFO_INTERFACE structure -// to values that indicate no change. -// -__inline void -IPV6_INIT_INFO_INTERFACE(IPV6_INFO_INTERFACE *Info) -{ - memset(Info, 0, sizeof *Info); - Info->Length = sizeof *Info; - - Info->Type = (unsigned int)-1; - Info->RouterDiscovers = -1; - Info->NeighborDiscovers = -1; - Info->PeriodicMLD = -1; - Info->Advertises = -1; - Info->Forwards = -1; - Info->MediaStatus = (unsigned int)-1; - Info->CurHopLimit = (unsigned int)-1; - Info->DupAddrDetectTransmits = (unsigned int)-1; - Info->Preference = (unsigned int)-1; - Info->FirewallEnabled = -1; - Info->DefSitePrefixLength = (unsigned int)-1; -#ifdef UNDER_CE - Info->AdvCurHopLimit = (unsigned int)-1; - Info->AdvReachableTime = (unsigned int)-1; -#endif -} - - -// -// This IOCTL retrieves information about an address -// on an interface. -// -#define IOCTL_IPV6_QUERY_ADDRESS \ - _IPV6_CTL_CODE(2, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_address { - IPV6_QUERY_INTERFACE IF; // Fields that identify an interface. - IPv6Addr Address; -} IPV6_QUERY_ADDRESS; - -typedef struct ipv6_info_address { - IPV6_QUERY_ADDRESS Next; - IPV6_QUERY_ADDRESS This; - - unsigned int Type; - unsigned int Scope; - unsigned int ScopeId; - - union { - struct { // If it's a unicast address. - unsigned int DADState; - unsigned int PrefixConf; - unsigned int InterfaceIdConf; - unsigned int ValidLifetime; // Seconds. - unsigned int PreferredLifetime; // Seconds. - int IsHomeAddress; // Boolean. - }; - struct { // If it's a multicast address. - unsigned int MCastRefCount; - unsigned int MCastFlags; - unsigned int MCastTimer; // Seconds. - }; - }; -} IPV6_INFO_ADDRESS; - -// -// Values for address Type. -// -#define ADE_UNICAST 0x00 -#define ADE_ANYCAST 0x01 -#define ADE_MULTICAST 0x02 -#define ADE_PROXY 0x03 - -// -// Values for address Scope. -// -#define ADE_SMALLEST_SCOPE 0x00 -#define ADE_INTERFACE_LOCAL 0x01 -#define ADE_LINK_LOCAL 0x02 -#define ADE_SUBNET_LOCAL 0x03 -#define ADE_ADMIN_LOCAL 0x04 -#define ADE_SITE_LOCAL 0x05 -#define ADE_ORG_LOCAL 0x08 -#define ADE_GLOBAL 0x0e -#define ADE_LARGEST_SCOPE 0x0f - -#define ADE_NUM_SCOPES (ADE_LARGEST_SCOPE - ADE_SMALLEST_SCOPE + 1) - -// -// Bit values for MCastFlags. -// -#define MAE_REPORTABLE 0x01 -#define MAE_LAST_REPORTER 0x02 - -// -// Values for PrefixConf. -// These must match the IP_PREFIX_ORIGIN values in iptypes.h. -// -#define PREFIX_CONF_OTHER 0 // None of the ones below. -#define PREFIX_CONF_MANUAL 1 // From a user or administrator. -#define PREFIX_CONF_WELLKNOWN 2 // IANA-assigned. -#define PREFIX_CONF_DHCP 3 // Configured via DHCP. -#define PREFIX_CONF_RA 4 // From a Router Advertisement. - -// -// Values for InterfaceIdConf. -// These must match the IP_SUFFIX_ORIGIN values in iptypes.h. -// -#define IID_CONF_OTHER 0 // None of the ones below. -#define IID_CONF_MANUAL 1 // From a user or administrator. -#define IID_CONF_WELLKNOWN 2 // IANA-assigned. -#define IID_CONF_DHCP 3 // Configured via DHCP. -#define IID_CONF_LL_ADDRESS 4 // Derived from the link-layer address. -#define IID_CONF_RANDOM 5 // Random, e.g. temporary address. - -// -// Values for DADState. -// -// The low bit set indicates whether the state is valid. -// Among valid states, bigger is better -// for source address selection. -// -#define DAD_STATE_INVALID 0 -#define DAD_STATE_TENTATIVE 1 -#define DAD_STATE_DUPLICATE 2 -#define DAD_STATE_DEPRECATED 3 -#define DAD_STATE_PREFERRED 4 - -#ifdef UNDER_CE -__inline int -IsDADStateValid(unsigned int State) -{ - return (State >= DAD_STATE_DEPRECATED); -} -#endif - -// -// We use this infinite lifetime value for prefix lifetimes, -// router lifetimes, address lifetimes, etc. -// -#define INFINITE_LIFETIME 0xffffffff - - -// -// This IOCTL retrieves information about an address -// that has been assigned persistently to an interface. -// It takes the IPV6_PERSISTENT_QUERY_ADDRESS structure -// and returns the IPV6_UPDATE_ADDRESS structure. -// -#define IOCTL_IPV6_PERSISTENT_QUERY_ADDRESS \ - _IPV6_CTL_CODE(47, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_persistent_query_address { - IPV6_PERSISTENT_QUERY_INTERFACE IF; - unsigned int RegistryIndex; // -1 means use the Address. - IPv6Addr Address; -} IPV6_PERSISTENT_QUERY_ADDRESS; - - -// -// This IOCTL retrieves information from the neighbor cache. -// -#define IOCTL_IPV6_QUERY_NEIGHBOR_CACHE \ - _IPV6_CTL_CODE(3, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_neighbor_cache { - IPV6_QUERY_INTERFACE IF; // Fields that identify an interface. - - IPv6Addr Address; -} IPV6_QUERY_NEIGHBOR_CACHE; - -typedef struct ipv6_info_neighbor_cache { - IPV6_QUERY_NEIGHBOR_CACHE Query; - - unsigned int IsRouter; // Whether neighbor is a router. - unsigned int IsUnreachable; // Whether neighbor is unreachable. - unsigned int NDState; // Current state of entry. - unsigned int ReachableTimer; // Reachable time remaining (in ms). - - unsigned int LinkLayerAddressLength; - // Link-layer address follows. -} IPV6_INFO_NEIGHBOR_CACHE; - -#define ND_STATE_INCOMPLETE 0 -#define ND_STATE_PROBE 1 -#define ND_STATE_DELAY 2 -#define ND_STATE_STALE 3 -#define ND_STATE_REACHABLE 4 -#define ND_STATE_PERMANENT 5 - -// -// This IOCTL retrieves information from the route cache. -// -#define IOCTL_IPV6_QUERY_ROUTE_CACHE \ - _IPV6_CTL_CODE(4, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_route_cache { - IPV6_QUERY_INTERFACE IF; // Fields that identify an interface. - IPv6Addr Address; //MIPV6_TODO: Change to Destination. -#if defined MIPV6 || defined UNDER_CE - IPv6Addr Source; -#endif //MIPV6 -} IPV6_QUERY_ROUTE_CACHE; - -typedef struct ipv6_info_route_cache { - IPV6_QUERY_ROUTE_CACHE Query; - - unsigned int Type; - unsigned int Flags; - int Valid; // Boolean - FALSE means it is stale. -#if defined MIPV6 || defined UNDER_CE - IPV6_QUERY_NEIGHBOR_CACHE NextHop; -#else - IPv6Addr SourceAddress; - IPv6Addr NextHopAddress; - unsigned int NextHopInterface; -#endif - unsigned int PathMTU; - unsigned int PMTUProbeTimer; // Time until next PMTU probe (in ms). - unsigned int ICMPLastError; // Time since last ICMP error sent (in ms). -#if defined MIPV6 || defined UNDER_CE - IPV6_QUERY_ROUTE_CACHE CareOfDestination; - IPV6_QUERY_ROUTE_CACHE CareOfSource; -#else - unsigned int BindingSeqNumber; - unsigned int BindingLifetime; // Seconds. - IPv6Addr CareOfAddress; -#endif -} IPV6_INFO_ROUTE_CACHE; - -#if defined MIPV6 || defined UNDER_CE -#define RCE_FLAG_CONSTRAINED_NTE 0x0001 -#define RCE_FLAG_CONSTRAINED_IF 0x0002 -#define RCE_FLAG_CONSTRAINED_ZONE 0x0004 -#define RCE_FLAG_BU_NEEDED 0x0100 -#define RCE_FLAG_BA_NEEDED 0x0200 -#define RCE_FLAG_BR_NEEDED 0x0400 -#define RCE_FLAG_HOME_AGENT 0x1000 -#else -#define RCE_FLAG_CONSTRAINED_IF 0x1 -#define RCE_FLAG_CONSTRAINED_SCOPEID 0x2 -#define RCE_FLAG_CONSTRAINED 0x3 -#endif - -#define RCE_TYPE_COMPUTED 1 -#define RCE_TYPE_REDIRECT 2 - - -#if 0 // obsolete -// -// This IOCTL retrieves information from the prefix list. -// -#define IOCTL_IPV6_QUERY_PREFIX_LIST \ - _IPV6_CTL_CODE(5, METHOD_BUFFERED, FILE_ANY_ACCESS) - -// -// This IOCTL retrieves information from the default router list. -// -#define IOCTL_IPV6_QUERY_ROUTER_LIST \ - _IPV6_CTL_CODE(6, METHOD_BUFFERED, FILE_ANY_ACCESS) - -// -// This IOCTL adds a multicast group to the desired interface. -// -#define IOCTL_IPV6_ADD_MEMBERSHIP \ - _IPV6_CTL_CODE(7, METHOD_BUFFERED, FILE_ANY_ACCESS) - -// -// This IOCTL drops a multicast group. -// -#define IOCTL_IPV6_DROP_MEMBERSHIP \ - _IPV6_CTL_CODE(8, METHOD_BUFFERED, FILE_ANY_ACCESS) -#endif - -// -// This IOCTL adds an SP to the SP list. -// -#define IOCTL_IPV6_CREATE_SECURITY_POLICY \ - _IPV6_CTL_CODE(9, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -typedef struct ipv6_create_security_policy { - unsigned long SPIndex; // Index of policy to create. - - unsigned int RemoteAddrField; - unsigned int RemoteAddrSelector; - IPv6Addr RemoteAddr; // Remote IP Address. - IPv6Addr RemoteAddrData; - - unsigned int LocalAddrField; // Single, range, or wildcard. - unsigned int LocalAddrSelector; // Packet or policy. - IPv6Addr LocalAddr; // Start of range or single value. - IPv6Addr LocalAddrData; // End of range. - - unsigned int TransportProtoSelector; // Packet or policy. - unsigned short TransportProto; - - unsigned int RemotePortField; // Single, range, or wildcard. - unsigned int RemotePortSelector; // Packet or policy. - unsigned short RemotePort; // Start of range or single value. - unsigned short RemotePortData; // End of range. - - unsigned int LocalPortField; // Single, range, or wildcard. - unsigned int LocalPortSelector; // Packet or policy. - unsigned short LocalPort; // Start of range or single value. - unsigned short LocalPortData; // End of range. - - unsigned int IPSecProtocol; - unsigned int IPSecMode; - IPv6Addr RemoteSecurityGWAddr; - unsigned int Direction; - unsigned int IPSecAction; - unsigned long SABundleIndex; - unsigned int SPInterface; -} IPV6_CREATE_SECURITY_POLICY; - - -// -// This IOCTL adds an SA to the SA list. -// -#define IOCTL_IPV6_CREATE_SECURITY_ASSOCIATION \ - _IPV6_CTL_CODE(10, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -typedef struct ipv6_create_security_association { - unsigned long SAIndex; - unsigned long SPI; // Security Parameter Index. - IPv6Addr SADestAddr; - IPv6Addr DestAddr; - IPv6Addr SrcAddr; - unsigned short TransportProto; - unsigned short DestPort; - unsigned short SrcPort; - unsigned int Direction; - unsigned long SecPolicyIndex; - unsigned int AlgorithmId; - unsigned int RawKeySize; -} IPV6_CREATE_SECURITY_ASSOCIATION; - - -// -// This IOCTL gets all the SPs from the SP list. -// -#define IOCTL_IPV6_QUERY_SECURITY_POLICY_LIST \ - _IPV6_CTL_CODE(11, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_security_policy_list { - unsigned int SPInterface; - unsigned long Index; -} IPV6_QUERY_SECURITY_POLICY_LIST; - -typedef struct ipv6_info_security_policy_list { - IPV6_QUERY_SECURITY_POLICY_LIST Query; - unsigned long SPIndex; - unsigned long NextSPIndex; - - unsigned int RemoteAddrField; - unsigned int RemoteAddrSelector; - IPv6Addr RemoteAddr; // Remote IP Address. - IPv6Addr RemoteAddrData; - - unsigned int LocalAddrField; // Single, range, or wildcard. - unsigned int LocalAddrSelector; // Packet or policy. - IPv6Addr LocalAddr; // Start of range or single value. - IPv6Addr LocalAddrData; // End of range. - - unsigned int TransportProtoSelector; // Packet or policy. - unsigned short TransportProto; - - unsigned int RemotePortField; // Single, range, or wildcard. - unsigned int RemotePortSelector; // Packet or policy. - unsigned short RemotePort; // Start of range or single value. - unsigned short RemotePortData; // End of range. - - unsigned int LocalPortField; // Single, range, or wildcard. - unsigned int LocalPortSelector; // Packet or policy. - unsigned short LocalPort; // Start of range or single value. - unsigned short LocalPortData; // End of range. - - unsigned int IPSecProtocol; - unsigned int IPSecMode; - IPv6Addr RemoteSecurityGWAddr; - unsigned int Direction; - unsigned int IPSecAction; - unsigned long SABundleIndex; - unsigned int SPInterface; -} IPV6_INFO_SECURITY_POLICY_LIST; - - -// -// This IOCTL gets all the SAs from the SA list. -// -#define IOCTL_IPV6_QUERY_SECURITY_ASSOCIATION_LIST \ - _IPV6_CTL_CODE(12, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_security_association_list { - unsigned long Index; -} IPV6_QUERY_SECURITY_ASSOCIATION_LIST; - -typedef struct ipv6_info_security_association_list { - IPV6_QUERY_SECURITY_ASSOCIATION_LIST Query; - unsigned long SAIndex; - unsigned long NextSAIndex; - unsigned long SPI; // Security Parameter Index. - IPv6Addr SADestAddr; - IPv6Addr DestAddr; - IPv6Addr SrcAddr; - unsigned short TransportProto; - unsigned short DestPort; - unsigned short SrcPort; - unsigned int Direction; - unsigned long SecPolicyIndex; - unsigned int AlgorithmId; -} IPV6_INFO_SECURITY_ASSOCIATION_LIST; - - -// -// This IOCTL retrieves information from the route table. -// It takes the IPV6_QUERY_ROUTE_TABLE structure -// and returns the IPV6_INFO_ROUTE_TABLE structure. -// -// -#define IOCTL_IPV6_QUERY_ROUTE_TABLE \ - _IPV6_CTL_CODE(13, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_route_table { - IPv6Addr Prefix; - unsigned int PrefixLength; - IPV6_QUERY_NEIGHBOR_CACHE Neighbor; -} IPV6_QUERY_ROUTE_TABLE; - -typedef struct ipv6_info_route_table { - union { - IPV6_QUERY_ROUTE_TABLE Next; // Non-persistent query results. - IPV6_QUERY_ROUTE_TABLE This; // All other uses. - }; - - unsigned int SitePrefixLength; - unsigned int ValidLifetime; // Seconds. - unsigned int PreferredLifetime; // Seconds. - unsigned int Preference; // Smaller is better. See below. - unsigned int Type; // See values below. - int Publish; // Boolean. - int Immortal; // Boolean. -} IPV6_INFO_ROUTE_TABLE; - -// -// The Type field indicates where the route came from. -// These are RFC 2465 ipv6RouteProtocol values. -// Routing protocols are free to define new values. -// -#define RTE_TYPE_SYSTEM 2 -#define RTE_TYPE_MANUAL 3 -#define RTE_TYPE_AUTOCONF 4 -#define RTE_TYPE_RIP 5 -#define RTE_TYPE_OSPF 6 -#define RTE_TYPE_BGP 7 -#define RTE_TYPE_IDRP 8 -#define RTE_TYPE_IGRP 9 - -// -// Standard route preference values. -// The value zero is reserved for administrative configuration. -// -#define ROUTE_PREF_LOW (16*16*16) -#define ROUTE_PREF_MEDIUM (16*16) -#define ROUTE_PREF_HIGH 16 -#define ROUTE_PREF_ON_LINK 8 -#define ROUTE_PREF_LOOPBACK 4 -#define ROUTE_PREF_HIGHEST 0 - - -// -// This IOCTL retrieves information about a persistent route. -// It takes the IPV6_PERSISTENT_QUERY_ROUTE_TABLE structure -// and returns the IPV6_INFO_ROUTE_TABLE structure. -// -#define IOCTL_IPV6_PERSISTENT_QUERY_ROUTE_TABLE \ - _IPV6_CTL_CODE(46, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_persistent_query_route_table { - IPV6_PERSISTENT_QUERY_INTERFACE IF; - unsigned int RegistryIndex; // -1 means use the parameters below. - IPv6Addr Neighbor; - IPv6Addr Prefix; - unsigned int PrefixLength; -} IPV6_PERSISTENT_QUERY_ROUTE_TABLE; - - -// -// This IOCTL adds/removes a route in the route table. -// It uses the IPV6_INFO_ROUTE_TABLE structure. -// -#define IOCTL_IPV6_UPDATE_ROUTE_TABLE \ - _IPV6_CTL_CODE(14, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_UPDATE_ROUTE_TABLE \ - _IPV6_CTL_CODE(40, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL adds/removes an address on an interface. -// It uses the IPV6_UPDATE_ADDRESS structure. -// -#define IOCTL_IPV6_UPDATE_ADDRESS \ - _IPV6_CTL_CODE(15, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_UPDATE_ADDRESS \ - _IPV6_CTL_CODE(38, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -typedef struct ipv6_update_address { - IPV6_QUERY_ADDRESS This; - unsigned int Type; // Unicast or anycast. - unsigned int PrefixConf; - unsigned int InterfaceIdConf; - unsigned int PreferredLifetime; // Seconds. - unsigned int ValidLifetime; // Seconds. -} IPV6_UPDATE_ADDRESS; - - -// -// This IOCTL retrieves information from the binding cache. -// -#define IOCTL_IPV6_QUERY_BINDING_CACHE \ - _IPV6_CTL_CODE(16, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_binding_cache { - IPv6Addr HomeAddress; -} IPV6_QUERY_BINDING_CACHE; - -typedef struct ipv6_info_binding_cache { - IPV6_QUERY_BINDING_CACHE Query; - - IPv6Addr HomeAddress; - IPv6Addr CareOfAddress; - unsigned int BindingSeqNumber; - unsigned int BindingLifetime; // Seconds. -#if defined MIPV6 || defined UNDER_CE - int HomeAgent; // Boolean. -#endif //MIPV6 -} IPV6_INFO_BINDING_CACHE; - - -// -// This IOCTL controls some attributes of an interface. -// It uses the IPV6_INFO_INTERFACE structure. -// -#define IOCTL_IPV6_UPDATE_INTERFACE \ - _IPV6_CTL_CODE(17, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_UPDATE_INTERFACE \ - _IPV6_CTL_CODE(36, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL flushes entries from the neighbor cache. -// It uses the IPV6_QUERY_NEIGHBOR_CACHE structure. -// -#define IOCTL_IPV6_FLUSH_NEIGHBOR_CACHE \ - _IPV6_CTL_CODE(18, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL flushes entries from the route cache. -// It uses the IPV6_QUERY_ROUTE_CACHE structure. -// -#define IOCTL_IPV6_FLUSH_ROUTE_CACHE \ - _IPV6_CTL_CODE(19, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL deletes SA entries from the SA list. -// It uses the IPV6_QUERY_SECURITY_ASSOCIATION_LIST structure. -// -#define IOCTL_IPV6_DELETE_SECURITY_ASSOCIATION \ - _IPV6_CTL_CODE(20, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL deletes SP entries from the SP list. -// It uses the IPV6_QUERY_SECURITY_POLICY_LIST structure. -// -#define IOCTL_IPV6_DELETE_SECURITY_POLICY \ - _IPV6_CTL_CODE(21, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL deletes an interface. -// It uses the IPV6_QUERY_INTERFACE structure. -// -// The persistent variant, in addition to deleting the runtime interface, -// also keeps the interface from being (re)created persistently. -// However, it does NOT reset or delete any persistent attributes -// of the interface. For example, suppose you have a persisent tunnel -// interface with a persistent attribute, the interface metric. -// If you delete the tunnel interface and reboot, the tunnel interface -// will be recreated with the non-default interface metric. -// If you persistently delete the tunnel interface and reboot, -// the tunnel interface will not be created. But if you then create -// the tunnel interface, it will get the non-default interface metric. -// This is analogous to persistent attributes on removable ethernet interfaces. -// -#define IOCTL_IPV6_DELETE_INTERFACE \ - _IPV6_CTL_CODE(22, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_DELETE_INTERFACE \ - _IPV6_CTL_CODE(44, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -#if 0 // obsolete -// -// This IOCTL sets the mobility security to either on or off. -// When mobility security is turned on, Binding Cache Updates -// must be protected via IPsec. -// -#define IOCTL_IPV6_SET_MOBILITY_SECURITY \ - _IPV6_CTL_CODE(23, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -typedef struct ipv6_set_mobility_security { - unsigned int MobilitySecurity; // See MOBILITY_SECURITY values in ipsec.h. -} IPV6_SET_MOBILITY_SECURITY; -#endif - - -// -// This IOCTL sorts a list of destination addresses. -// The returned list may contain fewer addresses. -// It uses an array of TDI_ADDRESS_IP6 in/out. -// -#define IOCTL_IPV6_SORT_DEST_ADDRS \ - _IPV6_CTL_CODE(24, METHOD_BUFFERED, FILE_ANY_ACCESS) - - -// -// This IOCTL retrieves information from the site prefix table. -// -#define IOCTL_IPV6_QUERY_SITE_PREFIX \ - _IPV6_CTL_CODE(25, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_site_prefix { - IPv6Addr Prefix; - unsigned int PrefixLength; - IPV6_QUERY_INTERFACE IF; -} IPV6_QUERY_SITE_PREFIX; - -typedef struct ipv6_info_site_prefix { - IPV6_QUERY_SITE_PREFIX Query; - - unsigned int ValidLifetime; // Seconds. -} IPV6_INFO_SITE_PREFIX; - - -// -// This IOCTL adds/removes a prefix in the site prefix table. -// It uses the IPV6_INFO_SITE_PREFIX structure. -// -// This ioctl is provided for testing purposes. -// Administrative configuration of site prefixes should never -// be required, because site prefixes are configured from -// Router Advertisements on hosts and from the routing table -// on routers. Hence there is no persistent version of this ioctl. -// -#define IOCTL_IPV6_UPDATE_SITE_PREFIX \ - _IPV6_CTL_CODE(26, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL create a new interface. -// It uses the IPV6_INFO_INTERFACE structure, -// with many fields ignored. -// -#define IOCTL_IPV6_CREATE_INTERFACE \ - _IPV6_CTL_CODE(27, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_CREATE_INTERFACE \ - _IPV6_CTL_CODE(43, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL requests a routing change notification. -// It uses the IPV6_RTCHANGE_NOTIFY_REQUEST (input) and -// IPV6_INFO_ROUTE_TABLE (output) structures. -// -// A notification request completes when a route -// that matches is added or deleted. -// A route matches the requested prefix if the route -// prefix and the request prefix intersect. -// So the ::/0 request prefix matches all route updates. -// -#define IOCTL_IPV6_RTCHANGE_NOTIFY_REQUEST \ - _IPV6_CTL_CODE(28, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_rtchange_notify_request { - unsigned int Flags; - unsigned int PrefixLength; - unsigned long ScopeId; - IPv6Addr Prefix; -} IPV6_RTCHANGE_NOTIFY_REQUEST; - -#define IPV6_RTCHANGE_NOTIFY_REQUEST_FLAG_SYNCHRONIZE 0x1 - // Only one wakeup per requestor per change. -#define IPV6_RTCHANGE_NOTIFY_REQUEST_FLAG_SUPPRESS_MINE 0x2 - // Ignore route changes from this requestor. - - -#if 0 // obsolete -// -// This IOCTL retrieves an interface index, given a device name. -// It takes a PWSTR for input, and uses the IPV6_QUERY_INTERFACE structure -// for output. -// -#define IOCTL_IPV6_QUERY_INTERFACE_INDEX \ - _IPV6_CTL_CODE(29, METHOD_BUFFERED, FILE_ANY_ACCESS) -#endif - - -// -// This IOCTL queries global IPv6 parameters. -// It uses the IPV6_GLOBAL_PARAMETERS structure. -// -// Note that changing these parameters typically does not affect -// existing uses of them. For example changing DefaultCurHopLimit -// will not affect the CurHopLimit of existing interfaces, -// but it will affect the CurHopLimit of new interfaces. -// -#define IOCTL_IPV6_QUERY_GLOBAL_PARAMETERS \ - _IPV6_CTL_CODE(30, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_QUERY_GLOBAL_PARAMETERS \ - _IPV6_CTL_CODE(49, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_global_parameters { - unsigned int DefaultCurHopLimit; // -1 means no change. - unsigned int UseTemporaryAddresses; // -1 means no change. - unsigned int MaxTempDADAttempts; // -1 means no change. - unsigned int MaxTempValidLifetime; // -1 means no change. - unsigned int MaxTempPreferredLifetime; // -1 means no change. - unsigned int TempRegenerateTime; // -1 means no change. - unsigned int MaxTempRandomTime; // -1 means no change. - unsigned int TempRandomTime; // -1 means no change. - unsigned int NeighborCacheLimit; // -1 means no change. - unsigned int RouteCacheLimit; // -1 means no change. - unsigned int BindingCacheLimit; // -1 means no change. - unsigned int ReassemblyLimit; // -1 means no change. - int MobilitySecurity; // Boolean, -1 means no change. - unsigned int BUSecurity; - unsigned int BASecurity; - unsigned int MobileIPv6Mode; // -1 means no change. -} IPV6_GLOBAL_PARAMETERS; - - -// -// Values for the UseTemporaryAddresses field. -// -#define USE_TEMP_NO 0 // Don't use temporary addresses. -#define USE_TEMP_YES 1 // Use them. -#define USE_TEMP_ALWAYS 2 // Always generating random numbers. -#define USE_TEMP_COUNTER 3 // Use them with per-interface counter. - -// -// Values for BUSecurity Field -// -#define BU_NONE 0 -#define BU_IPSEC 1 -#define BU_CAM 2 - - -// -// Values for BASecurity Field -// -#define BA_NONE 0 -#define BA_IPSEC 1 -// Bits in the MobileIPv6Mode field. -// -#define MOBILE_CORRESPONDENT 0x01 -#define MOBILE_MOBILE_NODE 0x02 -#define MOBILE_HOME_AGENT 0x04 - -// -// Initialize the fields of the IPV6_GLOBAL_PARAMETERS structure -// to values that indicate no change. -// -__inline void -IPV6_INIT_GLOBAL_PARAMETERS(IPV6_GLOBAL_PARAMETERS *Params) -{ - Params->DefaultCurHopLimit = (unsigned int) -1; - Params->UseTemporaryAddresses = (unsigned int) -1; - Params->MaxTempDADAttempts = (unsigned int) -1; - Params->MaxTempValidLifetime = (unsigned int) -1; - Params->MaxTempPreferredLifetime = (unsigned int) -1; - Params->TempRegenerateTime = (unsigned int) -1; - Params->MaxTempRandomTime = (unsigned int) -1; - Params->TempRandomTime = (unsigned int) -1; - Params->NeighborCacheLimit = (unsigned int) -1; - Params->RouteCacheLimit = (unsigned int) -1; - Params->BindingCacheLimit = (unsigned int) -1; - Params->ReassemblyLimit = (unsigned int) -1; - Params->MobilitySecurity = -1; - Params->BUSecurity = (unsigned int) -1; - Params->MobileIPv6Mode = (unsigned int) -1; - Params->BASecurity = (unsigned int) -1; -} - - -// -// This IOCTL sets global IPv6 parameters. -// It uses the IPV6_GLOBAL_PARAMETERS structure. -// -// Note that changing these parameters typically does not affect -// existing uses of them. For example changing DefaultCurHopLimit -// will not affect the CurHopLimit of existing interfaces, -// but it will affect the CurHopLimit of new interfaces. -// -#define IOCTL_IPV6_UPDATE_GLOBAL_PARAMETERS \ - _IPV6_CTL_CODE(31, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_UPDATE_GLOBAL_PARAMETERS \ - _IPV6_CTL_CODE(37, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL retrieves information from the prefix policy table. -// It takes as input an IPV6_QUERY_PREFIX_POLICY structure -// and returns as output an IPV6_INFO_PREFIX_POLICY structure. -// To perform an iteration, start with PrefixLength set to -1, in which case -// only an IPV6_QUERY_PREFIX_POLICY is returned, for the first policy. -// If there are no more policies, then the PrefixLength in the returned -// IPV6_QUERY_PREFIX_POLICY will be -1. -// -#define IOCTL_IPV6_QUERY_PREFIX_POLICY \ - _IPV6_CTL_CODE(32, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_prefix_policy { - IPv6Addr Prefix; - unsigned int PrefixLength; -} IPV6_QUERY_PREFIX_POLICY; - -typedef struct ipv6_info_prefix_policy { - IPV6_QUERY_PREFIX_POLICY Next; // For non-persistent queries only. - IPV6_QUERY_PREFIX_POLICY This; - - unsigned int Precedence; - unsigned int SrcLabel; - unsigned int DstLabel; -} IPV6_INFO_PREFIX_POLICY; - - -// -// This IOCTL retrieves information about persisted prefix policies. -// It takes as input an IPV6_PERSISTENT_QUERY_PREFIX_POLICY structure -// and returns as output an IPV6_INFO_PREFIX_POLICY structure. -// (The Next field is not returned.) -// To perform an iteration, start with index 0 and increment -// until getting STATUS_NO_MORE_ENTRIES / ERROR_NO_MORE_ITEMS. -// -// An IOCTL to retrieve persisted prefix policies via prefix -// (like IPV6_QUERY_PREFIX_POLICY) is conceivable but not supported. -// -#define IOCTL_IPV6_PERSISTENT_QUERY_PREFIX_POLICY \ - _IPV6_CTL_CODE(50, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_persistent_query_prefix_policy { - unsigned int RegistryIndex; -} IPV6_PERSISTENT_QUERY_PREFIX_POLICY; - - -// -// This IOCTL adds a prefix to the prefix policy table, -// or updates an existing prefix policy. -// It uses the IPV6_INFO_PREFIX_POLICY structure. -// (The Next field is ignored.) -// -#define IOCTL_IPV6_UPDATE_PREFIX_POLICY \ - _IPV6_CTL_CODE(33, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_UPDATE_PREFIX_POLICY \ - _IPV6_CTL_CODE(41, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL removes a prefix from the prefix policy table. -// It uses the IPV6_QUERY_PREFIX_POLICY structure. -// -#define IOCTL_IPV6_DELETE_PREFIX_POLICY \ - _IPV6_CTL_CODE(34, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_DELETE_PREFIX_POLICY \ - _IPV6_CTL_CODE(42, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL deletes all manual configuration. -// -#define IOCTL_IPV6_RESET \ - _IPV6_CTL_CODE(39, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#define IOCTL_IPV6_PERSISTENT_RESET \ - _IPV6_CTL_CODE(45, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - -// -// This IOCTL sets the link-layer address of a default router -// on a non-broadcast multi-access (NBMA) link, such as the ISATAP -// link, where Router Solicitations, Router Advertistments, and -// Redirects are desired. -// -// There is no persistent version of this ioctl because -// 6to4svc always configures this information dynamically. -// -#define IOCTL_IPV6_UPDATE_ROUTER_LL_ADDRESS \ - _IPV6_CTL_CODE(35, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -typedef struct ipv6_update_router_ll_address { - IPV6_QUERY_INTERFACE IF; - // Following this structure in memory are: - // Own link-layer address to use for EUI-64 creation. - // Link-layer address of router. -} IPV6_UPDATE_ROUTER_LL_ADDRESS; - - -// -// This IOCTL renews an interface, meaning that all -// auto-configured state is thrown away and regenerated. -// Same behavior as reconnecting the interface to a link. -// It uses the IPV6_QUERY_INTERFACE structure. -// -#define IOCTL_IPV6_RENEW_INTERFACE \ - _IPV6_CTL_CODE(51, METHOD_BUFFERED, FILE_WRITE_ACCESS) - -#if defined MIPV6 || defined UNDER_CE -// -// This IOCTL discovers a home address/home agent pair of a mobile node. -// -#define IOCTL_IPV6_QUERY_HOME_ADDRESS \ - _IPV6_CTL_CODE(52, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_home_address { - IPv6Addr Address; -} IPV6_QUERY_HOME_ADDRESS; - -// -// This IOCTL assigns a home address/home agent pair to a mobile node. -// -#define IOCTL_IPV6_UPDATE_HOME_ADDRESS \ - _IPV6_CTL_CODE(53, METHOD_BUFFERED, FILE_WRITE_ACCESS) -typedef struct ipv6_info_home_address { - IPV6_QUERY_HOME_ADDRESS Next; - IPV6_QUERY_HOME_ADDRESS This; - - IPv6Addr HomeAgent; - unsigned int Flags; -} IPV6_INFO_HOME_ADDRESS; - -#define IPV6_HA_INFO_AT_HOME 0x01 // Set if HAE is on-link -#define IPV6_HA_INFO_NO_BA_AUTH 0x04 // Set if HA cannot use IPSEC. -#define IPV6_HA_INFO_CAM_ENABLED 0x08 //Set if HA is derived using CAM - -// -// This IOCTL plumbs the Public/Private key pair to be used for CAM -// - -typedef struct ipv6_info_cam_key { - unsigned char *Private; - unsigned int PrivateLen; - unsigned char *Public; - unsigned int PublicLen; -} IPV6_INFO_CAM_KEY; - -#define IOCTL_IPV6_INIT_CAM_KEY \ - _IPV6_CTL_CODE(64, METHOD_BUFFERED, FILE_WRITE_ACCESS) - - - -// -// This IOCTL queries the binding update list -// -#define IOCTL_IPV6_QUERY_BINDING_LIST \ - _IPV6_CTL_CODE(54, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_query_binding_list { - IPV6_QUERY_HOME_ADDRESS HomeAddress; - IPv6Addr Correspondent; -} IPV6_QUERY_BINDING_LIST; - -typedef struct ipv6_info_binding_list { - IPV6_QUERY_BINDING_LIST Next; - IPV6_QUERY_BINDING_LIST This; - - unsigned int Flags; - unsigned int Lifetime; // Milliseconds. - unsigned int LastSend; // Milliseconds, 0 means never. - unsigned int LastSeq; - IPV6_QUERY_ROUTE_CACHE Route; -} IPV6_INFO_BINDING_LIST; - -#define IPV6_BLE_INFO_IS_HOME_AGENT 0x01 -#define IPV6_BLE_INFO_IS_AWAITING_ACK 0x02 - -// -// This IOCTL queries the current Mobile IPv6 mode -// -#define IOCTL_IPV6_QUERY_MOBILE_MODE \ - _IPV6_CTL_CODE(55, METHOD_BUFFERED, FILE_ANY_ACCESS) -typedef struct ipv6_query_mobile_mode { - unsigned int Correspondent; - unsigned int Mobile; - unsigned int HomeAgent; -} IPV6_QUERY_MOBILE_MODE; - -// -// This IOCTL sets the current Mobile IPv6 mode -// -#define IOCTL_IPV6_UPDATE_MOBILE_MODE \ - _IPV6_CTL_CODE(56, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#if 0 // obsolete -// -// This IOCTL queries the current preferred home address -// -#define IOCTL_IPV6_QUERY_PREF_HOME_ADDRESS \ - _IPV6_CTL_CODE(57, METHOD_BUFFERED, FILE_ANY_ACCESS) - -// -// This IOCTL updates the current preferred home address -// -#define IOCTL_IPV6_UPDATE_PREF_HOME_ADDRESS \ - _IPV6_CTL_CODE(58, METHOD_BUFFERED, FILE_ANY_ACCESS) -#endif - -#endif //MIPV6 - -#ifdef UNDER_CE -// -// This IOCTL reinitializes the stack, achieving the same result -// as unloading and then reloading the driver. -// -#define IOCTL_IPV6_RESTART \ - _IPV6_CTL_CODE(60, METHOD_BUFFERED, FILE_ANY_ACCESS) -#endif // UNDER_CE - -#if defined MIPV6 || defined UNDER_CE -// -// This IOCTL requests a home-agent prefix notification. -// It uses the IPV6_INFO_HA_ADV structure for output. -// IPV6_INFO_ROUTE_TABLE (output) structures. -// -// A notification request completes when the stack receives -// a prefix information option from a home agent router. -// -#define IOCTL_IPV6_HA_ADVERT_NOTIFY_REQUEST \ - _IPV6_CTL_CODE(61, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_info_ha_adv { - IPV6_QUERY_INTERFACE Interface; - IPv6Addr HomeAgent; - unsigned int PrefixLength; -} IPV6_INFO_HA_ADV; - -// -// This IOCTL queries the list of recently seen home agents. Provide no -// input data to find the first in the list. Provide the returned -// IPV6_INFO_HA_HISTORY as input to return the next in the list. Returns -// nothing when there are no more entries. -// -#define IOCTL_IPV6_QUERY_HA_HISTORY \ - _IPV6_CTL_CODE(62, METHOD_BUFFERED, FILE_ANY_ACCESS) - -typedef struct ipv6_info_ha_history { - IPV6_QUERY_INTERFACE Interface; - IPv6Addr HomeAgent; - unsigned int PrefixLength; - unsigned int LastAdvert; // Seconds since the last RA. -} IPV6_INFO_HA_HISTORY; - -#endif // MIPV6 - -#pragma warning(pop) -#endif // ifndef _NTDDIP6_ diff --git a/ipconfig/ipconfig/resourceppc.h b/ipconfig/ipconfig/resourceppc.h deleted file mode 100644 index d80791f..0000000 --- a/ipconfig/ipconfig/resourceppc.h +++ /dev/null @@ -1,43 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by ipconfigppc.rc -// -#define IDS_APP_TITLE 1 -#define IDC_IPCONFIG 2 -#define IDI_IPCONFIG 101 -#define IDR_MENU 102 -#define IDS_OK 103 -#define IDS_HELP 104 -#define IDD_ABOUTBOX 105 -#define IDD_ABOUTBOX_WIDE 106 -#define IDD_GetInput 129 -#define IDC_STATIC_1 201 -#define IDC_STATIC_2 202 -#define IDC_STATIC_3 203 -#define IDC_EDIT_INPUT 1000 -#define IDC_EDIT2 1001 -#define IDC_EDIT_INFO 1001 -#define ID_COMMANDS_IPINFO 32771 -#define IDM_COMMANDS_IPINFO 32772 -#define ID_COMMANDS_RELEASE 32773 -#define ID_COMMANDS_RENEW 32774 -#define ID_COMMANDS_CLEARDNS 32775 -#define ID_COMMANDS_FLUSHDNS 32776 -#define ID_COMMANDS_ 32777 -#define ID_COMMANDS_SAVETEXT 32778 -#define IDM_OK 40000 -#define IDM_HELP 40001 -#define IDM_HELP_ABOUT 40002 -#define IDC_STATIC -1 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 130 -#define _APS_NEXT_COMMAND_VALUE 32779 -#define _APS_NEXT_CONTROL_VALUE 1002 -#define _APS_NEXT_SYMED_VALUE 110 -#endif -#endif diff --git a/ipconfig/ipconfig/stdafx.cpp b/ipconfig/ipconfig/stdafx.cpp deleted file mode 100644 index f1871b6..0000000 --- a/ipconfig/ipconfig/stdafx.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// stdafx.cpp : source file that includes just the standard includes -// ipconfig.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/ipconfig/ipconfig/stdafx.h b/ipconfig/ipconfig/stdafx.h deleted file mode 100644 index 65d8052..0000000 --- a/ipconfig/ipconfig/stdafx.h +++ /dev/null @@ -1,62 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - -#pragma comment(linker, "/nodefaultlib:libc.lib") -#pragma comment(linker, "/nodefaultlib:libcd.lib") - -// NOTE - this value is not strongly correlated to the Windows CE OS version being targeted -#define WINVER _WIN32_WCE - -#include -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#define SHELL_AYGSHELL -#endif - -#ifdef _CE_DCOM -#define _ATL_APARTMENT_THREADED -#endif - -#include -#include - -#include -#pragma comment(lib, "aygshell.lib") - - -// Windows Header Files: -#include - -// C RunTime Header Files -#include -#include -#include -#include - -#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) -#ifndef _DEVICE_RESOLUTION_AWARE -#define _DEVICE_RESOLUTION_AWARE -#endif -#endif - -#ifdef _DEVICE_RESOLUTION_AWARE -#include "DeviceResolutionAware.h" -#endif - -#if _WIN32_WCE < 0x500 && ( defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP) ) - #pragma comment(lib, "ccrtrtti.lib") - #ifdef _X86_ - #if defined(_DEBUG) - #pragma comment(lib, "libcmtx86d.lib") - #else - #pragma comment(lib, "libcmtx86.lib") - #endif - #endif -#endif - -#include - -// TODO: reference additional headers your program requires here diff --git a/netstatCF2/AdaptersInfo.cs b/netstatCF2/AdaptersInfo.cs deleted file mode 100644 index fb724c5..0000000 --- a/netstatCF2/AdaptersInfo.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; - -namespace AdapterInfo -{ - class AdaptersInfo - { - public List _adapterList; - public AdaptersInfo() - { - _adapterList = new List(); - - int cb = 0; - int ret = GetAdaptersInfo(IntPtr.Zero, ref cb); - IntPtr pInfo = LocalAlloc(0x40, cb); //LPTR - ret = GetAdaptersInfo(pInfo, ref cb); - if (ret == 0) - { - IP_ADAPTER_INFO info = new IP_ADAPTER_INFO(pInfo, 0); - while (info != null) - { - IP_ADDR_STRING st = info.IpAddressList; - _adapterList.Add(info); - //listView1.Items.Add(new ListViewItem(new string[] { info.AdapterName, info.CurrentIpAddress.IpAddress.String, info.CurrentIpAddress.IpMask.String, info.GatewayList.IpAddress.String })); - info = info.Next; - } - } - LocalFree(pInfo); - } - - #region P/Invoke definitions - [DllImport("iphlpapi")] - extern public static int GetAdaptersInfo(IntPtr p, ref int cb); - [DllImport("coredll")] - extern public static IntPtr LocalAlloc(int flags, int cb); - [DllImport("coredll")] - extern public static IntPtr LocalFree(IntPtr p); - #endregion - } - /// - /// Class IP_ADAPTER_INFO - /// Description: - /// Implementation of custom marshaller for IPHLPAPI IP_ADAPTER_INFO - /// - public class IP_ADAPTER_INFO : SelfMarshalledStruct - { - #region Constructors - public IP_ADAPTER_INFO() - : base(640) - { - } - public IP_ADAPTER_INFO(byte[] data, int offset) - : base(data, offset) - { - } - - - public IP_ADAPTER_INFO(IntPtr pData, int offset) - : base(640) - { - Marshal.Copy(new IntPtr(pData.ToInt32() + offset), data, 0, 640); - } - #endregion - - #region Properties - public IP_ADAPTER_INFO Next - { - get - { - if (this.GetInt32(0) == 0) - return null; - return new IP_ADAPTER_INFO(new IntPtr(this.GetInt32(0)), 0); - } - } - public uint ComboIndex - { - get { return GetUInt32(4); } - set { Set(typeof(uint), 4, value); } - } - public string AdapterName - { - get { return GetStringAscii(8, 268 - 8); } - set { Set(typeof(string), 8, value); } - } - public string Description - { - get { return GetStringAscii(268, 400 - 268); } - set { Set(typeof(string), 268, value); } - } - public uint AddressLength - { - get { return GetUInt32(400); } - set { Set(typeof(uint), 400, value); } - } - public byte[] Address - { - get { return GetSlice(404, (int)AddressLength); } - } - public uint Index - { - get { return GetUInt32(412); } - set { Set(typeof(uint), 412, value); } - } - public uint Type - { - get { return GetUInt32(416); } - set { Set(typeof(uint), 416, value); } - } - public uint DhcpEnabled - { - get { return GetUInt32(420); } - set { Set(typeof(uint), 420, value); } - } - public IP_ADDR_STRING CurrentIpAddress - { - get - { - IntPtr p = new IntPtr(GetInt32(424)); - if (p == IntPtr.Zero) - return null; - return new IP_ADDR_STRING(p, 0); - } - } - public IP_ADDR_STRING IpAddressList - { - get - { - return new IP_ADDR_STRING(data, 428); - } - } - public IP_ADDR_STRING GatewayList - { - get - { - return new IP_ADDR_STRING(data, 468); - } - } - public IP_ADDR_STRING DhcpServer - { - get - { - return new IP_ADDR_STRING(data, 508); - } - } - public int HaveWins - { - get { return GetInt32(548); } - set { Set(typeof(int), 548, value); } - } - public IP_ADDR_STRING PrimaryWinsServer - { - get - { - return new IP_ADDR_STRING(data, 552); - } - } - public IP_ADDR_STRING SecondaryWinsServer - { - get - { - return new IP_ADDR_STRING(data, 592); - } - } - public uint LeaseObtained - { - get { return GetUInt32(632); } - set { Set(typeof(uint), 632, value); } - } - public uint LeaseExpires - { - get { return GetUInt32(636); } - set { Set(typeof(uint), 636, value); } - } - #endregion - } - - /// - /// Class IP_ADDR_STRING - /// Description: - /// Implementation of custom marshaller for IPHLPAPI IP_ADDR_STRING - /// - public class IP_ADDR_STRING : SelfMarshalledStruct - { - #region Contructors - public IP_ADDR_STRING() - : base(40) - { - } - public IP_ADDR_STRING(byte[] data, int offset) - : base(data, offset) - { - } - public IP_ADDR_STRING(IntPtr pData, int offset) - : base(40) - { - Marshal.Copy(new IntPtr(pData.ToInt32() + offset), data, 0, 40); - } - #endregion - - #region Properties - public IP_ADDR_STRING Next - { - get - { - if (this.GetInt32(0) == 0) - return null; - return new IP_ADDR_STRING(new IntPtr(GetInt32(0)), 0); - } - } - public IP_ADDRESS_STRING IpAddress - { - get { return new IP_ADDRESS_STRING(data, baseOffset + 4); } - - } - public IP_ADDRESS_STRING IpMask - { - get { return new IP_ADDRESS_STRING(data, baseOffset + 20); } - } - public uint Context - { - get { return GetUInt32(36); } - set { Set(typeof(uint), 36, value); } - } - #endregion - } - - /// - /// Class IP_ADDRESS_STRING - /// Description: - /// Implementation of custom marshaller for IPHLPAPI IP_ADDRESS_STRING - /// - public class IP_ADDRESS_STRING : SelfMarshalledStruct - { - #region Contructors - public IP_ADDRESS_STRING() - : base(16) - { - } - public IP_ADDRESS_STRING(byte[] data, int offset) - : base(data, offset) - { - } - public IP_ADDRESS_STRING(IntPtr pData, int offset) - : base(16) - { - Marshal.Copy(new IntPtr(pData.ToInt32() + offset), data, 0, 16); - } - #endregion - - #region Properties - public string String - { - get { return GetStringAscii(0, 15); } - set { Set(typeof(string), 0, value); } - } - public System.Net.IPAddress ipAddress{ - get { return System.Net.IPAddress.Parse(this.String); } - } - #endregion - } -} diff --git a/netstatCF2/IPHlpAPI32.cs b/netstatCF2/IPHlpAPI32.cs deleted file mode 100644 index be10a2d..0000000 --- a/netstatCF2/IPHlpAPI32.cs +++ /dev/null @@ -1,880 +0,0 @@ -using System; -using System.Net; -using System.Collections; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Text; - -using System.Collections.Generic; - - -namespace IpHlpApidotnet -{ - #region UDP - - [StructLayout(LayoutKind.Sequential)] - public struct MIB_UDPSTATS - { - public int dwInDatagrams; - public int dwNoPorts; - public int dwInErrors; - public int dwOutDatagrams; - public int dwNumAddrs; - } - - public struct MIB_UDPTABLE - { - public int dwNumEntries; - public MIB_UDPROW[] table; - - } - - public struct MIB_UDPROW - { - public IPEndPoint Local; - } - - public struct MIB_EXUDPTABLE - { - public int dwNumEntries; - public MIB_EXUDPROW[] table; - - } - - public struct MIB_EXUDPROW - { - public IPEndPoint Local; - public int dwProcessId; - public string ProcessName; - } - - #endregion - - #region TCP - - enum RtoAlgorithm - { - MIB_TCP_RTO_OTHER = 1, //Other - MIB_TCP_RTO_CONSTANT = 2, //Constant Time-out - MIB_TCP_RTO_RSRE = 3, //MIL-STD-1778 Appendix B - MIB_TCP_RTO_VANJ = 4, //Van Jacobson's Algorithm - } - - [StructLayout(LayoutKind.Sequential)] - public struct MIB_TCPSTATS - { - public int dwRtoAlgorithm; - public int dwRtoMin; - public int dwRtoMax; - public int dwMaxConn; - public int dwActiveOpens; - public int dwPassiveOpens; - public int dwAttemptFails; - public int dwEstabResets; - public int dwCurrEstab; - public int dwInSegs; - public int dwOutSegs; - public int dwRetransSegs; - public int dwInErrs; - public int dwOutRsts; - public int dwNumConns; - } - - - public struct MIB_TCPTABLE - { - public int dwNumEntries; - public MIB_TCPROW[] table; - - } - - public struct MIB_TCPROW - { - public string StrgState; - public int iState; - public IPEndPoint Local; - public IPEndPoint Remote; - } -#if !PocketPC - public struct MIB_EXTCPTABLE - { - public int dwNumEntries; - public MIB_EXTCPROW[] table; - - } - - public struct MIB_EXTCPROW - { - public string StrgState; - public int iState; - public IPEndPoint Local; - public IPEndPoint Remote; - public int dwProcessId; - public string ProcessName; - } -#endif - - - - #endregion - - - public class IPHlpAPI32Wrapper - { - public const byte NO_ERROR = 0; - public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; - public const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; - public const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; - public int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS; - - - - [DllImport("iphlpapi.dll", SetLastError = true)] - public extern static int GetUdpStatistics(ref MIB_UDPSTATS pStats); - - [DllImport("iphlpapi.dll", SetLastError = true)] - public static extern int GetUdpTable(byte[] UcpTable, out int pdwSize, bool bOrder); - - [DllImport("iphlpapi.dll", SetLastError = true)] - public extern static int GetTcpStatistics(ref MIB_TCPSTATS pStats); - - [DllImport("iphlpapi.dll", SetLastError = true)] - public static extern int GetTcpTable(byte[] pTcpTable, out int pdwSize, bool bOrder); - - [DllImport("iphlpapi.dll", SetLastError = true)] - public static extern int GetIpForwardTable(IntPtr pIpForwardTable, ref int pdwSize, bool bOrder); - [DllImport("iphlpapi.dll", SetLastError = true)] - public static extern int GetIpForwardTable(byte[] pIpForwardTable, ref int pdwSize, bool bOrder); - const int ANY_SIZE = 1; - [StructLayout(LayoutKind.Sequential)] - public struct MIB_IPFORWARDTABLE - { - public UInt32 dwNumEntries; - public MIB_IPFORWARDROW[] table /*[ANY_SIZE]*/; - } - [StructLayout(LayoutKind.Sequential)] - public struct MIB_IPFORWARDROW - { - /// - /// The destination IPv4 address of the route. An entry with a IPv4 address of 0.0.0.0 is considered a default route. - /// - public UInt32 dwForwardDest; - /// - /// The IPv4 subnet mask to use with the destination IPv4 address before being compared to the value in the dwForwardDest member. - /// - public UInt32 dwForwardMask; - /// - /// The set of conditions that would cause the selection of a multi-path route (the set of next hops for a given destination). This member is typically in IP TOS format. This encoding of this member is described in RFC 1354. - /// - public UInt32 dwForwardPolicy; - /// - /// For remote routes, the IPv4 address of the next system en route. Otherwise, this member should be an IPv4 address of 0.0.0.0. - /// - public UInt32 dwForwardNextHop; - /// - /// The index of the local interface through which the next hop of this route should be reached. - /// - public UInt32 dwForwardIfIndex; - /// - /// The route type as described in RFC 1354. For more information, see http://www.ietf.org/rfc/rfc1354.txt. - /// This member can be one of the values defined in the Iprtmib.h header file. - /// - public UInt32 dwForwardType; - /* - MIB_IPROUTE_TYPE_OTHER 1 Some other type not specified in RFC 1354. - MIB_IPROUTE_TYPE_INVALID 2 An invalid route. This value can result from a route added by an ICMP redirect. - MIB_IPROUTE_TYPE_DIRECT 3 A local route where the next hop is the final destination (a local interface). - MIB_IPROUTE_TYPE_INDIRECT 4 The remote route where the next hop is not the final destination (a remote destination). - */ - /// - /// The protocol or routing mechanism that generated the route as described in RFC 1354. For more information, see http://www.ietf.org/rfc/rfc1354.txt. See Protocol Identifiers for a list of possible protocol identifiers used by routing protocols. - /// - public UInt32 dwForwardProto; - /// - /// The number of seconds since the route was added or modified in the network routing table. - /// - public UInt32 dwForwardAge; - /// - /// The autonomous system number of the next hop. When this member is unknown or not relevant to the protocol or routing mechanism specified in dwForwardProto, this value should be set to zero. This value is documented in RFC 1354 - /// - public UInt32 dwForwardNextHopAS; - /// - /// The primary routing metric value for this route. The semantics of this metric are determined by the routing protocol specified in the dwForwardProto member. If this metric is not used, its value should be set to -1. This value is documented in in RFC 1354. For more information, see http://www.ietf.org/rfc/rfc1354.txt - /// - public UInt32 dwForwardMetric1; - /// - /// An alternate routing metric value for this route. The semantics of this metric are determined by the routing protocol specified in the dwForwardProto member. If this metric is not used, its value should be set to -1. This value is documented in RFC 1354. For more information, see http://www.ietf.org/rfc/rfc1354.txt - /// - public UInt32 dwForwardMetric2; - /// - /// An alternate routing metric value for this route. The semantics of this metric are determined by the routing protocol specified in the dwForwardProto member. If this metric is not used, its value should be set to -1. This value is documented in RFC 1354. For more information, see http://www.ietf.org/rfc/rfc1354.txt - /// - public UInt32 dwForwardMetric3; - /// - /// An alternate routing metric value for this route. The semantics of this metric are determined by the routing protocol specified in the dwForwardProto member. If this metric is not used, its value should be set to -1. This value is documented in RFC 1354. For more information, see http://www.ietf.org/rfc/rfc1354.txt - /// - public UInt32 dwForwardMetric4; - /// - /// An alternate routing metric value for this route. The semantics of this metric are determined by the routing protocol specified in the dwForwardProto member. If this metric is not used, its value should be set to -1. This value is documented in RFC 1354. For more information, see http://www.ietf.org/rfc/rfc1354.txt - /// - public UInt32 dwForwardMetric5; - } - -#if !PocketPC - [DllImport("iphlpapi.dll",SetLastError=true)] - public extern static int AllocateAndGetTcpExTableFromStack(ref IntPtr pTable, bool bOrder, IntPtr heap ,int zero,int flags ); - - [DllImport("iphlpapi.dll",SetLastError=true)] - public extern static int AllocateAndGetUdpExTableFromStack(ref IntPtr pTable, bool bOrder, IntPtr heap,int zero,int flags ); -#endif - [DllImport("coredll.dll", SetLastError = true)] - public static extern IntPtr GetProcessHeap(); - - [DllImport("coredll.dll", SetLastError = true)] - private static extern int FormatMessage(int flags, IntPtr source, int messageId, - int languageId, StringBuilder buffer, int size, IntPtr arguments); - - - public static string GetAPIErrorMessageDescription(int ApiErrNumber) - { - System.Text.StringBuilder sError = new System.Text.StringBuilder(512); - int lErrorMessageLength; - lErrorMessageLength = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, (IntPtr)0, ApiErrNumber, 0, sError, sError.Capacity, (IntPtr)0); - - if (lErrorMessageLength > 0) - { - string strgError = sError.ToString(); - strgError = strgError.Substring(0, strgError.Length - 2); - return strgError + " (" + ApiErrNumber.ToString() + ")"; - } - return "none"; - - } - } - - public class IPHelper - { - private const int NO_ERROR = 0; - private const int MIB_TCP_STATE_CLOSED = 1; - private const int MIB_TCP_STATE_LISTEN = 2; - private const int MIB_TCP_STATE_SYN_SENT = 3; - private const int MIB_TCP_STATE_SYN_RCVD = 4; - private const int MIB_TCP_STATE_ESTAB = 5; - private const int MIB_TCP_STATE_FIN_WAIT1 = 6; - private const int MIB_TCP_STATE_FIN_WAIT2 = 7; - private const int MIB_TCP_STATE_CLOSE_WAIT = 8; - private const int MIB_TCP_STATE_CLOSING = 9; - private const int MIB_TCP_STATE_LAST_ACK = 10; - private const int MIB_TCP_STATE_TIME_WAIT = 11; - private const int MIB_TCP_STATE_DELETE_TCB = 12; - - private const int ERROR_INSUFFICIENT_BUFFER = 122; - - /* - * Tcp Struct - * */ - public IpHlpApidotnet.MIB_TCPTABLE TcpConnexion; - public IpHlpApidotnet.MIB_TCPSTATS TcpStats; -#if !PocketPC - public IpHlpApidotnet.MIB_EXTCPTABLE TcpExConnexions; -#endif - - /* - * Udp Struct - * */ - public IpHlpApidotnet.MIB_UDPSTATS UdpStats; - public IpHlpApidotnet.MIB_UDPTABLE UdpConnexion; -#if !PocketPC - public IpHlpApidotnet.MIB_EXUDPTABLE UdpExConnexion; -#endif - - public static string[] RtoAlgorithmStr = new string[] { - "none", //0 - "Other", //1 - "Constant Time-out", - "MIL-STD-1778 Appendix B", - "Van Jacobson's Algorithm", - }; - - public IPHelper() - { - _routeEntry = new System.Collections.Generic.List(); - } - - #region ROUTING - //helper - class adapterIDs - { - AdapterInfo.AdaptersInfo aInfo = new AdapterInfo.AdaptersInfo(); - List ipList= new List(); - public class ID2IP - { - public int id; - public IPAddress ip; - public ID2IP(int i, IPAddress p) - { - this.id = i; - this.ip = p; - } - } - public adapterIDs() - { - foreach (AdapterInfo.IP_ADAPTER_INFO info in aInfo._adapterList) - { - ipList.Add(new ID2IP((int)info.Index, info.CurrentIpAddress.IpAddress.ipAddress)); - } - } - public string getIPstrForID(int id) - { - string s = id.ToString("000"); - foreach (ID2IP idip in this.ipList) - { - if (idip.id == id) - { - s = idip.ip.ToString(); - break; - } - } - return s; - } - } - - AdapterInfo.AdaptersInfo aInfo = new AdapterInfo.AdaptersInfo(); - - public System.Collections.Generic.List _routeEntry; - public void getRoutingTable() - { - - _routeEntry.Clear(); - - IPHlpAPI32Wrapper.MIB_IPFORWARDTABLE fTable = new IPHlpAPI32Wrapper.MIB_IPFORWARDTABLE(); - fTable.table = new IPHlpAPI32Wrapper.MIB_IPFORWARDROW[1]; - - int MIB_SIZE = Marshal.SizeOf(new IPHlpAPI32Wrapper.MIB_IPFORWARDROW()) + Marshal.SizeOf(new UInt32()); - // Initialize unmanged memory to hold one struct entry. - IntPtr pTable = Marshal.AllocHGlobal(MIB_SIZE); - try - { - - // Copy the struct to unmanaged memory. - // Marshal.StructureToPtr(fTable, pTable, false); //StructureToPtr does not like array inside struct - byte[] buffer = new byte[MIB_SIZE]; - - int dwSize = MIB_SIZE; - int iRes = IPHlpAPI32Wrapper.GetIpForwardTable(buffer, ref dwSize, true); - if (iRes == ERROR_INSUFFICIENT_BUFFER) - { - //need to get dwSize memory allocated - buffer = new byte[dwSize]; - iRes = IPHlpAPI32Wrapper.GetIpForwardTable(buffer, ref dwSize, true); - //now we have a list of structs - - //see also http://www.pcreview.co.uk/forums/changing-route-table-iphlpapi-dll-and-p-invoke-t2891061.html - //now we have the buffer filled, create an empty entry - IPHlpAPI32Wrapper.MIB_IPFORWARDTABLE ipForwardTable = new IPHlpAPI32Wrapper.MIB_IPFORWARDTABLE(); - - // ...and fill the MIB_IPFORWARDTABLE with the bytes from the buffer - int nOffset = 0; - // number of rows in the table - ipForwardTable.dwNumEntries = Convert.ToUInt32(buffer[nOffset]); - nOffset += 4; - - ipForwardTable.table = new IPHlpAPI32Wrapper.MIB_IPFORWARDROW[ipForwardTable.dwNumEntries]; - - for (int i = 0; i < ipForwardTable.dwNumEntries; i++) - { - //dwForwardDest - //((MIB_IPFORWARDROW)(ipForwardTable.table[i])).dwForwardDest = Convert.ToUInt32(buffer[nOffset]); - ((ipForwardTable.table[i])).dwForwardDest = toIPInt(buffer, nOffset); - nOffset += 4; - - //dwForwardMask - ((ipForwardTable.table[i])).dwForwardMask = toIPInt(buffer, nOffset); - nOffset += 4; - //dwForwardPolicy - ((ipForwardTable.table[i])).dwForwardPolicy = Convert.ToUInt32(buffer[nOffset]); - nOffset += 4; - //dwForwardNextHop - ((ipForwardTable.table[i])).dwForwardNextHop = toIPInt(buffer, nOffset); - nOffset += 4; - //dwForwardIfIndex - ((ipForwardTable.table[i])).dwForwardIfIndex = Convert.ToUInt32(buffer[nOffset]); - nOffset += 8; //8 since we're skipping the next item (dwForwardType) - //dwForwardProto - ((ipForwardTable.table[i])).dwForwardProto = Convert.ToUInt32(buffer[nOffset]); - nOffset += 4; - - _routeEntry.Add(ipForwardTable.table[i]); - } - - } - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message); - } - finally - { - Marshal.FreeHGlobal(pTable); - } - } - - private UInt32 toIPInt(byte[] bytes, int startOffset) - { - uint ipInt = 0; - for (int i = 3; i >= 0; i--) - { - ipInt += (uint)(bytes[startOffset + i] << (8 * i)); - } - return Convert.ToUInt32(ipInt); - } - - public string dumpRouteEntry(IPHlpAPI32Wrapper.MIB_IPFORWARDROW row){ - adapterIDs idList = new adapterIDs(); - - //Active Routes: - // 1 2 3 4 5 6 7 8 - //1234567890123456789012345678901234567890123456789012345678901234567890123456789012 - //Network Destination Netmask Gateway Interface Metric - string s = ""; - - s += (new IPAddress(row.dwForwardDest)).ToString().PadRight(27); - s += (new IPAddress(row.dwForwardMask)).ToString().PadRight(17); - s += (new IPAddress(row.dwForwardNextHop)).ToString().PadRight(17); - - //interface - //s += "".PadLeft(6) + row.dwForwardIfIndex.ToString("000") + " "; - s += "".PadLeft(2) + idList.getIPstrForID((int)row.dwForwardIfIndex).PadLeft(17) ; - //metric - s += row.dwForwardMetric1.ToString().PadLeft(5); - - return s; - } - #endregion - - #region Tcp Function - - public void GetTcpStats() - { - TcpStats = new MIB_TCPSTATS(); - IPHlpAPI32Wrapper.GetTcpStatistics(ref TcpStats); - } - -#if !PocketPC - public void GetExTcpConnexions() - { - - // the size of the MIB_EXTCPROW struct = 6*DWORD - int rowsize = 24; - int BufferSize = 100000; - // allocate a dumb memory space in order to retrieve nb of connexion - IntPtr lpTable = Marshal.AllocHGlobal(BufferSize); - //getting infos - int res = IPHlpAPI32Wrapper.AllocateAndGetTcpExTableFromStack(ref lpTable, true, IPHlpAPI32Wrapper.GetProcessHeap(), 0, 2); - if (res != NO_ERROR) - { - Debug.WriteLine("Erreur : " + IPHlpAPI32Wrapper.GetAPIErrorMessageDescription(res) + " " + res); - return; // Error. You should handle it - } - int CurrentIndex = 0; - //get the number of entries in the table - int NumEntries = (int)Marshal.ReadIntPtr(lpTable); - lpTable = IntPtr.Zero; - // free allocated space in memory - Marshal.FreeHGlobal(lpTable); - - /////////////////// - // calculate the real buffer size nb of entrie * size of the struct for each entrie(24) + the dwNumEntries - BufferSize = (NumEntries * rowsize) + 4; - // make the struct to hold the resullts - TcpExConnexions = new IpHlpApidotnet.MIB_EXTCPTABLE(); - // Allocate memory - lpTable = Marshal.AllocHGlobal(BufferSize); - res = IPHlpAPI32Wrapper.AllocateAndGetTcpExTableFromStack(ref lpTable, true, IPHlpAPI32Wrapper.GetProcessHeap(), 0, 2); - if (res != NO_ERROR) - { - Debug.WriteLine("Erreur : " + IPHlpAPI32Wrapper.GetAPIErrorMessageDescription(res) + " " + res); - return; // Error. You should handle it - } - // New pointer of iterating throught the data - IntPtr current = lpTable; - CurrentIndex = 0; - // get the (again) the number of entries - NumEntries = (int)Marshal.ReadIntPtr(current); - TcpExConnexions.dwNumEntries = NumEntries; - // Make the array of entries - TcpExConnexions.table = new MIB_EXTCPROW[NumEntries]; - // iterate the pointer of 4 (the size of the DWORD dwNumEntries) - CurrentIndex += 4; - current = (IntPtr)((int)current + CurrentIndex); - // for each entries - for (int i = 0; i < NumEntries; i++) - { - - // The state of the connexion (in string) - TcpExConnexions.table[i].StrgState = this.convert_state((int)Marshal.ReadIntPtr(current)); - // The state of the connexion (in ID) - TcpExConnexions.table[i].iState = (int)Marshal.ReadIntPtr(current); - // iterate the pointer of 4 - current = (IntPtr)((int)current + 4); - // get the local address of the connexion - UInt32 localAddr = (UInt32)Marshal.ReadIntPtr(current); - // iterate the pointer of 4 - current = (IntPtr)((int)current + 4); - // get the local port of the connexion - UInt32 localPort = (UInt32)Marshal.ReadIntPtr(current); - // iterate the pointer of 4 - current = (IntPtr)((int)current + 4); - // Store the local endpoint in the struct and convertthe port in decimal (ie convert_Port()) - TcpExConnexions.table[i].Local = new IPEndPoint(localAddr, (int)convert_Port(localPort)); - // get the remote address of the connexion - UInt32 RemoteAddr = (UInt32)Marshal.ReadIntPtr(current); - // iterate the pointer of 4 - current = (IntPtr)((int)current + 4); - UInt32 RemotePort = 0; - // if the remote address = 0 (0.0.0.0) the remote port is always 0 - // else get the remote port - if (RemoteAddr != 0) - { - RemotePort = (UInt32)Marshal.ReadIntPtr(current); - RemotePort = convert_Port(RemotePort); - } - current = (IntPtr)((int)current + 4); - // store the remote endpoint in the struct and convertthe port in decimal (ie convert_Port()) - TcpExConnexions.table[i].Remote = new IPEndPoint(RemoteAddr, (int)RemotePort); - // store the process ID - TcpExConnexions.table[i].dwProcessId = (int)Marshal.ReadIntPtr(current); - // Store and get the process name in the struct - TcpExConnexions.table[i].ProcessName = this.get_process_name(TcpExConnexions.table[i].dwProcessId); - current = (IntPtr)((int)current + 4); - - } - // free the buffer - Marshal.FreeHGlobal(lpTable); - // re init the pointer - current = IntPtr.Zero; - } -#endif //PocketPC - - public void GetTcpConnexions() - { - byte[] buffer = new byte[20000]; // Start with 20.000 bytes left for information about tcp table - int pdwSize = 20000; - int res = IPHlpAPI32Wrapper.GetTcpTable(buffer, out pdwSize, true); - if (res != NO_ERROR) - { - buffer = new byte[pdwSize]; - res = IPHlpAPI32Wrapper.GetTcpTable(buffer, out pdwSize, true); - if (res != 0) - return; // Error. You should handle it - } - - TcpConnexion = new IpHlpApidotnet.MIB_TCPTABLE(); - - int nOffset = 0; - // number of entry in the - TcpConnexion.dwNumEntries = Convert.ToInt32(buffer[nOffset]); - nOffset += 4; - TcpConnexion.table = new MIB_TCPROW[TcpConnexion.dwNumEntries]; - - for (int i = 0; i < TcpConnexion.dwNumEntries; i++) - { - // state - int st = Convert.ToInt32(buffer[nOffset]); - // state in string - //((MIB_TCPROW) - (TcpConnexion.table[i]).StrgState = convert_state(st); - // state by ID - //((MIB_TCPROW) - (TcpConnexion.table[i]).iState = st; - nOffset += 4; - // local address - string LocalAdrr = buffer[nOffset].ToString() + "." + buffer[nOffset + 1].ToString() + "." + buffer[nOffset + 2].ToString() + "." + buffer[nOffset + 3].ToString(); - nOffset += 4; - //local port in decimal - int LocalPort = (((int)buffer[nOffset]) << 8) + (((int)buffer[nOffset + 1])) + - (((int)buffer[nOffset + 2]) << 24) + (((int)buffer[nOffset + 3]) << 16); - - nOffset += 4; - // store the remote endpoint - //((MIB_TCPROW)( - (TcpConnexion.table[i]).Local = new IPEndPoint(IPAddress.Parse(LocalAdrr), LocalPort); - - // remote address - string RemoteAdrr = buffer[nOffset].ToString() + "." + buffer[nOffset + 1].ToString() + "." + buffer[nOffset + 2].ToString() + "." + buffer[nOffset + 3].ToString(); - nOffset += 4; - // if the remote address = 0 (0.0.0.0) the remote port is always 0 - // else get the remote port in decimal - int RemotePort; - // - if (RemoteAdrr == "0.0.0.0") - { - RemotePort = 0; - } - else - { - RemotePort = (((int)buffer[nOffset]) << 8) + (((int)buffer[nOffset + 1])) + - (((int)buffer[nOffset + 2]) << 24) + (((int)buffer[nOffset + 3]) << 16); - } - nOffset += 4; - //((MIB_TCPROW) - (TcpConnexion.table[i]).Remote = new IPEndPoint(IPAddress.Parse(RemoteAdrr), RemotePort); - } - } - - - #endregion - - #region Udp Functions - - public void GetUdpStats() - { - - UdpStats = new MIB_UDPSTATS(); - IPHlpAPI32Wrapper.GetUdpStatistics(ref UdpStats); - } - - - public void GetUdpConnexions() - { - byte[] buffer = new byte[20000]; // Start with 20.000 bytes left for information about tcp table - int pdwSize = 20000; - int res = IPHlpAPI32Wrapper.GetUdpTable(buffer, out pdwSize, true); - if (res != NO_ERROR) - { - buffer = new byte[pdwSize]; - res = IPHlpAPI32Wrapper.GetUdpTable(buffer, out pdwSize, true); - if (res != 0) - return; // Error. You should handle it - } - - UdpConnexion = new IpHlpApidotnet.MIB_UDPTABLE(); - - int nOffset = 0; - // number of entry in the - UdpConnexion.dwNumEntries = Convert.ToInt32(buffer[nOffset]); - nOffset += 4; - UdpConnexion.table = new MIB_UDPROW[UdpConnexion.dwNumEntries]; - for (int i = 0; i < UdpConnexion.dwNumEntries; i++) - { - string LocalAdrr = buffer[nOffset].ToString() + "." + buffer[nOffset + 1].ToString() + "." + buffer[nOffset + 2].ToString() + "." + buffer[nOffset + 3].ToString(); - nOffset += 4; - - int LocalPort = (((int)buffer[nOffset]) << 8) + (((int)buffer[nOffset + 1])) + - (((int)buffer[nOffset + 2]) << 24) + (((int)buffer[nOffset + 3]) << 16); - nOffset += 4; - //((MIB_UDPROW) - (UdpConnexion.table[i]).Local = new IPEndPoint(IPAddress.Parse(LocalAdrr), LocalPort); - } - } - -#if !PocketPC - public void GetExUdpConnexions() - { - - // the size of the MIB_EXTCPROW struct = 4*DWORD - int rowsize = 12; - int BufferSize = 100000; - // allocate a dumb memory space in order to retrieve nb of connexion - IntPtr lpTable = Marshal.AllocHGlobal(BufferSize); - //getting infos - int res = IPHlpAPI32Wrapper.AllocateAndGetUdpExTableFromStack(ref lpTable, true, IPHlpAPI32Wrapper.GetProcessHeap(), 0, 2); - if (res != NO_ERROR) - { - Debug.WriteLine("Erreur : " + IPHlpAPI32Wrapper.GetAPIErrorMessageDescription(res) + " " + res); - return; // Error. You should handle it - } - int CurrentIndex = 0; - //get the number of entries in the table - int NumEntries = (int)Marshal.ReadIntPtr(lpTable); - lpTable = IntPtr.Zero; - // free allocated space in memory - Marshal.FreeHGlobal(lpTable); - - /////////////////// - // calculate the real buffer size nb of entrie * size of the struct for each entrie(24) + the dwNumEntries - BufferSize = (NumEntries * rowsize) + 4; - // make the struct to hold the resullts - UdpExConnexion = new IpHlpApidotnet.MIB_EXUDPTABLE(); - // Allocate memory - lpTable = Marshal.AllocHGlobal(BufferSize); - res = IPHlpAPI32Wrapper.AllocateAndGetUdpExTableFromStack(ref lpTable, true, IPHlpAPI32Wrapper.GetProcessHeap(), 0, 2); - if (res != NO_ERROR) - { - Debug.WriteLine("Erreur : " + IPHlpAPI32Wrapper.GetAPIErrorMessageDescription(res) + " " + res); - return; // Error. You should handle it - } - // New pointer of iterating throught the data - IntPtr current = lpTable; - CurrentIndex = 0; - // get the (again) the number of entries - NumEntries = (int)Marshal.ReadIntPtr(current); - UdpExConnexion.dwNumEntries = NumEntries; - // Make the array of entries - UdpExConnexion.table = new MIB_EXUDPROW[NumEntries]; - // iterate the pointer of 4 (the size of the DWORD dwNumEntries) - CurrentIndex += 4; - current = (IntPtr)((int)current + CurrentIndex); - // for each entries - for (int i = 0; i < NumEntries; i++) - { - // get the local address of the connexion - UInt32 localAddr = (UInt32)Marshal.ReadIntPtr(current); - // iterate the pointer of 4 - current = (IntPtr)((int)current + 4); - // get the local port of the connexion - UInt32 localPort = (UInt32)Marshal.ReadIntPtr(current); - // iterate the pointer of 4 - current = (IntPtr)((int)current + 4); - // Store the local endpoint in the struct and convertthe port in decimal (ie convert_Port()) - UdpExConnexion.table[i].Local = new IPEndPoint(localAddr, convert_Port(localPort)); - // store the process ID - UdpExConnexion.table[i].dwProcessId = (int)Marshal.ReadIntPtr(current); - // Store and get the process name in the struct - UdpExConnexion.table[i].ProcessName = this.get_process_name(UdpExConnexion.table[i].dwProcessId); - current = (IntPtr)((int)current + 4); - - } - // free the buffer - Marshal.FreeHGlobal(lpTable); - // re init the pointer - current = IntPtr.Zero; - } -#endif //PocketPC - - #endregion - - #region helper fct - - public static string dump_MIB_TCPROW(MIB_TCPROW mib) - { - string s = "n/a"; - s = dumpEndPoint(mib.Local) + " " + dumpEndPoint(mib.Remote) + " " + mib.StrgState; - return s; - } - - public static string dump_MIB_UDPROW(MIB_UDPROW mib) - { - string s = "n/a"; - s = dumpEndPoint(mib.Local); - return s; - } - - public static string dump_MIB_TCPSTATS(MIB_TCPSTATS mib) - { - string s = ""; - //retransmission timeout (RTO) - s += "Retransmission timeout (min/max): ".PadLeft(34) + IPHelper.RtoAlgorithmStr[mib.dwRtoAlgorithm]; - s += ": " + mib.dwRtoMin.ToString() + "/" + mib.dwRtoMax.ToString(); - - //max connections - s += "\r\n" + "max connnections: ".PadLeft(34) + mib.dwMaxConn.ToString(); - - //active open connection - s += "\r\n" + "active open: ".PadLeft(34) + mib.dwActiveOpens.ToString(); - //passive open connection - s += "\r\n" + "passive open: ".PadLeft(34) + mib.dwPassiveOpens.ToString(); - - //failed attempts - s += "\r\n" + "failed attempts: ".PadLeft(34) + mib.dwAttemptFails.ToString(); - - //established resets - s += "\r\n" + "established resets: ".PadLeft(34) + mib.dwEstabResets.ToString(); - - //current established - s += "\r\n" + "current established: ".PadLeft(34) + mib.dwCurrEstab.ToString(); - - //data segs in - s += "\r\n" + "segments in: ".PadLeft(34) + mib.dwInSegs.ToString(); - - //data segs out - s += "\r\n" + "segments out: ".PadLeft(34) + mib.dwOutSegs.ToString(); - - //data segs re-transmitted - s += "\r\n" + "retransmitted segments: ".PadLeft(34) + mib.dwRetransSegs.ToString(); - - //errors received - s += "\r\n" + "in errors: ".PadLeft(34) + mib.dwInErrs.ToString(); - - //out resets - s += "\r\n" + "out resets: ".PadLeft(34) + mib.dwOutRsts.ToString(); - - //num connections - s += "\r\n" + "num connections: ".PadLeft(34) + mib.dwNumConns.ToString(); - - return s; - } - - public static string dump_MIB_UDPSTATS(MIB_UDPSTATS mib) - { - string s = ""; - // - s += "in datagrams: ".PadLeft(34) + mib.dwInDatagrams.ToString(); - s += "\r\n" + "in errors: ".PadLeft(34) + mib.dwInErrors.ToString(); - s += "\r\n" + "num ports: ".PadLeft(34) + mib.dwNoPorts.ToString(); - s += "\r\n" + "num addresses: ".PadLeft(34) + mib.dwNumAddrs.ToString(); - s += "\r\n" + "out datagrams: ".PadLeft(34) + mib.dwOutDatagrams.ToString(); - return s; - } - - static string dumpEndPoint(IPEndPoint addr) - { - string s = ""; - s = addr.Address.ToString().PadLeft(15) + ":" + addr.Port.ToString().PadLeft(6); - return s; - } - - private UInt16 convert_Port(UInt32 dwPort) - { - byte[] b = new Byte[2]; - // high weight byte - b[0] = byte.Parse((dwPort >> 8).ToString()); - // low weight byte - b[1] = byte.Parse((dwPort & 0xFF).ToString()); - return BitConverter.ToUInt16(b, 0); - } - - - private string convert_state(int state) - { - string strg_state = ""; - switch (state) - { - case MIB_TCP_STATE_CLOSED: strg_state = "CLOSED"; break; - case MIB_TCP_STATE_LISTEN: strg_state = "LISTEN"; break; - case MIB_TCP_STATE_SYN_SENT: strg_state = "SYN_SENT"; break; - case MIB_TCP_STATE_SYN_RCVD: strg_state = "SYN_RCVD"; break; - case MIB_TCP_STATE_ESTAB: strg_state = "ESTAB"; break; - case MIB_TCP_STATE_FIN_WAIT1: strg_state = "FIN_WAIT1"; break; - case MIB_TCP_STATE_FIN_WAIT2: strg_state = "FIN_WAIT2"; break; - case MIB_TCP_STATE_CLOSE_WAIT: strg_state = "CLOSE_WAIT"; break; - case MIB_TCP_STATE_CLOSING: strg_state = "CLOSING"; break; - case MIB_TCP_STATE_LAST_ACK: strg_state = "LAST_ACK"; break; - case MIB_TCP_STATE_TIME_WAIT: strg_state = "TIME_WAIT"; break; - case MIB_TCP_STATE_DELETE_TCB: strg_state = "DELETE_TCB"; break; - } - return strg_state; - } - - - private string get_process_name(int processID) - { - //could be an error here if the process die before we can get his name - try - { - Process p = Process.GetProcessById((int)processID); - return p.StartInfo.FileName;// ProcessName; - } - catch (Exception ex) - { - Debug.WriteLine(ex.Message); - return "unknown"; - } - - } - #endregion - } -} - diff --git a/netstatCF2/Program.cs b/netstatCF2/Program.cs deleted file mode 100644 index 2c88836..0000000 --- a/netstatCF2/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace netstatCF2 -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new frmNetStat()); - } - } -} \ No newline at end of file diff --git a/netstatCF2/Properties/AssemblyInfo.cs b/netstatCF2/Properties/AssemblyInfo.cs deleted file mode 100644 index d32ea66..0000000 --- a/netstatCF2/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("netstatCF2")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("netstatCF2")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2013")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9fb185b6-523d-4f42-9c44-e28b667c2061")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/netstatCF2/Properties/Resources.Designer.cs b/netstatCF2/Properties/Resources.Designer.cs deleted file mode 100644 index 35fd36d..0000000 --- a/netstatCF2/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5466 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace netstatCF2.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("netstatCF2.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/netstatCF2/Properties/Resources.resx b/netstatCF2/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/netstatCF2/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/netstatCF2/SelfMarshalledStruct.cs b/netstatCF2/SelfMarshalledStruct.cs deleted file mode 100644 index 12f5fec..0000000 --- a/netstatCF2/SelfMarshalledStruct.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Text; - -namespace AdapterInfo -{ - /// - /// This class implements base functionality for a bytearray-based structure - /// - public class SelfMarshalledStruct - { - #region Internal Data - protected byte[] data; - protected int baseOffset; - #endregion - - public SelfMarshalledStruct(int size) - { - data = new byte[size]; - baseOffset = 0; - } - - public SelfMarshalledStruct(byte[] data, int offset) - { - this.data = data; - baseOffset = offset; - } - - public Char GetChar( int offset ) - { - return BitConverter.ToChar(data, baseOffset + offset); - } - - public void SetChar( int offset, Char val ) - { - Buffer.BlockCopy(BitConverter.GetBytes( val ), 0, data, baseOffset + offset, 2 ); - } - - public Int32 GetInt32( int offset ) - { - return BitConverter.ToInt32(data, baseOffset + offset); - } - - public void SetInt32( int offset, Int32 val ) - { - Buffer.BlockCopy(BitConverter.GetBytes( val ), 0, data, baseOffset + offset, 4 ); - } - - public UInt32 GetUInt32( int offset ) - { - return BitConverter.ToUInt32(data, baseOffset + offset); - } - - public void SetUInt32( int offset, UInt32 val ) - { - Buffer.BlockCopy(BitConverter.GetBytes( val ), 0, data, baseOffset + offset, 4 ); - } - - public Int16 GetInt16( int offset ) - { - return BitConverter.ToInt16(data, baseOffset + offset); - } - - public void SetInt16( int offset, Int16 val ) - { - Buffer.BlockCopy(BitConverter.GetBytes( val ), 0, data, baseOffset + offset, 2 ); - } - - public UInt16 GetUInt16( int offset ) - { - return BitConverter.ToUInt16(data, baseOffset + offset); - } - - public void SetUInt16( int offset, UInt16 val ) - { - Buffer.BlockCopy(BitConverter.GetBytes( val ), 0, data, baseOffset + offset, 2 ); - } - - public string GetStringUni(int offset, int len) - { - string s = Encoding.Unicode.GetString(data, baseOffset + offset, len); - int nullPos = s.IndexOf('\0'); - if ( nullPos > -1 ) - s = s.Substring(0, nullPos); - return s; - } - - public string GetStringAscii(int offset, int len) - { - string s = Encoding.ASCII.GetString(data, baseOffset + offset, len); - int nullPos = s.IndexOf('\0'); - if ( nullPos > -1 ) - s = s.Substring(0, nullPos); - return s; - } - - public byte[] GetSlice(int offset, int len) - { - byte[] ret = new byte[len]; - Buffer.BlockCopy(data, baseOffset + offset, ret, 0, len); - return ret; - } - - public void SetStringUni(string str, int offset, int len) - { - Encoding.Unicode.GetBytes(str, 0, Math.Min(str.Length, len), data, baseOffset + offset); - } - - public byte this[int offset] - { - get { return data[baseOffset + offset]; } - set { data[baseOffset + offset] = value; } - } - - public object Get(Type t, int offset) - { - if ( t.IsPrimitive ) - { - if ( t.BaseType == typeof(Int32) || t == typeof(Int32)) - return GetInt32(baseOffset + offset); - else if ( t.BaseType == typeof(Int16) || t == typeof(Int16) ) - return GetInt16(baseOffset + offset); - else if ( t.BaseType == typeof(UInt32) || t == typeof(UInt32) ) - return GetInt32(baseOffset + offset); - else if ( t.BaseType == typeof(UInt16) || t == typeof(UInt16) ) - return GetUInt16(baseOffset + offset); - else if ( t.BaseType == typeof(byte)|| t == typeof(byte) ) - return this[baseOffset + offset]; - } - return null; - } - - public void Set(Type t, int offset, object Val) - { - if ( t.IsPrimitive ) - { - if ( t.BaseType == typeof(Int32) || t == typeof(Int32)) - SetInt32(baseOffset + offset, (int)Val); - else if ( t.BaseType == typeof(Int16) || t == typeof(Int16) ) - SetInt16(baseOffset + offset, (short)Val); - else if ( t.BaseType == typeof(UInt32) || t == typeof(UInt32) ) - SetUInt32(baseOffset + offset, (UInt32)Val); - else if ( t.BaseType == typeof(UInt16) || t == typeof(UInt16) ) - SetUInt16(baseOffset + offset, (ushort)Val); - else if ( t.BaseType == typeof(byte)|| t == typeof(byte) ) - this[baseOffset + offset] = (byte)Val; - } - else if ( t == typeof(string) ) - { - SetStringUni((string)Val, baseOffset + offset, ((string)Val).Length); - } - } - - public byte[] Data { get { return data; } } - } -} diff --git a/netstatCF2/bin/Debug/netstatCF2.exe b/netstatCF2/bin/Debug/netstatCF2.exe deleted file mode 100644 index 5900a49..0000000 Binary files a/netstatCF2/bin/Debug/netstatCF2.exe and /dev/null differ diff --git a/netstatCF2/doc/netstat.log b/netstatCF2/doc/netstat.log deleted file mode 100644 index e2785bb..0000000 --- a/netstatCF2/doc/netstat.log +++ /dev/null @@ -1,615 +0,0 @@ -5/3/14, 3:38 AM ################# -======= TCP table ======== -local remote - 0.0.0.0: 5655 0.0.0.0: 0 LISTEN - 0.0.0.0: 52241 0.0.0.0: 0 LISTEN - 127.0.0.1: 1029 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1031 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1032 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1033 127.0.0.1: 52241 ESTAB - 127.0.0.1: 8888 0.0.0.0: 0 LISTEN - 127.0.0.1: 52241 127.0.0.1: 1029 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1031 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1032 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1033 ESTAB - 169.254.2.1: 1025 169.254.2.2: 990 ESTAB - 169.254.2.1: 1027 169.254.2.2: 990 ESTAB - 169.254.2.1: 1085 169.254.2.2: 5721 SYN_SENT - 169.254.2.1: 1086 169.254.2.2: 990 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50288 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50289 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50290 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50291 ESTAB -======= UDP table ======== - 0.0.0.0: 68 - 0.0.0.0: 137 - 0.0.0.0: 138 - 0.0.0.0: 9204 - 0.0.0.0: 49111 - 169.254.2.1: 67 -192.168.128.102: 68 -======= TCP statistics ======== -Retransmission timeout (min/max): Van Jacobson's Algorithm: 300/120000 - max connnections: -1 - active open: 111 - passive open: 12 - failed attempts: 99 - established resets: 8 - current established: 15 - segments in: 3365 - segments out: 4566 - retransmitted segments: 301 - in errors: 0 - out resets: 7 - num connections: 19 -======= UDP statistics ======== - in datagrams: 1073 - in errors: 0 - num ports: 433 - num addresses: 7 - out datagrams: 405 -======= Adapter infos ========== -2: RNDISFN1, 169.254.2.1 -3: AR6K_SD1, 192.168.128.102 -======= Route entries ========== -Network Destination Netmask Gateway Interface Metric -0.0.0.0 0.0.0.0 192.168.128.1 192.168.128.102 0 -151.10.0.0 0.0.0.0 255.255.255.255 255 0 -127.0.0.0 255.0.0.0 127.0.0.1 001 0 -176.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.0 255.255.255.0 169.254.2.1 169.254.2.1 0 -166.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.1 255.255.255.255 127.0.0.1 001 0 -166.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.255.255 255.255.255.255 169.254.2.1 169.254.2.1 0 -166.10.0.0 0.0.0.0 255.255.255.255 255 0 -192.168.128.0 255.255.255.0 192.168.128.102 192.168.128.102 0 -151.10.0.0 0.0.0.0 255.255.255.255 255 0 - -5/3/14, 3:38 AM ################# -======= TCP table ======== -local remote - 0.0.0.0: 5655 0.0.0.0: 0 LISTEN - 0.0.0.0: 52241 0.0.0.0: 0 LISTEN - 127.0.0.1: 1029 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1031 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1032 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1033 127.0.0.1: 52241 ESTAB - 127.0.0.1: 8888 0.0.0.0: 0 LISTEN - 127.0.0.1: 52241 127.0.0.1: 1029 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1031 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1032 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1033 ESTAB - 169.254.2.1: 1025 169.254.2.2: 990 ESTAB - 169.254.2.1: 1027 169.254.2.2: 990 ESTAB - 169.254.2.1: 1085 169.254.2.2: 5721 SYN_SENT - 169.254.2.1: 1086 169.254.2.2: 990 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50288 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50289 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50290 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50291 ESTAB -======= UDP table ======== - 0.0.0.0: 68 - 0.0.0.0: 137 - 0.0.0.0: 138 - 0.0.0.0: 9204 - 0.0.0.0: 49111 - 169.254.2.1: 67 -192.168.128.102: 68 -======= TCP statistics ======== -Retransmission timeout (min/max): Van Jacobson's Algorithm: 300/120000 - max connnections: -1 - active open: 111 - passive open: 12 - failed attempts: 99 - established resets: 8 - current established: 15 - segments in: 3365 - segments out: 4566 - retransmitted segments: 301 - in errors: 0 - out resets: 7 - num connections: 19 -======= UDP statistics ======== - in datagrams: 1073 - in errors: 0 - num ports: 433 - num addresses: 7 - out datagrams: 405 -======= Adapter infos ========== -2: RNDISFN1, 169.254.2.1 -3: AR6K_SD1, 192.168.128.102 -======= Route entries ========== -Network Destination Netmask Gateway Interface Metric -0.0.0.0 0.0.0.0 192.168.128.1 192.168.128.102 0 -151.10.0.0 0.0.0.0 255.255.255.255 255 0 -127.0.0.0 255.0.0.0 127.0.0.1 001 0 -176.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.0 255.255.255.0 169.254.2.1 169.254.2.1 0 -166.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.1 255.255.255.255 127.0.0.1 001 0 -166.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.255.255 255.255.255.255 169.254.2.1 169.254.2.1 0 -166.10.0.0 0.0.0.0 255.255.255.255 255 0 -192.168.128.0 255.255.255.0 192.168.128.102 192.168.128.102 0 -151.10.0.0 0.0.0.0 255.255.255.255 255 0 - -5/3/14, 3:39 AM ################# -======= TCP table ======== -local remote - 0.0.0.0: 5655 0.0.0.0: 0 LISTEN - 0.0.0.0: 52241 0.0.0.0: 0 LISTEN - 127.0.0.1: 1029 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1031 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1032 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1033 127.0.0.1: 52241 ESTAB - 127.0.0.1: 8888 0.0.0.0: 0 LISTEN - 127.0.0.1: 52241 127.0.0.1: 1029 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1031 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1032 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1033 ESTAB - 169.254.2.1: 1025 169.254.2.2: 990 ESTAB - 169.254.2.1: 1027 169.254.2.2: 990 ESTAB - 169.254.2.1: 1034 169.254.2.2: 2500 SYN_SENT - 169.254.2.1: 1085 169.254.2.2: 5721 SYN_SENT - 169.254.2.1: 1086 169.254.2.2: 990 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50288 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50289 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50290 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50291 ESTAB -======= UDP table ======== - 0.0.0.0: 68 - 0.0.0.0: 137 - 0.0.0.0: 138 - 0.0.0.0: 9204 - 0.0.0.0: 49111 - 169.254.2.1: 67 -192.168.128.102: 68 -======= TCP statistics ======== -Retransmission timeout (min/max): Van Jacobson's Algorithm: 300/120000 - max connnections: -1 - active open: 112 - passive open: 12 - failed attempts: 99 - established resets: 8 - current established: 15 - segments in: 3370 - segments out: 4572 - retransmitted segments: 302 - in errors: 0 - out resets: 7 - num connections: 20 -======= UDP statistics ======== - in datagrams: 1073 - in errors: 0 - num ports: 433 - num addresses: 7 - out datagrams: 405 -======= Adapter infos ========== -2: RNDISFN1, 169.254.2.1 -3: AR6K_SD1, 192.168.128.102 -======= Route entries ========== -Network Destination Netmask Gateway Interface Metric -0.0.0.0 0.0.0.0 192.168.128.1 192.168.128.102 0 -157.10.0.0 0.0.0.0 255.255.255.255 255 0 -127.0.0.0 255.0.0.0 127.0.0.1 001 0 -182.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.0 255.255.255.0 169.254.2.1 169.254.2.1 0 -172.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.1 255.255.255.255 127.0.0.1 001 0 -172.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.255.255 255.255.255.255 169.254.2.1 169.254.2.1 0 -172.10.0.0 0.0.0.0 255.255.255.255 255 0 -192.168.128.0 255.255.255.0 192.168.128.102 192.168.128.102 0 -157.10.0.0 0.0.0.0 255.255.255.255 255 0 - -5/3/14, 3:39 AM ################# -======= TCP table ======== -local remote - 0.0.0.0: 5655 0.0.0.0: 0 LISTEN - 0.0.0.0: 52241 0.0.0.0: 0 LISTEN - 127.0.0.1: 1029 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1031 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1032 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1033 127.0.0.1: 52241 ESTAB - 127.0.0.1: 8888 0.0.0.0: 0 LISTEN - 127.0.0.1: 52241 127.0.0.1: 1029 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1031 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1032 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1033 ESTAB - 169.254.2.1: 1025 169.254.2.2: 990 ESTAB - 169.254.2.1: 1027 169.254.2.2: 990 ESTAB - 169.254.2.1: 1034 169.254.2.2: 2500 SYN_SENT - 169.254.2.1: 1085 169.254.2.2: 5721 SYN_SENT - 169.254.2.1: 1086 169.254.2.2: 990 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50288 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50289 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50290 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50291 ESTAB -======= UDP table ======== - 0.0.0.0: 68 - 0.0.0.0: 137 - 0.0.0.0: 138 - 0.0.0.0: 9204 - 0.0.0.0: 49111 - 169.254.2.1: 67 -192.168.128.102: 68 -======= TCP statistics ======== -Retransmission timeout (min/max): Van Jacobson's Algorithm: 300/120000 - max connnections: -1 - active open: 112 - passive open: 12 - failed attempts: 99 - established resets: 8 - current established: 15 - segments in: 3373 - segments out: 4576 - retransmitted segments: 303 - in errors: 0 - out resets: 7 - num connections: 20 -======= UDP statistics ======== - in datagrams: 1073 - in errors: 0 - num ports: 433 - num addresses: 7 - out datagrams: 405 -======= Adapter infos ========== -2: RNDISFN1, 169.254.2.1 -3: AR6K_SD1, 192.168.128.102 -======= Route entries ========== -Network Destination Netmask Gateway Interface Metric -0.0.0.0 0.0.0.0 192.168.128.1 192.168.128.102 0 -161.10.0.0 0.0.0.0 255.255.255.255 255 0 -127.0.0.0 255.0.0.0 127.0.0.1 001 0 -186.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.0 255.255.255.0 169.254.2.1 169.254.2.1 0 -176.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.1 255.255.255.255 127.0.0.1 001 0 -176.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.255.255 255.255.255.255 169.254.2.1 169.254.2.1 0 -176.10.0.0 0.0.0.0 255.255.255.255 255 0 -192.168.128.0 255.255.255.0 192.168.128.102 192.168.128.102 0 -161.10.0.0 0.0.0.0 255.255.255.255 255 0 - -5/3/14, 3:39 AM ################# -======= TCP table ======== -local remote - 0.0.0.0: 5655 0.0.0.0: 0 LISTEN - 0.0.0.0: 52241 0.0.0.0: 0 LISTEN - 127.0.0.1: 1029 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1031 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1032 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1033 127.0.0.1: 52241 ESTAB - 127.0.0.1: 8888 0.0.0.0: 0 LISTEN - 127.0.0.1: 52241 127.0.0.1: 1029 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1031 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1032 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1033 ESTAB - 169.254.2.1: 1025 169.254.2.2: 990 ESTAB - 169.254.2.1: 1027 169.254.2.2: 990 ESTAB - 169.254.2.1: 1034 169.254.2.2: 2500 SYN_SENT - 169.254.2.1: 1085 169.254.2.2: 5721 SYN_SENT - 169.254.2.1: 1086 169.254.2.2: 990 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50288 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50289 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50290 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50291 ESTAB -======= UDP table ======== - 0.0.0.0: 68 - 0.0.0.0: 137 - 0.0.0.0: 138 - 0.0.0.0: 9204 - 0.0.0.0: 49111 - 169.254.2.1: 67 -192.168.128.102: 68 -======= TCP statistics ======== -Retransmission timeout (min/max): Van Jacobson's Algorithm: 300/120000 - max connnections: -1 - active open: 112 - passive open: 12 - failed attempts: 99 - established resets: 8 - current established: 15 - segments in: 3378 - segments out: 4580 - retransmitted segments: 303 - in errors: 0 - out resets: 7 - num connections: 20 -======= UDP statistics ======== - in datagrams: 1075 - in errors: 0 - num ports: 434 - num addresses: 7 - out datagrams: 406 -======= Adapter infos ========== -2: RNDISFN1, 169.254.2.1 -3: AR6K_SD1, 192.168.128.102 -======= Route entries ========== -Network Destination Netmask Gateway Interface Metric -0.0.0.0 0.0.0.0 192.168.128.1 192.168.128.102 0 -166.10.0.0 0.0.0.0 255.255.255.255 255 0 -127.0.0.0 255.0.0.0 127.0.0.1 001 0 -191.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.0 255.255.255.0 169.254.2.1 169.254.2.1 0 -181.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.1 255.255.255.255 127.0.0.1 001 0 -181.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.255.255 255.255.255.255 169.254.2.1 169.254.2.1 0 -181.10.0.0 0.0.0.0 255.255.255.255 255 0 -192.168.128.0 255.255.255.0 192.168.128.102 192.168.128.102 0 -166.10.0.0 0.0.0.0 255.255.255.255 255 0 - -5/3/14, 3:39 AM ################# -======= TCP table ======== -local remote - 0.0.0.0: 5655 0.0.0.0: 0 LISTEN - 0.0.0.0: 52241 0.0.0.0: 0 LISTEN - 127.0.0.1: 1029 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1031 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1032 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1033 127.0.0.1: 52241 ESTAB - 127.0.0.1: 8888 0.0.0.0: 0 LISTEN - 127.0.0.1: 52241 127.0.0.1: 1029 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1031 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1032 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1033 ESTAB - 169.254.2.1: 1025 169.254.2.2: 990 ESTAB - 169.254.2.1: 1027 169.254.2.2: 990 ESTAB - 169.254.2.1: 1034 169.254.2.2: 2500 SYN_SENT - 169.254.2.1: 1086 169.254.2.2: 990 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50288 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50289 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50290 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50291 ESTAB -======= UDP table ======== - 0.0.0.0: 68 - 0.0.0.0: 137 - 0.0.0.0: 138 - 0.0.0.0: 9204 - 0.0.0.0: 49111 - 169.254.2.1: 67 -192.168.128.102: 68 -======= TCP statistics ======== -Retransmission timeout (min/max): Van Jacobson's Algorithm: 300/120000 - max connnections: -1 - active open: 112 - passive open: 12 - failed attempts: 100 - established resets: 8 - current established: 15 - segments in: 3381 - segments out: 4583 - retransmitted segments: 303 - in errors: 0 - out resets: 7 - num connections: 19 -======= UDP statistics ======== - in datagrams: 1076 - in errors: 0 - num ports: 435 - num addresses: 7 - out datagrams: 407 -======= Adapter infos ========== -2: RNDISFN1, 169.254.2.1 -3: AR6K_SD1, 192.168.128.102 -======= Route entries ========== -Network Destination Netmask Gateway Interface Metric -0.0.0.0 0.0.0.0 192.168.128.1 192.168.128.102 0 -170.10.0.0 0.0.0.0 255.255.255.255 255 0 -127.0.0.0 255.0.0.0 127.0.0.1 001 0 -195.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.0 255.255.255.0 169.254.2.1 169.254.2.1 0 -185.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.1 255.255.255.255 127.0.0.1 001 0 -185.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.255.255 255.255.255.255 169.254.2.1 169.254.2.1 0 -185.10.0.0 0.0.0.0 255.255.255.255 255 0 -192.168.128.0 255.255.255.0 192.168.128.102 192.168.128.102 0 -170.10.0.0 0.0.0.0 255.255.255.255 255 0 - -5/3/14, 3:39 AM ################# -======= TCP table ======== -local remote - 0.0.0.0: 5655 0.0.0.0: 0 LISTEN - 0.0.0.0: 52241 0.0.0.0: 0 LISTEN - 127.0.0.1: 1029 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1031 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1032 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1033 127.0.0.1: 52241 ESTAB - 127.0.0.1: 8888 0.0.0.0: 0 LISTEN - 127.0.0.1: 52241 127.0.0.1: 1029 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1031 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1032 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1033 ESTAB - 169.254.2.1: 1025 169.254.2.2: 990 ESTAB - 169.254.2.1: 1027 169.254.2.2: 990 ESTAB - 169.254.2.1: 1034 169.254.2.2: 2500 SYN_SENT - 169.254.2.1: 1086 169.254.2.2: 990 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50288 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50289 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50290 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50291 ESTAB -======= UDP table ======== - 0.0.0.0: 68 - 0.0.0.0: 137 - 0.0.0.0: 138 - 0.0.0.0: 9204 - 0.0.0.0: 49111 - 169.254.2.1: 67 -192.168.128.102: 68 -======= TCP statistics ======== -Retransmission timeout (min/max): Van Jacobson's Algorithm: 300/120000 - max connnections: -1 - active open: 112 - passive open: 12 - failed attempts: 100 - established resets: 8 - current established: 15 - segments in: 3385 - segments out: 4588 - retransmitted segments: 304 - in errors: 0 - out resets: 7 - num connections: 19 -======= UDP statistics ======== - in datagrams: 1077 - in errors: 0 - num ports: 436 - num addresses: 7 - out datagrams: 408 -======= Adapter infos ========== -2: RNDISFN1, 169.254.2.1 -3: AR6K_SD1, 192.168.128.102 -======= Route entries ========== -Network Destination Netmask Gateway Interface Metric -0.0.0.0 0.0.0.0 192.168.128.1 192.168.128.102 0 -174.10.0.0 0.0.0.0 255.255.255.255 255 0 -127.0.0.0 255.0.0.0 127.0.0.1 001 0 -199.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.0 255.255.255.0 169.254.2.1 169.254.2.1 0 -189.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.1 255.255.255.255 127.0.0.1 001 0 -189.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.255.255 255.255.255.255 169.254.2.1 169.254.2.1 0 -189.10.0.0 0.0.0.0 255.255.255.255 255 0 -192.168.128.0 255.255.255.0 192.168.128.102 192.168.128.102 0 -174.10.0.0 0.0.0.0 255.255.255.255 255 0 - -5/3/14, 3:39 AM ################# -======= TCP table ======== -local remote - 0.0.0.0: 5655 0.0.0.0: 0 LISTEN - 0.0.0.0: 52241 0.0.0.0: 0 LISTEN - 127.0.0.1: 1029 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1031 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1032 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1033 127.0.0.1: 52241 ESTAB - 127.0.0.1: 8888 0.0.0.0: 0 LISTEN - 127.0.0.1: 52241 127.0.0.1: 1029 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1031 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1032 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1033 ESTAB - 169.254.2.1: 1025 169.254.2.2: 990 ESTAB - 169.254.2.1: 1027 169.254.2.2: 990 ESTAB - 169.254.2.1: 1034 169.254.2.2: 2500 SYN_SENT - 169.254.2.1: 1086 169.254.2.2: 990 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50288 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50289 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50290 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50291 ESTAB -======= UDP table ======== - 0.0.0.0: 68 - 0.0.0.0: 137 - 0.0.0.0: 138 - 0.0.0.0: 9204 - 0.0.0.0: 49111 - 169.254.2.1: 67 -192.168.128.102: 68 -======= TCP statistics ======== -Retransmission timeout (min/max): Van Jacobson's Algorithm: 300/120000 - max connnections: -1 - active open: 112 - passive open: 12 - failed attempts: 100 - established resets: 8 - current established: 15 - segments in: 3391 - segments out: 4592 - retransmitted segments: 304 - in errors: 0 - out resets: 7 - num connections: 19 -======= UDP statistics ======== - in datagrams: 1079 - in errors: 0 - num ports: 438 - num addresses: 7 - out datagrams: 410 -======= Adapter infos ========== -2: RNDISFN1, 169.254.2.1 -3: AR6K_SD1, 192.168.128.102 -======= Route entries ========== -Network Destination Netmask Gateway Interface Metric -0.0.0.0 0.0.0.0 192.168.128.1 192.168.128.102 0 -179.10.0.0 0.0.0.0 255.255.255.255 255 0 -127.0.0.0 255.0.0.0 127.0.0.1 001 0 -204.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.0 255.255.255.0 169.254.2.1 169.254.2.1 0 -194.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.1 255.255.255.255 127.0.0.1 001 0 -194.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.255.255 255.255.255.255 169.254.2.1 169.254.2.1 0 -194.10.0.0 0.0.0.0 255.255.255.255 255 0 -192.168.128.0 255.255.255.0 192.168.128.102 192.168.128.102 0 -179.10.0.0 0.0.0.0 255.255.255.255 255 0 - -5/3/14, 3:39 AM ################# -======= TCP table ======== -local remote - 0.0.0.0: 5655 0.0.0.0: 0 LISTEN - 0.0.0.0: 52241 0.0.0.0: 0 LISTEN - 127.0.0.1: 1029 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1031 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1032 127.0.0.1: 52241 ESTAB - 127.0.0.1: 1033 127.0.0.1: 52241 ESTAB - 127.0.0.1: 8888 0.0.0.0: 0 LISTEN - 127.0.0.1: 52241 127.0.0.1: 1029 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1031 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1032 ESTAB - 127.0.0.1: 52241 127.0.0.1: 1033 ESTAB - 169.254.2.1: 1025 169.254.2.2: 990 ESTAB - 169.254.2.1: 1027 169.254.2.2: 990 ESTAB - 169.254.2.1: 1034 169.254.2.2: 2500 SYN_SENT - 169.254.2.1: 1086 169.254.2.2: 990 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50288 ESTAB - 169.254.2.1: 5655 169.254.2.2: 50289 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50290 ESTAB - 169.254.2.1: 6510 169.254.2.2: 50291 ESTAB -======= UDP table ======== - 0.0.0.0: 68 - 0.0.0.0: 137 - 0.0.0.0: 138 - 0.0.0.0: 9204 - 0.0.0.0: 49111 - 169.254.2.1: 67 -192.168.128.102: 68 -======= TCP statistics ======== -Retransmission timeout (min/max): Van Jacobson's Algorithm: 300/120000 - max connnections: -1 - active open: 112 - passive open: 12 - failed attempts: 100 - established resets: 8 - current established: 15 - segments in: 3395 - segments out: 4596 - retransmitted segments: 304 - in errors: 0 - out resets: 7 - num connections: 19 -======= UDP statistics ======== - in datagrams: 1080 - in errors: 0 - num ports: 438 - num addresses: 7 - out datagrams: 410 -======= Adapter infos ========== -2: RNDISFN1, 169.254.2.1 -3: AR6K_SD1, 192.168.128.102 -======= Route entries ========== -Network Destination Netmask Gateway Interface Metric -0.0.0.0 0.0.0.0 192.168.128.1 192.168.128.102 0 -183.10.0.0 0.0.0.0 255.255.255.255 255 0 -127.0.0.0 255.0.0.0 127.0.0.1 001 0 -208.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.0 255.255.255.0 169.254.2.1 169.254.2.1 0 -198.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.2.1 255.255.255.255 127.0.0.1 001 0 -198.10.0.0 0.0.0.0 255.255.255.255 255 0 -169.254.255.255 255.255.255.255 169.254.2.1 169.254.2.1 0 -198.10.0.0 0.0.0.0 255.255.255.255 255 0 -192.168.128.0 255.255.255.0 192.168.128.102 192.168.128.102 0 -183.10.0.0 0.0.0.0 255.255.255.255 255 0 - diff --git a/netstatCF2/doc/netstatCF2.jpg b/netstatCF2/doc/netstatCF2.jpg deleted file mode 100644 index f0cb853..0000000 Binary files a/netstatCF2/doc/netstatCF2.jpg and /dev/null differ diff --git a/netstatCF2/frmNetStat.Designer.cs b/netstatCF2/frmNetStat.Designer.cs deleted file mode 100644 index 7292c2f..0000000 --- a/netstatCF2/frmNetStat.Designer.cs +++ /dev/null @@ -1,116 +0,0 @@ -namespace netstatCF2 -{ - partial class frmNetStat - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuFile = new System.Windows.Forms.MenuItem(); - this.mnuSave = new System.Windows.Forms.MenuItem(); - this.mnuRefresh = new System.Windows.Forms.MenuItem(); - this.mnuExit = new System.Windows.Forms.MenuItem(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.mnuBackgroundLogging = new System.Windows.Forms.MenuItem(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuFile); - // - // mnuFile - // - this.mnuFile.MenuItems.Add(this.mnuBackgroundLogging); - this.mnuFile.MenuItems.Add(this.mnuSave); - this.mnuFile.MenuItems.Add(this.mnuRefresh); - this.mnuFile.MenuItems.Add(this.mnuExit); - this.mnuFile.Text = "File"; - // - // mnuSave - // - this.mnuSave.Text = "Save"; - this.mnuSave.Click += new System.EventHandler(this.mnuSave_Click); - // - // mnuRefresh - // - this.mnuRefresh.Text = "Refresh"; - this.mnuRefresh.Click += new System.EventHandler(this.mnuRefresh_Click); - // - // mnuExit - // - this.mnuExit.Text = "Exit"; - this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click); - // - // textBox1 - // - this.textBox1.AcceptsReturn = true; - this.textBox1.AcceptsTab = true; - this.textBox1.BackColor = System.Drawing.SystemColors.Info; - this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill; - this.textBox1.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular); - this.textBox1.Location = new System.Drawing.Point(0, 0); - this.textBox1.Multiline = true; - this.textBox1.Name = "textBox1"; - this.textBox1.ReadOnly = true; - this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.textBox1.Size = new System.Drawing.Size(240, 268); - this.textBox1.TabIndex = 1; - this.textBox1.WordWrap = false; - // - // mnuBackgroundLogging - // - this.mnuBackgroundLogging.Text = "Background Logging"; - this.mnuBackgroundLogging.Click += new System.EventHandler(this.mnuBackgroundLogging_Click); - // - // frmNetStat - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.Controls.Add(this.textBox1); - this.KeyPreview = true; - this.Menu = this.mainMenu1; - this.Name = "frmNetStat"; - this.Text = "TCP/UDP Info CF2"; - this.Closing += new System.ComponentModel.CancelEventHandler(this.frmNetStat_Closing); - this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.MenuItem mnuFile; - private System.Windows.Forms.MenuItem mnuSave; - private System.Windows.Forms.MenuItem mnuRefresh; - private System.Windows.Forms.MenuItem mnuExit; - private System.Windows.Forms.MenuItem mnuBackgroundLogging; - } -} - diff --git a/netstatCF2/frmNetStat.cs b/netstatCF2/frmNetStat.cs deleted file mode 100644 index bedc35c..0000000 --- a/netstatCF2/frmNetStat.cs +++ /dev/null @@ -1,301 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -using System.Threading; -using System.IO; - -namespace netstatCF2 -{ - public partial class frmNetStat : Form - { -#if DEBUG - int iLogInterval = 3; -#else - int iLogInterval = 30; -#endif - Thread loggingThread = null; - bool bStopThread = false; - IpHlpApidotnet.IPHelper g_iphlp=null; - - static string sAppPath = "\\"; - string getAppPath - { - get - { - if (sAppPath == "\\") - { - string AppPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); - if (!AppPath.EndsWith(@"\")) - AppPath += @"\"; - sAppPath = AppPath; - return sAppPath; - } - else - return sAppPath; - } - } - - public frmNetStat() - { - InitializeComponent(); - refreshScreen(); - mnuBackgroundLogging_Click(this, null); - } - void refreshScreen() - { - SuspendLayout(); - textBox1.Text = doLog(); - - //IpHlpApidotnet.IPHelper iphlp = new IpHlpApidotnet.IPHelper(); - //iphlp.GetTcpConnexions(); - //System.Diagnostics.Debug.WriteLine("TCP table\n" + "local".PadRight(28) + "remote"); - //textBox1.Text += "======= TCP table ========\r\n" + "local".PadRight(28) + "remote\r\n"; - //foreach (IpHlpApidotnet.MIB_TCPROW stat in iphlp.TcpConnexion.table) - //{ - // //System.Diagnostics.Debug.WriteLine( stat.Local.Address.ToString() + " " +stat.Remote.Address.ToString() ); - // System.Diagnostics.Debug.WriteLine(IpHlpApidotnet.IPHelper.dump_MIB_TCPROW(stat)); - // textBox1.Text += IpHlpApidotnet.IPHelper.dump_MIB_TCPROW(stat) + "\r\n"; - //} - - //iphlp.GetUdpConnexions(); - //System.Diagnostics.Debug.WriteLine("UDP table\n" + "local"); - //textBox1.Text += "======= UDP table ========\r\n"; - //foreach (IpHlpApidotnet.MIB_UDPROW stat in iphlp.UdpConnexion.table) - //{ - // System.Diagnostics.Debug.WriteLine(IpHlpApidotnet.IPHelper.dump_MIB_UDPROW(stat)); - // textBox1.Text += IpHlpApidotnet.IPHelper.dump_MIB_UDPROW(stat) + "\r\n"; - //} - - //iphlp.GetTcpStats(); - //System.Diagnostics.Debug.WriteLine("TCP statistics:"); - //textBox1.Text += "======= TCP statistics ========\r\n"; - //System.Diagnostics.Debug.WriteLine(IpHlpApidotnet.IPHelper.dump_MIB_TCPSTATS(iphlp.TcpStats)); - //textBox1.Text += IpHlpApidotnet.IPHelper.dump_MIB_TCPSTATS(iphlp.TcpStats) + "\r\n"; - - //iphlp.GetUdpStats(); - //System.Diagnostics.Debug.WriteLine("UDP statistics:"); - //textBox1.Text += "======= UDP statistics ========\r\n"; - //System.Diagnostics.Debug.WriteLine(IpHlpApidotnet.IPHelper.dump_MIB_UDPSTATS(iphlp.UdpStats)); - //textBox1.Text += IpHlpApidotnet.IPHelper.dump_MIB_UDPSTATS(iphlp.UdpStats) + "\r\n"; - - - //AdapterInfo.AdaptersInfo aInfo = new AdapterInfo.AdaptersInfo(); - //System.Diagnostics.Debug.WriteLine("Adapter infos: "); - //textBox1.Text += "======= Adapter infos ==========\r\n"; - //foreach (AdapterInfo.IP_ADAPTER_INFO info in aInfo._adapterList) - //{ - // System.Diagnostics.Debug.WriteLine(info.Index.ToString() + ": " + info.AdapterName + ", " + info.CurrentIpAddress.IpAddress.String); - // textBox1.Text += info.Index.ToString() + ": " + info.AdapterName + ", " + info.CurrentIpAddress.IpAddress.String + "\r\n"; - //} - - //iphlp.getRoutingTable(); - //// 1 2 3 4 5 6 7 8 - //// 12345678901234567890123456789012345678901234567890123456789012345678901234567890123 - //System.Diagnostics.Debug.WriteLine("Route entries: \r\nNetwork Destination Netmask Gateway Interface Metric"); - //textBox1.Text += "Route entries: \r\nNetwork Destination Netmask Gateway Interface Metric\r\n"; - //foreach (IpHlpApidotnet.IPHlpAPI32Wrapper.MIB_IPFORWARDROW row in iphlp._routeEntry) - //{ - // System.Diagnostics.Debug.WriteLine(iphlp.dumpRouteEntry(row)); - // textBox1.Text += iphlp.dumpRouteEntry(row) + "\r\n"; - //} - - ResumeLayout(); - textBox1.Refresh(); - - } - - private void mnuExit_Click(object sender, EventArgs e) - { - this.Close(); - Application.Exit(); - } - - private void mnuRefresh_Click(object sender, EventArgs e) - { - refreshScreen(); - } - - private void mnuSave_Click(object sender, EventArgs e) - { - SaveFileDialog ofd = new SaveFileDialog(); - if (ofd.ShowDialog() == DialogResult.OK) - { - using (System.IO.TextWriter tw = new System.IO.StreamWriter(ofd.FileName)) - { - tw.WriteLine(textBox1.Text); - tw.Flush(); - } - MessageBox.Show("File saved to " + ofd.FileName); - } - } - - private void Form1_KeyDown(object sender, KeyEventArgs e) - { - if ((e.KeyCode == System.Windows.Forms.Keys.Up)) - { - // Up - } - if ((e.KeyCode == System.Windows.Forms.Keys.Down)) - { - // Down - } - if ((e.KeyCode == System.Windows.Forms.Keys.Left)) - { - // Left - } - if ((e.KeyCode == System.Windows.Forms.Keys.Right)) - { - // Right - } - if ((e.KeyCode == System.Windows.Forms.Keys.Enter)) - { - // Enter - } - - } - - private void mnuBackgroundLogging_Click(object sender, EventArgs e) - { - mnuBackgroundLogging.Checked = !mnuBackgroundLogging.Checked; - if (mnuBackgroundLogging.Checked) - { - stopThread(); - startThread(); - } - else - stopThread(); - } - - void startThread() - { - stopThread(); - bStopThread = false; - loggingThread = new Thread(loggerThread); - loggingThread.Name = "logger thread"; - loggingThread.Start(); - System.Diagnostics.Debug.WriteLine("startThread: " + loggingThread.ManagedThreadId.ToString() + ", '" + loggingThread.Name + "'"); - } - - void stopThread() - { - if (loggingThread == null) - return; - try - { - bStopThread = true; - bool bJoined = loggingThread.Join(1000); - if (!bJoined) - loggingThread.Abort(); - loggingThread = null; - } - catch (Exception ex) { - System.Diagnostics.Debug.WriteLine("Exception in stopThread: " + ex.Message); - } - } - - void loggerThread() - { - System.Diagnostics.Debug.WriteLine("+++++ loggerThread started"); - try - { - int iCount = 0; - //log to file - doLog(); - do{ - //wait - Thread.Sleep(1000); - if (iCount > iLogInterval) - { - doLog(); - iCount = 0; - } - iCount++; - }while(!bStopThread); - } - catch (ThreadAbortException ex) - { - System.Diagnostics.Debug.WriteLine("ThreadAbortException in loggerThread: " + ex.Message); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in loggerThread: " + ex.Message); - } - System.Diagnostics.Debug.WriteLine("----- loggerThread ended"); - } - - string doLog() - { - DateTime dt = DateTime.Now; - string dtStr = dt.ToShortDateString() + ", " + dt.ToShortTimeString(); - if (g_iphlp == null) - g_iphlp = new IpHlpApidotnet.IPHelper(); - - string sOut = ""; - g_iphlp.GetTcpConnexions(); - sOut += "======= TCP table ========\r\n" + "local".PadRight(28) + "remote\r\n"; - foreach (IpHlpApidotnet.MIB_TCPROW stat in g_iphlp.TcpConnexion.table) - { - sOut += IpHlpApidotnet.IPHelper.dump_MIB_TCPROW(stat) + "\r\n"; - } - - g_iphlp.GetUdpConnexions(); - sOut += "======= UDP table ========\r\n"; - foreach (IpHlpApidotnet.MIB_UDPROW stat in g_iphlp.UdpConnexion.table) - { - sOut += IpHlpApidotnet.IPHelper.dump_MIB_UDPROW(stat) + "\r\n"; - } - - g_iphlp.GetTcpStats(); - sOut += "======= TCP statistics ========\r\n"; - sOut += IpHlpApidotnet.IPHelper.dump_MIB_TCPSTATS(g_iphlp.TcpStats) + "\r\n"; - - g_iphlp.GetUdpStats(); - sOut += "======= UDP statistics ========\r\n"; - sOut += IpHlpApidotnet.IPHelper.dump_MIB_UDPSTATS(g_iphlp.UdpStats) + "\r\n"; - - - AdapterInfo.AdaptersInfo aInfo = new AdapterInfo.AdaptersInfo(); - sOut += "======= Adapter infos ==========\r\n"; - foreach (AdapterInfo.IP_ADAPTER_INFO info in aInfo._adapterList) - { - sOut += info.Index.ToString() + ": " + info.AdapterName + ", " + info.CurrentIpAddress.IpAddress.String + "\r\n"; - } - - g_iphlp.getRoutingTable(); - sOut += "======= Route entries ==========\r\n"; - // 1 2 3 4 5 6 7 8 - // 12345678901234567890123456789012345678901234567890123456789012345678901234567890123 - sOut += "Network Destination Netmask Gateway Interface Metric\r\n"; - foreach (IpHlpApidotnet.IPHlpAPI32Wrapper.MIB_IPFORWARDROW row in g_iphlp._routeEntry) - { - sOut += g_iphlp.dumpRouteEntry(row) + "\r\n"; - } - - string sFile = "\\netstat.log"; - try - { - StreamWriter sw = new StreamWriter(sFile, true, Encoding.UTF8, 2000); - sw.WriteLine(dtStr + " #################\r\n" + sOut); - sw.Flush(); - sw.Close(); - System.Diagnostics.Debug.WriteLine("logged to file"); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in writeLog: " + ex.Message); - } - return sOut; - } - - private void frmNetStat_Closing(object sender, CancelEventArgs e) - { - stopThread(); - } - } -} \ No newline at end of file diff --git a/netstatCF2/frmNetStat.resx b/netstatCF2/frmNetStat.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/netstatCF2/frmNetStat.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/netstatCF2/netstatCF2.csproj b/netstatCF2/netstatCF2.csproj deleted file mode 100644 index bf31280..0000000 --- a/netstatCF2/netstatCF2.csproj +++ /dev/null @@ -1,96 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {40811E7B-70C5-4967-9891-258F3C616D00} - WinExe - Properties - netstatCF2 - netstatCF2 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.1 - netstatCF2 - v2.0 - Windows Mobile 5.0 Pocket PC SDK - - - %25CSIDL_PROGRAM_FILES%25 - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - Form - - - frmNetStat.cs - - - - - - frmNetStat.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - - \ No newline at end of file diff --git a/netstatCF2/netstatCF2.exe b/netstatCF2/netstatCF2.exe deleted file mode 100644 index 5900a49..0000000 Binary files a/netstatCF2/netstatCF2.exe and /dev/null differ diff --git a/netstatCF2/netstatCF2.sln b/netstatCF2/netstatCF2.sln deleted file mode 100644 index 5a66324..0000000 --- a/netstatCF2/netstatCF2.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "netstatCF2", "netstatCF2.csproj", "{40811E7B-70C5-4967-9891-258F3C616D00}" -EndProject -Global - GlobalSection(SubversionScc) = preSolution - Svn-Managed = True - Manager = AnkhSVN - Subversion Support for Visual Studio - EndGlobalSection - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {40811E7B-70C5-4967-9891-258F3C616D00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {40811E7B-70C5-4967-9891-258F3C616D00}.Debug|Any CPU.Build.0 = Debug|Any CPU - {40811E7B-70C5-4967-9891-258F3C616D00}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {40811E7B-70C5-4967-9891-258F3C616D00}.Release|Any CPU.ActiveCfg = Release|Any CPU - {40811E7B-70C5-4967-9891-258F3C616D00}.Release|Any CPU.Build.0 = Release|Any CPU - {40811E7B-70C5-4967-9891-258F3C616D00}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/pingalert.md b/pingalert.md new file mode 100644 index 0000000..650c5b6 --- /dev/null +++ b/pingalert.md @@ -0,0 +1,3 @@ +PingAlert is a toolset to periodically check hosts availability using pings. It supports a scheduler, the Ping apllication and a notification alert so far. + +See http://www.hjgode.de/wp/2011/03/01/mobile-development-pingalert-watch-your-servers-2/ for more details. \ No newline at end of file diff --git a/pocketHosts/pocketHosts.sln b/pocketHosts/pocketHosts.sln deleted file mode 100644 index 6a66501..0000000 --- a/pocketHosts/pocketHosts.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "pocketHosts", "pocketHosts\pocketHosts.csproj", "{66FCCCAA-C4AC-41F4-9D11-187C78823C5C}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {66FCCCAA-C4AC-41F4-9D11-187C78823C5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {66FCCCAA-C4AC-41F4-9D11-187C78823C5C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {66FCCCAA-C4AC-41F4-9D11-187C78823C5C}.Debug|Any CPU.Deploy.0 = Debug|Any CPU - {66FCCCAA-C4AC-41F4-9D11-187C78823C5C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {66FCCCAA-C4AC-41F4-9D11-187C78823C5C}.Release|Any CPU.Build.0 = Release|Any CPU - {66FCCCAA-C4AC-41F4-9D11-187C78823C5C}.Release|Any CPU.Deploy.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/pocketHosts/pocketHosts/Program.cs b/pocketHosts/pocketHosts/Program.cs deleted file mode 100644 index 72e78f4..0000000 --- a/pocketHosts/pocketHosts/Program.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Windows.Forms; - -namespace pocketHosts -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [MTAThread] - static void Main() - { - Application.Run(new pocketHosts()); - } - } -} \ No newline at end of file diff --git a/pocketHosts/pocketHosts/Properties/AssemblyInfo.cs b/pocketHosts/pocketHosts/Properties/AssemblyInfo.cs deleted file mode 100644 index c4be62e..0000000 --- a/pocketHosts/pocketHosts/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("pocketHosts")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Intermec Technologies")] -[assembly: AssemblyProduct("pocketHosts")] -[assembly: AssemblyCopyright("Copyright © Intermec Technologies 2013")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("5a766d21-7ebd-4f84-82b1-3f4c73c6dd84")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("1.0.0.0")] - -// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly" -// as Device app does not support STA thread. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")] diff --git a/pocketHosts/pocketHosts/Properties/Resources.Designer.cs b/pocketHosts/pocketHosts/Properties/Resources.Designer.cs deleted file mode 100644 index ef64b3e..0000000 --- a/pocketHosts/pocketHosts/Properties/Resources.Designer.cs +++ /dev/null @@ -1,68 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:2.0.50727.5472 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace pocketHosts.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the Strongly Typed Resource Builder - // class via a tool like ResGen or Visual Studio.NET. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - class Resources - { - - private static System.Resources.ResourceManager _resMgr; - - private static System.Globalization.CultureInfo _resCulture; - - /*FamANDAssem*/ - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Resources.ResourceManager ResourceManager - { - get - { - if ((_resMgr == null)) - { - System.Resources.ResourceManager temp = new System.Resources.ResourceManager("pocketHosts.Properties.Resources", typeof(Resources).Assembly); - _resMgr = temp; - } - return _resMgr; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] - public static System.Globalization.CultureInfo Culture - { - get - { - return _resCulture; - } - set - { - _resCulture = value; - } - } - } -} diff --git a/pocketHosts/pocketHosts/Properties/Resources.resx b/pocketHosts/pocketHosts/Properties/Resources.resx deleted file mode 100644 index a814449..0000000 --- a/pocketHosts/pocketHosts/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/pocketHosts/pocketHosts/bin/Debug/pocketHosts.exe b/pocketHosts/pocketHosts/bin/Debug/pocketHosts.exe deleted file mode 100644 index 173c69a..0000000 Binary files a/pocketHosts/pocketHosts/bin/Debug/pocketHosts.exe and /dev/null differ diff --git a/pocketHosts/pocketHosts/frmEditAliases.Designer.cs b/pocketHosts/pocketHosts/frmEditAliases.Designer.cs deleted file mode 100644 index 29590c7..0000000 --- a/pocketHosts/pocketHosts/frmEditAliases.Designer.cs +++ /dev/null @@ -1,115 +0,0 @@ -namespace pocketHosts -{ - partial class frmEditAliases - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.mnuCancel = new System.Windows.Forms.MenuItem(); - this.mnuOK = new System.Windows.Forms.MenuItem(); - this.txtAlias = new System.Windows.Forms.TextBox(); - this.btnAdd = new System.Windows.Forms.Button(); - this.btnRemove = new System.Windows.Forms.Button(); - this.lstAliases = new System.Windows.Forms.ListBox(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.mnuCancel); - this.mainMenu1.MenuItems.Add(this.mnuOK); - // - // mnuCancel - // - this.mnuCancel.Text = "Cancel"; - // - // mnuOK - // - this.mnuOK.Text = "OK"; - this.mnuOK.Click += new System.EventHandler(this.mnuOK_Click); - // - // txtAlias - // - this.txtAlias.Location = new System.Drawing.Point(25, 31); - this.txtAlias.Name = "txtAlias"; - this.txtAlias.Size = new System.Drawing.Size(191, 21); - this.txtAlias.TabIndex = 6; - this.txtAlias.TextChanged += new System.EventHandler(this.txtIP_TextChanged); - // - // btnAdd - // - this.btnAdd.Location = new System.Drawing.Point(120, 58); - this.btnAdd.Name = "btnAdd"; - this.btnAdd.Size = new System.Drawing.Size(96, 23); - this.btnAdd.TabIndex = 5; - this.btnAdd.Text = "Add"; - this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); - // - // btnRemove - // - this.btnRemove.Location = new System.Drawing.Point(119, 214); - this.btnRemove.Name = "btnRemove"; - this.btnRemove.Size = new System.Drawing.Size(96, 23); - this.btnRemove.TabIndex = 4; - this.btnRemove.Text = "Remove"; - this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); - // - // lstAliases - // - this.lstAliases.Location = new System.Drawing.Point(25, 106); - this.lstAliases.Name = "lstAliases"; - this.lstAliases.Size = new System.Drawing.Size(191, 100); - this.lstAliases.TabIndex = 3; - // - // frmEditAliases - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.txtAlias); - this.Controls.Add(this.btnAdd); - this.Controls.Add(this.btnRemove); - this.Controls.Add(this.lstAliases); - this.Menu = this.mainMenu1; - this.Name = "frmEditAliases"; - this.Text = "edit aliases"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem mnuCancel; - private System.Windows.Forms.MenuItem mnuOK; - private System.Windows.Forms.TextBox txtAlias; - private System.Windows.Forms.Button btnAdd; - private System.Windows.Forms.Button btnRemove; - private System.Windows.Forms.ListBox lstAliases; - } -} \ No newline at end of file diff --git a/pocketHosts/pocketHosts/frmEditAliases.cs b/pocketHosts/pocketHosts/frmEditAliases.cs deleted file mode 100644 index 33b7ea5..0000000 --- a/pocketHosts/pocketHosts/frmEditAliases.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace pocketHosts -{ - public partial class frmEditAliases : Form - { - public List m_Aliases; - public frmEditAliases(List lAliases) - { - InitializeComponent(); - m_Aliases = lAliases; - foreach (string s in lAliases) - lstAliases.Items.Add(s); - } - - private void txtIP_TextChanged(object sender, EventArgs e) - { - //txtAlias.BackColor = Color.White; - } - - private void btnAdd_Click(object sender, EventArgs e) - { - lstAliases.Items.Add(txtAlias.Text); - } - - private void btnRemove_Click(object sender, EventArgs e) - { - if (lstAliases.SelectedIndex == -1) - return; - if (MessageBox.Show("Remove " + lstAliases.Items[lstAliases.SelectedIndex].ToString() + "?", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) - { - lstAliases.Items.RemoveAt(lstAliases.SelectedIndex); - } - - } - - private void mnuOK_Click(object sender, EventArgs e) - { - m_Aliases.Clear(); - foreach (object o in lstAliases.Items) - { - m_Aliases.Add(o.ToString()); - } - this.DialogResult = DialogResult.OK; - this.Close(); - } - } -} \ No newline at end of file diff --git a/pocketHosts/pocketHosts/frmEditAliases.resx b/pocketHosts/pocketHosts/frmEditAliases.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/pocketHosts/pocketHosts/frmEditAliases.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/pocketHosts/pocketHosts/frmEnterIP.Designer.cs b/pocketHosts/pocketHosts/frmEnterIP.Designer.cs deleted file mode 100644 index f01505d..0000000 --- a/pocketHosts/pocketHosts/frmEnterIP.Designer.cs +++ /dev/null @@ -1,116 +0,0 @@ -namespace pocketHosts -{ - partial class frmEnterIP - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.menuItem1 = new System.Windows.Forms.MenuItem(); - this.mnuOK = new System.Windows.Forms.MenuItem(); - this.lstIPaddresses = new System.Windows.Forms.ListBox(); - this.btnRemove = new System.Windows.Forms.Button(); - this.txtIP = new System.Windows.Forms.TextBox(); - this.btnAdd = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.menuItem1); - this.mainMenu1.MenuItems.Add(this.mnuOK); - // - // menuItem1 - // - this.menuItem1.Text = "Cancel"; - this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click); - // - // mnuOK - // - this.mnuOK.Text = "OK"; - this.mnuOK.Click += new System.EventHandler(this.mnuOK_Click); - // - // lstIPaddresses - // - this.lstIPaddresses.Location = new System.Drawing.Point(26, 105); - this.lstIPaddresses.Name = "lstIPaddresses"; - this.lstIPaddresses.Size = new System.Drawing.Size(191, 100); - this.lstIPaddresses.TabIndex = 0; - // - // btnRemove - // - this.btnRemove.Location = new System.Drawing.Point(120, 213); - this.btnRemove.Name = "btnRemove"; - this.btnRemove.Size = new System.Drawing.Size(96, 23); - this.btnRemove.TabIndex = 1; - this.btnRemove.Text = "Remove"; - this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); - // - // txtIP - // - this.txtIP.Location = new System.Drawing.Point(26, 30); - this.txtIP.Name = "txtIP"; - this.txtIP.Size = new System.Drawing.Size(191, 21); - this.txtIP.TabIndex = 2; - this.txtIP.TextChanged += new System.EventHandler(this.txtIP_TextChanged); - // - // btnAdd - // - this.btnAdd.Location = new System.Drawing.Point(121, 57); - this.btnAdd.Name = "btnAdd"; - this.btnAdd.Size = new System.Drawing.Size(96, 23); - this.btnAdd.TabIndex = 1; - this.btnAdd.Text = "Add"; - this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); - // - // frmEnterIP - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.ControlBox = false; - this.Controls.Add(this.txtIP); - this.Controls.Add(this.btnAdd); - this.Controls.Add(this.btnRemove); - this.Controls.Add(this.lstIPaddresses); - this.Menu = this.mainMenu1; - this.Name = "frmEnterIP"; - this.Text = "Enter IP address"; - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.MenuItem menuItem1; - private System.Windows.Forms.MenuItem mnuOK; - private System.Windows.Forms.ListBox lstIPaddresses; - private System.Windows.Forms.Button btnRemove; - private System.Windows.Forms.TextBox txtIP; - private System.Windows.Forms.Button btnAdd; - } -} \ No newline at end of file diff --git a/pocketHosts/pocketHosts/frmEnterIP.cs b/pocketHosts/pocketHosts/frmEnterIP.cs deleted file mode 100644 index f6c0b5f..0000000 --- a/pocketHosts/pocketHosts/frmEnterIP.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace pocketHosts -{ - public partial class frmEnterIP : Form - { - public List m_ipList; - public frmEnterIP(List ipList) - { - InitializeComponent(); - foreach (System.Net.IPAddress ip in ipList) - lstIPaddresses.Items.Add(ip); - m_ipList = ipList; - } - - private void btnAdd_Click(object sender, EventArgs e) - { - try - { - System.Net.IPAddress ip = System.Net.IPAddress.Parse(txtIP.Text); - lstIPaddresses.Items.Add(ip.ToString()); - } - catch (Exception) - { - txtIP.BackColor = Color.LightPink; - } - } - - private void txtIP_TextChanged(object sender, EventArgs e) - { - txtIP.BackColor = Color.White; - } - - private void btnRemove_Click(object sender, EventArgs e) - { - if (lstIPaddresses.SelectedIndex == -1) - return; - if (MessageBox.Show("Remove " + lstIPaddresses.Items[lstIPaddresses.SelectedIndex].ToString() + "?", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) - { - lstIPaddresses.Items.RemoveAt(lstIPaddresses.SelectedIndex); - } - } - - private void mnuOK_Click(object sender, EventArgs e) - { - m_ipList.Clear(); - foreach (object o in lstIPaddresses.Items) - { - System.Net.IPAddress ip = System.Net.IPAddress.Parse(o.ToString()); - m_ipList.Add(ip); - } - this.DialogResult = DialogResult.OK; - this.Close(); - } - - private void menuItem1_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.Cancel; - } - } -} \ No newline at end of file diff --git a/pocketHosts/pocketHosts/frmEnterIP.resx b/pocketHosts/pocketHosts/frmEnterIP.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/pocketHosts/pocketHosts/frmEnterIP.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/pocketHosts/pocketHosts/hostsentries.cs b/pocketHosts/pocketHosts/hostsentries.cs deleted file mode 100644 index f3c4a74..0000000 --- a/pocketHosts/pocketHosts/hostsentries.cs +++ /dev/null @@ -1,317 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using Microsoft.Win32; -using System.Collections; - -using System.Security; -using System.Security.Permissions; - -namespace pocketHosts -{ - public class hostsentries:IDisposable - { - const string regSubKey = @"Comm\Tcpip\Hosts"; - RegistryKey rKeyTCPIP; - public Dictionary allHosts; - public hostsentries() - { - allHosts = new Dictionary(); - init(); - } - private void init() - { - try - { - rKeyTCPIP = Registry.LocalMachine.OpenSubKey(regSubKey, true); - if (rKeyTCPIP == null) - System.Diagnostics.Debug.WriteLine("Error opening reg key: " + regSubKey); - loadRegistry(); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception opening reg key: " + regSubKey + ", " + ex.Message); - } - } - - public void Dispose() - { - try - { - rKeyTCPIP.Flush(); - rKeyTCPIP.Close(); - rKeyTCPIP = null; - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in Dispose(): " + ex.Message); - } - } - - public int removeEntry(hostsentry he) - { - int iRet =0; - try - { - string[] lVals = rKeyTCPIP.OpenSubKey(he.sHost, true).GetValueNames(); - foreach (string s in lVals) - { - rKeyTCPIP.DeleteValue(s); - } - try - { - rKeyTCPIP.DeleteValue("");//delete default value - } - catch (Exception) { } - rKeyTCPIP.Close(); - rKeyTCPIP = null; - if (myregistry.RegDelKey(regSubKey, he.sHost) == 0) - { - iRet = 1; - this.allHosts.Remove(he.sHost); - } - rKeyTCPIP = Registry.LocalMachine.OpenSubKey(regSubKey, true); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in remove(): " + ex.Message); - } - return iRet; - } - - public int saveAll(){ - int iRet = 0; - foreach (hostsentry he in this.allHosts.Values) - { - saveEntry(he); - iRet++; - } - return iRet; - } - - public int saveEntry(hostsentry he) - { - int iRet = 0; - RegistryKey regWork=null; - //create subkey if not exist - try - { - regWork = rKeyTCPIP.CreateSubKey(he.sHost); - List b = new List(); - foreach (System.Net.IPAddress ip in he.ipAddress) - { - b.AddRange(ip.GetAddressBytes()); //can be ip4 or ip6 - iRet++; - } - if(b.Count>=4) - regWork.SetValue("ipaddr", b.ToArray(), RegistryValueKind.Binary); - - b.Clear(); - foreach (System.Net.IPAddress ip6 in he.ipAddress6) - { - b.AddRange(ip6.GetAddressBytes()); //can be ip4 or ip6 - iRet++; - } - if (b.Count >= 4) - regWork.SetValue("ipaddr6", b.ToArray(), RegistryValueKind.Binary); - - if(he.aliases.Count>0) - regWork.SetValue("aliases", he.aliases.ToArray(), RegistryValueKind.MultiString); - - if(he.expireTime!=0) - regWork.SetValue("expireTime", BitConverter.GetBytes(he.expireTime), RegistryValueKind.Binary); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in saveEntry(): " + ex.Message); - } - return iRet; - } - - int loadRegistry() - { - int iRet = 0; - string[] subKeys = rKeyTCPIP.GetSubKeyNames(); - allHosts.Clear(); - foreach (string sHost in subKeys) - { - hostsentry hEntry = new hostsentry(); - hEntry.sHost = sHost; - - if (existsValue(sHost, "Aliases")) - { - string[] sAliases = (string[])rKeyTCPIP.OpenSubKey(sHost).GetValue("Aliases", null); - if (sAliases != null) - { - foreach(string s in sAliases) - hEntry.aliases.Add(s); - } - } - - hEntry.expireTime = 0; //do not save! - if (existsValue(sHost, "ExpireTime")) - { - byte[] bExpires = (byte[])rKeyTCPIP.OpenSubKey(sHost).GetValue("ExpireTime ", null); - if (bExpires != null) - { - ulong ul = BitConverter.ToUInt64(bExpires, 0); - hEntry.expireTime = ul; - } - } - - if (existsValue(sHost, "ipAddr")) - { - byte[] bIpAddress4 = (byte[])rKeyTCPIP.OpenSubKey(sHost).GetValue("ipAddr", null); - if (bIpAddress4 != null && bIpAddress4.Length >= 4) - { - if (bIpAddress4.Length > 4) - { - for (int offset = 0; offset < bIpAddress4.Length; offset += 4) - { - byte[] bIp = new byte[4]; - Array.Copy(bIpAddress4, offset, bIp, 0, 4); - System.Net.IPAddress ip = System.Net.IPAddress.Parse( - bIp[0].ToString() + "." + - bIp[1].ToString() + "." + - bIp[2].ToString() + "." + - bIp[3].ToString()); - hEntry.ipAddress.Add(ip); - } - } - else - { - System.Net.IPAddress ip = System.Net.IPAddress.Parse( - bIpAddress4[0].ToString() + "." + - bIpAddress4[1].ToString() + "." + - bIpAddress4[2].ToString() + "." + - bIpAddress4[3].ToString()); - hEntry.ipAddress.Add(ip); - } - } - } - - //ip6 address is 16 bytes - // ie 2001:0db8:ac10:fe01:0000:0000:0000:0000 - if (existsValue(sHost, "ipAddr6")) - { - byte[] bIpAddress6 = (byte[])rKeyTCPIP.OpenSubKey(sHost).GetValue("ipAddr6", null); - if (bIpAddress6 != null && bIpAddress6.Length >= 16) - { - if (bIpAddress6.Length > 16) - { - for (int offset = 0; offset < bIpAddress6.Length; offset += 16) - { - byte[] bIp = new byte[16]; - Array.Copy(bIpAddress6, offset, bIp, 0, 16); - System.Net.IPAddress ip6 = getIP6fromByte(bIp); - if (ip6 != System.Net.IPAddress.None) - hEntry.ipAddress6.Add(ip6); - } - } - else - { - System.Net.IPAddress ip6 = getIP6fromByte(bIpAddress6); - if(ip6!=System.Net.IPAddress.None) - hEntry.ipAddress6.Add(ip6); - } - } - } - - this.allHosts.Add(hEntry.sHost, hEntry); - } - - - return iRet; - } - - //convert 20010db8ac10fe010000000000000000 - //to 2001:0db8:ac10:fe01:0000:0000:0000:0000 - private string getIP6StrfromByte(byte[] bIpAddress6) - { - if (bIpAddress6.Length != 16) - return ""; - string sIP6 = ""; - for (int i = 0; i < 16; i++) - { - byte b = bIpAddress6[i]; - sIP6 += b.ToString("x02"); - if (i > 0 && i % 2 != 0 && i != 15) - sIP6 += ":"; - } - return sIP6; - } - - private System.Net.IPAddress getIP6fromByte(byte[] bIpAddress6) - { - System.Net.IPAddress ip6 = new System.Net.IPAddress((long)0); - string sIP = getIP6StrfromByte(bIpAddress6); - if (sIP != "") - { - try{ - ip6 = System.Net.IPAddress.Parse(sIP); - } - catch(Exception){} - } - return ip6; - } - - /// - /// add or change host entry - /// - /// - /// true for added a new entry - /// false if existing entry is replaced - public bool addChangeEntry(hostsentry he) - { - bool bRet = false; - hostsentry hTest = new hostsentry(); - if (this.allHosts.TryGetValue(he.sHost, out hTest)) - { - //there is already an entry - this.allHosts.Remove(he.sHost); - //replace old entry by new one - this.allHosts.Add(he.sHost, he); - bRet = false; - } - else - { - this.allHosts.Add(he.sHost, he); - bRet = true; - } - return bRet; - } - - public hostsentry getEntry(string sHost) - { - hostsentry he = new hostsentry(); - //test if entry exists - if (this.allHosts.TryGetValue(sHost, out he)) - return he; - return he; - } - - /// - /// check registry for existence of a reg key value - /// - /// - /// - /// - bool existsValue(string sKey, string sVal) - { - bool bRet = false; - try - { - object o = rKeyTCPIP.OpenSubKey(sKey).GetValue(sVal, null); - if (o != null) - bRet = true; - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine("Exception in existsValue(): " + ex.Message); - } - return bRet; - } - } -} diff --git a/pocketHosts/pocketHosts/hostsentry.cs b/pocketHosts/pocketHosts/hostsentry.cs deleted file mode 100644 index 50e5ddd..0000000 --- a/pocketHosts/pocketHosts/hostsentry.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -namespace pocketHosts -{ - public class hostsentry - { - - //################################################################## - public string sHost { get; set; } - public List ipAddress { get; set; } - public List ipAddress6 { get; set; } - public List aliases { get; set; } - private ulong _expireTime = 0; - public ulong expireTime { get { return (uint)_expireTime; } set { _expireTime = (ulong)value; } } - - public bool isIpaddress4(System.Net.IPAddress ip) - { - if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) - return true; - else - return false; - } - public hostsentry() - { - sHost = ""; - aliases = new List(); - ipAddress = new List(); - ipAddress6 = new List(); - expireTime = 0; - } - public override string ToString() - { - return sHost; - } - } -} diff --git a/pocketHosts/pocketHosts/myRegistry.cs b/pocketHosts/pocketHosts/myRegistry.cs deleted file mode 100644 index c8d3b8b..0000000 --- a/pocketHosts/pocketHosts/myRegistry.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.Text; - -using System.Runtime.InteropServices; - -namespace pocketHosts -{ - class myregistry - { - [DllImport("coredll.dll", SetLastError=true)] - static extern int RegOpenKeyEx(UIntPtr hKey, string lpSubKey, uint ulOptions,int samDesired, out IntPtr phkResult); - - [DllImport("coredll.dll", SetLastError = true)] - static extern int RegOpenKeyEx(uint hKey, string lpSubKey, uint ulOptions, int samDesired, out IntPtr phkResult); - - [DllImport("coredll.dll", SetLastError = true)] - static extern int RegDeleteKey(IntPtr hKey, string lpSubKey); - - [DllImport("coredll.dll", SetLastError = true)] - static extern int RegDeleteKey(UIntPtr hKey, string lpSubKey); - - [DllImport("coredll.dll")] - static extern int RegCloseKey(IntPtr hKey); - - const uint HKEY_LOCAL_MACHINE = 0x80000002;// IntPtr (-2147483646); // 0x80000002 - - static int mRegOpenKeyEx(UIntPtr hKey, string lpSubKey, out IntPtr phkResult){ - int iRes = RegOpenKeyEx(hKey, lpSubKey, 0, 0, out phkResult); - if (iRes != 0) - System.Diagnostics.Debug.WriteLine("RegOpenKeyEx: LastError=" + Marshal.GetLastWin32Error().ToString()); - return iRes; - } - static int mRegOpenKeyEx(uint hKey, string lpSubKey, out IntPtr phkResult){ - int iRes = RegOpenKeyEx(hKey, lpSubKey, 0, 0, out phkResult); - if (iRes != 0) - System.Diagnostics.Debug.WriteLine("RegOpenKeyEx: LastError=" + Marshal.GetLastWin32Error().ToString()); - return iRes; - } - - public static int RegDelKey(string lpSubKey) - { - IntPtr hKey; - int iRes = mRegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, out hKey); - iRes = RegDeleteKey(hKey, lpSubKey); - if (iRes != 0) - System.Diagnostics.Debug.WriteLine("RegDelKey: LastError=" + Marshal.GetLastWin32Error().ToString()); - - RegCloseKey(hKey); - return iRes; - } - - public static int RegDelKey(string lpSubKey, string sKey) - { - IntPtr hKey; - int iRes = mRegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, out hKey); - iRes = RegDeleteKey(hKey, sKey); - if (iRes != 0) - System.Diagnostics.Debug.WriteLine("RegDelKey: LastError=" + Marshal.GetLastWin32Error().ToString()); - RegCloseKey(hKey); - return iRes; - } } -} diff --git a/pocketHosts/pocketHosts/pocketHosts.Designer.cs b/pocketHosts/pocketHosts/pocketHosts.Designer.cs deleted file mode 100644 index ec39c80..0000000 --- a/pocketHosts/pocketHosts/pocketHosts.Designer.cs +++ /dev/null @@ -1,229 +0,0 @@ -namespace pocketHosts -{ - partial class pocketHosts - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - private System.Windows.Forms.MainMenu mainMenu1; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.mainMenu1 = new System.Windows.Forms.MainMenu(); - this.menuItem1 = new System.Windows.Forms.MenuItem(); - this.menuItem2 = new System.Windows.Forms.MenuItem(); - this.label1 = new System.Windows.Forms.Label(); - this.label2 = new System.Windows.Forms.Label(); - this.label3 = new System.Windows.Forms.Label(); - this.label4 = new System.Windows.Forms.Label(); - this.label5 = new System.Windows.Forms.Label(); - this.txtHost = new System.Windows.Forms.TextBox(); - this.listIP = new System.Windows.Forms.ComboBox(); - this.listAliases = new System.Windows.Forms.ComboBox(); - this.txtExpires = new System.Windows.Forms.TextBox(); - this.btnIPadd = new System.Windows.Forms.Button(); - this.btnAliasAdd = new System.Windows.Forms.Button(); - this.mnuSaveChanges = new System.Windows.Forms.MenuItem(); - this.listHosts = new System.Windows.Forms.ListBox(); - this.btnNew = new System.Windows.Forms.Button(); - this.btnRemove = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // mainMenu1 - // - this.mainMenu1.MenuItems.Add(this.menuItem1); - this.mainMenu1.MenuItems.Add(this.mnuSaveChanges); - // - // menuItem1 - // - this.menuItem1.MenuItems.Add(this.menuItem2); - this.menuItem1.Text = "File"; - // - // menuItem2 - // - this.menuItem2.Text = "Save All"; - this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click); - // - // label1 - // - this.label1.Location = new System.Drawing.Point(8, 7); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(84, 15); - this.label1.Text = "Hosts:"; - // - // label2 - // - this.label2.Location = new System.Drawing.Point(4, 121); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(59, 19); - this.label2.Text = "host:"; - // - // label3 - // - this.label3.Location = new System.Drawing.Point(4, 147); - this.label3.Name = "label3"; - this.label3.Size = new System.Drawing.Size(59, 19); - this.label3.Text = "ip:"; - // - // label4 - // - this.label4.Location = new System.Drawing.Point(4, 175); - this.label4.Name = "label4"; - this.label4.Size = new System.Drawing.Size(59, 19); - this.label4.Text = "aliases:"; - // - // label5 - // - this.label5.Location = new System.Drawing.Point(4, 205); - this.label5.Name = "label5"; - this.label5.Size = new System.Drawing.Size(59, 19); - this.label5.Text = "expires:"; - // - // txtHost - // - this.txtHost.Location = new System.Drawing.Point(69, 121); - this.txtHost.Name = "txtHost"; - this.txtHost.Size = new System.Drawing.Size(168, 21); - this.txtHost.TabIndex = 7; - // - // listIP - // - this.listIP.Location = new System.Drawing.Point(69, 147); - this.listIP.Name = "listIP"; - this.listIP.Size = new System.Drawing.Size(134, 22); - this.listIP.TabIndex = 8; - // - // listAliases - // - this.listAliases.Location = new System.Drawing.Point(69, 175); - this.listAliases.Name = "listAliases"; - this.listAliases.Size = new System.Drawing.Size(134, 22); - this.listAliases.TabIndex = 8; - // - // txtExpires - // - this.txtExpires.Location = new System.Drawing.Point(69, 203); - this.txtExpires.Name = "txtExpires"; - this.txtExpires.Size = new System.Drawing.Size(134, 21); - this.txtExpires.TabIndex = 9; - // - // btnIPadd - // - this.btnIPadd.Location = new System.Drawing.Point(209, 150); - this.btnIPadd.Name = "btnIPadd"; - this.btnIPadd.Size = new System.Drawing.Size(26, 18); - this.btnIPadd.TabIndex = 10; - this.btnIPadd.Text = "..."; - this.btnIPadd.Click += new System.EventHandler(this.btnIPadd_Click); - // - // btnAliasAdd - // - this.btnAliasAdd.Location = new System.Drawing.Point(209, 176); - this.btnAliasAdd.Name = "btnAliasAdd"; - this.btnAliasAdd.Size = new System.Drawing.Size(26, 18); - this.btnAliasAdd.TabIndex = 10; - this.btnAliasAdd.Text = "..."; - this.btnAliasAdd.Click += new System.EventHandler(this.btnAliasAdd_Click); - // - // mnuSaveChanges - // - this.mnuSaveChanges.Text = "SAVE change"; - this.mnuSaveChanges.Click += new System.EventHandler(this.mnuSaveChanges_Click); - // - // listHosts - // - this.listHosts.Location = new System.Drawing.Point(69, 7); - this.listHosts.Name = "listHosts"; - this.listHosts.Size = new System.Drawing.Size(166, 72); - this.listHosts.TabIndex = 16; - this.listHosts.SelectedIndexChanged += new System.EventHandler(this.listHosts_SelectedIndexChanged); - // - // btnNew - // - this.btnNew.Location = new System.Drawing.Point(159, 85); - this.btnNew.Name = "btnNew"; - this.btnNew.Size = new System.Drawing.Size(76, 22); - this.btnNew.TabIndex = 17; - this.btnNew.Text = "NEW entry"; - this.btnNew.Click += new System.EventHandler(this.btnNew_Click); - // - // btnRemove - // - this.btnRemove.Location = new System.Drawing.Point(69, 85); - this.btnRemove.Name = "btnRemove"; - this.btnRemove.Size = new System.Drawing.Size(72, 22); - this.btnRemove.TabIndex = 18; - this.btnRemove.Text = "remove"; - this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); - // - // pocketHosts - // - this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; - this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(240, 268); - this.Controls.Add(this.btnRemove); - this.Controls.Add(this.btnNew); - this.Controls.Add(this.listHosts); - this.Controls.Add(this.btnAliasAdd); - this.Controls.Add(this.btnIPadd); - this.Controls.Add(this.txtExpires); - this.Controls.Add(this.listAliases); - this.Controls.Add(this.listIP); - this.Controls.Add(this.txtHost); - this.Controls.Add(this.label5); - this.Controls.Add(this.label4); - this.Controls.Add(this.label3); - this.Controls.Add(this.label2); - this.Controls.Add(this.label1); - this.Menu = this.mainMenu1; - this.MinimizeBox = false; - this.Name = "pocketHosts"; - this.Text = "pocketHosts"; - this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Label label3; - private System.Windows.Forms.Label label4; - private System.Windows.Forms.Label label5; - private System.Windows.Forms.TextBox txtHost; - private System.Windows.Forms.ComboBox listIP; - private System.Windows.Forms.ComboBox listAliases; - private System.Windows.Forms.TextBox txtExpires; - private System.Windows.Forms.Button btnIPadd; - private System.Windows.Forms.Button btnAliasAdd; - private System.Windows.Forms.MenuItem menuItem1; - private System.Windows.Forms.MenuItem menuItem2; - private System.Windows.Forms.MenuItem mnuSaveChanges; - private System.Windows.Forms.ListBox listHosts; - private System.Windows.Forms.Button btnNew; - private System.Windows.Forms.Button btnRemove; - } -} - diff --git a/pocketHosts/pocketHosts/pocketHosts.cs b/pocketHosts/pocketHosts/pocketHosts.cs deleted file mode 100644 index 2927d37..0000000 --- a/pocketHosts/pocketHosts/pocketHosts.cs +++ /dev/null @@ -1,174 +0,0 @@ -using System; - -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace pocketHosts -{ - public partial class pocketHosts : Form - { - hostsentries hEntries; - - public pocketHosts() - { - InitializeComponent(); - hEntries = new hostsentries(); - - loadItems(); - } - - void loadItems() - { - listHosts.Items.Clear(); - foreach (hostsentry he in hEntries.allHosts.Values) - { - listHosts.Items.Add(he); - } - if(hEntries.allHosts.Count>0) - listHosts.SelectedIndex = 0; - } - - private void Form1_Closing(object sender, CancelEventArgs e) - { - if (MessageBox.Show("Are you sure to end now?", "EXIT?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel) - e.Cancel = true; - } - - private void listHosts_SelectedIndexChanged(object sender, EventArgs e) - { - hostsentry he = (hostsentry)listHosts.SelectedItem; - txtHost.Text = he.sHost; - listIP.Items.Clear(); - if (he.ipAddress.Count > 0) - { - foreach (System.Net.IPAddress ip in he.ipAddress) - listIP.Items.Add(ip.ToString()); - listIP.SelectedIndex = 0; - } - if (he.ipAddress6.Count > 0) - { - foreach (System.Net.IPAddress ip in he.ipAddress6) - listIP.Items.Add(ip.ToString()); - listIP.SelectedIndex = 0; - } - - listAliases.Items.Clear(); - if (he.aliases.Count > 0) - { - foreach (string s in he.aliases) - listAliases.Items.Add(s); - listAliases.SelectedIndex = 0; - } - - txtExpires.Text = he.expireTime.ToString(); - } - - private void btnIPadd_Click(object sender, EventArgs e) - { - List ipTmp=new List(); - foreach (object o in listIP.Items) - { - ipTmp.Add(System.Net.IPAddress.Parse(o.ToString())); - } - frmEnterIP dlg = new frmEnterIP(ipTmp); - if (dlg.ShowDialog() == DialogResult.OK) - { - listIP.Items.Clear(); - foreach (System.Net.IPAddress ip in dlg.m_ipList) - listIP.Items.Add(ip); - listIP.SelectedIndex = 0; - string sHost = txtHost.Text; - } - dlg.Dispose(); - } - - private void btnAliasAdd_Click(object sender, EventArgs e) - { - List sAlias=new List(); - foreach(object o in listAliases.Items) - sAlias.Add(o.ToString()); - frmEditAliases dlg = new frmEditAliases(sAlias); - if (dlg.ShowDialog() == DialogResult.OK) - { - listAliases.Items.Clear(); - foreach (string s in dlg.m_Aliases) - listAliases.Items.Add(s); - listAliases.SelectedIndex = 0; - } - dlg.Dispose(); - - } - - private void menuItem2_Click(object sender, EventArgs e) - { - int iCount = this.hEntries.saveAll(); - } - - private void mnuSaveChanges_Click(object sender, EventArgs e) - { - if (txtHost.Text.Length == 0 || listIP.Items.Count==0) - return; - hostsentry heTmp = (hostsentry) listHosts.SelectedItem; - - List lAliases = new List(); - List lIP4 = new List(); - List lIP6 = new List(); - ulong lExpireTime = Convert.ToUInt64(txtExpires.Text); - - foreach (object o in listAliases.Items) - { - lAliases.Add(o.ToString()); - } - - foreach (object o in listIP.Items) - { - try - { - System.Net.IPAddress ipTemp = System.Net.IPAddress.Parse(o.ToString()); - if(ipTemp.AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork) - lIP4.Add(ipTemp); - else if(ipTemp.AddressFamily==System.Net.Sockets.AddressFamily.InterNetworkV6) - lIP6.Add(ipTemp); - } - catch { } - } - - heTmp.sHost = txtHost.Text; - heTmp.aliases = lAliases; - if(lExpireTime!=0) - heTmp.expireTime = lExpireTime; - heTmp.ipAddress = lIP4; - heTmp.ipAddress6 = lIP6; - hEntries.addChangeEntry(heTmp); - hEntries.saveEntry(heTmp); - loadItems(); - } - - private void btnNew_Click(object sender, EventArgs e) - { - hostsentry he = new hostsentry(); - he.sHost = "NEW ENTRY - PLEASE CHANGE"; - he.ipAddress.Add(new System.Net.IPAddress(0)); - listHosts.Items.Insert(0, he); - listHosts.SelectedIndex = 0; - } - - private void btnRemove_Click(object sender, EventArgs e) - { - if (listHosts.SelectedIndex == -1) - return; - hostsentry he = (hostsentry)listHosts.SelectedItem; - if (MessageBox.Show("Are you sure to remove '" + he.sHost + "' now?", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Cancel) - return; - if (hEntries.removeEntry(he) == 1) - loadItems(); - else - MessageBox.Show("Remove failed"); - } - - } -} \ No newline at end of file diff --git a/pocketHosts/pocketHosts/pocketHosts.csproj b/pocketHosts/pocketHosts/pocketHosts.csproj deleted file mode 100644 index 6236af1..0000000 --- a/pocketHosts/pocketHosts/pocketHosts.csproj +++ /dev/null @@ -1,113 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {66FCCCAA-C4AC-41F4-9D11-187C78823C5C} - WinExe - Properties - pocketHosts - pocketHosts - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - PocketPC - 4118C335-430C-497f-BE48-11C3316B135E - 5.1 - pocketHosts - v2.0 - Windows Mobile 5.0 Pocket PC SDK - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - bin\Release\ - TRACE;$(PlatformFamilyName) - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - Form - - - frmEditAliases.cs - - - Form - - - frmEnterIP.cs - - - - - - Form - - - pocketHosts.cs - - - - - frmEditAliases.cs - - - frmEnterIP.cs - - - pocketHosts.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - - - - - - - - - \ No newline at end of file diff --git a/pocketHosts/pocketHosts/pocketHosts.resx b/pocketHosts/pocketHosts/pocketHosts.resx deleted file mode 100644 index c9d1ac5..0000000 --- a/pocketHosts/pocketHosts/pocketHosts.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - Pocket_PC - - - True - - \ No newline at end of file diff --git a/qrcode-scanner-live/BarcodeFormat.cs b/qrcode-scanner-live/BarcodeFormat.cs deleted file mode 100644 index 3cdf6bf..0000000 --- a/qrcode-scanner-live/BarcodeFormat.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - - /// Enumerates barcode formats known to this package. - /// * - /// - /// Sean Owen - /// - /// - public sealed class BarcodeFormat - { - - // No, we can't use an enum here. J2ME doesn't support it. - - /// QR Code 2D barcode format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'QR_CODE '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat QR_CODE = new BarcodeFormat("QR_CODE"); - - /// DataMatrix 2D barcode format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'DATAMATRIX '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat DATAMATRIX = new BarcodeFormat("DATAMATRIX"); - - /// UPC-E 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'UPC_E '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat UPC_E = new BarcodeFormat("UPC_E"); - - /// UPC-A 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'UPC_A '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat UPC_A = new BarcodeFormat("UPC_A"); - - /// EAN-8 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'EAN_8 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat EAN_8 = new BarcodeFormat("EAN_8"); - - /// EAN-13 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'EAN_13 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat EAN_13 = new BarcodeFormat("EAN_13"); - - /// Code 128 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'CODE_128 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat CODE_128 = new BarcodeFormat("CODE_128"); - - /// Code 39 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'CODE_39 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat CODE_39 = new BarcodeFormat("CODE_39"); - - /// ITF (Interleaved Two of Five) 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'ITF '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat ITF = new BarcodeFormat("ITF"); - - //UPGRADE_NOTE: Final was removed from the declaration of 'name '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - private System.String name; - - private BarcodeFormat(System.String name) - { - this.name = name; - } - - public override System.String ToString() - { - return name; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/BlackPointEstimationMethod.cs b/qrcode-scanner-live/BlackPointEstimationMethod.cs deleted file mode 100644 index 5217afe..0000000 --- a/qrcode-scanner-live/BlackPointEstimationMethod.cs +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing -{ - - ///

Enumerates different methods of sampling an imagine to estimate a black point.

- /// - ///
- /// srowen@google.com (Sean Owen), dswitkin@google.com (Daniel Switkin) - /// - public sealed class BlackPointEstimationMethod - { - /** - * Method probably most suitable for use with 2D barcdoe format. - */ - public static BlackPointEstimationMethod TWO_D_SAMPLING = new BlackPointEstimationMethod(); - /** - * Method probably most suitable for 1D barcode decoding, where one row at a time is sampled. - */ - public static BlackPointEstimationMethod ROW_SAMPLING = new BlackPointEstimationMethod(); - - private BlackPointEstimationMethod() { - // do nothing - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/BufferedImageMonochromeBitmapSource.cs b/qrcode-scanner-live/BufferedImageMonochromeBitmapSource.cs deleted file mode 100644 index 5871022..0000000 --- a/qrcode-scanner-live/BufferedImageMonochromeBitmapSource.cs +++ /dev/null @@ -1,181 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Drawing; -using MonochromeBitmapSource = com.google.zxing.MonochromeBitmapSource; -using BlackPointEstimationMethod = com.google.zxing.BlackPointEstimationMethod; -using BitArray = com.google.zxing.common.BitArray; -using BlackPointEstimator = com.google.zxing.common.BlackPointEstimator; - - -namespace com.google.zxing.client.j2se -{ - - ///

An implementation based upon {@link BufferedImage}. This provides access to the - /// underlying image as if it were a monochrome image. Behind the scenes, it is evaluating - /// the luminance of the underlying image by retrieving its pixels' RGB values.

- /// - ///
- /// srowen@google.com (Sean Owen), Daniel Switkin (dswitkin@google.com) - /// - public sealed class BufferedImageMonochromeBitmapSource : MonochromeBitmapSource - { - public bool iRotateSupported = false; - - public bool isRotateSupported() { - return iRotateSupported; - } - - public int getWidth() { - return (iRotateSupported ? image.Height : image.Width); - } - - public BlackPointEstimationMethod getLastEstimationMethod() { - return lastMethod; - } - - public int getHeight() - { - return (iRotateSupported ? image.Width : image.Height); - } - - - public MonochromeBitmapSource rotateCounterClockwise() { - return null; - } - - public BitArray getBlackColumn(int x, BitArray column, int startY, int getHeight) { - return null; - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Drawing.Bitmap image; - private int blackPoint; - private BlackPointEstimationMethod lastMethod; - private int lastArgument; - - private const int LUMINANCE_BITS = 5; - //UPGRADE_NOTE: Final was removed from the declaration of 'LUMINANCE_SHIFT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; - //UPGRADE_NOTE: Final was removed from the declaration of 'LUMINANCE_BUCKETS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; - - public BufferedImageMonochromeBitmapSource(System.Drawing.Bitmap image, bool rotated) - { - this.image = image; - blackPoint = 0x7F; - lastMethod = null; - lastArgument = 0; - iRotateSupported = rotated; - } - - public bool isBlack(int x, int y) - { - return (iRotateSupported ? computeRGBLuminance(image.GetPixel(y, x).ToArgb()) < blackPoint : computeRGBLuminance(image.GetPixel(x, y).ToArgb()) < blackPoint); - } - - int[] getRGB(int startx, int starty, int width) - { - int[] pixels = new int[width]; - for (int k = 0; k < width; k++) - { - Color c = (iRotateSupported ? image.GetPixel(starty, startx + k) : image.GetPixel(startx + k, starty)); - pixels[k] = ((int)c.R) << 16 | ((int)c.G) << 8 | ((int)c.B); - } - - return pixels; - } - - public BitArray getBlackRow(int y, BitArray row, int startX, int getWidth) - { - if (row == null) - { - row = new BitArray(getWidth); - } - else - { - row.clear(); - } - //UPGRADE_ISSUE: Method 'java.awt.image.BufferedImage.getRGB' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaawtimageBufferedImagegetRGB_int_int_int_int_int[]_int_int'" - int[] pixelRow = getRGB(startX, y, getWidth); - for (int i = 0; i < getWidth; i++) - { - if (computeRGBLuminance(pixelRow[i]) < blackPoint) - { - row.set(i); - } - } - return row; - } - - public void estimateBlackPoint(BlackPointEstimationMethod method, int argument) - { - if (!method.Equals(lastMethod) || argument != lastArgument) - { - int width = getWidth(); - int height = getHeight(); - int[] histogram = new int[LUMINANCE_BUCKETS]; - float biasTowardsWhite = 1.0f; - if (method.Equals(BlackPointEstimationMethod.TWO_D_SAMPLING)) - { - int minDimension = width < height?width:height; - int startI = height == minDimension?0:(height - width) >> 1; - int startJ = width == minDimension?0:(width - height) >> 1; - for (int n = 0; n < minDimension; n++) - { - int pixel = (iRotateSupported ? image.GetPixel(startI + n, startJ + n).ToArgb() : image.GetPixel(startJ + n, startI + n).ToArgb()); - histogram[computeRGBLuminance(pixel) >> LUMINANCE_SHIFT]++; - } - } - else if (method.Equals(BlackPointEstimationMethod.ROW_SAMPLING)) - { - if (argument < 0 || argument >= height) - { - throw new System.ArgumentException("Row is not within the image: " + argument); - } - biasTowardsWhite = 2.0f; - int[] rgbArray = getRGB(0, argument, width); - for (int x = 0; x < width; x++) - { - int l = computeRGBLuminance(rgbArray[x]); - histogram[l >> LUMINANCE_SHIFT]++; - } - } - else - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.ArgumentException("Unknown method: " + method); - } - blackPoint = BlackPointEstimator.estimate(histogram) << LUMINANCE_SHIFT; - lastMethod = method; - lastArgument = argument; - } - } - - /// Extracts luminance from a pixel from this source. By default, the source is assumed to use RGB, - /// so this implementation computes luminance is a function of a red, green and blue components as - /// follows: - /// - /// Y = 0.299R + 0.587G + 0.114B - /// - /// where R, G, and B are values in [0,1]. - /// - private static int computeRGBLuminance(int pixel) - { - // Coefficients add up to 1024 to make the divide into a fast shift - return (306 * ((pixel >> 16) & 0xFF) + 601 * ((pixel >> 8) & 0xFF) + 117 * (pixel & 0xFF)) >> 10; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/DecodeHintType.cs b/qrcode-scanner-live/DecodeHintType.cs deleted file mode 100644 index 8bc3190..0000000 --- a/qrcode-scanner-live/DecodeHintType.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class DecodeHintType - { - // No, we can't use an enum here. J2ME doesn't support it. - /** - * Unspecified, application-specific hint. Maps to an unspecified {@link Object}. - */ - public static DecodeHintType OTHER = new DecodeHintType(); - - /** - * Image is a pure monochrome image of a barcode. Doesn't matter what it maps to; - * use {@link Boolean#TRUE}. - */ - public static DecodeHintType PURE_BARCODE = new DecodeHintType(); - - /** - * Image is known to be of one of a few possible formats. - * Maps to a {@link java.util.Vector} of {@link BarcodeFormat}s. - */ - public static DecodeHintType POSSIBLE_FORMATS = new DecodeHintType(); - - /** - * Spend more time to try to find a barcode; optimize for accuracy, not speed. - * Doesn't matter what it maps to; use {@link Boolean#TRUE}. - */ - public static DecodeHintType TRY_HARDER = new DecodeHintType(); - - private DecodeHintType() { - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/EncodeHintType.cs b/qrcode-scanner-live/EncodeHintType.cs deleted file mode 100644 index 3ee58a1..0000000 --- a/qrcode-scanner-live/EncodeHintType.cs +++ /dev/null @@ -1,44 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class EncodeHintType - { - /** - * Specifies what degree of error correction to use, for example in QR Codes (type Integer). - */ - public static EncodeHintType ERROR_CORRECTION = new EncodeHintType(); - - private EncodeHintType() { - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/MonochromeBitmapSource.cs b/qrcode-scanner-live/MonochromeBitmapSource.cs deleted file mode 100644 index 58dd985..0000000 --- a/qrcode-scanner-live/MonochromeBitmapSource.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing -{ - - ///

Encapsulates a generic black-and-white bitmap -- a collection of pixels in two dimensions. - /// This unifies many possible representations, like AWT's BufferedImage.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public interface MonochromeBitmapSource - { - /** - * @param x horizontal offset, from left, of the pixel - * @param y vertical offset, from top, of the pixel - * @return true iff the pixel at (x,y) is black - */ - bool isBlack(int x, int y); - - /** - *

Returns an entire row of black/white pixels as an array of bits, where "true" means "black". - * This is a sort of "bulk get" operation intended to enable efficient access in - * certain situations.

- * - * @param y vertical offset, from top, of the row of pixels - * @param row if not null, {@link BitArray} to write pixels into. If null, a new {@link BitArray} - * is allocated and returned. - * @param startX horizontal offset, from left, from which to start getting pixels - * @param getWidth number of pixels to get from the row - * @return {@link BitArray} representing the (subset of the) row of pixels. If row parameter - * was not null, it is returned. - */ - BitArray getBlackRow(int y, BitArray row, int startX, int getWidth); - - /** - * Entirely analogous to {@link #getBlackRow(int, BitArray, int, int)} but gets a column. - */ - BitArray getBlackColumn(int x, BitArray column, int startY, int getHeight); - - /** - * @return height of underlying image - */ - int getHeight(); - - /** - * @return width of underlying image - */ - int getWidth(); - - /** - *

Estimates black point according to the given method, which is optionally parameterized by - * a single int argument. For {@link BlackPointEstimationMethod#ROW_SAMPLING}, this - * specifies the row to sample.

- * - *

The estimated value will be used in subsequent computations that rely on an estimated black - * point.

- * - * @param method black point estimation method - * @param argument method-specific argument - */ - void estimateBlackPoint(BlackPointEstimationMethod method, int argument); - - /** - * @return {@link BlackPointEstimationMethod} representing last sampling method used - */ - BlackPointEstimationMethod getLastEstimationMethod(); - - /** - *

Optional operation which returns an implementation based on the same underlying - * image, but which behaves as if the underlying image had been rotated 90 degrees - * counterclockwise. This is useful in the context of 1D barcodes and the - * {@link DecodeHintType#TRY_HARDER} decode hint, and is only intended to be - * used in non-resource-constrained environments. Hence, implementations - * of this class which are only used in resource-constrained mobile environments - * don't have a need to implement this.

- * - * @throws IllegalArgumentException if not supported - */ - MonochromeBitmapSource rotateCounterClockwise(); - - /** - * @return true iff rotation is supported - * @see #rotateCounterClockwise() - */ - bool isRotateSupported(); - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/MultiFormatReader.cs b/qrcode-scanner-live/MultiFormatReader.cs deleted file mode 100644 index 74a04ed..0000000 --- a/qrcode-scanner-live/MultiFormatReader.cs +++ /dev/null @@ -1,171 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; -using com.google.zxing.qrcode; -using com.google.zxing.oned; -using com.google.zxing.datamatrix; - -namespace com.google.zxing -{ - public sealed class MultiFormatReader : Reader - { - private Hashtable hints; - private ArrayList readers; - - /** - * This version of decode honors the intent of Reader.decode(MonochromeBitmapSource) in that it - * passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly. - * Use setHints() followed by decodeWithState() for continuous scan applications. - * - * @param image The pixel data to decode - * @return The contents of the image - * @throws ReaderException Any errors which occurred - */ - public Result decode(MonochromeBitmapSource image){ - try{ - setHints(null); - return decodeInternal(image); - } - catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - /** - * Decode an image using the hints provided. Does not honor existing state. - * - * @param image The pixel data to decode - * @param hints The hints to use, clearing the previous state. - * @return The contents of the image - * @throws ReaderException Any errors which occurred - */ - public Result decode(MonochromeBitmapSource image, Hashtable hints){ - try{ - setHints(hints); - return decodeInternal(image); - }catch(Exception e){ - throw new ReaderException (e.Message); - } - } - - /** - * Decode an image using the state set up by calling setHints() previously. Continuous scan - * clients will get a large speed increase by using this instead of decode(). - * - * @param image The pixel data to decode - * @return The contents of the image - * @throws ReaderException Any errors which occurred - */ - public Result decodeWithState(MonochromeBitmapSource image){ - try{ - // Make sure to set up the default state so we don't crash - if (readers == null) { - setHints(null); - } - return decodeInternal(image); - }catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - /** - * This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls - * to decodeWithState(image) can reuse the same set of readers without reallocating memory. This - * is important for performance in continuous scan clients. - * - * @param hints The set of hints to use for subsequent calls to decode(image) - */ - public void setHints(Hashtable hints) { - this.hints = hints; - - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - - ArrayList possibleFormats = hints == null ? null : (ArrayList)hints[(DecodeHintType.POSSIBLE_FORMATS)]; - readers = new ArrayList(); - if (possibleFormats != null) - { - bool addOneDReader = - possibleFormats.Contains(BarcodeFormat.UPC_A) || - possibleFormats.Contains(BarcodeFormat.UPC_E) || - possibleFormats.Contains(BarcodeFormat.EAN_13) || - possibleFormats.Contains(BarcodeFormat.EAN_8) || - possibleFormats.Contains(BarcodeFormat.CODE_39) || - possibleFormats.Contains(BarcodeFormat.CODE_128); - // Put 1D readers upfront in "normal" mode - - if (addOneDReader && !tryHarder) - { - readers.Add(new MultiFormatOneDReader(hints)); - } - - if (possibleFormats.Contains(BarcodeFormat.QR_CODE)) - { - readers.Add(new QRCodeReader()); - } - // TODO re-enable once Data Matrix is ready - if (possibleFormats.Contains(BarcodeFormat.DATAMATRIX)) { - readers.Add(new DataMatrixReader()); - } - // At end in "try harder" mode - if (addOneDReader && tryHarder) - { - readers.Add(new MultiFormatOneDReader(hints)); - } - } - - if (readers.Count == 0) - { - if (!tryHarder) - { - readers.Add(new MultiFormatOneDReader(hints)); - } - readers.Add(new QRCodeReader()); - // TODO re-enable once Data Matrix is ready - readers.Add(new DataMatrixReader()); - if (tryHarder) - { - readers.Add(new MultiFormatOneDReader(hints)); - } - } - } - - private Result decodeInternal(MonochromeBitmapSource image) { - try - { - int size = readers.Count; - for (int i = 0; i < size; i++) - { - Reader reader = (Reader)readers[i]; - try - { - return reader.decode(image, hints); - } - catch (ReaderException re) - { - // continue - } - } - - throw new ReaderException(""); - } - catch (Exception e) { - throw new ReaderException(e.Message); - } - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/MultiFormatWriter.cs b/qrcode-scanner-live/MultiFormatWriter.cs deleted file mode 100644 index 42f244c..0000000 --- a/qrcode-scanner-live/MultiFormatWriter.cs +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; -using com.google.zxing.qrcode; -using com.google.zxing.common; - -namespace com.google.zxing -{ - public sealed class MultiFormatWriter : Writer - { - public ByteMatrix encode(String contents, BarcodeFormat format, int width,int height) { - return encode(contents, format, width, height,null); - } - - public ByteMatrix encode(String contents, BarcodeFormat format, int width, int height,Hashtable hints){ - if (format == BarcodeFormat.QR_CODE) { - return new QRCodeWriter().encode(contents, format, width, height, hints); - } else { - throw new ArgumentException("No encoder available for format " + format); - } - } - } -} - - - diff --git a/qrcode-scanner-live/Properties/AssemblyInfo.cs b/qrcode-scanner-live/Properties/AssemblyInfo.cs deleted file mode 100644 index 672bae1..0000000 --- a/qrcode-scanner-live/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("QRCodeLib3")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("QRCodeLib3")] -[assembly: AssemblyCopyright("Copyright © 2009")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("869eed67-0f3d-424a-8e40-d8bb61c8dc7b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/qrcode-scanner-live/README b/qrcode-scanner-live/README deleted file mode 100644 index 49dcb93..0000000 --- a/qrcode-scanner-live/README +++ /dev/null @@ -1 +0,0 @@ -This port was contributed and is maintained by Mohamad Fairol. \ No newline at end of file diff --git a/qrcode-scanner-live/Reader.cs b/qrcode-scanner-live/Reader.cs deleted file mode 100644 index 631cab8..0000000 --- a/qrcode-scanner-live/Reader.cs +++ /dev/null @@ -1,45 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; - -namespace com.google.zxing -{ - public interface Reader - { - /** - * Locates and decodes a barcode in some format within an image. - * - * @param image image of barcode to decode - * @return String which the barcode encodes - * @throws ReaderException if the barcode cannot be located or decoded for any reason - */ - Result decode(MonochromeBitmapSource image); - - /** - * Locates and decodes a barcode in some format within an image. This method also accepts - * hints, each possibly associated to some data, which may help the implementation decode. - * - * @param image image of barcode to decode - * @param hints passed as a {@link Hashtable} from {@link DecodeHintType} to aribtrary data. The - * meaning of the data depends upon the hint type. The implementation may or may not do - * anything with these hints. - * @return String which the barcode encodes - * @throws ReaderException if the barcode cannot be located or decoded for any reason - */ - Result decode(MonochromeBitmapSource image, Hashtable hints); - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live/ReaderException.cs b/qrcode-scanner-live/ReaderException.cs deleted file mode 100644 index c84928a..0000000 --- a/qrcode-scanner-live/ReaderException.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing -{ - - /// The general exception class throw when something goes wrong during decoding of a barcode. - /// This includes, but is not limited to, failing checksums / error correction algorithms, being - /// unable to locate finder timing patterns, and so on. - /// - /// - /// srowen@google.com (Sean Owen) - /// - //[Serializable] - public sealed class ReaderException : System.Exception - { - - private static ReaderException instance = new ReaderException(); - - public ReaderException() { - // do nothing - } - - public ReaderException(System.String message): base(message) - { - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/Result.cs b/qrcode-scanner-live/Result.cs deleted file mode 100644 index 1bc5841..0000000 --- a/qrcode-scanner-live/Result.cs +++ /dev/null @@ -1,106 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; - -namespace com.google.zxing -{ - - /// The general exception class throw when something goes wrong during decoding of a barcode. - /// This includes, but is not limited to, failing checksums / error correction algorithms, being - /// unable to locate finder timing patterns, and so on. - /// - /// - /// srowen@google.com (Sean Owen) - /// - //[Serializable] - public sealed class Result - { - private String text; - private sbyte[] rawBytes; - private ResultPoint[] resultPoints; - private BarcodeFormat format; - private Hashtable resultMetadata; - - public Result(String text, - sbyte[] rawBytes, - ResultPoint[] resultPoints, - BarcodeFormat format) { - if (text == null && rawBytes == null) { - throw new ArgumentException("Text and bytes are null"); - } - this.text = text; - this.rawBytes = rawBytes; - this.resultPoints = resultPoints; - this.format = format; - this.resultMetadata = null; - } - - /** - * @return raw text encoded by the barcode, if applicable, otherwise null - */ - public String getText() { - return text; - } - - /** - * @return raw bytes encoded by the barcode, if applicable, otherwise null - */ - public sbyte[] getRawBytes() { - return rawBytes; - } - - /** - * @return points related to the barcode in the image. These are typically points - * identifying finder patterns or the corners of the barcode. The exact meaning is - * specific to the type of barcode that was decoded. - */ - public ResultPoint[] getResultPoints() { - return resultPoints; - } - - /** - * @return {@link BarcodeFormat} representing the format of the barcode that was recognized and decoded - */ - public BarcodeFormat getBarcodeFormat() { - return format; - } - - /** - * @return {@link Hashtable} mapping {@link ResultMetadataType} keys to values. May be null. - * This contains optional metadata about what was detected about the barcode, like orientation. - */ - public Hashtable getResultMetadata() { - return resultMetadata; - } - - public void putMetadata(ResultMetadataType type, Object value) { - if (resultMetadata == null) { - resultMetadata = new Hashtable(3); - } - resultMetadata.Add(type, value); - } - - public String toString() { - if (text == null) { - return "[" + rawBytes.Length + " bytes]"; - } else { - return text; - } - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/ResultMetadataType.cs b/qrcode-scanner-live/ResultMetadataType.cs deleted file mode 100644 index 5a37130..0000000 --- a/qrcode-scanner-live/ResultMetadataType.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; - -namespace com.google.zxing -{ - - /// The general exception class throw when something goes wrong during decoding of a barcode. - /// This includes, but is not limited to, failing checksums / error correction algorithms, being - /// unable to locate finder timing patterns, and so on. - /// - /// - /// srowen@google.com (Sean Owen) - /// - //[Serializable] - public sealed class ResultMetadataType - { - // No, we can't use an enum here. J2ME doesn't support it. - - /** - * Unspecified, application-specific metadata. Maps to an unspecified {@link Object}. - */ - public static ResultMetadataType OTHER = new ResultMetadataType(); - - /** - * Denotes the likely approximate orientation of the barcode in the image. This value - * is given as degrees rotated clockwise from the normal, upright orientation. - * For example a 1D barcode which was found by reading top-to-bottom would be - * said to have orientation "90". This key maps to an {@link Integer} whose - * value is in the range [0,360). - */ - public static ResultMetadataType ORIENTATION = new ResultMetadataType(); - - /** - *

2D barcode formats typically encode text, but allow for a sort of 'byte mode' - * which is sometimes used to encode binary data. While {@link Result} makes available - * the complete raw bytes in the barcode for these formats, it does not offer the bytes - * from the byte segments alone.

- * - *

This maps to a {@link java.util.Vector} of byte arrays corresponding to the - * raw bytes in the byte segments in the barcode, in order.

- */ - public static ResultMetadataType BYTE_SEGMENTS = new ResultMetadataType(); - - private ResultMetadataType() { - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/ResultPoint.cs b/qrcode-scanner-live/ResultPoint.cs deleted file mode 100644 index 378c0cd..0000000 --- a/qrcode-scanner-live/ResultPoint.cs +++ /dev/null @@ -1,38 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public interface ResultPoint - { - float getX(); - float getY(); - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/SupportClass.cs b/qrcode-scanner-live/SupportClass.cs deleted file mode 100644 index 5058d7d..0000000 --- a/qrcode-scanner-live/SupportClass.cs +++ /dev/null @@ -1,456 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - - /// - /// This interface should be implemented by any class whose instances are intended - /// to be executed by a thread. - /// - public interface IThreadRunnable - { - /// - /// This method has to be implemented in order that starting of the thread causes the object's - /// run method to be called in that separately executing thread. - /// - void Run(); - } - -/// -/// Contains conversion support elements such as classes, interfaces and static methods. -/// -public class SupportClass -{ - - - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static int URShift(int number, int bits) - { - if ( number >= 0) - return number >> bits; - else - return (number >> bits) + (2 << ~bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static int URShift(int number, long bits) - { - return URShift(number, (int)bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static long URShift(long number, int bits) - { - if ( number >= 0) - return number >> bits; - else - return (number >> bits) + (2L << ~bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static long URShift(long number, long bits) - { - return URShift(number, (int)bits); - } - - /*******************************/ - /// - /// Copies an array of chars obtained from a String into a specified array of chars - /// - /// The String to get the chars from - /// Position of the String to start getting the chars - /// Position of the String to end getting the chars - /// Array to return the chars - /// Position of the destination array of chars to start storing the chars - /// An array of chars - public static void GetCharsFromString(System.String sourceString, int sourceStart, int sourceEnd, char[] destinationArray, int destinationStart) - { - int sourceCounter; - int destinationCounter; - sourceCounter = sourceStart; - destinationCounter = destinationStart; - while (sourceCounter < sourceEnd) - { - destinationArray[destinationCounter] = (char) sourceString[sourceCounter]; - sourceCounter++; - destinationCounter++; - } - } - - /*******************************/ - /// - /// Converts an array of sbytes to an array of bytes - /// - /// The array of sbytes to be converted - /// The new array of bytes - public static byte[] ToByteArray(sbyte[] sbyteArray) - { - byte[] byteArray = null; - - if (sbyteArray != null) - { - byteArray = new byte[sbyteArray.Length]; - for(int index=0; index < sbyteArray.Length; index++) - byteArray[index] = (byte) sbyteArray[index]; - } - return byteArray; - } - - /// - /// Converts a string to an array of bytes - /// - /// The string to be converted - /// The new array of bytes - public static byte[] ToByteArray(System.String sourceString) - { - return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); - } - - /// - /// Converts a array of object-type instances to a byte-type array. - /// - /// Array to convert. - /// An array of byte type elements. - public static byte[] ToByteArray(System.Object[] tempObjectArray) - { - byte[] byteArray = null; - if (tempObjectArray != null) - { - byteArray = new byte[tempObjectArray.Length]; - for (int index = 0; index < tempObjectArray.Length; index++) - byteArray[index] = (byte)tempObjectArray[index]; - } - return byteArray; - } - - /*******************************/ - /// - /// Sets the capacity for the specified ArrayList - /// - /// The ArrayList which capacity will be set - /// The new capacity value - public static void SetCapacity(System.Collections.ArrayList vector, int newCapacity) - { - if (newCapacity > vector.Count) - vector.AddRange(new Array[newCapacity-vector.Count]); - else if (newCapacity < vector.Count) - vector.RemoveRange(newCapacity, vector.Count - newCapacity); - vector.Capacity = newCapacity; - } - - - - /*******************************/ - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static long Identity(long literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static ulong Identity(ulong literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static float Identity(float literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static double Identity(double literal) - { - return literal; - } - - /*******************************/ - /// - /// Support class used to handle threads - /// - public class ThreadClass : IThreadRunnable - { - /// - /// The instance of System.Threading.Thread - /// - private System.Threading.Thread threadField; - - /// - /// Initializes a new instance of the ThreadClass class - /// - public ThreadClass() - { - threadField = new System.Threading.Thread(new System.Threading.ThreadStart(Run)); - } - - /// - /// Initializes a new instance of the Thread class. - /// - /// The name of the thread - public ThreadClass(System.String Name) - { - threadField = new System.Threading.Thread(new System.Threading.ThreadStart(Run)); - this.Name = Name; - } - - /// - /// Initializes a new instance of the Thread class. - /// - /// A ThreadStart delegate that references the methods to be invoked when this thread begins executing - public ThreadClass(System.Threading.ThreadStart Start) - { - threadField = new System.Threading.Thread(Start); - } - - /// - /// Initializes a new instance of the Thread class. - /// - /// A ThreadStart delegate that references the methods to be invoked when this thread begins executing - /// The name of the thread - public ThreadClass(System.Threading.ThreadStart Start, System.String Name) - { - threadField = new System.Threading.Thread(Start); - this.Name = Name; - } - - /// - /// This method has no functionality unless the method is overridden - /// - public virtual void Run() - { - } - - /// - /// Causes the operating system to change the state of the current thread instance to ThreadState.Running - /// - public virtual void Start() - { - threadField.Start(); - } - - ///// - ///// Interrupts a thread that is in the WaitSleepJoin thread state - ///// - //public virtual void Interrupt() - //{ - // threadField.Interrupt(); - //} - - /// - /// Gets the current thread instance - /// - public System.Threading.Thread Instance - { - get - { - return threadField; - } - set - { - threadField = value; - } - } - - /// - /// Gets or sets the name of the thread - /// - public System.String Name - { - get - { - return threadField.Name; - } - set - { - if (threadField.Name == null) - threadField.Name = value; - } - } - - /// - /// Gets or sets a value indicating the scheduling priority of a thread - /// - public System.Threading.ThreadPriority Priority - { - get - { - return threadField.Priority; - } - set - { - threadField.Priority = value; - } - } - - ///// - ///// Gets a value indicating the execution status of the current thread - ///// - //public bool IsAlive - //{ - // get - // { - // return threadField.IsAlive; - // } - //} - - /// - /// Gets or sets a value indicating whether or not a thread is a background thread. - /// - public bool IsBackground - { - get - { - return threadField.IsBackground; - } - set - { - threadField.IsBackground = value; - } - } - - /// - /// Blocks the calling thread until a thread terminates - /// - public void Join() - { - threadField.Join(); - } - - /// - /// Blocks the calling thread until a thread terminates or the specified time elapses - /// - /// Time of wait in milliseconds - public void Join(int MiliSeconds) - { - lock(this) - { - threadField.Join(MiliSeconds); - } - } - - ///// - ///// Blocks the calling thread until a thread terminates or the specified time elapses - ///// - ///// Time of wait in milliseconds - ///// Time of wait in nanoseconds - //public void Join(long MiliSeconds, int NanoSeconds) - //{ - // lock(this) - // { - // threadField.Join(new System.TimeSpan(MiliSeconds * 10000 + NanoSeconds * 100)); - // } - //} - - ///// - ///// Resumes a thread that has been suspended - ///// - //public void Resume() - //{ - // threadField.Resume(); - //} - - /// - /// Raises a ThreadAbortException in the thread on which it is invoked, - /// to begin the process of terminating the thread. Calling this method - /// usually terminates the thread - /// - public void Abort() - { - threadField.Abort(); - } - - /// - /// Raises a ThreadAbortException in the thread on which it is invoked, - /// to begin the process of terminating the thread while also providing - /// exception information about the thread termination. - /// Calling this method usually terminates the thread. - /// - /// An object that contains application-specific information, such as state, which can be used by the thread being aborted - public void Abort(System.Object stateInfo) - { - lock(this) - { - threadField.Abort(stateInfo); - } - } - - ///// - ///// Suspends the thread, if the thread is already suspended it has no effect - ///// - //public void Suspend() - //{ - // threadField.Suspend(); - //} - - /// - /// Obtain a String that represents the current Object - /// - /// A String that represents the current Object - public override System.String ToString() - { - return "Thread[" + Name + "," + Priority.ToString() + "," + "" + "]"; - } - - /// - /// Gets the currently running thread - /// - /// The currently running thread - public static ThreadClass Current() - { - ThreadClass CurrentThread = new ThreadClass(); - CurrentThread.Instance = System.Threading.Thread.CurrentThread; - return CurrentThread; - } - } - - -} diff --git a/qrcode-scanner-live/Writer.cs b/qrcode-scanner-live/Writer.cs deleted file mode 100644 index dcba9ec..0000000 --- a/qrcode-scanner-live/Writer.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - using ByteMatrix = com.google.zxing.common.ByteMatrix; - /// The base class for all objects which encode/generate a barcode image. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public interface Writer - { - /// Encode a barcode using the default settings. - /// * - /// - /// The contents to encode in the barcode - /// - /// The barcode format to generate - /// - /// The preferred width in pixels - /// - /// The preferred height in pixels - /// - /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) - /// - /// - ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height); - /// * - /// - /// The contents to encode in the barcode - /// - /// The barcode format to generate - /// - /// The preferred width in pixels - /// - /// The preferred height in pixels - /// - /// Additional parameters to supply to the encoder - /// - /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) - /// - /// - ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height, System.Collections.Hashtable hints); - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/WriterException.cs b/qrcode-scanner-live/WriterException.cs deleted file mode 100644 index 6148a1a..0000000 --- a/qrcode-scanner-live/WriterException.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - - /// A base class which covers the range of exceptions which may occur when encoding a barcode using - /// the Writer framework. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class WriterException : System.Exception - { - - public WriterException() - : base() - { - } - - public WriterException(System.String message) - : base(message) - { - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/bin/Debug/com.google.zxing.dll b/qrcode-scanner-live/bin/Debug/com.google.zxing.dll deleted file mode 100644 index ce6f612..0000000 Binary files a/qrcode-scanner-live/bin/Debug/com.google.zxing.dll and /dev/null differ diff --git a/qrcode-scanner-live/bin/Debug/com.google.zxing.dll.mdb b/qrcode-scanner-live/bin/Debug/com.google.zxing.dll.mdb deleted file mode 100644 index fb4c668..0000000 Binary files a/qrcode-scanner-live/bin/Debug/com.google.zxing.dll.mdb and /dev/null differ diff --git a/qrcode-scanner-live/bin/Release/com.google.zxing.dll b/qrcode-scanner-live/bin/Release/com.google.zxing.dll deleted file mode 100644 index 107727e..0000000 Binary files a/qrcode-scanner-live/bin/Release/com.google.zxing.dll and /dev/null differ diff --git a/qrcode-scanner-live/bin/Release/com.google.zxing.pdb b/qrcode-scanner-live/bin/Release/com.google.zxing.pdb deleted file mode 100644 index 3aef474..0000000 Binary files a/qrcode-scanner-live/bin/Release/com.google.zxing.pdb and /dev/null differ diff --git a/qrcode-scanner-live/common/BaseMonochromeBitmapSource.cs b/qrcode-scanner-live/common/BaseMonochromeBitmapSource.cs deleted file mode 100644 index 9d2ad27..0000000 --- a/qrcode-scanner-live/common/BaseMonochromeBitmapSource.cs +++ /dev/null @@ -1,196 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using BitArray = com.google.zxing.common.BitArray; -using com.google.zxing.common; -namespace com.google.zxing -{ - /** - * @author dswitkin@google.com (Daniel Switkin) - */ - public abstract class BaseMonochromeBitmapSource: MonochromeBitmapSource - { - private static int LUMINANCE_BITS = 5; - private static int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; - private static int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; - - private int blackPoint; - private BlackPointEstimationMethod lastMethod; - private int lastArgument; - private int[] luminances; - - protected BaseMonochromeBitmapSource() { - blackPoint = 0x7F; - lastMethod = null; - lastArgument = 0; - } - - private void initLuminances() { - if (luminances == null) { - int width = getWidth(); - int height = getHeight(); - int max = width > height ? width : height; - luminances = new int[max]; - } - } - - public bool isBlack(int x, int y) { - return getLuminance(x, y) < blackPoint; - } - - public BitArray getBlackRow(int y, BitArray row, int startX, int getWidth) { - if (row == null || row.getSize() < getWidth) { - row = new BitArray(getWidth); - } else { - row.clear(); - } - - // Reuse the same int array each time - initLuminances(); - luminances = getLuminanceRow(y, luminances); - - // If the current decoder calculated the blackPoint based on one row, assume we're trying to - // decode a 1D barcode, and apply some sharpening. - if (lastMethod.Equals(BlackPointEstimationMethod.ROW_SAMPLING)) { - int left = luminances[startX]; - int center = luminances[startX + 1]; - for (int x = 1; x < getWidth - 1; x++) { - int right = luminances[startX + x + 1]; - // Simple -1 4 -1 box filter with a weight of 2 - int luminance = ((center << 2) - left - right) >> 1; - if (luminance < blackPoint) { - row.set(x); - } - left = center; - center = right; - } - } else { - for (int x = 0; x < getWidth; x++) { - if (luminances[startX + x] < blackPoint) { - row.set(x); - } - } - } - return row; - } - - public BitArray getBlackColumn(int x, BitArray column, int startY, int getHeight) { - if (column == null || column.getSize() < getHeight) { - column = new BitArray(getHeight); - } else { - column.clear(); - } - - // Reuse the same int array each time - initLuminances(); - luminances = getLuminanceColumn(x, luminances); - - // We don't handle "row sampling" specially here - for (int y = 0; y < getHeight; y++) { - if (luminances[startY + y] < blackPoint) { - column.set(y); - } - } - return column; - } - - public void estimateBlackPoint(BlackPointEstimationMethod method, int argument){ - if (!method.Equals(lastMethod) || argument != lastArgument) { - int width = getWidth(); - int height = getHeight(); - int[] histogram = new int[LUMINANCE_BUCKETS]; - if (method.Equals(BlackPointEstimationMethod.TWO_D_SAMPLING)) { - int minDimension = width < height ? width : height; - int startX = (width - minDimension) >> 1; - int startY = (height - minDimension) >> 1; - for (int n = 0; n < minDimension; n++) { - int luminance = getLuminance(startX + n, startY + n); - histogram[luminance >> LUMINANCE_SHIFT]++; - } - } else if (method.Equals(BlackPointEstimationMethod.ROW_SAMPLING)) { - if (argument < 0 || argument >= height) { - throw new Exception("Row is not within the image: " + argument); - } - initLuminances(); - luminances = getLuminanceRow(argument, luminances); - for (int x = 0; x < width; x++) { - histogram[luminances[x] >> LUMINANCE_SHIFT]++; - } - } else { - throw new Exception("Unknown method: " + method); - } - blackPoint = BlackPointEstimator.estimate(histogram) << LUMINANCE_SHIFT; - lastMethod = method; - lastArgument = argument; - } - } - - public BlackPointEstimationMethod getLastEstimationMethod() { - return lastMethod; - } - - public MonochromeBitmapSource rotateCounterClockwise() { - throw new Exception("Rotate not supported"); - } - - public bool isRotateSupported() { - return false; - } - - // These two methods should not need to exist because they are defined in the interface that - // this abstract class implements. However this seems to cause problems on some Nokias. - // So we write these redundant declarations. - - public abstract int getHeight(); - - public abstract int getWidth(); - - /** - * Retrieves the luminance at the pixel x,y in the bitmap. This method is only used for estimating - * the black point and implementing getBlackRow() - it is not meant for decoding, hence it is not - * part of MonochromeBitmapSource itself, and is protected. - * - * @param x The x coordinate in the image. - * @param y The y coordinate in the image. - * @return The luminance value between 0 and 255. - */ - protected abstract int getLuminance(int x, int y); - - /** - * This is the main mechanism for retrieving luminance data. It is dramatically more efficient - * than repeatedly calling getLuminance(). As above, this is not meant for decoders. - * - * @param y The row to fetch - * @param row The array to write luminance values into. It is strongly suggested that you - * allocate this yourself, making sure row.length >= getWidth(), and reuse the same - * array on subsequent calls for performance. If you pass null, you will be flogged, - * but then I will take pity on you and allocate a sufficient array internally. - * @return The array containing the luminance data. This is the same as row if it was usable. - */ - protected abstract int[] getLuminanceRow(int y, int[] row); - - /** - * The same as getLuminanceRow(), but for columns. - * - * @param x The column to fetch - * @param column The array to write luminance values into. See above. - * @return The array containing the luminance data. - */ - protected abstract int[] getLuminanceColumn(int x, int[] column); - - } -} - - diff --git a/qrcode-scanner-live/common/BitArray.cs b/qrcode-scanner-live/common/BitArray.cs deleted file mode 100644 index 84a8fe4..0000000 --- a/qrcode-scanner-live/common/BitArray.cs +++ /dev/null @@ -1,178 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class BitArray - { - // TODO: I have changed these members to be public so ProGuard can inline get() and set(). Ideally - // they'd be private and we'd use the -allowaccessmodification flag, but Dalvik rejects the - // resulting binary at runtime on Android. If we find a solution to this, these should be changed - // back to private. - public int[] bits; - public int Size; - - public BitArray(int size) { - if (size < 1) { - throw new Exception("size must be at least 1"); - } - this.Size = size; - this.bits = makeArray(size); - } - - public int getSize() { - return Size; - } - - /** - * @param i bit to get - * @return true iff bit i is set - */ - public bool get(int i) { - return (bits[i >> 5] & (1 << (i & 0x1F))) != 0; - } - - /** - * Sets bit i. - * - * @param i bit to set - */ - public void set(int i) { - bits[i >> 5] |= 1 << (i & 0x1F); - } - - /** - * Sets a block of 32 bits, starting at bit i. - * - * @param i first bit to set - * @param newBits the new value of the next 32 bits. Note again that the least-significant bit - * corresponds to bit i, the next-least-significant to i+1, and so on. - */ - public void setBulk(int i, int newBits) { - bits[i >> 5] = newBits; - } - - /** - * Clears all bits (sets to false). - */ - public void clear() { - int max = bits.Length; - for (int i = 0; i < max; i++) { - bits[i] = 0; - } - } - - /** - * Efficient method to check if a range of bits is set, or not set. - * - * @param start start of range, inclusive. - * @param end end of range, exclusive - * @param value if true, checks that bits in range are set, otherwise checks that they are not set - * @return true iff all bits are set or not set in range, according to value argument - * @throws IllegalArgumentException if end is less than or equal to start - */ - public bool isRange(int start, int end, bool value) { - if (end < start) { - throw new Exception(); - } - if (end == start) { - return true; // empty range matches - } - end--; // will be easier to treat this as the last actually set bit -- inclusive - int firstInt = start >> 5; - int lastInt = end >> 5; - for (int i = firstInt; i <= lastInt; i++) { - int firstBit = i > firstInt ? 0 : start & 0x1F; - int lastBit = i < lastInt ? 31 : end & 0x1F; - int mask; - if (firstBit == 0 && lastBit == 31) { - mask = -1; - } else { - mask = 0; - for (int j = firstBit; j <= lastBit; j++) { - mask |= 1 << j; - } - } - - // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, - // equals the mask, or we're looking for 0s and the masked portion is not all 0s - if ((bits[i] & mask) != (value ? mask : 0)) { - return false; - } - } - return true; - } - - /** - * @return underlying array of ints. The first element holds the first 32 bits, and the least - * significant bit is bit 0. - */ - public int[] getBitArray() { - return bits; - } - - /** - * Reverses all bits in the array. - */ - public void reverse() { - int[] newBits = makeArray(Size); - int max = newBits.Length; - for (int i = 0; i < max; i++) { - newBits[i] = 0; - } - int size = this.Size; - for (int i = 0; i < size; i++) { - if (get(size - i - 1)) { - newBits[i >> 5] |= 1 << (i & 0x1F); - } - } - bits = newBits; - } - - private static int[] makeArray(int size) { - int arraySize = size >> 5; - if ((size & 0x1F) != 0) { - arraySize++; - } - return new int[arraySize]; - } - - public String toString() { - StringBuilder result = new StringBuilder(Size); - for (int i = 0; i < Size; i++) { - if (i % 8 == 0) { - result.Append(' '); - } - result.Append(get(i) ? 'X' : '.'); - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/BitMatrix.cs b/qrcode-scanner-live/common/BitMatrix.cs deleted file mode 100644 index 3d9a993..0000000 --- a/qrcode-scanner-live/common/BitMatrix.cs +++ /dev/null @@ -1,129 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class BitMatrix - { - private int dimension; - private int[] bits; - - public BitMatrix(int dimension) { - if (dimension < 1) { - throw new Exception("dimension must be at least 1"); - } - this.dimension = dimension; - int numBits = dimension * dimension; - int arraySize = numBits >> 5; // one int per 32 bits - if ((numBits & 0x1F) != 0) { // plus one more if there are leftovers - arraySize++; - } - bits = new int[arraySize]; - } - - /** - * @param i row offset - * @param j column offset - * @return value of given bit in matrix - */ - public bool get(int i, int j) { - int offset = i + dimension * j; - //return ((bits[offset >> 5] >>> (offset & 0x1F)) & 0x01) != 0; - return ((SupportClass.URShift(bits[offset >> 5], (offset & 0x1F))) & 0x01) != 0; - } - - /** - *

Sets the given bit to true.

- * - * @param i row offset - * @param j column offset - */ - public void set(int i, int j) { - int offset = i + dimension * j; - bits[offset >> 5] |= 1 << (offset & 0x1F); - } - - /** - *

Sets a square region of the bit matrix to true.

- * - * @param topI row offset of region's top-left corner (inclusive) - * @param leftJ column offset of region's top-left corner (inclusive) - * @param height height of region - * @param width width of region - */ - public void setRegion(int topI, int leftJ, int height, int width) { - if (topI < 0 || leftJ < 0) { - throw new Exception("topI and leftJ must be nonnegative"); - } - if (height < 1 || width < 1) { - throw new Exception("height and width must be at least 1"); - } - int maxJ = leftJ + width; - int maxI = topI + height; - if (maxI > dimension || maxJ > dimension) { - throw new Exception( - "topI + height and leftJ + width must be <= matrix dimension"); - } - for (int j = leftJ; j < maxJ; j++) { - int jOffset = dimension * j; - for (int i = topI; i < maxI; i++) { - int offset = i + jOffset; - bits[offset >> 5] |= 1 << (offset & 0x1F); - } - } - } - - /** - * @return row/column dimension of this matrix - */ - public int getDimension() { - return dimension; - } - - /** - * @return array of ints holding internal representation of this matrix's bits - */ - public int[] getBits() { - return bits; - } - - public String toString() { - StringBuilder result = new StringBuilder(dimension * (dimension + 1)); - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - result.Append(get(i, j) ? "X " : " "); - } - result.Append('\n'); - } - return result.ToString(); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/BitSource.cs b/qrcode-scanner-live/common/BitSource.cs deleted file mode 100644 index 91df66e..0000000 --- a/qrcode-scanner-live/common/BitSource.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class BitSource - { - private sbyte[] bytes; - private int byteOffset; - private int bitOffset; - - /** - * @param bytes bytes from which this will read bits. Bits will be read from the first byte first. - * Bits are read within a byte from most-significant to least-significant bit. - */ - public BitSource(sbyte[] bytes) { - this.bytes = bytes; - } - - /** - * @param numBits number of bits to read - * @return int representing the bits read. The bits will appear as the least-significant - * bits of the int - * @throws IllegalArgumentException if numBits isn't in [1,32] - */ - public int readBits(int numBits) { - if (numBits < 1 || numBits > 32) { - throw new Exception(); - } - - int result = 0; - - // First, read remainder from current byte - if (bitOffset > 0) { - int bitsLeft = 8 - bitOffset; - int toRead = numBits < bitsLeft ? numBits : bitsLeft; - int bitsToNotRead = bitsLeft - toRead; - int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; - result = (bytes[byteOffset] & mask) >> bitsToNotRead; - numBits -= toRead; - bitOffset += toRead; - if (bitOffset == 8) { - bitOffset = 0; - byteOffset++; - } - } - - // Next read whole bytes - if (numBits > 0) { - while (numBits >= 8) { - result = (result << 8) | (bytes[byteOffset] & 0xFF); - byteOffset++; - numBits -= 8; - } - - // Finally read a partial byte - if (numBits > 0) { - int bitsToNotRead = 8 - numBits; - int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; - result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead); - bitOffset += numBits; - } - } - - return result; - } - - /** - * @return number of bits that can be read successfully - */ - public int available() { - return 8 * (bytes.Length - byteOffset) - bitOffset; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/BlackPointEstimator.cs b/qrcode-scanner-live/common/BlackPointEstimator.cs deleted file mode 100644 index d922193..0000000 --- a/qrcode-scanner-live/common/BlackPointEstimator.cs +++ /dev/null @@ -1,118 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common -{ - - ///

Encapsulates logic that estimates the optimal "black point", the luminance value - /// which is the best line between "white" and "black" in a grayscale image.

- /// - ///

For an interesting discussion of this issue, see - /// http://webdiis.unizar.es/~neira/12082/thresholding.pdf. - ///

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - /// dswitkin@google.com (Daniel Switkin) - /// - public sealed class BlackPointEstimator - { - private BlackPointEstimator() - { - } - - /** - *

Given an array of counts of luminance values (i.e. a histogram), this method - * decides which bucket of values corresponds to the black point -- which bucket contains the - * count of the brightest luminance values that should be considered "black".

- * - * @param histogram an array of counts of luminance values - * @return index within argument of bucket corresponding to brightest values which should be - * considered "black" - * @throws ReaderException if "black" and "white" appear to be very close in luminance in the image - */ - public static int estimate(int[] histogram) - { - try{ - - int numBuckets = histogram.Length; - int maxBucketCount = 0; - // Find tallest peak in histogram - int firstPeak = 0; - int firstPeakSize = 0; - for (int i = 0; i < numBuckets; i++) { - if (histogram[i] > firstPeakSize) { - firstPeak = i; - firstPeakSize = histogram[i]; - } - if (histogram[i] > maxBucketCount) { - maxBucketCount = histogram[i]; - } - } - - // Find second-tallest peak -- well, another peak that is tall and not - // so close to the first one - int secondPeak = 0; - int secondPeakScore = 0; - for (int i = 0; i < numBuckets; i++) { - int distanceToBiggest = i - firstPeak; - // Encourage more distant second peaks by multiplying by square of distance - int score = histogram[i] * distanceToBiggest * distanceToBiggest; - if (score > secondPeakScore) { - secondPeak = i; - secondPeakScore = score; - } - } - - // Put firstPeak first - if (firstPeak > secondPeak) { - int temp = firstPeak; - firstPeak = secondPeak; - secondPeak = temp; - } - - // Kind of aribtrary; if the two peaks are very close, then we figure there is so little - // dynamic range in the image, that discriminating black and white is too error-prone. - // Decoding the image/line is either pointless, or may in some cases lead to a false positive - // for 1D formats, which are relatively lenient. - // We arbitrarily say "close" is "<= 1/16 of the total histogram buckets apart" - if (secondPeak - firstPeak <= numBuckets >> 4) { - throw new ReaderException(""); - } - - // Find a valley between them that is low and closer to the white peak - int bestValley = secondPeak - 1; - int bestValleyScore = -1; - for (int i = secondPeak - 1; i > firstPeak; i--) { - int fromFirst = i - firstPeak; - // Favor a "valley" that is not too close to either peak -- especially not the black peak -- - // and that has a low value of course - int score = fromFirst * fromFirst * (secondPeak - i) * (maxBucketCount - histogram[i]); - if (score > bestValleyScore) { - bestValley = i; - bestValleyScore = score; - } - } - - return bestValley; - } - catch (Exception e) - { - throw (ReaderException) e; - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/ByteArray.cs b/qrcode-scanner-live/common/ByteArray.cs deleted file mode 100644 index 5c4d828..0000000 --- a/qrcode-scanner-live/common/ByteArray.cs +++ /dev/null @@ -1,117 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class ByteArray - { - private static int INITIAL_SIZE = 32; - private sbyte[] bytes; - private int Size; - - public ByteArray() - { - bytes = null; - this.Size = 0; - } - - public ByteArray(int size) - { - bytes = new sbyte[size]; - this.Size = size; - } - - public ByteArray(sbyte[] byteArray) - { - bytes = byteArray; - this.Size = bytes.Length; - } - - /** - * Access an unsigned byte at location index. - * @param index The index in the array to access. - * @return The unsigned value of the byte as an int. - */ - public int at(int index) - { - return bytes[index] & 0xff; - } - - public void set(int index, int value) - { - bytes[index] = (sbyte)value; - } - - public int size() - { - return Size; - } - - public bool empty() - { - return Size == 0; - } - - public void appendByte(int value) - { - if (Size == 0 || Size >= bytes.Length) - { - int newSize = Math.Max(INITIAL_SIZE, Size << 1); - reserve(newSize); - } - bytes[Size] = (sbyte)value; - Size++; - } - - public void reserve(int capacity) - { - if (bytes == null || bytes.Length < capacity) - { - sbyte[] newArray = new sbyte[capacity]; - if (bytes != null) - { - System.Array.Copy(bytes, 0, newArray, 0, bytes.Length); - } - bytes = newArray; - } - } - - // Copy count bytes from array source starting at offset. - public void set(sbyte[] source, int offset, int count) - { - bytes = new sbyte[count]; - Size = count; - for (int x = 0; x < count; x++) - { - bytes[x] = source[offset + x]; - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/ByteMatrix.cs b/qrcode-scanner-live/common/ByteMatrix.cs deleted file mode 100644 index b1daa72..0000000 --- a/qrcode-scanner-live/common/ByteMatrix.cs +++ /dev/null @@ -1,115 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class ByteMatrix - { - private sbyte[][] bytes; - private int Height; - private int Width; - - - public ByteMatrix(int height, int width) { - bytes = new sbyte[height][]; - for (int i = 0; i < height; i++) { - bytes[i] = new sbyte[width]; - } - this.Height = height; - this.Width = width; - } - - public int height() - { - return Height; - } - - public int width() - { - return Width; - } - - public sbyte get(int y, int x) - { - return bytes[y][x]; - } - - public sbyte[][] getArray() - { - return bytes; - } - - public void set(int y, int x, sbyte value) - { - bytes[y][x] = value; - } - - public void set(int y, int x, int value) - { - bytes[y][x] = (sbyte)value; - } - - public void clear(sbyte value) - { - for (int y = 0; y < Height; ++y) - { - for (int x = 0; x < Width; ++x) - { - bytes[y][x] = value; - } - } - } - - public String toString() - { - StringBuilder result = new StringBuilder(); - for (int y = 0; y < Height; ++y) - { - for (int x = 0; x < Width; ++x) - { - switch (bytes[y][x]) - { - case 0: - result.Append(" 0"); - break; - case 1: - result.Append(" 1"); - break; - default: - result.Append(" "); - break; - } - } - result.Append('\n'); - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/CharacterSetECI.cs b/qrcode-scanner-live/common/CharacterSetECI.cs deleted file mode 100644 index 35e0e10..0000000 --- a/qrcode-scanner-live/common/CharacterSetECI.cs +++ /dev/null @@ -1,101 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - using System.Collections; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class CharacterSetECI : ECI - { - private static Hashtable VALUE_TO_ECI=new Hashtable(29); - /*static VALUE_TO_ECI = new Hashtable(29){ - // TODO figure out if these values are even right! - addCharacterSet(0, "Cp437"); - addCharacterSet(1, "ISO8859_1"); - addCharacterSet(2, "Cp437"); - addCharacterSet(3, "ISO8859_1"); - addCharacterSet(4, "ISO8859_2"); - addCharacterSet(5, "ISO8859_3"); - addCharacterSet(6, "ISO8859_4"); - addCharacterSet(7, "ISO8859_5"); - addCharacterSet(8, "ISO8859_6"); - addCharacterSet(9, "ISO8859_7"); - addCharacterSet(10, "ISO8859_8"); - addCharacterSet(11, "ISO8859_9"); - addCharacterSet(12, "ISO8859_10"); - addCharacterSet(13, "ISO8859_11"); - addCharacterSet(15, "ISO8859_13"); - addCharacterSet(16, "ISO8859_14"); - addCharacterSet(17, "ISO8859_15"); - addCharacterSet(18, "ISO8859_16"); - addCharacterSet(20, "SJIS"); - }*/ - - private String encodingName; - - private CharacterSetECI(int value, String encodingName):base(value) { - addCharacterSet(0, "Cp437"); - addCharacterSet(1, "ISO8859_1"); - addCharacterSet(2, "Cp437"); - addCharacterSet(3, "ISO8859_1"); - addCharacterSet(4, "ISO8859_2"); - addCharacterSet(5, "ISO8859_3"); - addCharacterSet(6, "ISO8859_4"); - addCharacterSet(7, "ISO8859_5"); - addCharacterSet(8, "ISO8859_6"); - addCharacterSet(9, "ISO8859_7"); - addCharacterSet(10, "ISO8859_8"); - addCharacterSet(11, "ISO8859_9"); - addCharacterSet(12, "ISO8859_10"); - addCharacterSet(13, "ISO8859_11"); - addCharacterSet(15, "ISO8859_13"); - addCharacterSet(16, "ISO8859_14"); - addCharacterSet(17, "ISO8859_15"); - addCharacterSet(18, "ISO8859_16"); - addCharacterSet(20, "SJIS"); - this.encodingName = encodingName; - } - - public String getEncodingName() { - return encodingName; - } - - private static void addCharacterSet(int value, String encodingName) { - VALUE_TO_ECI.Add(value, new CharacterSetECI(value, encodingName)); - } - - public static CharacterSetECI getCharacterSetECIByValue(int value) { - CharacterSetECI eci = (CharacterSetECI) VALUE_TO_ECI[value]; - if (eci == null) { - throw new Exception("Unsupported value: " + value); - } - return eci; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/Collections.cs b/qrcode-scanner-live/common/Collections.cs deleted file mode 100644 index 85e8c74..0000000 --- a/qrcode-scanner-live/common/Collections.cs +++ /dev/null @@ -1,64 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class Collections - { - - private Collections() - { - } - - /** - * Sorts its argument (destructively) using insert sort; in the context of this package - * insertion sort is simple and efficient given its relatively small inputs. - * - * @param vector vector to sort - * @param comparator comparator to define sort ordering - */ - public static void insertionSort(System.Collections.ArrayList vector, Comparator comparator) - { - int max = vector.Count; - for (int i = 1; i < max; i++) - { - System.Object value_Renamed = vector[i]; - int j = i - 1; - System.Object valueB; - while (j >= 0 && comparator.compare((valueB = vector[j]), value_Renamed) > 0) - { - vector[j + 1] = valueB; - j--; - } - vector[j + 1] = value_Renamed; - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/Comparator.cs b/qrcode-scanner-live/common/Comparator.cs deleted file mode 100644 index 4d8bc9f..0000000 --- a/qrcode-scanner-live/common/Comparator.cs +++ /dev/null @@ -1,27 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common -{ - - /// This is merely a clone of Comparator since it is not available in - /// CLDC 1.1 / MIDP 2.0. - /// - public interface Comparator - { - - int compare(System.Object o1, System.Object o2); - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/DecoderResult.cs b/qrcode-scanner-live/common/DecoderResult.cs deleted file mode 100644 index ad3c81a..0000000 --- a/qrcode-scanner-live/common/DecoderResult.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class DecoderResult - { - private sbyte[] rawBytes; - private String text; - private System.Collections.ArrayList byteSegments; - - public DecoderResult(sbyte[] rawBytes, String text, System.Collections.ArrayList byteSegments) - { - if (rawBytes == null && text == null) { - throw new Exception(); - } - this.rawBytes = rawBytes; - this.text = text; - this.byteSegments = byteSegments; - } - - public sbyte[] getRawBytes() { - return this.rawBytes; - } - - public String getText() { - return text; - } - - public System.Collections.ArrayList getByteSegments() - { - return byteSegments; - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/DefaultGridSampler.cs b/qrcode-scanner-live/common/DefaultGridSampler.cs deleted file mode 100644 index 95d1ee0..0000000 --- a/qrcode-scanner-live/common/DefaultGridSampler.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using MonochromeBitmapSource = com.google.zxing.MonochromeBitmapSource; - using ReaderException = com.google.zxing.ReaderException; - /// Sean Owen - /// - /// - public sealed class DefaultGridSampler : GridSampler - { - - public override BitMatrix sampleGrid(MonochromeBitmapSource image, int dimension, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) - { - PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); - - BitMatrix bits = new BitMatrix(dimension); - float[] points = new float[dimension << 1]; - for (int i = 0; i < dimension; i++) - { - int max = points.Length; - float iValue = (float)i + 0.5f; - for (int j = 0; j < max; j += 2) - { - points[j] = (float)(j >> 1) + 0.5f; - points[j + 1] = iValue; - } - transform.transformPoints(points); - // Quick check to see if points transformed to something inside the image; - // sufficent to check the endpoints - checkAndNudgePoints(image, points); - try - { - for (int j = 0; j < max; j += 2) - { - //UPGRADE_WARNING: Narrowing conversions may produce unexpected results in C#. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1042"' - if (image.isBlack((int)points[j], (int)points[j + 1])) - { - // Black(-ish) pixel - bits.set(i, j >> 1); - } - } - } - catch (System.IndexOutOfRangeException aioobe) - { - // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting - // transform gets "twisted" such that it maps a straight line of points to a set of points - // whose endpoints are in bounds, but others are not. There is probably some mathematical - // way to detect this about the transformation that I don't know yet. - // This results in an ugly runtime exception despite our clever checks above -- can't have that. - // We could check each point's coordinates but that feels duplicative. We settle for - // catching and wrapping ArrayIndexOutOfBoundsException. - throw new ReaderException(aioobe.Message); - } - } - return bits; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/DetectorResult.cs b/qrcode-scanner-live/common/DetectorResult.cs deleted file mode 100644 index bce786a..0000000 --- a/qrcode-scanner-live/common/DetectorResult.cs +++ /dev/null @@ -1,51 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class DetectorResult - { - private BitMatrix bits; - private ResultPoint[] points; - - public DetectorResult(BitMatrix bits, ResultPoint[] points) { - this.bits = bits; - this.points = points; - } - - public BitMatrix getBits() { - return bits; - } - - public ResultPoint[] getPoints() { - return points; - } - } -} diff --git a/qrcode-scanner-live/common/ECI.cs b/qrcode-scanner-live/common/ECI.cs deleted file mode 100644 index 05f8dc6..0000000 --- a/qrcode-scanner-live/common/ECI.cs +++ /dev/null @@ -1,56 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public abstract class ECI - { - private int value; - - public ECI(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - - public static ECI getECIByValue(int value) { - if (value < 0 || value > 999999) { - throw new Exception("Bad ECI value: " + value); - } - if (value < 900) { // Character set ECIs use 000000 - 000899 - return CharacterSetECI.getCharacterSetECIByValue(value); - } - throw new Exception("Unsupported ECI value: " + value); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/GenericResultPoint.cs b/qrcode-scanner-live/common/GenericResultPoint.cs deleted file mode 100644 index 3a3c20a..0000000 --- a/qrcode-scanner-live/common/GenericResultPoint.cs +++ /dev/null @@ -1,136 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class GenericResultPoint : ResultPoint - { - private float posX; - private float posY; - - public GenericResultPoint(float posX, float posY) { - this.posX = posX; - this.posY = posY; - } - - public float getX() { - return posX; - } - - public float getY() { - return posY; - } - - public String toString() { - StringBuilder result = new StringBuilder(25); - result.Append('('); - result.Append(posX); - result.Append(','); - result.Append(posY); - result.Append(')'); - return result.ToString(); - } - - public bool equals(Object other) { - - if (other.GetType() == typeof(GenericResultPoint)) { - GenericResultPoint otherPoint = (GenericResultPoint) other; - return posX == otherPoint.posX && posY == otherPoint.posY; - } - return false; - } - - public int hashCode() { - return 31 * posX.GetHashCode() + posY.GetHashCode(); - } - - /** - *

Orders an array of three ResultPoints in an order [A,B,C] such that AB < AC and - * BC < AC and the angle between BC and BA is less than 180 degrees. - */ - public static void orderBestPatterns(ResultPoint[] patterns) { - - // Find distances between pattern centers - float zeroOneDistance = distance(patterns[0], patterns[1]); - float oneTwoDistance = distance(patterns[1], patterns[2]); - float zeroTwoDistance = distance(patterns[0], patterns[2]); - - ResultPoint pointA, pointB, pointC; - // Assume one closest to other two is B; A and C will just be guesses at first - if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) { - pointB = patterns[0]; - pointA = patterns[1]; - pointC = patterns[2]; - } else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) { - pointB = patterns[1]; - pointA = patterns[0]; - pointC = patterns[2]; - } else { - pointB = patterns[2]; - pointA = patterns[0]; - pointC = patterns[1]; - } - - // Use cross product to figure out whether A and C are correct or flipped. - // This asks whether BC x BA has a positive z component, which is the arrangement - // we want for A, B, C. If it's negative, then we've got it flipped around and - // should swap A and C. - if (crossProductZ(pointA, pointB, pointC) < 0.0f) { - ResultPoint temp = pointA; - pointA = pointC; - pointC = temp; - } - - patterns[0] = pointA; - patterns[1] = pointB; - patterns[2] = pointC; - } - - - /** - * @return distance between two points - */ - public static float distance(ResultPoint pattern1, ResultPoint pattern2) { - float xDiff = pattern1.getX() - pattern2.getX(); - float yDiff = pattern1.getY() - pattern2.getY(); - return (float) Math.Sqrt((double) (xDiff * xDiff + yDiff * yDiff)); - } - - /** - * Returns the z component of the cross product between vectors BC and BA. - */ - public static float crossProductZ(ResultPoint pointA, ResultPoint pointB, ResultPoint pointC) { - float bX = pointB.getX(); - float bY = pointB.getY(); - return ((pointC.getX() - bX) * (pointA.getY() - bY)) - ((pointC.getY() - bY) * (pointA.getX() - bX)); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/GridSampler.cs b/qrcode-scanner-live/common/GridSampler.cs deleted file mode 100644 index 1964708..0000000 --- a/qrcode-scanner-live/common/GridSampler.cs +++ /dev/null @@ -1,168 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using MonochromeBitmapSource = com.google.zxing.MonochromeBitmapSource; - using ReaderException = com.google.zxing.ReaderException; - ///

Implementations of this class can, given locations of finder patterns for a QR code in an - /// image, sample the right points in the image to reconstruct the QR code, accounting for - /// perspective distortion. It is abstracted since it is relatively expensive and should be allowed - /// to take advantage of platform-specific optimized implementations, like Sun's Java Advanced - /// Imaging library, but which may not be available in other environments such as J2ME, and vice - /// versa. - /// * - /// The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)} - /// with an instance of a class which implements this interface. - /// * - /// - /// Sean Owen - /// - /// - public abstract class GridSampler - { - public static GridSampler Instance - { - get - { - // No real point in trying to make this thread-safe; - // doesn't matter if a second instance is created - if (gridSampler == null) - { - gridSampler = new DefaultGridSampler(); - } - return gridSampler; - } - - } - - private static GridSampler gridSampler = null; - ///

Samples an image for a square matrix of bits of the given dimension. This is used to extract the - /// black/white modules of a 2D barcode like a QR Code found in an image. Because this barcode may be - /// rotated or perspective-distorted, the caller supplies four points in the source image that define - /// known points in the barcode, so that the image may be sampled appropriately.

- /// * - ///

The last eight "from" parameters are four X/Y coordinate pairs of locations of points in - /// the image that define some significant points in the image to be sample. For example, - /// these may be the location of finder pattern in a QR Code.

- /// * - ///

The first eight "to" parameters are four X/Y coordinate pairs measured in the destination - /// {@link BitMatrix}, from the top left, where the known points in the image given by the "from" parameters - /// map to.

- /// * - ///

These 16 parameters define the transformation needed to sample the image.

- /// * - ///
- /// image to sample - /// - /// width/height of {@link BitMatrix} to sample from iamge - /// - /// {@link BitMatrix} representing a grid of points sampled from the image within a region - /// defined by the "from" parameters - /// @throws ReaderException if image can't be sampled, for example, if the transformation defined by - /// the given points is invalid or results in sampling outside the image boundaries - /// - /// - public abstract BitMatrix sampleGrid(MonochromeBitmapSource image, int dimension, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY); - - ///

Checks a set of points that have been transformed to sample points on an image against - /// the image's dimensions to see if the point are even within the image.

- /// * - ///

This method will actually "nudge" the endpoints back onto the image if they are found to be barely - /// (less than 1 pixel) off the image. This accounts for imperfect detection of finder patterns in an image - /// where the QR Code runs all the way to the image border.

- /// * - ///

For efficiency, the method will check points from either end of the line until one is found - /// to be within the image. Because the set of points are assumed to be linear, this is valid.

- /// * - ///
- /// image into which the points should map - /// - /// actual points in x1,y1,...,xn,yn form - /// @throws ReaderException if an endpoint is lies outside the image boundaries - /// - /// - protected internal static void checkAndNudgePoints(MonochromeBitmapSource image, float[] points) - { - int width = image.getWidth(); - int height = image.getHeight(); - // Check and nudge points from start until we see some that are OK: - bool nudged = true; - for (int offset = 0; offset < points.Length && nudged; offset += 2) - { - int x = (int)points[offset]; - int y = (int)points[offset + 1]; - if (x < -1 || x > width || y < -1 || y > height) - { - throw new ReaderException(""); - } - nudged = false; - if (x == -1) - { - points[offset] = 0.0f; - nudged = true; - } - else if (x == width) - { - points[offset] = width - 1; - nudged = true; - } - if (y == -1) - { - points[offset + 1] = 0.0f; - nudged = true; - } - else if (y == height) - { - points[offset + 1] = height - 1; - nudged = true; - } - } - // Check and nudge points from end: - nudged = true; - for (int offset = points.Length - 2; offset >= 0 && nudged; offset -= 2) - { - int x = (int)points[offset]; - int y = (int)points[offset + 1]; - if (x < -1 || x > width || y < -1 || y > height) - { - throw new ReaderException(""); - } - nudged = false; - if (x == -1) - { - points[offset] = 0.0f; - nudged = true; - } - else if (x == width) - { - points[offset] = width - 1; - nudged = true; - } - if (y == -1) - { - points[offset + 1] = 0.0f; - nudged = true; - } - else if (y == height) - { - points[offset + 1] = height - 1; - nudged = true; - } - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/PerspectiveTransform.cs b/qrcode-scanner-live/common/PerspectiveTransform.cs deleted file mode 100644 index a42a83e..0000000 --- a/qrcode-scanner-live/common/PerspectiveTransform.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - - ///

This class implements a perspective transform in two dimensions. Given four source and four destination - /// points, it will compute the transformation implied between them. The code is based directly upon section - /// 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.

- /// * - ///
- /// Sean Owen - /// - /// - sealed class PerspectiveTransform - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'a11 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a12 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a13 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a21 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a22 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a23 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a31 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a32 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a33 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - private float a11; - private float a12; - private float a13; - private float a21; - private float a22; - private float a23; - private float a31; - private float a32; - private float a33; - - private PerspectiveTransform(float a11, float a21, float a31, float a12, float a22, float a32, float a13, float a23, float a33) - { - this.a11 = a11; - this.a12 = a12; - this.a13 = a13; - this.a21 = a21; - this.a22 = a22; - this.a23 = a23; - this.a31 = a31; - this.a32 = a32; - this.a33 = a33; - } - - internal static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x3p, float y3p) - { - - PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); - PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); - return sToQ.times(qToS); - } - - internal void transformPoints(float[] points) - { - int max = points.Length; - float a11 = this.a11; - float a12 = this.a12; - float a13 = this.a13; - float a21 = this.a21; - float a22 = this.a22; - float a23 = this.a23; - float a31 = this.a31; - float a32 = this.a32; - float a33 = this.a33; - for (int i = 0; i < max; i += 2) - { - float x = points[i]; - float y = points[i + 1]; - float denominator = a13 * x + a23 * y + a33; - points[i] = (a11 * x + a21 * y + a31) / denominator; - points[i + 1] = (a12 * x + a22 * y + a32) / denominator; - } - } - - internal static PerspectiveTransform squareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) - { - float dy2 = y3 - y2; - float dy3 = y0 - y1 + y2 - y3; - if (dy2 == 0.0f && dy3 == 0.0f) - { - return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0f, 0.0f, 1.0f); - } - else - { - float dx1 = x1 - x2; - float dx2 = x3 - x2; - float dx3 = x0 - x1 + x2 - x3; - float dy1 = y1 - y2; - float denominator = dx1 * dy2 - dx2 * dy1; - float a13 = (dx3 * dy2 - dx2 * dy3) / denominator; - float a23 = (dx1 * dy3 - dx3 * dy1) / denominator; - return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0f); - } - } - - private static PerspectiveTransform quadrilateralToSquare(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) - { - // Here, the adjoint serves as the inverse: - return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); - } - - internal PerspectiveTransform buildAdjoint() - { - // Adjoint is the transpose of the cofactor matrix: - return new PerspectiveTransform(a22 * a33 - a23 * a32, a23 * a31 - a21 * a33, a21 * a32 - a22 * a31, a13 * a32 - a12 * a33, a11 * a33 - a13 * a31, a12 * a31 - a11 * a32, a12 * a23 - a13 * a22, a13 * a21 - a11 * a23, a11 * a22 - a12 * a21); - } - - internal PerspectiveTransform times(PerspectiveTransform other) - { - return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13, a11 * other.a21 + a21 * other.a22 + a31 * other.a23, a11 * other.a31 + a21 * other.a32 + a31 * other.a33, a12 * other.a11 + a22 * other.a12 + a32 * other.a13, a12 * other.a21 + a22 * other.a22 + a32 * other.a23, a12 * other.a31 + a22 * other.a32 + a32 * other.a33, a13 * other.a11 + a23 * other.a12 + a33 * other.a13, a13 * other.a21 + a23 * other.a22 + a33 * other.a23, a13 * other.a31 + a23 * other.a32 + a33 * other.a33); - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/reedsolomon/GF256.cs b/qrcode-scanner-live/common/reedsolomon/GF256.cs deleted file mode 100644 index f1aaeb3..0000000 --- a/qrcode-scanner-live/common/reedsolomon/GF256.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

This class contains utility methods for performing mathematical operations over - /// the Galois Field GF(256). Operations use the primitive polynomial - /// x^8 + x^4 + x^3 + x^2 + 1 in calculations.

- /// - ///

Throughout this package, elements of GF(256) are represented as an int - /// for convenience and speed (but at the cost of memory). - /// Only the bottom 8 bits are really used.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public sealed class GF256 - { - public static GF256 QR_CODE_FIELD = new GF256(0x011D); // x^8 + x^4 + x^3 + x^2 + 1 - public static GF256 DATA_MATRIX_FIELD = new GF256(0x012D); // x^8 + x^5 + x^3 + x^2 + 1 - - private int[] expTable; - private int[] logTable; - private GF256Poly zero; - private GF256Poly one; - - /** - * Create a representation of GF(256) using the given primitive polynomial. - * - * @param primitive irreducible polynomial whose coefficients are represented by - * the bits of an int, where the least-significant bit represents the constant - * coefficient - */ - private GF256(int primitive) { - expTable = new int[256]; - logTable = new int[256]; - int x = 1; - for (int i = 0; i < 256; i++) { - expTable[i] = x; - x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 - if (x >= 0x100) { - x ^= primitive; - } - } - for (int i = 0; i < 255; i++) { - logTable[expTable[i]] = i; - } - // logTable[0] == 0 but this should never be used - zero = new GF256Poly(this, new int[]{0}); - one = new GF256Poly(this, new int[]{1}); - } - - public GF256Poly getZero() { - return zero; - } - - public GF256Poly getOne() - { - return one; - } - - /** - * @return the monomial representing coefficient * x^degree - */ - public GF256Poly buildMonomial(int degree, int coefficient) - { - if (degree < 0) { - throw new ArgumentException(); - } - if (coefficient == 0) { - return zero; - } - int[] coefficients = new int[degree + 1]; - coefficients[0] = coefficient; - return new GF256Poly(this, coefficients); - } - - /** - * Implements both addition and subtraction -- they are the same in GF(256). - * - * @return sum/difference of a and b - */ - public static int addOrSubtract(int a, int b) { - return a ^ b; - } - - /** - * @return 2 to the power of a in GF(256) - */ - public int exp(int a) - { - return expTable[a]; - } - - /** - * @return base 2 log of a in GF(256) - */ - public int log(int a) - { - if (a == 0) { - throw new ArgumentException(); - } - return logTable[a]; - } - - /** - * @return multiplicative inverse of a - */ - public int inverse(int a) - { - if (a == 0) { - throw new ArithmeticException(); - } - return expTable[255 - logTable[a]]; - } - - /** - * @param a - * @param b - * @return product of a and b in GF(256) - */ - public int multiply(int a, int b) - { - if (a == 0 || b == 0) { - return 0; - } - if (a == 1) { - return b; - } - if (b == 1) { - return a; - } - return expTable[(logTable[a] + logTable[b]) % 255]; - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/reedsolomon/GF256Poly.cs b/qrcode-scanner-live/common/reedsolomon/GF256Poly.cs deleted file mode 100644 index 86eb3d3..0000000 --- a/qrcode-scanner-live/common/reedsolomon/GF256Poly.cs +++ /dev/null @@ -1,274 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Text; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Represents a polynomial whose coefficients are elements of GF(256). - /// Instances of this class are immutable.

- /// - ///

Much credit is due to William Rucklidge since portions of this code are an indirect - /// port of his C++ Reed-Solomon implementation.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public sealed class GF256Poly - { - private GF256 field; - private int[] coefficients; - - /** - * @param field the {@link GF256} instance representing the field to use - * to perform computations - * @param coefficients coefficients as ints representing elements of GF(256), arranged - * from most significant (highest-power term) coefficient to least significant - * @throws ArgumentException if argument is null or empty, - * or if leading coefficient is 0 and this is not a - * constant polynomial (that is, it is not the monomial "0") - */ - public GF256Poly(GF256 field, int[] coefficients) { - if (coefficients == null || coefficients.Length == 0) { - throw new ArgumentException(); - } - this.field = field; - int coefficientsLength = coefficients.Length; - if (coefficientsLength > 1 && coefficients[0] == 0) { - // Leading term must be non-zero for anything except the constant polynomial "0" - int firstNonZero = 1; - while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) { - firstNonZero++; - } - if (firstNonZero == coefficientsLength) { - this.coefficients = field.getZero().coefficients; - } else { - this.coefficients = new int[coefficientsLength - firstNonZero]; - System.Array.Copy(coefficients,firstNonZero,this.coefficients,0,this.coefficients.Length); - } - } else { - this.coefficients = coefficients; - } - } - - public int[] getCoefficients() - { - return coefficients; - } - - /** - * @return degree of this polynomial - */ - public int getDegree() - { - return coefficients.Length - 1; - } - - /** - * @return true iff this polynomial is the monomial "0" - */ - public bool isZero() - { - return coefficients[0] == 0; - } - - /** - * @return coefficient of x^degree term in this polynomial - */ - public int getCoefficient(int degree) - { - return coefficients[coefficients.Length - 1 - degree]; - } - - /** - * @return evaluation of this polynomial at a given point - */ - public int evaluateAt(int a) - { - if (a == 0) { - // Just return the x^0 coefficient - return getCoefficient(0); - } - int size = coefficients.Length; - int result = 0; - - if (a == 1) { - // Just the sum of the coefficients - result = 0; - for (int i = 0; i < size; i++) { - result = GF256.addOrSubtract(result, coefficients[i]); - } - return result; - } - - result = coefficients[0]; - for (int i = 1; i < size; i++) { - result = GF256.addOrSubtract(field.multiply(a, result), coefficients[i]); - } - return result; - } - - public GF256Poly addOrSubtract(GF256Poly other) - { - if (!field.Equals(other.field)) { - throw new ArgumentException("GF256Polys do not have same GF256 field"); - } - if (isZero()) { - return other; - } - if (other.isZero()) { - return this; - } - - int[] smallerCoefficients = this.coefficients; - int[] largerCoefficients = other.coefficients; - if (smallerCoefficients.Length > largerCoefficients.Length) { - int[] temp = smallerCoefficients; - smallerCoefficients = largerCoefficients; - largerCoefficients = temp; - } - int[] sumDiff = new int[largerCoefficients.Length]; - int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length; - // Copy high-order terms only found in higher-degree polynomial's coefficients - System.Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); - - for (int i = lengthDiff; i < largerCoefficients.Length; i++) { - sumDiff[i] = GF256.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); - } - - return new GF256Poly(field, sumDiff); - } - - public GF256Poly multiply(GF256Poly other) - { - if (!field.Equals(other.field)) { - throw new ArgumentException("GF256Polys do not have same GF256 field"); - } - if (isZero() || other.isZero()) { - return field.getZero(); - } - int[] aCoefficients = this.coefficients; - int aLength = aCoefficients.Length; - int[] bCoefficients = other.coefficients; - int bLength = bCoefficients.Length; - int[] product = new int[aLength + bLength - 1]; - for (int i = 0; i < aLength; i++) { - int aCoeff = aCoefficients[i]; - for (int j = 0; j < bLength; j++) { - product[i + j] = GF256.addOrSubtract(product[i + j], - field.multiply(aCoeff, bCoefficients[j])); - } - } - return new GF256Poly(field, product); - } - - public GF256Poly multiply(int scalar) - { - if (scalar == 0) { - return field.getZero(); - } - if (scalar == 1) { - return this; - } - int size = coefficients.Length; - int[] product = new int[size]; - for (int i = 0; i < size; i++) { - product[i] = field.multiply(coefficients[i], scalar); - } - return new GF256Poly(field, product); - } - - public GF256Poly multiplyByMonomial(int degree, int coefficient) - { - if (degree < 0) { - throw new ArgumentException(); - } - if (coefficient == 0) { - return field.getZero(); - } - int size = coefficients.Length; - int[] product = new int[size + degree]; - for (int i = 0; i < size; i++) { - product[i] = field.multiply(coefficients[i], coefficient); - } - return new GF256Poly(field, product); - } - - public GF256Poly[] divide(GF256Poly other) - { - if (!field.Equals(other.field)) { - throw new ArgumentException("GF256Polys do not have same GF256 field"); - } - if (other.isZero()) { - throw new ArgumentException("Divide by 0"); - } - - GF256Poly quotient = field.getZero(); - GF256Poly remainder = this; - - int denominatorLeadingTerm = other.getCoefficient(other.getDegree()); - int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm); - - while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) { - int degreeDifference = remainder.getDegree() - other.getDegree(); - int scale = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm); - GF256Poly term = other.multiplyByMonomial(degreeDifference, scale); - GF256Poly iterationQuotient = field.buildMonomial(degreeDifference, scale); - quotient = quotient.addOrSubtract(iterationQuotient); - remainder = remainder.addOrSubtract(term); - } - - return new GF256Poly[] { quotient, remainder }; - } - - public String toString() { - StringBuilder result = new StringBuilder(8 * getDegree()); - for (int degree = getDegree(); degree >= 0; degree--) { - int coefficient = getCoefficient(degree); - if (coefficient != 0) { - if (coefficient < 0) { - result.Append(" - "); - coefficient = -coefficient; - } else { - if (result.Length > 0) { - result.Append(" + "); - } - } - if (degree == 0 || coefficient != 1) { - int alphaPower = field.log(coefficient); - if (alphaPower == 0) { - result.Append('1'); - } else if (alphaPower == 1) { - result.Append('a'); - } else { - result.Append("a^"); - result.Append(alphaPower); - } - } - if (degree != 0) { - if (degree == 1) { - result.Append('x'); - } else { - result.Append("x^"); - result.Append(degree); - } - } - } - } - return result.ToString(); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/reedsolomon/ReedSolomonDecoder.cs b/qrcode-scanner-live/common/reedsolomon/ReedSolomonDecoder.cs deleted file mode 100644 index 0ab74eb..0000000 --- a/qrcode-scanner-live/common/reedsolomon/ReedSolomonDecoder.cs +++ /dev/null @@ -1,195 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Implements Reed-Solomon decoding, as the name implies.

- /// - ///

The algorithm will not be explained here, but the following references were helpful - /// in creating this implementation:

- /// - /// - /// - ///

Much credit is due to William Rucklidge since portions of this code are an indirect - /// port of his C++ Reed-Solomon implementation.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - /// William Rucklidge - /// - public sealed class ReedSolomonDecoder - { - private GF256 field; - - public ReedSolomonDecoder(GF256 field) { - this.field = field; - } - - /** - *

Decodes given set of received codewords, which include both data and error-correction - * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place, - * in the input.

- * - * @param received data and error-correction codewords - * @param twoS number of error-correction codewords available - * @throws ReedSolomonException if decoding fails for any reason - */ - public void decode(int[] received, int twoS) { - try{ - - - GF256Poly poly = new GF256Poly(field, received); - int[] syndromeCoefficients = new int[twoS]; - bool dataMatrix = field.Equals(GF256.DATA_MATRIX_FIELD); - bool noError = true; - for (int i = 0; i < twoS; i++) { - // Thanks to sanfordsquires for this fix: - int eval = poly.evaluateAt(field.exp(dataMatrix ? i + 1 : i)); - syndromeCoefficients[syndromeCoefficients.Length - 1 - i] = eval; - if (eval != 0) { - noError = false; - } - } - if (noError) { - return; - } - GF256Poly syndrome = new GF256Poly(field, syndromeCoefficients); - GF256Poly[] sigmaOmega = - runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS); - GF256Poly sigma = sigmaOmega[0]; - GF256Poly omega = sigmaOmega[1]; - int[] errorLocations = findErrorLocations(sigma); - int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations, dataMatrix); - for (int i = 0; i < errorLocations.Length; i++) { - int position = received.Length - 1 - field.log(errorLocations[i]); - if (position < 0) { - throw new ReedSolomonException("Bad error location"); - } - received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]); - } - }catch(ReedSolomonException e){ - throw new ReedSolomonException(e.Message); - } - } - - private GF256Poly[] runEuclideanAlgorithm(GF256Poly a, GF256Poly b, int R){ - // Assume a's degree is >= b's - if (a.getDegree() < b.getDegree()) { - GF256Poly temp = a; - a = b; - b = temp; - } - - GF256Poly rLast = a; - GF256Poly r = b; - GF256Poly sLast = field.getOne(); - GF256Poly s = field.getZero(); - GF256Poly tLast = field.getZero(); - GF256Poly t = field.getOne(); - - // Run Euclidean algorithm until r's degree is less than R/2 - while (r.getDegree() >= R / 2) { - GF256Poly rLastLast = rLast; - GF256Poly sLastLast = sLast; - GF256Poly tLastLast = tLast; - rLast = r; - sLast = s; - tLast = t; - - // Divide rLastLast by rLast, with quotient in q and remainder in r - if (rLast.isZero()) { - // Oops, Euclidean algorithm already terminated? - throw new ReedSolomonException("r_{i-1} was zero"); - } - r = rLastLast; - GF256Poly q = field.getZero(); - int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree()); - int dltInverse = field.inverse(denominatorLeadingTerm); - while (r.getDegree() >= rLast.getDegree() && !r.isZero()) { - int degreeDiff = r.getDegree() - rLast.getDegree(); - int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse); - q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale)); - r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); - } - - s = q.multiply(sLast).addOrSubtract(sLastLast); - t = q.multiply(tLast).addOrSubtract(tLastLast); - } - - int sigmaTildeAtZero = t.getCoefficient(0); - if (sigmaTildeAtZero == 0) { - throw new ReedSolomonException("sigmaTilde(0) was zero"); - } - - int inverse = field.inverse(sigmaTildeAtZero); - GF256Poly sigma = t.multiply(inverse); - GF256Poly omega = r.multiply(inverse); - return new GF256Poly[]{sigma, omega}; - } - - private int[] findErrorLocations(GF256Poly errorLocator){ - // This is a direct application of Chien's search - int numErrors = errorLocator.getDegree(); - if (numErrors == 1) { // shortcut - return new int[] { errorLocator.getCoefficient(1) }; - } - int[] result = new int[numErrors]; - int e = 0; - for (int i = 1; i < 256 && e < numErrors; i++) { - if (errorLocator.evaluateAt(i) == 0) { - result[e] = field.inverse(i); - e++; - } - } - if (e != numErrors) { - throw new ReedSolomonException("Error locator degree does not match number of roots"); - } - return result; - } - - private int[] findErrorMagnitudes(GF256Poly errorEvaluator, int[] errorLocations, bool dataMatrix) { - // This is directly applying Forney's Formula - int s = errorLocations.Length; - int[] result = new int[s]; - for (int i = 0; i < s; i++) { - int xiInverse = field.inverse(errorLocations[i]); - int denominator = 1; - for (int j = 0; j < s; j++) { - if (i != j) { - denominator = field.multiply(denominator, - GF256.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse))); - } - } - result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), - field.inverse(denominator)); - // Thanks to sanfordsquires for this fix: - if (dataMatrix) { - result[i] = field.multiply(result[i], xiInverse); - } - } - return result; - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/reedsolomon/ReedSolomonEncoder.cs b/qrcode-scanner-live/common/reedsolomon/ReedSolomonEncoder.cs deleted file mode 100644 index db76156..0000000 --- a/qrcode-scanner-live/common/reedsolomon/ReedSolomonEncoder.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; - -namespace com.google.zxing.common.reedsolomon -{ - public sealed class ReedSolomonEncoder - { - private GF256 Field; - private ArrayList cachedGenerators; - - public ReedSolomonEncoder(GF256 field) { - if (!GF256.QR_CODE_FIELD.Equals(field)) { - throw new ArgumentException("Only QR Code is supported at this time"); - } - this.Field = field; - this.cachedGenerators = new ArrayList(); - cachedGenerators.Add(new GF256Poly(field, new int[] { 1 })); - } - - private GF256Poly buildGenerator(int degree) { - if (degree >= cachedGenerators.Count) { - GF256Poly lastGenerator = (GF256Poly)cachedGenerators[(cachedGenerators.Count - 1)]; - for (int d = cachedGenerators.Count; d <= degree; d++) - { - GF256Poly nextGenerator = lastGenerator.multiply(new GF256Poly(Field, new int[] { 1, Field.exp(d - 1) })); - cachedGenerators.Add(nextGenerator); - lastGenerator = nextGenerator; - } - } - return (GF256Poly) cachedGenerators[(degree)]; - } - - public void encode(int[] toEncode, int ecBytes) { - if (ecBytes == 0) { - throw new ArgumentException("No error correction bytes"); - } - int dataBytes = toEncode.Length - ecBytes; - if (dataBytes <= 0) { - throw new ArgumentException("No data bytes provided"); - } - GF256Poly generator = buildGenerator(ecBytes); - int[] infoCoefficients = new int[dataBytes]; - System.Array.Copy(toEncode, 0, infoCoefficients, 0, dataBytes); - GF256Poly info = new GF256Poly(this.Field, infoCoefficients); - info = info.multiplyByMonomial(ecBytes, 1); - GF256Poly remainder = info.divide(generator)[1]; - int[] coefficients = remainder.getCoefficients(); - int numZeroCoefficients = ecBytes - coefficients.Length; - for (int i = 0; i < numZeroCoefficients; i++) { - toEncode[dataBytes + i] = 0; - } - System.Array.Copy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.Length); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/common/reedsolomon/ReedSolomonException.cs b/qrcode-scanner-live/common/reedsolomon/ReedSolomonException.cs deleted file mode 100644 index e965339..0000000 --- a/qrcode-scanner-live/common/reedsolomon/ReedSolomonException.cs +++ /dev/null @@ -1,38 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Thrown when an exception occurs during Reed-Solomon decoding, such as when - /// there are too many errors to correct.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - //[Serializable] - public sealed class ReedSolomonException : System.Exception - { - - public ReedSolomonException() - { - } - - public ReedSolomonException(System.String message) - : base(message) - { - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/datamatrix/DataMatrixReader.cs b/qrcode-scanner-live/datamatrix/DataMatrixReader.cs deleted file mode 100644 index 4c87612..0000000 --- a/qrcode-scanner-live/datamatrix/DataMatrixReader.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.datamatrix.decoder; -using com.google.zxing.datamatrix.detector; - -namespace com.google.zxing.datamatrix -{ - public sealed class DataMatrixReader - { - private static ResultPoint[] NO_POINTS = new ResultPoint[0]; - private Decoder decoder = new Decoder(); - - /** - * Locates and decodes a Data Matrix code in an image. - * - * @return a String representing the content encoded by the Data Matrix code - * @throws ReaderException if a Data Matrix code cannot be found, or cannot be decoded - */ - public Result decode(MonochromeBitmapSource image) { - return decode(image, null); - } - - public Result decode(MonochromeBitmapSource image, System.Collections.Hashtable hints) - { - DecoderResult decoderResult; - ResultPoint[] points; - if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) { - BitMatrix bits = extractPureBits(image); - decoderResult = decoder.decode(bits); - points = NO_POINTS; - } else { - DetectorResult detectorResult = new Detector(image).detect(); - decoderResult = decoder.decode(detectorResult.getBits()); - points = detectorResult.getPoints(); - } - Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.DATAMATRIX); - if (decoderResult.getByteSegments() != null) { - result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.getByteSegments()); - } - return result; - } - - /** - * This method detects a Data Matrix code in a "pure" image -- that is, pure monochrome image - * which contains only an unrotated, unskewed, image of a Data Matrix code, with some white border - * around it. This is a specialized method that works exceptionally fast in this special - * case. - */ - private static BitMatrix extractPureBits(MonochromeBitmapSource image) { - // Now need to determine module size in pixels - - int height = image.getHeight(); - int width = image.getWidth(); - int minDimension = Math.Min(height, width); - - // First, skip white border by tracking diagonally from the top left down and to the right: - int borderWidth = 0; - while (borderWidth < minDimension && !image.isBlack(borderWidth, borderWidth)) { - borderWidth++; - } - if (borderWidth == minDimension) { - throw new ReaderException(); - } - - // And then keep tracking across the top-left black module to determine module size - int moduleEnd = borderWidth + 1; - while (moduleEnd < width && image.isBlack(moduleEnd, borderWidth)) { - moduleEnd++; - } - if (moduleEnd == width) { - throw new ReaderException(); - } - - int moduleSize = moduleEnd - borderWidth; - - // And now find where the bottommost black module on the first column ends - int columnEndOfSymbol = height - 1; - while (columnEndOfSymbol >= 0 && !image.isBlack(borderWidth, columnEndOfSymbol)) { - columnEndOfSymbol--; - } - if (columnEndOfSymbol < 0) { - throw new ReaderException(); - } - columnEndOfSymbol++; - - // Make sure width of barcode is a multiple of module size - if ((columnEndOfSymbol - borderWidth) % moduleSize != 0) { - throw new ReaderException(); - } - int dimension = (columnEndOfSymbol - borderWidth) / moduleSize; - - // Push in the "border" by half the module width so that we start - // sampling in the middle of the module. Just in case the image is a - // little off, this will help recover. - borderWidth += moduleSize >> 1; - - int sampleDimension = borderWidth + (dimension - 1) * moduleSize; - if (sampleDimension >= width || sampleDimension >= height) { - throw new ReaderException(); - } - - // Now just read off the bits - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) { - int iOffset = borderWidth + i * moduleSize; - for (int j = 0; j < dimension; j++) { - if (image.isBlack(borderWidth + j * moduleSize, iOffset)) { - bits.set(i, j); - } - } - } - return bits; - } - } -} diff --git a/qrcode-scanner-live/datamatrix/decoder/BitMatrixParser.cs b/qrcode-scanner-live/datamatrix/decoder/BitMatrixParser.cs deleted file mode 100644 index 653810a..0000000 --- a/qrcode-scanner-live/datamatrix/decoder/BitMatrixParser.cs +++ /dev/null @@ -1,450 +0,0 @@ -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using com.google.zxing.common; - -namespace com.google.zxing.datamatrix.decoder -{ - /** - * @author bbrown@google.com (Brian Brown) - */ - public sealed class BitMatrixParser - { - - private BitMatrix mappingBitMatrix; - private BitMatrix readMappingMatrix; - private Version version; - - /** - * @param bitMatrix {@link BitMatrix} to parse - * @throws ReaderException if dimension is < 10 or > 144 or not 0 mod 2 - */ - public BitMatrixParser(BitMatrix bitMatrix) { - int dimension = bitMatrix.getDimension(); - if (dimension < 10 || dimension > 144 || (dimension & 0x01) != 0) { - throw new ReaderException(); - } - - version = readVersion(bitMatrix); - this.mappingBitMatrix = extractDataRegion(bitMatrix); - // TODO(bbrown): Make this work for rectangular symbols - this.readMappingMatrix = new BitMatrix(this.mappingBitMatrix.getDimension()); - } - - /** - *

Creates the version object based on the dimension of the original bit matrix from - * the datamatrix code.

- * - *

See ISO 16022:2006 Table 7 - ECC 200 symbol attributes

- * - * @param bitMatrix Original {@link BitMatrix} including alignment patterns - * @return {@link Version} encapsulating the Data Matrix Code's "version" - * @throws ReaderException if the dimensions of the mapping matrix are not valid - * Data Matrix dimensions. - */ - public Version readVersion(BitMatrix bitMatrix) { - - if (version != null) { - return version; - } - - // TODO(bbrown): make this work for rectangular dimensions as well. - int numRows = bitMatrix.getDimension(); - int numColumns = numRows; - - return Version.getVersionForDimensions(numRows, numColumns); - } - - /** - *

Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns) - * in the correct order in order to reconstitute the codewords bytes contained within the - * Data Matrix Code.

- * - * @return bytes encoded within the Data Matrix Code - * @throws ReaderException if the exact number of bytes expected is not read - */ - public sbyte[] readCodewords() { - - sbyte[] result = new sbyte[version.getTotalCodewords()]; - int resultOffset = 0; - - int row = 4; - int column = 0; - // TODO(bbrown): Data Matrix can be rectangular, assuming square for now - int numRows = mappingBitMatrix.getDimension(); - int numColumns = numRows; - - bool corner1Read = false; - bool corner2Read = false; - bool corner3Read = false; - bool corner4Read = false; - - // Read all of the codewords - do { - // Check the four corner cases - if ((row == numRows) && (column == 0) && !corner1Read) { - result[resultOffset++] = (sbyte) readCorner1(numRows, numColumns); - row -= 2; - column +=2; - corner1Read = true; - } else if ((row == numRows-2) && (column == 0) && ((numColumns & 0x03) != 0) && !corner2Read) { - result[resultOffset++] = (sbyte)readCorner2(numRows, numColumns); - row -= 2; - column +=2; - corner2Read = true; - } else if ((row == numRows+4) && (column == 2) && ((numColumns & 0x07) == 0) && !corner3Read) { - result[resultOffset++] = (sbyte)readCorner3(numRows, numColumns); - row -= 2; - column +=2; - corner3Read = true; - } else if ((row == numRows-2) && (column == 0) && ((numColumns & 0x07) == 4) && !corner4Read) { - result[resultOffset++] = (sbyte)readCorner4(numRows, numColumns); - row -= 2; - column +=2; - corner4Read = true; - } else { - // Sweep upward diagonally to the right - do { - if ((row < numRows) && (column >= 0) && !readMappingMatrix.get(row, column)) { - result[resultOffset++] = (sbyte)readUtah(row, column, numRows, numColumns); - } - row -= 2; - column +=2; - } while ((row >= 0) && (column < numColumns)); - row += 1; - column +=3; - - // Sweep downward diagonally to the left - do { - if ((row >= 0) && (column < numColumns) && !readMappingMatrix.get(row, column)) { - result[resultOffset++] = (sbyte) readUtah(row, column, numRows, numColumns); - } - row += 2; - column -=2; - } while ((row < numRows) && (column >= 0)); - row += 3; - column +=1; - } - } while ((row < numRows) || (column < numColumns)); - - if (resultOffset != version.getTotalCodewords()) { - throw new ReaderException(); - } - return result; - } - - /** - *

Reads a bit of the mapping matrix accounting for boundary wrapping.

- * - * @param row Row to read in the mapping matrix - * @param column Column to read in the mapping matrix - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return value of the given bit in the mapping matrix - */ - bool readModule(int row, int column, int numRows, int numColumns) { - // Adjust the row and column indices based on boundary wrapping - if (row < 0) { - row += numRows; - column += 4 - ((numRows + 4) & 0x07); - } - if (column < 0) { - column += numColumns; - row += 4 - ((numColumns + 4) & 0x07); - } - readMappingMatrix.set(row, column); - return mappingBitMatrix.get(row, column); - } - - /** - *

Reads the 8 bits of the standard utah shaped pattern.

- * - *

See ISO 16022:2006, 5.8.1 Figure 6

- * - * @param row Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern - * @param column Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the utah shape - */ - int readUtah(int row, int column, int numRows, int numColumns) { - int currentByte = 0; - if (readModule(row - 2, column - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 2, column - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 1, column - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 1, column - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 1, column, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row, column - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row, column - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row, column, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Reads the 8 bits of the special corner condition 1.

- * - *

See ISO 16022:2006, Figure F.3

- * - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the Corner condition 1 - */ - int readCorner1(int numRows, int numColumns) { - int currentByte = 0; - if (readModule(numRows - 1, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(2, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(3, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Reads the 8 bits of the special corner condition 2.

- * - *

See ISO 16022:2006, Figure F.4

- * - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the Corner condition 2 - */ - int readCorner2(int numRows, int numColumns) { - int currentByte = 0; - if (readModule(numRows - 3, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 2, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 4, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 3, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Reads the 8 bits of the special corner condition 3.

- * - *

See ISO 16022:2006, Figure F.5

- * - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the Corner condition 3 - */ - int readCorner3(int numRows, int numColumns) { - int currentByte = 0; - if (readModule(numRows - 1, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 3, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 3, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Reads the 8 bits of the special corner condition 4.

- * - *

See ISO 16022:2006, Figure F.6

- * - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the Corner condition 4 - */ - int readCorner4(int numRows, int numColumns) { - int currentByte = 0; - if (readModule(numRows - 3, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 2, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(2, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(3, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Extracts the data region from a {@link BitMatrix} that contains - * alignment patterns.

- * - * @param bitMatrix Original {@link BitMatrix} with alignment patterns - * @return BitMatrix that has the alignment patterns removed - */ - BitMatrix extractDataRegion(BitMatrix bitMatrix) { - int symbolSizeRows = version.getSymbolSizeRows(); - int symbolSizeColumns = version.getSymbolSizeColumns(); - - // TODO(bbrown): Make this work with rectangular codes - if (bitMatrix.getDimension() != symbolSizeRows) { - throw new ArgumentException("Dimension of bitMarix must match the version size"); - } - - int dataRegionSizeRows = version.getDataRegionSizeRows(); - int dataRegionSizeColumns = version.getDataRegionSizeColumns(); - - int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows; - int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns; - - int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows; - //int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns; - - // TODO(bbrown): Make this work with rectangular codes - BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionRow); - for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) { - int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows; - for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) { - int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns; - for (int i = 0; i < dataRegionSizeRows; ++i) { - int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i; - int writeRowOffset = dataRegionRowOffset + i; - for (int j = 0; j < dataRegionSizeColumns; ++j) { - int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j; - if (bitMatrix.get(readRowOffset, readColumnOffset)) { - int writeColumnOffset = dataRegionColumnOffset + j; - bitMatrixWithoutAlignment.set(writeRowOffset, writeColumnOffset); - } - } - } - } - } - return bitMatrixWithoutAlignment; - } - - } -} diff --git a/qrcode-scanner-live/datamatrix/decoder/DataBlock.cs b/qrcode-scanner-live/datamatrix/decoder/DataBlock.cs deleted file mode 100644 index 8e4893e..0000000 --- a/qrcode-scanner-live/datamatrix/decoder/DataBlock.cs +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace com.google.zxing.datamatrix.decoder -{ - - /** - *

Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into - * multiple blocks, each of which is a unit of data and error-correction codewords. Each - * is represented by an instance of this class.

- * - * @author bbrown@google.com (Brian Brown) - */ - public sealed class DataBlock - { - private int numDataCodewords; - private sbyte[] codewords; - - private DataBlock(int numDataCodewords, sbyte[] codewords) { - this.numDataCodewords = numDataCodewords; - this.codewords = codewords; - } - - /** - *

When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them. - * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This - * method will separate the data into original blocks.

- * - * @param rawCodewords bytes as read directly from the Data Matrix Code - * @param version version of the Data Matrix Code - * @return {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the - * Data Matrix Code - */ - public static DataBlock[] getDataBlocks(sbyte[] rawCodewords, - Version version) { - // Figure out the number and size of data blocks used by this version - Version.ECBlocks ecBlocks = version.getECBlocks(); - - // First count the total number of data blocks - int totalBlocks = 0; - Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); - for (int i = 0; i < ecBlockArray.Length; i++) { - totalBlocks += ecBlockArray[i].getCount(); - } - - // Now establish DataBlocks of the appropriate size and number of data codewords - DataBlock[] result = new DataBlock[totalBlocks]; - int numResultBlocks = 0; - for (int j = 0; j < ecBlockArray.Length; j++) { - Version.ECB ecBlock = ecBlockArray[j]; - for (int i = 0; i < ecBlock.getCount(); i++) { - int numDataCodewords = ecBlock.getDataCodewords(); - int numBlockCodewords = ecBlocks.getECCodewords() + numDataCodewords; - result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]); - } - } - - // All blocks have the same amount of data, except that the last n - // (where n may be 0) have 1 less byte. Figure out where these start. - // TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144 - int longerBlocksTotalCodewords = result[0].codewords.Length; - //int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1; - - int longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.getECCodewords(); - int shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1; - // The last elements of result may be 1 element shorter for 144 matrix - // first fill out as many elements as all of them have minus 1 - int rawCodewordsOffset = 0; - for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { - for (int j = 0; j < numResultBlocks; j++) { - result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; - } - } - - // Fill out the last data block in the longer ones - bool specialVersion = version.getVersionNumber() == 24; - int numLongerBlocks = specialVersion ? 8 : numResultBlocks; - for (int j = 0; j < numLongerBlocks; j++) { - result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++]; - } - - // Now add in error correction blocks - int max = result[0].codewords.Length; - for (int i = longerBlocksNumDataCodewords; i < max; i++) { - for (int j = 0; j < numResultBlocks; j++) { - int iOffset = (specialVersion && j > 7) ? i - 1 : i; - result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; - } - } - - if (rawCodewordsOffset != rawCodewords.Length) { - throw new ArgumentException(); - } - - return result; - } - - public int getNumDataCodewords() { - return numDataCodewords; - } - - public sbyte[] getCodewords() { - return codewords; - } - } -} diff --git a/qrcode-scanner-live/datamatrix/decoder/DecodedBitStreamParser.cs b/qrcode-scanner-live/datamatrix/decoder/DecodedBitStreamParser.cs deleted file mode 100644 index 15bf322..0000000 --- a/qrcode-scanner-live/datamatrix/decoder/DecodedBitStreamParser.cs +++ /dev/null @@ -1,449 +0,0 @@ -/* - * Copyright 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using com.google.zxing.common; - -namespace com.google.zxing.datamatrix.decoder -{ - /** - *

Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into - * multiple blocks, each of which is a unit of data and error-correction codewords. Each - * is represented by an instance of this class.

- * - * @author bbrown@google.com (Brian Brown) - */ - public sealed class DecodedBitStreamParser - { - /** - * See ISO 16022:2006, Annex C Table C.1 - * The C40 Basic Character Set (*'s used for placeholders for the shift values) - */ - private static char[] C40_BASIC_SET_CHARS = { - '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' - }; - - private static char[] C40_SHIFT2_SET_CHARS = { - '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', - '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_' - }; - - /** - * See ISO 16022:2006, Annex C Table C.2 - * The Text Basic Character Set (*'s used for placeholders for the shift values) - */ - private static char[] TEXT_BASIC_SET_CHARS = { - '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' - }; - - private static char[] TEXT_SHIFT3_SET_CHARS = { - '\'', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char) 127 - }; - - private const int PAD_ENCODE = 0; // Not really an encoding - private const int ASCII_ENCODE = 1; - private const int C40_ENCODE = 2; - private const int TEXT_ENCODE = 3; - private const int ANSIX12_ENCODE = 4; - private const int EDIFACT_ENCODE = 5; - private const int BASE256_ENCODE = 6; - - private DecodedBitStreamParser() { - } - - public static DecoderResult decode(sbyte[] bytes) { - BitSource bits = new BitSource(bytes); - StringBuilder result = new StringBuilder(); - StringBuilder resultTrailer = new StringBuilder(0); - System.Collections.ArrayList byteSegments = new System.Collections.ArrayList(1); - int mode = ASCII_ENCODE; - do { - if (mode == ASCII_ENCODE) { - mode = decodeAsciiSegment(bits, result, resultTrailer); - } else { - switch (mode) { - case C40_ENCODE: - decodeC40Segment(bits, result); - break; - case TEXT_ENCODE: - decodeTextSegment(bits, result); - break; - case ANSIX12_ENCODE: - decodeAnsiX12Segment(bits, result); - break; - case EDIFACT_ENCODE: - decodeEdifactSegment(bits, result); - break; - case BASE256_ENCODE: - decodeBase256Segment(bits, result, byteSegments); - break; - default: - throw new ReaderException(); - } - mode = ASCII_ENCODE; - } - } while (mode != PAD_ENCODE && bits.available() > 0); - if (resultTrailer.Length > 0) { - result.Append(resultTrailer); - } - return new DecoderResult(bytes, result.ToString(), int.Equals(byteSegments.Count,0) ? null : byteSegments); - } - - /** - * See ISO 16022:2006, 5.2.3 and Annex C, Table C.2 - */ - private static int decodeAsciiSegment(BitSource bits, StringBuilder result, StringBuilder resultTrailer) - { - bool upperShift = false; - do { - int oneByte = bits.readBits(8); - if (oneByte == 0) { - throw new ReaderException(); - } else if (oneByte <= 128) { // ASCII data (ASCII value + 1) - oneByte = upperShift ? (oneByte + 128) : oneByte; - upperShift = false; - result.Append((char) (oneByte - 1)); - return ASCII_ENCODE; - } else if (oneByte == 129) { // Pad - return PAD_ENCODE; - } else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130) - int value = oneByte - 130; - if (value < 10) { // padd with '0' for single digit values - result.Append('0'); - } - result.Append(value); - } else if (oneByte == 230) { // Latch to C40 encodation - return C40_ENCODE; - } else if (oneByte == 231) { // Latch to Base 256 encodation - return BASE256_ENCODE; - } else if (oneByte == 232) { // FNC1 - throw new ReaderException(); - } else if (oneByte == 233) { // Structured Append - throw new ReaderException(); - } else if (oneByte == 234) { // Reader Programming - throw new ReaderException(); - } else if (oneByte == 235) { // Upper Shift (shift to Extended ASCII) - upperShift = true; - } else if (oneByte == 236) { // 05 Macro - result.Append("[)>\u001E05\u001D"); - resultTrailer.Insert(0, "\u001E\u0004"); - } else if (oneByte == 237) { // 06 Macro - result.Append("[)>\u001E06\u001D"); - resultTrailer.Insert(0, "\u001E\u0004"); - } else if (oneByte == 238) { // Latch to ANSI X12 encodation - return ANSIX12_ENCODE; - } else if (oneByte == 239) { // Latch to Text encodation - return TEXT_ENCODE; - } else if (oneByte == 240) { // Latch to EDIFACT encodation - return EDIFACT_ENCODE; - } else if (oneByte == 241) { // ECI Character - // TODO(bbrown): I think we need to support ECI - throw new ReaderException(); - } else if (oneByte >= 242) { // Not to be used in ASCII encodation - throw new ReaderException(); - } - } while (bits.available() > 0); - return ASCII_ENCODE; - } - - /** - * See ISO 16022:2006, 5.2.5 and Annex C, Table C.1 - */ - private static void decodeC40Segment(BitSource bits, StringBuilder result) { - // Three C40 values are encoded in a 16-bit value as - // (1600 * C1) + (40 * C2) + C3 + 1 - // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time - bool upperShift = false; - - int[] cValues = new int[3]; - do { - // If there is only one byte left then it will be encoded as ASCII - if (bits.available() == 8) { - return; - } - int firstByte = bits.readBits(8); - if (firstByte == 254) { // Unlatch codeword - return; - } - - parseTwoBytes(firstByte, bits.readBits(8), cValues); - - int shift = 0; - for (int i = 0; i < 3; i++) { - int cValue = cValues[i]; - switch (shift) { - case 0: - if (cValue < 3) { - shift = cValue + 1; - } else { - if (upperShift) { - result.Append((char) (C40_BASIC_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(C40_BASIC_SET_CHARS[cValue]); - } - } - break; - case 1: - if (upperShift) { - result.Append((char) (cValue + 128)); - upperShift = false; - } else { - result.Append(cValue); - } - shift = 0; - break; - case 2: - if (cValue < 27) { - if (upperShift) { - result.Append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(C40_SHIFT2_SET_CHARS[cValue]); - } - } else if (cValue == 27) { // FNC1 - throw new ReaderException(); - } else if (cValue == 30) { // Upper Shift - upperShift = true; - } else { - throw new ReaderException(); - } - shift = 0; - break; - case 3: - if (upperShift) { - result.Append((char) (cValue + 224)); - upperShift = false; - } else { - result.Append((char) (cValue + 96)); - } - shift = 0; - break; - default: - throw new ReaderException(); - } - } - } while (bits.available() > 0); - } - - /** - * See ISO 16022:2006, 5.2.6 and Annex C, Table C.2 - */ - private static void decodeTextSegment(BitSource bits, StringBuilder result) { - // Three Text values are encoded in a 16-bit value as - // (1600 * C1) + (40 * C2) + C3 + 1 - // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time - bool upperShift = false; - - int[] cValues = new int[3]; - do { - // If there is only one byte left then it will be encoded as ASCII - if (bits.available() == 8) { - return; - } - int firstByte = bits.readBits(8); - if (firstByte == 254) { // Unlatch codeword - return; - } - - parseTwoBytes(firstByte, bits.readBits(8), cValues); - - int shift = 0; - for (int i = 0; i < 3; i++) { - int cValue = cValues[i]; - switch (shift) { - case 0: - if (cValue < 3) { - shift = cValue + 1; - } else { - if (upperShift) { - result.Append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(TEXT_BASIC_SET_CHARS[cValue]); - } - } - break; - case 1: - if (upperShift) { - result.Append((char) (cValue + 128)); - upperShift = false; - } else { - result.Append(cValue); - } - shift = 0; - break; - case 2: - // Shift 2 for Text is the same encoding as C40 - if (cValue < 27) { - if (upperShift) { - result.Append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(C40_SHIFT2_SET_CHARS[cValue]); - } - } else if (cValue == 27) { // FNC1 - throw new ReaderException(); - } else if (cValue == 30) { // Upper Shift - upperShift = true; - } else { - throw new ReaderException(); - } - shift = 0; - break; - case 3: - if (upperShift) { - result.Append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(TEXT_SHIFT3_SET_CHARS[cValue]); - } - shift = 0; - break; - default: - throw new ReaderException(); - } - } - } while (bits.available() > 0); - } - - /** - * See ISO 16022:2006, 5.2.7 - */ - private static void decodeAnsiX12Segment(BitSource bits, StringBuilder result) { - // Three ANSI X12 values are encoded in a 16-bit value as - // (1600 * C1) + (40 * C2) + C3 + 1 - - int[] cValues = new int[3]; - do { - // If there is only one byte left then it will be encoded as ASCII - if (bits.available() == 8) { - return; - } - int firstByte = bits.readBits(8); - if (firstByte == 254) { // Unlatch codeword - return; - } - - parseTwoBytes(firstByte, bits.readBits(8), cValues); - - for (int i = 0; i < 3; i++) { - int cValue = cValues[i]; - if (cValue == 0) { // X12 segment terminator - result.Append('\r'); - } else if (cValue == 1) { // X12 segment separator * - result.Append('*'); - } else if (cValue == 2) { // X12 sub-element separator > - result.Append('>'); - } else if (cValue == 3) { // space - result.Append(' '); - } else if (cValue < 14) { // 0 - 9 - result.Append((char) (cValue + 44)); - } else if (cValue < 40) { // A - Z - result.Append((char) (cValue + 51)); - } else { - throw new ReaderException(); - } - } - } while (bits.available() > 0); - } - - private static void parseTwoBytes(int firstByte, int secondByte, int[] result) { - int fullBitValue = (firstByte << 8) + secondByte - 1; - int temp = fullBitValue / 1600; - result[0] = temp; - fullBitValue -= temp * 1600; - temp = fullBitValue / 40; - result[1] = temp; - result[2] = fullBitValue - temp * 40; - } - - /** - * See ISO 16022:2006, 5.2.8 and Annex C Table C.3 - */ - private static void decodeEdifactSegment(BitSource bits, StringBuilder result) { - bool unlatch = false; - do { - // If there is only two or less bytes left then it will be encoded as ASCII - if (bits.available() <= 16) { - return; - } - - for (int i = 0; i < 4; i++) { - int edifactValue = bits.readBits(6); - - // Check for the unlatch character - if (edifactValue == 0x2B67) { // 011111 - unlatch = true; - // If we encounter the unlatch code then continue reading because the Codeword triple - // is padded with 0's - } - - if (!unlatch) { - if ((edifactValue & 32) == 0) { // no 1 in the leading (6th) bit - edifactValue |= 64; // Add a leading 01 to the 6 bit binary value - } - result.Append(edifactValue); - } - } - } while (!unlatch && bits.available() > 0); - } - - /** - * See ISO 16022:2006, 5.2.9 and Annex B, B.2 - */ - private static void decodeBase256Segment(BitSource bits, StringBuilder result, System.Collections.ArrayList byteSegments) { - // Figure out how long the Base 256 Segment is. - int d1 = bits.readBits(8); - int count; - if (d1 == 0) { // Read the remainder of the symbol - count = bits.available() / 8; - } else if (d1 < 250) { - count = d1; - } else { - count = 250 * (d1 - 249) + bits.readBits(8); - } - byte[] bytes = new byte[count]; - for (int i = 0; i < count; i++) { - bytes[i] = unrandomize255State(bits.readBits(8), i); - } - byteSegments.Add(bytes); - try { - result.Append(System.Text.Encoding.GetEncoding("iso-8859-1").GetString(bytes)); - } catch (Exception uee) { - throw new Exception("Platform does not support required encoding: " + uee); - } - } - - /** - * See ISO 16022:2006, Annex B, B.2 - */ - private static byte unrandomize255State(int randomizedBase256Codeword, - int base256CodewordPosition) { - int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1; - int tempVariable = randomizedBase256Codeword - pseudoRandomNumber; - return (byte) (tempVariable >= 0 ? tempVariable : (tempVariable + 256)); - } - } -} diff --git a/qrcode-scanner-live/datamatrix/decoder/Decoder.cs b/qrcode-scanner-live/datamatrix/decoder/Decoder.cs deleted file mode 100644 index d30b4be..0000000 --- a/qrcode-scanner-live/datamatrix/decoder/Decoder.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using com.google.zxing.common; -using com.google.zxing.common.reedsolomon; - -namespace com.google.zxing.datamatrix.decoder -{ - - /** - *

The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting - * the Data Matrix Code from an image.

- * - * @author bbrown@google.com (Brian Brown) - */ - public sealed class Decoder - { - private ReedSolomonDecoder rsDecoder; - public Decoder() { - rsDecoder = new ReedSolomonDecoder(GF256.DATA_MATRIX_FIELD); - } - - /** - *

Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans. - * "true" is taken to mean a black module.

- * - * @param image booleans representing white/black Data Matrix Code modules - * @return text and bytes encoded within the Data Matrix Code - * @throws ReaderException if the Data Matrix Code cannot be decoded - */ - public DecoderResult decode(bool[][] image) { - int dimension = image.Length; - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - if (image[i][j]) { - bits.set(i, j); - } - } - } - return decode(bits); - } - - /** - *

Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken - * to mean a black module.

- * - * @param bits booleans representing white/black Data Matrix Code modules - * @return text and bytes encoded within the Data Matrix Code - * @throws ReaderException if the Data Matrix Code cannot be decoded - */ - public DecoderResult decode(BitMatrix bits) { - - // Construct a parser and read version, error-correction level - BitMatrixParser parser = new BitMatrixParser(bits); - Version version = parser.readVersion(bits); - - // Read codewords - sbyte[] codewords = parser.readCodewords(); - // Separate into data blocks - DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version); - - // Count total number of data bytes - int totalBytes = 0; - for (int i = 0; i < dataBlocks.Length; i++) { - totalBytes += dataBlocks[i].getNumDataCodewords(); - } - sbyte[] resultBytes = new sbyte[totalBytes]; - int resultOffset = 0; - - // Error-correct and copy data blocks together into a stream of bytes - for (int j = 0; j < dataBlocks.Length; j++) { - DataBlock dataBlock = dataBlocks[j]; - sbyte[] codewordBytes = dataBlock.getCodewords(); - int numDataCodewords = dataBlock.getNumDataCodewords(); - correctErrors(codewordBytes, numDataCodewords); - for (int i = 0; i < numDataCodewords; i++) { - resultBytes[resultOffset++] = codewordBytes[i]; - } - } - - // Decode the contents of that stream of bytes - return DecodedBitStreamParser.decode(resultBytes); - } - - /** - *

Given data and error-correction codewords received, possibly corrupted by errors, attempts to - * correct the errors in-place using Reed-Solomon error correction.

- * - * @param codewordBytes data and error correction codewords - * @param numDataCodewords number of codewords that are data bytes - * @throws ReaderException if error correction fails - */ - private void correctErrors(sbyte[] codewordBytes, int numDataCodewords) { - int numCodewords = codewordBytes.Length; - // First read into an array of ints - int[] codewordsInts = new int[numCodewords]; - for (int i = 0; i < numCodewords; i++) { - codewordsInts[i] = codewordBytes[i] & 0xFF; - } - int numECCodewords = codewordBytes.Length - numDataCodewords; - try { - rsDecoder.decode(codewordsInts, numECCodewords); - } catch (ReedSolomonException rse) { - throw new ReaderException(); - } - // Copy back into array of bytes -- only need to worry about the bytes that were data - // We don't care about errors in the error-correction codewords - for (int i = 0; i < numDataCodewords; i++) { - codewordBytes[i] = (sbyte) codewordsInts[i]; - } - } - - } -} diff --git a/qrcode-scanner-live/datamatrix/decoder/Version.cs b/qrcode-scanner-live/datamatrix/decoder/Version.cs deleted file mode 100644 index 25e3274..0000000 --- a/qrcode-scanner-live/datamatrix/decoder/Version.cs +++ /dev/null @@ -1,222 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace com.google.zxing.datamatrix.decoder -{ - public sealed class Version - { - private static Version[] VERSIONS = buildVersions(); - private int versionNumber; - private int symbolSizeRows; - private int symbolSizeColumns; - private int dataRegionSizeRows; - private int dataRegionSizeColumns; - private ECBlocks ecBlocks; - private int totalCodewords; - - private Version(int versionNumber, - int symbolSizeRows, - int symbolSizeColumns, - int dataRegionSizeRows, - int dataRegionSizeColumns, - ECBlocks ecBlocks) { - this.versionNumber = versionNumber; - this.symbolSizeRows = symbolSizeRows; - this.symbolSizeColumns = symbolSizeColumns; - this.dataRegionSizeRows = dataRegionSizeRows; - this.dataRegionSizeColumns = dataRegionSizeColumns; - this.ecBlocks = ecBlocks; - - // Calculate the total number of codewords - int total = 0; - int ecCodewords = ecBlocks.getECCodewords(); - ECB[] ecbArray = ecBlocks.getECBlocks(); - for (int i = 0; i < ecbArray.Length; i++) { - ECB ecBlock = ecbArray[i]; - total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords); - } - this.totalCodewords = total; - } - - public int getVersionNumber() { - return versionNumber; - } - - public int getSymbolSizeRows() { - return symbolSizeRows; - } - - public int getSymbolSizeColumns() { - return symbolSizeColumns; - } - - public int getDataRegionSizeRows() { - return dataRegionSizeRows; - } - - public int getDataRegionSizeColumns() { - return dataRegionSizeColumns; - } - - public int getTotalCodewords() { - return totalCodewords; - } - - public ECBlocks getECBlocks() { - return ecBlocks; - } - - /** - *

Deduces version information from Data Matrix dimensions.

- * - * @param numRows Number of rows in modules - * @param numColumns Number of columns in modules - * @return {@link Version} for a Data Matrix Code of those dimensions - * @throws ReaderException if dimensions do correspond to a valid Data Matrix size - */ - public static Version getVersionForDimensions(int numRows, int numColumns) { - if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0) { - throw new ReaderException(); - } - - // TODO(bbrown): This is doing a linear search through the array of versions. - // If we interleave the rectangular versions with the square versions we could - // do a binary search. - int numVersions = VERSIONS.Length; - for (int i = 0; i < numVersions; ++i){ - Version version = VERSIONS[i]; - if (version.symbolSizeRows == numRows && version.symbolSizeColumns == numColumns) { - return version; - } - } - - throw new ReaderException(); - } - - /** - *

Encapsulates a set of error-correction blocks in one symbol version. Most versions will - * use blocks of differing sizes within one version, so, this encapsulates the parameters for - * each set of blocks. It also holds the number of error-correction codewords per block since it - * will be the same across all blocks within one version.

- */ - public class ECBlocks { - private int ecCodewords; - private ECB[] ecBlocks; - - public ECBlocks(int ecCodewords, ECB ecBlocks) { - this.ecCodewords = ecCodewords; - this.ecBlocks = new ECB[] { ecBlocks }; - } - - public ECBlocks(int ecCodewords, ECB ecBlocks1, ECB ecBlocks2) { - this.ecCodewords = ecCodewords; - this.ecBlocks = new ECB[] { ecBlocks1, ecBlocks2 }; - } - - public int getECCodewords() { - return ecCodewords; - } - - public ECB[] getECBlocks() { - return ecBlocks; - } - } - - /** - *

Encapsualtes the parameters for one error-correction block in one symbol version. - * This includes the number of data codewords, and the number of times a block with these - * parameters is used consecutively in the Data Matrix code version's format.

- */ - public class ECB { - private int count; - private int dataCodewords; - - public ECB(int count, int dataCodewords) { - this.count = count; - this.dataCodewords = dataCodewords; - } - - public int getCount() { - return count; - } - - public int getDataCodewords() { - return dataCodewords; - } - } - - public String toString() { - return versionNumber.ToString(); - } - - /** - * See ISO 16022:2006 5.5.1 Table 7 - */ - private static Version[] buildVersions() { - return new Version[]{ - new Version(1, 10, 10, 8, 8, - new ECBlocks(5, new ECB(1, 3))), - new Version(2, 12, 12, 10, 10, - new ECBlocks(7, new ECB(1, 5))), - new Version(3, 14, 14, 12, 12, - new ECBlocks(10, new ECB(1, 8))), - new Version(4, 16, 16, 14, 14, - new ECBlocks(12, new ECB(1, 12))), - new Version(5, 18, 18, 16, 16, - new ECBlocks(14, new ECB(1, 18))), - new Version(6, 20, 20, 18, 18, - new ECBlocks(18, new ECB(1, 22))), - new Version(7, 22, 22, 20, 20, - new ECBlocks(20, new ECB(1, 30))), - new Version(8, 24, 24, 22, 22, - new ECBlocks(24, new ECB(1, 36))), - new Version(9, 26, 26, 24, 24, - new ECBlocks(28, new ECB(1, 44))), - new Version(10, 32, 32, 14, 14, - new ECBlocks(36, new ECB(1, 62))), - new Version(11, 36, 36, 16, 16, - new ECBlocks(42, new ECB(1, 86))), - new Version(12, 40, 40, 18, 18, - new ECBlocks(48, new ECB(1, 114))), - new Version(13, 44, 44, 20, 20, - new ECBlocks(56, new ECB(1, 144))), - new Version(14, 48, 48, 22, 22, - new ECBlocks(68, new ECB(1, 174))), - new Version(15, 52, 52, 24, 24, - new ECBlocks(42, new ECB(2, 102))), - new Version(16, 64, 64, 14, 14, - new ECBlocks(56, new ECB(2, 140))), - new Version(17, 72, 72, 16, 16, - new ECBlocks(36, new ECB(4, 92))), - new Version(18, 80, 80, 18, 18, - new ECBlocks(48, new ECB(4, 114))), - new Version(19, 88, 88, 20, 20, - new ECBlocks(56, new ECB(4, 144))), - new Version(20, 96, 96, 22, 22, - new ECBlocks(68, new ECB(4, 174))), - new Version(21, 104, 104, 24, 24, - new ECBlocks(56, new ECB(6, 136))), - new Version(22, 120, 120, 18, 18, - new ECBlocks(68, new ECB(6, 175))), - new Version(23, 132, 132, 20, 20, - new ECBlocks(62, new ECB(8, 163))), - new Version(24, 144, 144, 22, 22, - new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))), - new Version(25, 8, 18, 6, 16, - new ECBlocks(7, new ECB(1, 5))), - new Version(26, 8, 32, 6, 14, - new ECBlocks(11, new ECB(1, 10))), - new Version(27, 12, 26, 10, 24, - new ECBlocks(14, new ECB(1, 16))), - new Version(28, 12, 36, 10, 16, - new ECBlocks(18, new ECB(1, 22))), - new Version(29, 16, 36, 10, 16, - new ECBlocks(24, new ECB(1, 32))), - new Version(30, 16, 48, 14, 22, - new ECBlocks(28, new ECB(1, 49))) - }; - } - } -} diff --git a/qrcode-scanner-live/datamatrix/detector/Detector.cs b/qrcode-scanner-live/datamatrix/detector/Detector.cs deleted file mode 100644 index 777d1ab..0000000 --- a/qrcode-scanner-live/datamatrix/detector/Detector.cs +++ /dev/null @@ -1,424 +0,0 @@ -/* - * Copyright 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.datamatrix.detector -{ - /** - *

Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code - * is rotated or skewed, or partially obscured.

- * - * @author Sean Owen - */ - public sealed class Detector - { - private static int MAX_MODULES = 32; - - // Trick to avoid creating new int objects below -- a sort of crude copy of - // the int.valueOf(int) optimization added in Java 5, not in J2ME - private static int[] intS = - {0, 1, 2, 3, 4}; - - private MonochromeBitmapSource image; - - public Detector(MonochromeBitmapSource image) { - this.image = image; - } - - /** - *

Detects a Data Matrix Code in an image.

- * - * @return {@link DetectorResult} encapsulating results of detecting a QR Code - * @throws ReaderException if no Data Matrix Code can be found - */ - public DetectorResult detect() { - - if (!BlackPointEstimationMethod.TWO_D_SAMPLING.Equals(image.getLastEstimationMethod())) { - image.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0); - } - - int height = image.getHeight(); - int width = image.getWidth(); - int halfHeight = height >> 1; - int halfWidth = width >> 1; - int iSkip = Math.Max(1, height / (MAX_MODULES << 3)); - int jSkip = Math.Max(1, width / (MAX_MODULES << 3)); - - int minI = 0; - int maxI = height; - int minJ = 0; - int maxJ = width; - ResultPoint pointA = findCornerFromCenter(halfHeight, -iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 1); - minI = (int) pointA.getY() - 1; - ResultPoint pointB = findCornerFromCenter(halfHeight, 0, minI, maxI, halfWidth, -jSkip, minJ, maxJ, halfHeight >> 1); - minJ = (int) pointB.getX() - 1; - ResultPoint pointC = findCornerFromCenter(halfHeight, 0, minI, maxI, halfWidth, jSkip, minJ, maxJ, halfHeight >> 1); - maxJ = (int) pointC.getX() + 1; - ResultPoint pointD = findCornerFromCenter(halfHeight, iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 1); - maxI = (int) pointD.getY() + 1; - // Go try to find point A again with better information -- might have been off at first. - pointA = findCornerFromCenter(halfHeight, -iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 2); - - // Point A and D are across the diagonal from one another, - // as are B and C. Figure out which are the solid black lines - // by counting transitions - System.Collections.ArrayList transitions = new System.Collections.ArrayList(4); - transitions.Add(transitionsBetween(pointA, pointB)); - transitions.Add(transitionsBetween(pointA, pointC)); - transitions.Add(transitionsBetween(pointB, pointD)); - transitions.Add(transitionsBetween(pointC, pointD)); - Collections.insertionSort(transitions, new ResultPointsAndTransitionsComparator()); - - // Sort by number of transitions. First two will be the two solid sides; last two - // will be the two alternating black/white sides - ResultPointsAndTransitions lSideOne = (ResultPointsAndTransitions) transitions[0]; - ResultPointsAndTransitions lSideTwo = (ResultPointsAndTransitions) transitions[1]; - - // Figure out which point is their intersection by tallying up the number of times we see the - // endpoints in the four endpoints. One will show up twice. - System.Collections.Hashtable pointCount = new System.Collections.Hashtable(); - increment(pointCount, lSideOne.getFrom()); - increment(pointCount, lSideOne.getTo()); - increment(pointCount, lSideTwo.getFrom()); - increment(pointCount, lSideTwo.getTo()); - - ResultPoint maybeTopLeft = null; - ResultPoint bottomLeft = null; - ResultPoint maybeBottomRight = null; - System.Collections.IEnumerator points = pointCount.GetEnumerator(); - - while (points.MoveNext()) { - ResultPoint point = (ResultPoint) points.Current; - int value = (int) pointCount[point]; - if (value == 2) { - bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides - } else { - // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now - if (maybeTopLeft == null) { - maybeTopLeft = point; - } else { - maybeBottomRight = point; - } - } - } - - if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null) { - throw new ReaderException(); - } - - // Bottom left is correct but top left and bottom right might be switched - ResultPoint[] corners = { maybeTopLeft, bottomLeft, maybeBottomRight }; - // Use the dot product trick to sort them out - GenericResultPoint.orderBestPatterns(corners); - - // Now we know which is which: - ResultPoint bottomRight = corners[0]; - bottomLeft = corners[1]; - ResultPoint topLeft = corners[2]; - - // Which point didn't we find in relation to the "L" sides? that's the top right corner - ResultPoint topRight; - if (!pointCount.ContainsKey(pointA)) { - topRight = pointA; - } else if (!pointCount.ContainsKey(pointB)) { - topRight = pointB; - } else if (!pointCount.ContainsKey(pointC)) { - topRight = pointC; - } else { - topRight = pointD; - } - - // Next determine the dimension by tracing along the top or right side and counting black/white - // transitions. Since we start inside a black module, we should see a number of transitions - // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to - // end on a black module: - - // The top right point is actually the corner of a module, which is one of the two black modules - // adjacent to the white module at the top right. Tracing to that corner from either the top left - // or bottom right should work here, but, one will be more reliable since it's traced straight - // up or across, rather than at a slight angle. We use dot products to figure out which is - // better to use: - int dimension; - if (GenericResultPoint.crossProductZ(bottomLeft, bottomRight, topRight) < - GenericResultPoint.crossProductZ(topRight, topLeft, bottomLeft)) { - dimension = transitionsBetween(topLeft, topRight).getTransitions(); - } else { - dimension = transitionsBetween(bottomRight, topRight).getTransitions(); - } - dimension += 2; - - BitMatrix bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, dimension); - return new DetectorResult(bits, new ResultPoint[] {pointA, pointB, pointC, pointD}); - } - - /** - * Attempts to locate a corner of the barcode by scanning up, down, left or right from a center - * point which should be within the barcode. - * - * @param centerI center's i componennt (vertical) - * @param di change in i per step. If scanning up this is negative; down, positive; left or right, 0 - * @param minI minimum value of i to search through (meaningless when di == 0) - * @param maxI maximum value of i - * @param centerJ center's j component (horizontal) - * @param dj same as di but change in j per step instead - * @param minJ see minI - * @param maxJ see minJ - * @param maxWhiteRun maximum run of white pixels that can still be considered to be within - * the barcode - * @return a {@link ResultPoint} encapsulating the corner that was found - * @throws ReaderException if such a point cannot be found - */ - private ResultPoint findCornerFromCenter(int centerI, int di, int minI, int maxI, - int centerJ, int dj, int minJ, int maxJ, - int maxWhiteRun) { - int[] lastRange = null; - for (int i = centerI, j = centerJ; - i < maxI && i >= minI && j < maxJ && j >= minJ; - i += di, j += dj) { - int[] range; - if (dj == 0) { - // horizontal slices, up and down - range = blackWhiteRange(i, maxWhiteRun, minJ, maxJ, true); - } else { - // vertical slices, left and right - range = blackWhiteRange(j, maxWhiteRun, minI, maxI, false); - } - if (range == null) { - if (lastRange == null) { - throw new ReaderException(); - } - // lastRange was found - if (dj == 0) { - int lastI = i - di; - if (lastRange[0] < centerJ) { - if (lastRange[1] > centerJ) { - // straddle, choose one or the other based on direction - return new GenericResultPoint(di > 0 ? lastRange[0] : lastRange[1], lastI); - } - return new GenericResultPoint(lastRange[0], lastI); - } else { - return new GenericResultPoint(lastRange[1], lastI); - } - } else { - int lastJ = j - dj; - if (lastRange[0] < centerI) { - if (lastRange[1] > centerI) { - return new GenericResultPoint(lastJ, dj < 0 ? lastRange[0] : lastRange[1]); - } - return new GenericResultPoint(lastJ, lastRange[0]); - } else { - return new GenericResultPoint(lastJ, lastRange[1]); - } - } - } - lastRange = range; - } - throw new ReaderException(); - } - - /** - * Increments the int associated with a key by one. - */ - private static void increment(System.Collections.Hashtable table, ResultPoint key) { - int value = (int) table[key]; - table[key] = value.Equals(null) ? intS[1] : intS[value + 1]; - //table.put(key, value == null ? intS[1] : intS[value.intValue() + 1]); - } - - /** - * Computes the start and end of a region of pixels, either horizontally or vertically, that could be - * part of a Data Matrix barcode. - * - * @param fixedDimension if scanning horizontally, this is the row (the fixed vertical location) where - * we are scanning. If scanning vertically it's the colummn, the fixed horizontal location - * @param maxWhiteRun largest run of white pixels that can still be considered part of the barcode region - * @param minDim minimum pixel location, horizontally or vertically, to consider - * @param maxDim maximum pixel location, horizontally or vertically, to consider - * @param horizontal if true, we're scanning left-right, instead of up-down - * @return int[] with start and end of found range, or null if no such range is found (e.g. only white was found) - */ - private int[] blackWhiteRange(int fixedDimension, int maxWhiteRun, int minDim, int maxDim, bool horizontal) { - - int center = (minDim + maxDim) / 2; - - BitArray rowOrColumn = horizontal ? image.getBlackRow(fixedDimension, null, 0, image.getWidth()) - : image.getBlackColumn(fixedDimension, null, 0, image.getHeight()); - - // Scan left/up first - int start = center; - while (start >= minDim) { - if (rowOrColumn.get(start)) { - start--; - } else { - int whiteRunStart = start; - do { - start--; - } while (start >= minDim && !rowOrColumn.get(start)); - int whiteRunSize = whiteRunStart - start; - if (start < minDim || whiteRunSize > maxWhiteRun) { - start = whiteRunStart + 1; // back up - break; - } - } - } - start++; - - // Then try right/down - int end = center; - while (end < maxDim) { - if (rowOrColumn.get(end)) { - end++; - } else { - int whiteRunStart = end; - do { - end++; - } while (end < maxDim && !rowOrColumn.get(end)); - int whiteRunSize = end - whiteRunStart; - if (end >= maxDim || whiteRunSize > maxWhiteRun) { - end = whiteRunStart - 1; - break; - } - } - } - end--; - - if (end > start) { - return new int[] { start, end }; - } else { - return null; - } - } - - private static BitMatrix sampleGrid(MonochromeBitmapSource image, - ResultPoint topLeft, - ResultPoint bottomLeft, - ResultPoint bottomRight, - int dimension) { - - // We make up the top right point for now, based on the others. - // TODO: we actually found a fourth corner above and figured out which of two modules - // it was the corner of. We could use that here and adjust for perspective distortion. - float topRightX = (bottomRight.getX() - bottomLeft.getX()) + topLeft.getX(); - float topRightY = (bottomRight.getY() - bottomLeft.getY()) + topLeft.getY(); - - // Note that unlike in the QR Code sampler, we didn't find the center of modules, but the - // very corners. So there is no 0.5f here; 0.0f is right. - GridSampler sampler = GridSampler.Instance; - return sampler.sampleGrid( - image, - dimension, - 0.0f, - 0.0f, - dimension, - 0.0f, - dimension, - dimension, - 0.0f, - dimension, - topLeft.getX(), - topLeft.getY(), - topRightX, - topRightY, - bottomRight.getX(), - bottomRight.getY(), - bottomLeft.getX(), - bottomLeft.getY()); - } - - /** - * Counts the number of black/white transitions between two points, using something like Bresenham's algorithm. - */ - private ResultPointsAndTransitions transitionsBetween(ResultPoint from, ResultPoint to) { - // See QR Code Detector, sizeOfBlackWhiteBlackRun() - int fromX = (int) from.getX(); - int fromY = (int) from.getY(); - int toX = (int) to.getX(); - int toY = (int) to.getY(); - bool steep = Math.Abs(toY - fromY) > Math.Abs(toX - fromX); - if (steep) { - int temp = fromX; - fromX = fromY; - fromY = temp; - temp = toX; - toX = toY; - toY = temp; - } - - int dx = Math.Abs(toX - fromX); - int dy = Math.Abs(toY - fromY); - int error = -dx >> 1; - int ystep = fromY < toY ? 1 : -1; - int xstep = fromX < toX ? 1 : -1; - int transitions = 0; - bool inBlack = image.isBlack(steep ? fromY : fromX, steep ? fromX : fromY); - for (int x = fromX, y = fromY; x != toX; x += xstep) { - bool isBlack = image.isBlack(steep ? y : x, steep ? x : y); - if (isBlack == !inBlack) { - transitions++; - inBlack = isBlack; - } - error += dy; - if (error > 0) { - y += ystep; - error -= dx; - } - } - return new ResultPointsAndTransitions(from, to, transitions); - } - - /** - * Simply encapsulates two points and a number of transitions between them. - */ - private class ResultPointsAndTransitions { - private ResultPoint from; - private ResultPoint to; - private int transitions; - - public ResultPointsAndTransitions(ResultPoint from, ResultPoint to, int transitions) { - this.from = from; - this.to = to; - this.transitions = transitions; - } - - public ResultPoint getFrom() { - return from; - } - public ResultPoint getTo() { - return to; - } - public int getTransitions() { - return transitions; - } - public String toString() { - return from + "/" + to + '/' + transitions; - } - } - - /** - * Orders ResultPointsAndTransitions by number of transitions, ascending. - */ - private class ResultPointsAndTransitionsComparator : Comparator { - public int compare(Object o1, Object o2) { - return ((ResultPointsAndTransitions) o1).getTransitions() - ((ResultPointsAndTransitions) o2).getTransitions(); - } - } - } -} diff --git a/qrcode-scanner-live/obj/Release/com.google.zxing.dll b/qrcode-scanner-live/obj/Release/com.google.zxing.dll deleted file mode 100644 index 107727e..0000000 Binary files a/qrcode-scanner-live/obj/Release/com.google.zxing.dll and /dev/null differ diff --git a/qrcode-scanner-live/obj/Release/com.google.zxing.pdb b/qrcode-scanner-live/obj/Release/com.google.zxing.pdb deleted file mode 100644 index 3aef474..0000000 Binary files a/qrcode-scanner-live/obj/Release/com.google.zxing.pdb and /dev/null differ diff --git a/qrcode-scanner-live/obj/Release/zxing.csproj.FileListAbsolute.txt b/qrcode-scanner-live/obj/Release/zxing.csproj.FileListAbsolute.txt deleted file mode 100644 index 2d04eed..0000000 --- a/qrcode-scanner-live/obj/Release/zxing.csproj.FileListAbsolute.txt +++ /dev/null @@ -1,5 +0,0 @@ -C:\projects\my open source project\zxingsharp\obj\Release\ResolveAssemblyReference.cache -C:\projects\my open source project\zxingsharp\bin\Release\com.google.zxing.dll -C:\projects\my open source project\zxingsharp\bin\Release\com.google.zxing.pdb -C:\projects\my open source project\zxingsharp\obj\Release\com.google.zxing.dll -C:\projects\my open source project\zxingsharp\obj\Release\com.google.zxing.pdb diff --git a/qrcode-scanner-live/oned/AbstractOneDReader.cs b/qrcode-scanner-live/oned/AbstractOneDReader.cs deleted file mode 100644 index 4ffd611..0000000 --- a/qrcode-scanner-live/oned/AbstractOneDReader.cs +++ /dev/null @@ -1,231 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using com.google.zxing.common; - - public abstract class AbstractOneDReader - { - private static int INTEGER_MATH_SHIFT = 8; - public static int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT; - - public Result decode(MonochromeBitmapSource image) { - return decode(image, null); - } - - public Result decode(MonochromeBitmapSource image, System.Collections.Hashtable hints) { - try { - return doDecode(image, hints); - } catch (ReaderException re) { - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - if (tryHarder && image.isRotateSupported()) { - MonochromeBitmapSource rotatedImage = image.rotateCounterClockwise(); - Result result = doDecode(rotatedImage, hints); - // Record that we found it rotated 90 degrees CCW / 270 degrees CW - System.Collections.Hashtable metadata = result.getResultMetadata(); - int orientation = 270; - if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION)) { - // But if we found it reversed in doDecode(), add in that result here: - orientation = (orientation + ((int) metadata[ResultMetadataType.ORIENTATION])) % 360; - } - result.putMetadata(ResultMetadataType.ORIENTATION, orientation); - return result; - } else { - throw re; - } - } - } - - /** - * We're going to examine rows from the middle outward, searching alternately above and below the - * middle, and farther out each time. rowStep is the number of rows between each successive - * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then - * middle + rowStep, then middle - (2 * rowStep), etc. - * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily - * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the - * image if "trying harder". - * - * @param image The image to decode - * @param hints Any hints that were requested - * @return The contents of the decoded barcode - * @throws ReaderException Any spontaneous errors which occur - */ - private Result doDecode(MonochromeBitmapSource image, System.Collections.Hashtable hints) { - int width = image.getWidth(); - int height = image.getHeight(); - BitArray row = new BitArray(width); - - int middle = height >> 1; - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - int rowStep = Math.Max(1, height >> (tryHarder ? 7 : 4)); - int MaxLines; - if (tryHarder) { - MaxLines = height; // Look at the whole image, not just the center - } else { - MaxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image - } - - for (int x = 0; x < MaxLines; x++) { - - // Scanning from the middle out. Determine which row we're looking at next: - int rowStepsAboveOrBelow = (x + 1) >> 1; - bool isAbove = (x & 0x01) == 0; // i.e. is x even? - int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); - if (rowNumber < 0 || rowNumber >= height) { - // Oops, if we run off the top or bottom, stop - break; - } - - // Estimate black point for this row and load it: - try { - image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber); - } catch (ReaderException re) { - continue; - } - - image.getBlackRow(rowNumber, row,0, width); - - // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to - // handle decoding upside down barcodes. - for (int attempt = 0; attempt < 2; attempt++) { - if (attempt == 1) { // trying again? - row.reverse(); // reverse the row and continue - } - try { - // Look for a barcode - Result result = decodeRow(rowNumber, row, hints); - // We found our barcode - if (attempt == 1) { - // But it was upside down, so note that - result.putMetadata(ResultMetadataType.ORIENTATION, 180); - // And remember to flip the result points horizontally. - ResultPoint[] points = result.getResultPoints(); - points[0] = (ResultPoint) new GenericResultPoint(width - points[0].getX() - 1, points[0].getY()); - points[1] = (ResultPoint)new GenericResultPoint(width - points[1].getX() - 1, points[1].getY()); - } - return result; - } catch (ReaderException re) { - // continue -- just couldn't decode this row - } - } - } - - throw new ReaderException(); - } - - /** - * Records the size of successive runs of white and black pixels in a row, starting at a given point. - * The values are recorded in the given array, and the number of runs recorded is equal to the size - * of the array. If the row starts on a white pixel at the given start point, then the first count - * recorded is the run of white pixels starting from that point; likewise it is the count of a run - * of black pixels if the row begin on a black pixels at that point. - * - * @param row row to count from - * @param start offset into row to start at - * @param counters array into which to record counts - * @throws ReaderException if counters cannot be filled entirely from row before running out of pixels - */ - public static void recordPattern(BitArray row, int start, int[] counters) { - int numCounters = counters.Length; - for (int i = 0; i < numCounters; i++) { - counters[i] = 0; - } - int end = row.getSize(); - if (start >= end) { - throw new ReaderException(); - } - bool isWhite = !row.get(start); - int counterPosition = 0; - - int k = start; - while (k < end) { - bool pixel = row.get(k); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - counterPosition++; - if (counterPosition == numCounters) { - break; - } else { - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - k++; - } - // If we read fully the last section of pixels and filled up our counters -- or filled - // the last counter but ran off the side of the image, OK. Otherwise, a problem. - if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && k == end))) { - throw new ReaderException(); - } - } - - /** - * Determines how closely a set of observed counts of runs of black/white values matches a given - * target pattern. This is reported as the ratio of the total variance from the expected pattern - * proportions across all pattern elements, to the length of the pattern. - * - * @param counters observed counters - * @param pattern expected pattern - * @param MaxIndividualVariance The most any counter can differ before we give up - * @return ratio of total variance between counters and pattern compared to total pattern size, - * where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means - * the total variance between counters and patterns equals the pattern length, higher values mean - * even more variance - */ - public static int patternMatchVariance(int[] counters, int[] pattern, int MaxIndividualVariance) { - int numCounters = counters.Length; - int total = 0; - int patternLength = 0; - for (int i = 0; i < numCounters; i++) { - total += counters[i]; - patternLength += pattern[i]; - } - if (total < patternLength) { - // If we don't even have one pixel per unit of bar width, assume this is too small - // to reliably match, so fail: - return int.MaxValue; - } - // We're going to fake floating-point math in integers. We just need to use more bits. - // Scale up patternLength so that intermediate values below like scaledCounter will have - // more "significant digits" - int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength; - MaxIndividualVariance = (MaxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT; - - int totalVariance = 0; - for (int x = 0; x < numCounters; x++) { - int counter = counters[x] << INTEGER_MATH_SHIFT; - int scaledPattern = pattern[x] * unitBarWidth; - int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter; - if (variance > MaxIndividualVariance) { - return int.MaxValue; - } - totalVariance += variance; - } - return totalVariance / total; - } - - // This declaration should not be necessary, since this class is - // abstract and so does not have to provide an implementation for every - // method of an interface it implements, but it is causing NoSuchMethodError - // issues on some Nokia JVMs. So we add this superfluous declaration: - - public abstract Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints); - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/AbstractUPCEANReader.cs b/qrcode-scanner-live/oned/AbstractUPCEANReader.cs deleted file mode 100644 index ef18078..0000000 --- a/qrcode-scanner-live/oned/AbstractUPCEANReader.cs +++ /dev/null @@ -1,295 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using System.Text; - using com.google.zxing.common; - - /** - *

Encapsulates functionality and implementation that is common to UPC and EAN families - * of one-dimensional barcodes.

- * - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - * @author alasdair@google.com (Alasdair Mackintosh) - */ - - public abstract class AbstractUPCEANReader : AbstractOneDReader,UPCEANReader - { - private static int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f); - private static int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); - - /** - * Start/end guard pattern. - */ - private static int[] START_END_PATTERN = {1, 1, 1,}; - - /** - * Pattern marking the middle of a UPC/EAN pattern, separating the two halves. - */ - public static int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1}; - - /** - * "Odd", or "L" patterns used to encode UPC/EAN digits. - */ - public static int[][] L_PATTERNS = new int[][]{ - new int[]{3, 2, 1, 1}, // 0 - new int[]{2, 2, 2, 1}, // 1 - new int[]{2, 1, 2, 2}, // 2 - new int[]{1, 4, 1, 1}, // 3 - new int[]{1, 1, 3, 2}, // 4 - new int[]{1, 2, 3, 1}, // 5 - new int[]{1, 1, 1, 4}, // 6 - new int[]{1, 3, 1, 2}, // 7 - new int[]{1, 2, 1, 3}, // 8 - new int[]{3, 1, 1, 2} // 9 - }; - - /** - * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits. - */ - public static int[][] L_AND_G_PATTERNS=new int[20][]; - - //static { - // L_AND_G_PATTERNS = new int[20][]; - // for (int i = 0; i < 10; i++) { - // L_AND_G_PATTERNS[i] = L_PATTERNS[i]; - // } - // for (int i = 10; i < 20; i++) { - // int[] widths = L_PATTERNS[i - 10]; - // int[] reversedWidths = new int[widths.length]; - // for (int j = 0; j < widths.length; j++) { - // reversedWidths[j] = widths[widths.length - j - 1]; - // } - // L_AND_G_PATTERNS[i] = reversedWidths; - // } - //} - - private StringBuilder decodeRowStringBuffer; - - protected AbstractUPCEANReader() { - for (int i = 0; i < 10; i++) { - L_AND_G_PATTERNS[i] = L_PATTERNS[i]; - } - for (int i = 10; i < 20; i++) { - int[] widths = L_PATTERNS[i - 10]; - int[] reversedWidths = new int[widths.Length]; - for (int j = 0; j < widths.Length; j++) { - reversedWidths[j] = widths[widths.Length - j - 1]; - } - L_AND_G_PATTERNS[i] = reversedWidths; - } - decodeRowStringBuffer = new StringBuilder(20); - } - - public static int[] findStartGuardPattern(BitArray row) { - bool foundStart = false; - int[] startRange = null; - int nextStart = 0; - while (!foundStart) { - startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN); - int start = startRange[0]; - nextStart = startRange[1]; - // Make sure there is a quiet zone at least as big as the start pattern before the barcode. If - // this check would run off the left edge of the image, do not accept this barcode, as it is - // very likely to be a false positive. - int quietStart = start - (nextStart - start); - if (quietStart >= 0) { - foundStart = row.isRange(quietStart, start, false); - } - } - return startRange; - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - return decodeRow(rowNumber, row, findStartGuardPattern(row)); - } - - public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange) { - StringBuilder result = decodeRowStringBuffer; - result.Length = 0; - int endStart = decodeMiddle(row, startGuardRange, result); - int[] endRange = decodeEnd(row, endStart); - - // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The - // spec might want more whitespace, but in practice this is the maximum we can count on. - int end = endRange[1]; - int quietEnd = end + (end - endRange[0]); - if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) { - throw new ReaderException(); - } - - String resultString = result.ToString(); - if (!checkChecksum(resultString)) { - throw new ReaderException(); - } - - float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f; - float right = (float) (endRange[1] + endRange[0]) / 2.0f; - return new Result(resultString, - null, // no natural byte representation for these barcodes - new ResultPoint[]{ - new GenericResultPoint(left, (float) rowNumber), - new GenericResultPoint(right, (float) rowNumber)}, - getBarcodeFormat()); - } - - public abstract BarcodeFormat getBarcodeFormat(); - - /** - * @return {@link #checkStandardUPCEANChecksum(String)} - */ - public bool checkChecksum(String s) { - return checkStandardUPCEANChecksum(s); - } - - /** - * Computes the UPC/EAN checksum on a string of digits, and reports - * whether the checksum is correct or not. - * - * @param s string of digits to check - * @return true iff string of digits passes the UPC/EAN checksum algorithm - * @throws ReaderException if the string does not contain only digits - */ - public static bool checkStandardUPCEANChecksum(String s) { - int length = s.Length; - if (length == 0) { - return false; - } - - int sum = 0; - for (int i = length - 2; i >= 0; i -= 2) { - int digit = (int) s[i] - (int) '0'; - if (digit < 0 || digit > 9) { - throw new ReaderException(); - } - sum += digit; - } - sum *= 3; - for (int i = length - 1; i >= 0; i -= 2) { - int digit = (int) s[i] - (int) '0'; - if (digit < 0 || digit > 9) { - throw new ReaderException(); - } - sum += digit; - } - return sum % 10 == 0; - } - - /** - * Subclasses override this to decode the portion of a barcode between the start and end guard patterns. - * - * @param row row of black/white values to search - * @param startRange start/end offset of start guard pattern - * @param resultString {@link StringBuffer} to append decoded chars to - * @return horizontal offset of first pixel after the "middle" that was decoded - * @throws ReaderException if decoding could not complete successfully - */ - protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString); - - int[] decodeEnd(BitArray row, int endStart) { - return findGuardPattern(row, endStart, false, START_END_PATTERN); - } - - /** - * @param row row of black/white values to search - * @param rowOffset position to start search - * @param whiteFirst if true, indicates that the pattern specifies white/black/white/... - * pixel counts, otherwise, it is interpreted as black/white/black/... - * @param pattern pattern of counts of number of black and white pixels that are being - * searched for as a pattern - * @return start/end horizontal offset of guard pattern, as an array of two ints - * @throws ReaderException if pattern is not found - */ - public static int[] findGuardPattern(BitArray row, int rowOffset, bool whiteFirst, int[] pattern) - { - int patternLength = pattern.Length; - int[] counters = new int[patternLength]; - int width = row.getSize(); - bool isWhite = false; - while (rowOffset < width) { - isWhite = !row.get(rowOffset); - if (whiteFirst == isWhite) { - break; - } - rowOffset++; - } - - int counterPosition = 0; - int patternStart = rowOffset; - for (int x = rowOffset; x < width; x++) { - bool pixel = row.get(x); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - if (counterPosition == patternLength - 1) { - if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { - return new int[]{patternStart, x}; - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } else { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw new ReaderException(); - } - - /** - * Attempts to decode a single UPC/EAN-encoded digit. - * - * @param row row of black/white values to decode - * @param counters the counts of runs of observed black/white/black/... values - * @param rowOffset horizontal offset to start decoding from - * @param patterns the set of patterns to use to decode -- sometimes different encodings - * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should - * be used - * @return horizontal offset of first pixel beyond the decoded digit - * @throws ReaderException if digit cannot be decoded - */ - public static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns) - { - recordPattern(row, rowOffset, counters); - int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept - int bestMatch = -1; - int max = patterns.Length; - for (int i = 0; i < max; i++) { - int[] pattern = patterns[i]; - int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) { - bestVariance = variance; - bestMatch = i; - } - } - if (bestMatch >= 0) { - return bestMatch; - } else { - throw new ReaderException(); - } - } - - - } - - -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/Code128Reader.cs b/qrcode-scanner-live/oned/Code128Reader.cs deleted file mode 100644 index 3be0c5a..0000000 --- a/qrcode-scanner-live/oned/Code128Reader.cs +++ /dev/null @@ -1,459 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using System.Text; - using com.google.zxing.common; - - - public sealed class Code128Reader : AbstractOneDReader - { - private static int[][] CODE_PATTERNS = new int[][]{ - new int[]{2, 1, 2, 2, 2, 2}, // 0 - new int[]{2, 2, 2, 1, 2, 2}, - new int[]{2, 2, 2, 2, 2, 1}, - new int[]{1, 2, 1, 2, 2, 3}, - new int[]{1, 2, 1, 3, 2, 2}, - new int[]{1, 3, 1, 2, 2, 2}, // 5 - new int[]{1, 2, 2, 2, 1, 3}, - new int[]{1, 2, 2, 3, 1, 2}, - new int[]{1, 3, 2, 2, 1, 2}, - new int[]{2, 2, 1, 2, 1, 3}, - new int[]{2, 2, 1, 3, 1, 2}, // 10 - new int[]{2, 3, 1, 2, 1, 2}, - new int[]{1, 1, 2, 2, 3, 2}, - new int[]{1, 2, 2, 1, 3, 2}, - new int[]{1, 2, 2, 2, 3, 1}, - new int[]{1, 1, 3, 2, 2, 2}, // 15 - new int[]{1, 2, 3, 1, 2, 2}, - new int[]{1, 2, 3, 2, 2, 1}, - new int[]{2, 2, 3, 2, 1, 1}, - new int[]{2, 2, 1, 1, 3, 2}, - new int[]{2, 2, 1, 2, 3, 1}, // 20 - new int[]{2, 1, 3, 2, 1, 2}, - new int[]{2, 2, 3, 1, 1, 2}, - new int[]{3, 1, 2, 1, 3, 1}, - new int[]{3, 1, 1, 2, 2, 2}, - new int[]{3, 2, 1, 1, 2, 2}, // 25 - new int[]{3, 2, 1, 2, 2, 1}, - new int[]{3, 1, 2, 2, 1, 2}, - new int[]{3, 2, 2, 1, 1, 2}, - new int[]{3, 2, 2, 2, 1, 1}, - new int[]{2, 1, 2, 1, 2, 3}, // 30 - new int[]{2, 1, 2, 3, 2, 1}, - new int[]{2, 3, 2, 1, 2, 1}, - new int[]{1, 1, 1, 3, 2, 3}, - new int[]{1, 3, 1, 1, 2, 3}, - new int[]{1, 3, 1, 3, 2, 1}, // 35 - new int[]{1, 1, 2, 3, 1, 3}, - new int[]{1, 3, 2, 1, 1, 3}, - new int[]{1, 3, 2, 3, 1, 1}, - new int[]{2, 1, 1, 3, 1, 3}, - new int[]{2, 3, 1, 1, 1, 3}, // 40 - new int[]{2, 3, 1, 3, 1, 1}, - new int[]{1, 1, 2, 1, 3, 3}, - new int[]{1, 1, 2, 3, 3, 1}, - new int[]{1, 3, 2, 1, 3, 1}, - new int[]{1, 1, 3, 1, 2, 3}, // 45 - new int[]{1, 1, 3, 3, 2, 1}, - new int[]{1, 3, 3, 1, 2, 1}, - new int[]{3, 1, 3, 1, 2, 1}, - new int[]{2, 1, 1, 3, 3, 1}, - new int[]{2, 3, 1, 1, 3, 1}, // 50 - new int[]{2, 1, 3, 1, 1, 3}, - new int[]{2, 1, 3, 3, 1, 1}, - new int[]{2, 1, 3, 1, 3, 1}, - new int[]{3, 1, 1, 1, 2, 3}, - new int[]{3, 1, 1, 3, 2, 1}, // 55 - new int[]{3, 3, 1, 1, 2, 1}, - new int[]{3, 1, 2, 1, 1, 3}, - new int[]{3, 1, 2, 3, 1, 1}, - new int[]{3, 3, 2, 1, 1, 1}, - new int[]{3, 1, 4, 1, 1, 1}, // 60 - new int[]{2, 2, 1, 4, 1, 1}, - new int[]{4, 3, 1, 1, 1, 1}, - new int[]{1, 1, 1, 2, 2, 4}, - new int[]{1, 1, 1, 4, 2, 2}, - new int[] {1, 2, 1, 1, 2, 4}, // 65 - new int[]{1, 2, 1, 4, 2, 1}, - new int[]{1, 4, 1, 1, 2, 2}, - new int[]{1, 4, 1, 2, 2, 1}, - new int[]{1, 1, 2, 2, 1, 4}, - new int[]{1, 1, 2, 4, 1, 2}, // 70 - new int[]{1, 2, 2, 1, 1, 4}, - new int[]{1, 2, 2, 4, 1, 1}, - new int[]{1, 4, 2, 1, 1, 2}, - new int[]{1, 4, 2, 2, 1, 1}, - new int[]{2, 4, 1, 2, 1, 1}, // 75 - new int[]{2, 2, 1, 1, 1, 4}, - new int[]{4, 1, 3, 1, 1, 1}, - new int[]{2, 4, 1, 1, 1, 2}, - new int[]{1, 3, 4, 1, 1, 1}, - new int[]{1, 1, 1, 2, 4, 2}, // 80 - new int[]{1, 2, 1, 1, 4, 2}, - new int[]{1, 2, 1, 2, 4, 1}, - new int[]{1, 1, 4, 2, 1, 2}, - new int[]{1, 2, 4, 1, 1, 2}, - new int[]{1, 2, 4, 2, 1, 1}, // 85 - new int[]{4, 1, 1, 2, 1, 2}, - new int[]{4, 2, 1, 1, 1, 2}, - new int[]{4, 2, 1, 2, 1, 1}, - new int[]{2, 1, 2, 1, 4, 1}, - new int[]{2, 1, 4, 1, 2, 1}, // 90 - new int[]{4, 1, 2, 1, 2, 1}, - new int[]{1, 1, 1, 1, 4, 3}, - new int[]{1, 1, 1, 3, 4, 1}, - new int[]{1, 3, 1, 1, 4, 1}, - new int[]{1, 1, 4, 1, 1, 3}, // 95 - new int[]{1, 1, 4, 3, 1, 1}, - new int[]{4, 1, 1, 1, 1, 3}, - new int[]{4, 1, 1, 3, 1, 1}, - new int[]{1, 1, 3, 1, 4, 1}, - new int[]{1, 1, 4, 1, 3, 1}, // 100 - new int[]{3, 1, 1, 1, 4, 1}, - new int[]{4, 1, 1, 1, 3, 1}, - new int[]{2, 1, 1, 4, 1, 2}, - new int[]{2, 1, 1, 2, 1, 4}, - new int[]{2, 1, 1, 2, 3, 2}, // 105 - new int[]{2, 3, 3, 1, 1, 1, 2} - }; - - private static int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f); - private static int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); - - private const int CODE_SHIFT = 98; - - private const int CODE_CODE_C = 99; - private const int CODE_CODE_B = 100; - private const int CODE_CODE_A = 101; - - private const int CODE_FNC_1 = 102; - private const int CODE_FNC_2 = 97; - private const int CODE_FNC_3 = 96; - private const int CODE_FNC_4_A = 101; - private const int CODE_FNC_4_B = 100; - - private const int CODE_START_A = 103; - private const int CODE_START_B = 104; - private const int CODE_START_C = 105; - private const int CODE_STOP = 106; - - private static int[] findStartPattern(BitArray row) { - int width = row.getSize(); - int rowOffset = 0; - while (rowOffset < width) { - if (row.get(rowOffset)) { - break; - } - rowOffset++; - } - - int counterPosition = 0; - int[] counters = new int[6]; - int patternStart = rowOffset; - bool isWhite = false; - int patternLength = counters.Length; - - for (int i = rowOffset; i < width; i++) { - bool pixel = row.get(i); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - if (counterPosition == patternLength - 1) { - int bestVariance = MAX_AVG_VARIANCE; - int bestMatch = -1; - for (int startCode = CODE_START_A; startCode <= CODE_START_C; startCode++) { - int variance = patternMatchVariance(counters, CODE_PATTERNS[startCode], MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) { - bestVariance = variance; - bestMatch = startCode; - } - } - if (bestMatch >= 0) { - // Look for whitespace before start pattern, >= 50% of width of start pattern - if (row.isRange(Math.Max(0, patternStart - (i - patternStart) / 2), patternStart, false)) { - return new int[]{patternStart, i, bestMatch}; - } - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } else { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw new ReaderException(); - } - - private static int decodeCode(BitArray row, int[] counters, int rowOffset) { - recordPattern(row, rowOffset, counters); - int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept - int bestMatch = -1; - for (int d = 0; d < CODE_PATTERNS.Length; d++) { - int[] pattern = CODE_PATTERNS[d]; - int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) { - bestVariance = variance; - bestMatch = d; - } - } - // TODO We're overlooking the fact that the STOP pattern has 7 values, not 6 - if (bestMatch >= 0) { - return bestMatch; - } else { - throw new ReaderException(); - } - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - - int[] startPatternInfo = findStartPattern(row); - int startCode = startPatternInfo[2]; - int codeSet; - switch (startCode) { - case CODE_START_A: - codeSet = CODE_CODE_A; - break; - case CODE_START_B: - codeSet = CODE_CODE_B; - break; - case CODE_START_C: - codeSet = CODE_CODE_C; - break; - default: - throw new ReaderException(); - } - - bool done = false; - bool isNextShifted = false; - - StringBuilder result = new StringBuilder(); - int lastStart = startPatternInfo[0]; - int nextStart = startPatternInfo[1]; - int[] counters = new int[6]; - - int lastCode = 0; - int code = 0; - int checksumTotal = startCode; - int multiplier = 0; - bool lastCharacterWasPrintable = true; - - while (!done) { - - bool unshift = isNextShifted; - isNextShifted = false; - - // Save off last code - lastCode = code; - - // Decode another code from image - code = decodeCode(row, counters, nextStart); - - // Remember whether the last code was printable or not (excluding CODE_STOP) - if (code != CODE_STOP) { - lastCharacterWasPrintable = true; - } - - // Add to checksum computation (if not CODE_STOP of course) - if (code != CODE_STOP) { - multiplier++; - checksumTotal += multiplier * code; - } - - // Advance to where the next code will to start - lastStart = nextStart; - for (int i = 0; i < counters.Length; i++) { - nextStart += counters[i]; - } - - // Take care of illegal start codes - switch (code) { - case CODE_START_A: - case CODE_START_B: - case CODE_START_C: - throw new ReaderException(); - } - - switch (codeSet) { - - case CODE_CODE_A: - if (code < 64) { - result.Append((char) (' ' + code)); - } else if (code < 96) { - result.Append((char) (code - 64)); - } else { - // Don't let CODE_STOP, which always appears, affect whether whether we think the last code - // was printable or not - if (code != CODE_STOP) { - lastCharacterWasPrintable = false; - } - switch (code) { - case CODE_FNC_1: - case CODE_FNC_2: - case CODE_FNC_3: - case CODE_FNC_4_A: - // do nothing? - break; - case CODE_SHIFT: - isNextShifted = true; - codeSet = CODE_CODE_B; - break; - case CODE_CODE_B: - codeSet = CODE_CODE_B; - break; - case CODE_CODE_C: - codeSet = CODE_CODE_C; - break; - case CODE_STOP: - done = true; - break; - } - } - break; - case CODE_CODE_B: - if (code < 96) { - result.Append((char) (' ' + code)); - } else { - if (code != CODE_STOP) { - lastCharacterWasPrintable = false; - } - switch (code) { - case CODE_FNC_1: - case CODE_FNC_2: - case CODE_FNC_3: - case CODE_FNC_4_B: - // do nothing? - break; - case CODE_SHIFT: - isNextShifted = true; - codeSet = CODE_CODE_C; - break; - case CODE_CODE_A: - codeSet = CODE_CODE_A; - break; - case CODE_CODE_C: - codeSet = CODE_CODE_C; - break; - case CODE_STOP: - done = true; - break; - } - } - break; - case CODE_CODE_C: - if (code < 100) { - if (code < 10) { - result.Append('0'); - } - result.Append(code); - } else { - if (code != CODE_STOP) { - lastCharacterWasPrintable = false; - } - switch (code) { - case CODE_FNC_1: - // do nothing? - break; - case CODE_CODE_A: - codeSet = CODE_CODE_A; - break; - case CODE_CODE_B: - codeSet = CODE_CODE_B; - break; - case CODE_STOP: - done = true; - break; - } - } - break; - } - - // Unshift back to another code set if we were shifted - if (unshift) { - switch (codeSet) { - case CODE_CODE_A: - codeSet = CODE_CODE_C; - break; - case CODE_CODE_B: - codeSet = CODE_CODE_A; - break; - case CODE_CODE_C: - codeSet = CODE_CODE_B; - break; - } - } - - } - - // Check for ample whitespice following pattern, but, to do this we first need to remember that we - // fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left to read off. - // Would be slightly better to properly read. Here we just skip it: - while (row.get(nextStart)) { - nextStart++; - } - if (!row.isRange(nextStart, Math.Min(row.getSize(), nextStart + (nextStart - lastStart) / 2), false)) { - throw new ReaderException(); - } - - // Pull out from sum the value of the penultimate check code - checksumTotal -= multiplier * lastCode; - // lastCode is the checksum then: - if (checksumTotal % 103 != lastCode) { - throw new ReaderException(); - } - - // Need to pull out the check digits from string - int resultLength = result.Length; - // Only bother if, well, the result had at least one character, and if the checksum digit happened - // to be a printable character. If it was just interpreted as a control code, nothing to remove - if (resultLength > 0 && lastCharacterWasPrintable) { - if (codeSet == CODE_CODE_C) { - result.Remove(resultLength - 2, 2); - } else { - result.Remove(resultLength - 1, 1); - } - } - - String resultString = result.ToString(); - - if (resultString.Length == 0) { - // Almost surely a false positive - throw new ReaderException(); - } - - float left = (float) (startPatternInfo[1] + startPatternInfo[0]) / 2.0f; - float right = (float) (nextStart + lastStart) / 2.0f; - return new Result( - resultString, - null, - new ResultPoint[]{ - new GenericResultPoint(left, (float) rowNumber), - new GenericResultPoint(right, (float) rowNumber)}, - BarcodeFormat.CODE_128); - - } - - } - - - -} diff --git a/qrcode-scanner-live/oned/Code39Reader.cs b/qrcode-scanner-live/oned/Code39Reader.cs deleted file mode 100644 index ebddc97..0000000 --- a/qrcode-scanner-live/oned/Code39Reader.cs +++ /dev/null @@ -1,319 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using System.Text; - using com.google.zxing.common; - - - public sealed class Code39Reader : AbstractOneDReader - { - private static String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; - private static char[] ALPHABET = ALPHABET_STRING.ToCharArray(); - - /** - * These represent the encodings of characters, as patterns of wide and narrow bars. - * The 9 least-significant bits of each int correspond to the pattern of wide and narrow, - * with 1s representing "wide" and 0s representing narrow. - */ - private static int[] CHARACTER_ENCODINGS = { - 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9 - 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J - 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T - 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-* - 0x0A8, 0x0A2, 0x08A, 0x02A // $-% - }; - - private static int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; - - private bool usingCheckDigit; - private bool extendedMode; - - /** - * Creates a reader that assumes all encoded data is data, and does not treat the - * character as a check digit. It will not decoded "extended Code 39" sequences. - */ - public Code39Reader() { - usingCheckDigit = false; - extendedMode = false; - } - - /** - * Creates a reader that can be configured to check the last character as a check digit. - * It will not decoded "extended Code 39" sequences. - * - * @param usingCheckDigit if true, treat the last data character as a check digit, not - * data, and verify that the checksum passes. - */ - public Code39Reader(bool usingCheckDigit) { - this.usingCheckDigit = usingCheckDigit; - this.extendedMode = false; - } - - /** - * Creates a reader that can be configured to check the last character as a check digit, - * or optionally attempt to decode "extended Code 39" sequences that are used to encode - * the full ASCII character set. - * - * @param usingCheckDigit if true, treat the last data character as a check digit, not - * data, and verify that the checksum passes. - * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the - * text. - */ - public Code39Reader(bool usingCheckDigit, bool extendedMode) { - this.usingCheckDigit = usingCheckDigit; - this.extendedMode = extendedMode; - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - - int[] start = findAsteriskPattern(row); - int nextStart = start[1]; - int end = row.getSize(); - - // Read off white space - while (nextStart < end && !row.get(nextStart)) { - nextStart++; - } - - StringBuilder result = new StringBuilder(); - int[] counters = new int[9]; - char decodedChar; - int lastStart; - do { - recordPattern(row, nextStart, counters); - int pattern = toNarrowWidePattern(counters); - decodedChar = patternToChar(pattern); - result.Append(decodedChar); - lastStart = nextStart; - for (int i = 0; i < counters.Length; i++) { - nextStart += counters[i]; - } - // Read off white space - while (nextStart < end && !row.get(nextStart)) { - nextStart++; - } - } while (decodedChar != '*'); - - result.Remove(result.Length - 1, 1); // remove asterisk - - // Look for whitespace after pattern: - int lastPatternSize = 0; - for (int i = 0; i < counters.Length; i++) { - lastPatternSize += counters[i]; - } - int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; - // If 50% of last pattern size, following last pattern, is not whitespace, fail - // (but if it's whitespace to the very end of the image, that's OK) - if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) { - throw new ReaderException(); - } - - if (usingCheckDigit) { - int max = result.Length - 1; - int total = 0; - for (int i = 0; i < max; i++) { - total += ALPHABET_STRING.IndexOf(result[i]); - } - if (total % 43 != ALPHABET_STRING.IndexOf(result[max])) - { - throw new ReaderException(); - } - result.Remove(max,1); - } - - String resultString = result.ToString(); - if (extendedMode) { - resultString = decodeExtended(resultString); - } - - if (resultString.Length == 0) { - // Almost surely a false positive - throw new ReaderException(); - } - - float left = (float) (start[1] + start[0]) / 2.0f; - float right = (float) (nextStart + lastStart) / 2.0f; - return new Result( - resultString, - null, - new ResultPoint[]{ - new GenericResultPoint(left, (float) rowNumber), - new GenericResultPoint(right, (float) rowNumber)}, - BarcodeFormat.CODE_39); - - } - - private static int[] findAsteriskPattern(BitArray row) { - int width = row.getSize(); - int rowOffset = 0; - while (rowOffset < width) { - if (row.get(rowOffset)) { - break; - } - rowOffset++; - } - - int counterPosition = 0; - int[] counters = new int[9]; - int patternStart = rowOffset; - bool isWhite = false; - int patternLength = counters.Length; - - for (int i = rowOffset; i < width; i++) { - bool pixel = row.get(i); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - if (counterPosition == patternLength - 1) { - try { - if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) { - // Look for whitespace before start pattern, >= 50% of width of start pattern - if (row.isRange(Math.Max(0, patternStart - (i - patternStart) / 2), patternStart, false)) { - return new int[]{patternStart, i}; - } - } - } catch (ReaderException re) { - // no match, continue - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } else { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw new ReaderException(); - } - - private static int toNarrowWidePattern(int[] counters) { - int numCounters = counters.Length; - int maxNarrowCounter = 0; - int wideCounters; - do { - int minCounter = int.MaxValue; - for (int i = 0; i < numCounters; i++) { - int counter = counters[i]; - if (counter < minCounter && counter > maxNarrowCounter) { - minCounter = counter; - } - } - maxNarrowCounter = minCounter; - wideCounters = 0; - int totalWideCountersWidth = 0; - int pattern = 0; - for (int i = 0; i < numCounters; i++) { - int counter = counters[i]; - if (counters[i] > maxNarrowCounter) { - pattern |= 1 << (numCounters - 1 - i); - wideCounters++; - totalWideCountersWidth += counter; - } - } - if (wideCounters == 3) { - // Found 3 wide counters, but are they close enough in width? - // We can perform a cheap, conservative check to see if any individual - // counter is more than 1.5 times the average: - for (int i = 0; i < numCounters && wideCounters > 0; i++) { - int counter = counters[i]; - if (counters[i] > maxNarrowCounter) { - wideCounters--; - // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average - if ((counter << 1) >= totalWideCountersWidth) { - throw new ReaderException(); - } - } - } - return pattern; - } - } while (wideCounters > 3); - throw new ReaderException(); - } - - private static char patternToChar(int pattern) { - for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++) { - if (CHARACTER_ENCODINGS[i] == pattern) { - return ALPHABET[i]; - } - } - throw new ReaderException(); - } - - private static String decodeExtended(String encoded) { - int Length = encoded.Length; - StringBuilder decoded = new StringBuilder(Length); - for (int i = 0; i < Length; i++) { - char c = encoded[i]; - if (c == '+' || c == '$' || c == '%' || c == '/') { - char next = encoded[i + 1]; - char decodedChar = '\0'; - switch (c) { - case '+': - // +A to +Z map to a to z - if (next >= 'A' && next <= 'Z') { - decodedChar = (char) (next + 32); - } else { - throw new ReaderException(); - } - break; - case '$': - // $A to $Z map to control codes SH to SB - if (next >= 'A' && next <= 'Z') { - decodedChar = (char) (next - 64); - } else { - throw new ReaderException(); - } - break; - case '%': - // %A to %E map to control codes ESC to US - if (next >= 'A' && next <= 'E') { - decodedChar = (char) (next - 38); - } else if (next >= 'F' && next <= 'W') { - decodedChar = (char) (next - 11); - } else { - throw new ReaderException(); - } - break; - case '/': - // /A to /O map to ! to , and /Z maps to : - if (next >= 'A' && next <= 'O') { - decodedChar = (char) (next - 32); - } else if (next == 'Z') { - decodedChar = ':'; - } else { - throw new ReaderException(); - } - break; - } - decoded.Append(decodedChar); - // bump up i again since we read two characters - i++; - } else { - decoded.Append(c); - } - } - return decoded.ToString(); - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/EAN13Reader.cs b/qrcode-scanner-live/oned/EAN13Reader.cs deleted file mode 100644 index 0dda005..0000000 --- a/qrcode-scanner-live/oned/EAN13Reader.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - *

Implements decoding of the EAN-13 format.

- * - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - * @author alasdair@google.com (Alasdair Mackintosh) - */ - - using System.Text; - using com.google.zxing.common; - - public sealed class EAN13Reader : AbstractUPCEANReader - { - // For an EAN-13 barcode, the first digit is represented by the parities used - // to encode the next six digits, according to the table below. For example, - // if the barcode is 5 123456 789012 then the value of the first digit is - // signified by using odd for '1', even for '2', even for '3', odd for '4', - // odd for '5', and even for '6'. See http://en.wikipedia.org/wiki/EAN-13 - // - // Parity of next 6 digits - // Digit 0 1 2 3 4 5 - // 0 Odd Odd Odd Odd Odd Odd - // 1 Odd Odd Even Odd Even Even - // 2 Odd Odd Even Even Odd Even - // 3 Odd Odd Even Even Even Odd - // 4 Odd Even Odd Odd Even Even - // 5 Odd Even Even Odd Odd Even - // 6 Odd Even Even Even Odd Odd - // 7 Odd Even Odd Even Odd Even - // 8 Odd Even Odd Even Even Odd - // 9 Odd Even Even Odd Even Odd - // - // Note that the encoding for '0' uses the same parity as a UPC barcode. Hence - // a UPC barcode can be converted to an EAN-13 barcode by prepending a 0. - // - // The encodong is represented by the following array, which is a bit pattern - // using Odd = 0 and Even = 1. For example, 5 is represented by: - // - // Odd Even Even Odd Odd Even - // in binary: - // 0 1 1 0 0 1 == 0x19 - // - private static int[] FIRST_DIGIT_ENCODINGS = { - 0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A - }; - - private int[] decodeMiddleCounters; - - public EAN13Reader() { - decodeMiddleCounters = new int[4]; - } - - protected override int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) { - int[] counters = decodeMiddleCounters; - counters[0] = 0; - counters[1] = 0; - counters[2] = 0; - counters[3] = 0; - int end = row.getSize(); - int rowOffset = startRange[1]; - - int lgPatternFound = 0; - - for (int x = 0; x < 6 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); - resultString.Append((char) ('0' + bestMatch % 10)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - if (bestMatch >= 10) { - lgPatternFound |= 1 << (5 - x); - } - } - - determineFirstDigit(resultString, lgPatternFound); - - int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); - rowOffset = middleRange[1]; - - for (int x = 0; x < 6 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); - resultString.Append((char) ('0' + bestMatch)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - } - - return rowOffset; - } - - public override BarcodeFormat getBarcodeFormat() { - return BarcodeFormat.EAN_13; - } - - /** - * Based on pattern of odd-even ('L' and 'G') patterns used to encoded the explicitly-encoded digits - * in a barcode, determines the implicitly encoded first digit and adds it to the result string. - * - * @param resultString string to insert decoded first digit into - * @param lgPatternFound int whose bits indicates the pattern of odd/even L/G patterns used to - * encode digits - * @throws ReaderException if first digit cannot be determined - */ - private static void determineFirstDigit(StringBuilder resultString, int lgPatternFound) { - for (int d = 0; d < 10; d++) { - if (lgPatternFound == FIRST_DIGIT_ENCODINGS[d]) { - resultString.Insert(0, (char) ('0' + d)); - return; - } - } - throw new ReaderException(); - } - - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/EAN8Reader.cs b/qrcode-scanner-live/oned/EAN8Reader.cs deleted file mode 100644 index 6a21b19..0000000 --- a/qrcode-scanner-live/oned/EAN8Reader.cs +++ /dev/null @@ -1,64 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using System.Text; - using com.google.zxing.common; - - public sealed class EAN8Reader : AbstractUPCEANReader - { - private int[] decodeMiddleCounters; - public EAN8Reader() { - decodeMiddleCounters = new int[4]; - } - - protected override int decodeMiddle(BitArray row, int[] startRange, StringBuilder result) { - int[] counters = decodeMiddleCounters; - counters[0] = 0; - counters[1] = 0; - counters[2] = 0; - counters[3] = 0; - int end = row.getSize(); - int rowOffset = startRange[1]; - - for (int x = 0; x < 4 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); - result.Append((char) ('0' + bestMatch)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - } - - int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); - rowOffset = middleRange[1]; - - for (int x = 0; x < 4 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); - result.Append((char) ('0' + bestMatch)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - } - - return rowOffset; - } - - public override BarcodeFormat getBarcodeFormat() { - return BarcodeFormat.EAN_8; - } - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/ITFReader.cs b/qrcode-scanner-live/oned/ITFReader.cs deleted file mode 100644 index 264e234..0000000 --- a/qrcode-scanner-live/oned/ITFReader.cs +++ /dev/null @@ -1,323 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - *

Implements decoding of the EAN-13 format.

- * - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - * @author alasdair@google.com (Alasdair Mackintosh) - */ - - using System.Text; - using com.google.zxing.common; - - public sealed class ITFReader : AbstractOneDReader - { - private static int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f); - private static int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.8f); - - private static int W = 3; // Pixel width of a wide line - private static int N = 1; // Pixed width of a narrow line - - // Stores the actual narrow line width of the image being decoded. - private int narrowLineWidth = -1; - - /** - * Start/end guard pattern. - * - * Note: The end pattern is reversed because the row is reversed before - * searching for the END_PATTERN - */ - private static int[] START_PATTERN = {N, N, N, N}; - private static int[] END_PATTERN_REVERSED = {N, N, W}; - - /** - * Patterns of Wide / Narrow lines to indicate each digit - */ - private static int[][] PATTERNS = new int[][]{ - new int[]{N, N, W, W, N}, // 0 - new int[]{W, N, N, N, W}, // 1 - new int[]{N, W, N, N, W}, // 2 - new int[]{W, W, N, N, N}, // 3 - new int[]{N, N, W, N, W}, // 4 - new int[]{W, N, W, N, N}, // 5 - new int[]{N, W, W, N, N}, // 6 - new int[]{N, N, N, W, W}, // 7 - new int[]{W, N, N, W, N}, // 8 - new int[]{N, W, N, W, N} // 9 - }; - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - - StringBuilder result = new StringBuilder(20); - - // Find out where the Middle section (payload) starts & ends - int[] startRange = decodeStart(row); - int[] endRange = decodeEnd(row); - - decodeMiddle(row, startRange[1], endRange[0], result); - - string resultString = result.ToString(); - - // To avoid false positives with 2D barcodes (and other patterns), make - // an assumption that the decoded string must be 6, 10 or 14 digits. - int length = resultString.Length; - if (length != 6 && length != 10 && length != 14) { - throw new ReaderException(); - } - - return new Result( - resultString, - null, // no natural byte representation for these barcodes - new ResultPoint[] { new GenericResultPoint(startRange[1], (float) rowNumber), - new GenericResultPoint(startRange[0], (float) rowNumber)}, - BarcodeFormat.ITF); - } - - /** - * @param row row of black/white values to search - * @param payloadStart offset of start pattern - * @param resultString {@link StringBuilder} to Append decoded chars to - * @throws ReaderException if decoding could not complete successfully - */ - static void decodeMiddle(BitArray row, int payloadStart, int payloadEnd, StringBuilder resultString) { - - // Digits are interleaved in pairs - 5 black lines for one digit, and the - // 5 - // interleaved white lines for the second digit. - // Therefore, need to scan 10 lines and then - // split these into two arrays - int[] counterDigitPair = new int[10]; - int[] counterBlack = new int[5]; - int[] counterWhite = new int[5]; - - while (payloadStart < payloadEnd) { - - // Get 10 runs of black/white. - recordPattern(row, payloadStart, counterDigitPair); - // Split them into each array - for (int k = 0; k < 5; k++) { - int twoK = k << 1; - counterBlack[k] = counterDigitPair[twoK]; - counterWhite[k] = counterDigitPair[twoK + 1]; - } - - int bestMatch = decodeDigit(counterBlack); - resultString.Append((char) ('0' + bestMatch)); - bestMatch = decodeDigit(counterWhite); - resultString.Append((char) ('0' + bestMatch)); - - for (int i = 0; i < counterDigitPair.Length; i++) { - payloadStart += counterDigitPair[i]; - } - } - } - - /** - * Identify where the start of the middle / payload section starts. - * - * @param row row of black/white values to search - * @return Array, containing index of start of 'start block' and end of - * 'start block' - * @throws ReaderException - */ - int[] decodeStart(BitArray row) { - int endStart = skipWhiteSpace(row); - int[] startPattern = findGuardPattern(row, endStart, START_PATTERN); - - // Determine the width of a narrow line in pixels. We can do this by - // getting the width of the start pattern and dividing by 4 because its - // made up of 4 narrow lines. - this.narrowLineWidth = (startPattern[1] - startPattern[0]) >> 2; - - validateQuietZone(row, startPattern[0]); - - return startPattern; - } - - /** - * The start & end patterns must be pre/post fixed by a quiet zone. This - * zone must be at least 10 times the width of a narrow line. Scan back until - * we either get to the start of the barcode or match the necessary number of - * quiet zone pixels. - * - * Note: Its assumed the row is reversed when using this method to find - * quiet zone after the end pattern. - * - * ref: http://www.barcode-1.net/i25code.html - * - * @param row bit array representing the scanned barcode. - * @param startPattern index into row of the start or end pattern. - * @throws ReaderException if the quiet zone cannot be found, a ReaderException is thrown. - */ - private void validateQuietZone(BitArray row, int startPattern) { - - int quietCount = this.narrowLineWidth * 10; // expect to find this many pixels of quiet zone - - for (int i = startPattern - 1; quietCount > 0 && i >= 0; i--) { - if (row.get(i)) { - break; - } - quietCount--; - } - if (quietCount != 0) { - // Unable to find the necessary number of quiet zone pixels. - throw new ReaderException(); - } - } - - /** - * Skip all whitespace until we get to the first black line. - * - * @param row row of black/white values to search - * @return index of the first black line. - * @throws ReaderException Throws exception if no black lines are found in the row - */ - private int skipWhiteSpace(BitArray row) { - int width = row.getSize(); - int endStart = 0; - while (endStart < width) { - if (row.get(endStart)) { - break; - } - endStart++; - } - if (endStart == width) { - throw new ReaderException(); - } - - return endStart; - } - - /** - * Identify where the end of the middle / payload section ends. - * - * @param row row of black/white values to search - * @return Array, containing index of start of 'end block' and end of 'end - * block' - * @throws ReaderException - */ - - int[] decodeEnd(BitArray row) { - - // For convenience, reverse the row and then - // search from 'the start' for the end block - row.reverse(); - - int endStart = skipWhiteSpace(row); - int[] endPattern; - try { - endPattern = findGuardPattern(row, endStart, END_PATTERN_REVERSED); - } catch (ReaderException e) { - // Put our row of data back the right way before throwing - row.reverse(); - throw e; - } - - // The start & end patterns must be pre/post fixed by a quiet zone. This - // zone must be at least 10 times the width of a narrow line. - // ref: http://www.barcode-1.net/i25code.html - validateQuietZone(row, endPattern[0]); - - // Now recalc the indicies of where the 'endblock' starts & stops to - // accomodate - // the reversed nature of the search - int temp = endPattern[0]; - endPattern[0] = row.getSize() - endPattern[1]; - endPattern[1] = row.getSize() - temp; - - // Put the row back the righ way. - row.reverse(); - return endPattern; - } - - /** - * @param row row of black/white values to search - * @param rowOffset position to start search - * @param pattern pattern of counts of number of black and white pixels that are - * being searched for as a pattern - * @return start/end horizontal offset of guard pattern, as an array of two - * ints - * @throws ReaderException if pattern is not found - */ - int[] findGuardPattern(BitArray row, int rowOffset, int[] pattern) { - - // TODO: This is very similar to implementation in AbstractUPCEANReader. Consider if they can be merged to - // a single method. - - int patternLength = pattern.Length; - int[] counters = new int[patternLength]; - int width = row.getSize(); - bool isWhite = false; - - int counterPosition = 0; - int patternStart = rowOffset; - for (int x = rowOffset; x < width; x++) { - bool pixel = row.get(x); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - if (counterPosition == patternLength - 1) { - if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { - return new int[]{patternStart, x}; - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } else { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw new ReaderException(); - } - - /** - * Attempts to decode a sequence of ITF black/white lines into single - * digit. - * - * @param counters the counts of runs of observed black/white/black/... values - * @return The decoded digit - * @throws ReaderException if digit cannot be decoded - */ - private static int decodeDigit(int[] counters) { - - int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept - int bestMatch = -1; - int max = PATTERNS.Length; - for (int i = 0; i < max; i++) { - int[] pattern = PATTERNS[i]; - int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) { - bestVariance = variance; - bestMatch = i; - } - } - if (bestMatch >= 0) { - return bestMatch; - } else { - throw new ReaderException(); - } - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/MultiFormatOneDReader.cs b/qrcode-scanner-live/oned/MultiFormatOneDReader.cs deleted file mode 100644 index b421435..0000000 --- a/qrcode-scanner-live/oned/MultiFormatOneDReader.cs +++ /dev/null @@ -1,76 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - */ - using System.Text; - using com.google.zxing.common; - - public sealed class MultiFormatOneDReader : AbstractOneDReader - { - private System.Collections.ArrayList readers; - - public MultiFormatOneDReader(System.Collections.Hashtable hints) - { - System.Collections.ArrayList possibleFormats = hints == null ? null : (System.Collections.ArrayList) hints[DecodeHintType.POSSIBLE_FORMATS]; - readers = new System.Collections.ArrayList(); - if (possibleFormats != null) { - if (possibleFormats.Contains(BarcodeFormat.EAN_13) || - possibleFormats.Contains(BarcodeFormat.UPC_A) || - possibleFormats.Contains(BarcodeFormat.EAN_8) || - possibleFormats.Contains(BarcodeFormat.UPC_E)) - { - readers.Add(new MultiFormatUPCEANReader(hints)); - } - if (possibleFormats.Contains(BarcodeFormat.CODE_39)) { - readers.Add(new Code39Reader()); - } - if (possibleFormats.Contains(BarcodeFormat.CODE_128)) - { - readers.Add(new Code128Reader()); - } - if (possibleFormats.Contains(BarcodeFormat.ITF)) - { - readers.Add(new ITFReader()); - } - } - if (readers.Count==0) { - readers.Contains(new MultiFormatUPCEANReader(hints)); - readers.Contains(new Code39Reader()); - readers.Contains(new Code128Reader()); - // TODO: Add ITFReader once it is validated as production ready, and tested for performance. - //readers.addElement(new ITFReader()); - } - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) - { - int size = readers.Count; - for (int i = 0; i < size; i++) { - OneDReader reader = (OneDReader) readers[i]; - try { - return reader.decodeRow(rowNumber, row, hints); - } catch (ReaderException re) { - // continue - } - } - - throw new ReaderException(); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/MultiFormatUPCEANReader.cs b/qrcode-scanner-live/oned/MultiFormatUPCEANReader.cs deleted file mode 100644 index 98dbf79..0000000 --- a/qrcode-scanner-live/oned/MultiFormatUPCEANReader.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - */ - using System.Text; - using com.google.zxing.common; - - public sealed class MultiFormatUPCEANReader : AbstractOneDReader - { - private System.Collections.ArrayList readers; - public MultiFormatUPCEANReader(System.Collections.Hashtable hints) { - System.Collections.ArrayList possibleFormats = hints == null ? null : (System.Collections.ArrayList) hints[DecodeHintType.POSSIBLE_FORMATS]; - readers = new System.Collections.ArrayList(); - if (possibleFormats != null) { - if (possibleFormats.Contains(BarcodeFormat.EAN_13)) { - readers.Add(new EAN13Reader()); - } else if (possibleFormats.Contains(BarcodeFormat.UPC_A)) { - readers.Add(new UPCAReader()); - } - if (possibleFormats.Contains(BarcodeFormat.EAN_8)) { - readers.Add(new EAN8Reader()); - } - if (possibleFormats.Contains(BarcodeFormat.UPC_E)) { - readers.Add(new UPCEReader()); - } - } - if (readers.Count==0) { - readers.Add(new EAN13Reader()); - // UPC-A is covered by EAN-13 - readers.Add(new EAN8Reader()); - readers.Add(new UPCEReader()); - } - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - // Compute this location once and reuse it on multiple implementations - int[] startGuardPattern = AbstractUPCEANReader.findStartGuardPattern(row); - int size = readers.Count; - for (int i = 0; i < size; i++) { - UPCEANReader reader = (UPCEANReader) readers[i]; - Result result; - try { - result = reader.decodeRow(rowNumber, row, startGuardPattern); - } catch (ReaderException re) { - continue; - } - // Special case: a 12-digit code encoded in UPC-A is identical to a "0" - // followed by those 12 digits encoded as EAN-13. Each will recognize such a code, - // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0". - // Individually these are correct and their readers will both read such a code - // and correctly call it EAN-13, or UPC-A, respectively. - // - // In this case, if we've been looking for both types, we'd like to call it - // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read - // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A - // result if appropriate. - if (result.getBarcodeFormat().Equals(BarcodeFormat.EAN_13) && result.getText()[0] == '0') { - return new Result(result.getText().Substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A); - } - return result; - } - - throw new ReaderException(); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/OneDReader.cs b/qrcode-scanner-live/oned/OneDReader.cs deleted file mode 100644 index d7d0ae4..0000000 --- a/qrcode-scanner-live/oned/OneDReader.cs +++ /dev/null @@ -1,41 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - *

{@link Reader}s which also implement this interface read one-dimensional barcode - * formats, and expose additional functionality that is specific to this type of barcode.

- * - * @author Sean Owen - */ - - using com.google.zxing.common; - - public interface OneDReader :Reader - { - /** - *

Attempts to decode a one-dimensional barcode format given a single row of - * an image.

- * - * @param rowNumber row number from top of the row - * @param row the black/white pixel data of the row - * @param hints decode hints - * @return {@link Result} containing encoded string and start/end of barcode - * @throws ReaderException if an error occurs or barcode cannot be found - */ - Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints); - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/UPCAReader.cs b/qrcode-scanner-live/oned/UPCAReader.cs deleted file mode 100644 index 257e4c2..0000000 --- a/qrcode-scanner-live/oned/UPCAReader.cs +++ /dev/null @@ -1,54 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - */ - using System.Text; - using com.google.zxing.common; - - public sealed class UPCAReader : UPCEANReader - { - private UPCEANReader ean13Reader = new EAN13Reader(); - - public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange) { - return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange)); - } - - public Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, hints)); - } - - public Result decode(MonochromeBitmapSource image) { - return maybeReturnResult(ean13Reader.decode(image)); - } - - public Result decode(MonochromeBitmapSource image, System.Collections.Hashtable hints) { - return maybeReturnResult(ean13Reader.decode(image, hints)); - } - - private static Result maybeReturnResult(Result result) { - string text = result.getText(); - if (text[0] == '0') { - return new Result(text.Substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A); - } else { - throw new ReaderException(); - } - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/UPCEANReader.cs b/qrcode-scanner-live/oned/UPCEANReader.cs deleted file mode 100644 index c4af834..0000000 --- a/qrcode-scanner-live/oned/UPCEANReader.cs +++ /dev/null @@ -1,34 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using com.google.zxing.common; - /** - *

This interfaces captures addtional functionality that readers of - * UPC/EAN family of barcodes should expose.

- * - * @author Sean Owen - */ - - public interface UPCEANReader : OneDReader - { - /** - *

Like {@link #decodeRow(int, BitArray, java.util.Hashtable)}, but - * allows caller to inform method about where the UPC/EAN start pattern is - * found. This allows this to be computed once and reused across many implementations.

- */ - Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange); - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live/oned/UPCEReader.cs b/qrcode-scanner-live/oned/UPCEReader.cs deleted file mode 100644 index bed8653..0000000 --- a/qrcode-scanner-live/oned/UPCEReader.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System.Text; - using com.google.zxing.common; - /** - *

Implements decoding of the UPC-E format.

- *

- *

This is a great reference for - * UPC-E information.

- * - * @author Sean Owen - */ - - - public sealed class UPCEReader : AbstractUPCEANReader - { - /** - * The pattern that marks the middle, and end, of a UPC-E pattern. - * There is no "second half" to a UPC-E barcode. - */ - private int[] MIDDLE_END_PATTERN = new int[]{1, 1, 1, 1, 1, 1}; - - /** - * See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of - * even-odd parity encodings of digits that imply both the number system (0 or 1) - * used, and the check digit. - */ - private static int[][] NUMSYS_AND_CHECK_DIGIT_PATTERNS = new int[][]{ - new int[]{0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25}, - new int[]{0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A} - }; - - private int[] decodeMiddleCounters; - - public UPCEReader() { - decodeMiddleCounters = new int[4]; - } - - protected override int decodeMiddle(BitArray row, int[] startRange, StringBuilder result) { - int[] counters = decodeMiddleCounters; - counters[0] = 0; - counters[1] = 0; - counters[2] = 0; - counters[3] = 0; - int end = row.getSize(); - int rowOffset = startRange[1]; - - int lgPatternFound = 0; - - for (int x = 0; x < 6 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); - result.Append((char) ('0' + bestMatch % 10)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - if (bestMatch >= 10) { - lgPatternFound |= 1 << (5 - x); - } - } - - determineNumSysAndCheckDigit(result, lgPatternFound); - - return rowOffset; - } - - public int[] decodeEnd(BitArray row, int endStart) { - return findGuardPattern(row, endStart, true, MIDDLE_END_PATTERN); - } - - public bool checkChecksum(string s) { - return base.checkChecksum(convertUPCEtoUPCA(s)); - } - - private static void determineNumSysAndCheckDigit(StringBuilder resultString, int lgPatternFound) - { - - for (int numSys = 0; numSys <= 1; numSys++) { - for (int d = 0; d < 10; d++) { - if (lgPatternFound == NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]) { - resultString.Insert(0, (char) ('0' + numSys)); - resultString.Append((char) ('0' + d)); - return; - } - } - } - throw new ReaderException(); - } - - public override BarcodeFormat getBarcodeFormat() { - return BarcodeFormat.UPC_E; - } - - /** - * Expands a UPC-E value back into its full, equivalent UPC-A code value. - * - * @param upce UPC-E code as string of digits - * @return equivalent UPC-A code as string of digits - */ - public static string convertUPCEtoUPCA(string upce) { - char[] upceChars = new char[6]; - SupportClass.GetCharsFromString(upce, 1, 7, upceChars, 0); - StringBuilder result = new StringBuilder(12); - result.Append(upce[0]); - char lastChar = upceChars[5]; - switch (lastChar) { - case '0': - case '1': - case '2': - result.Append(upceChars, 0, 2); - result.Append(lastChar); - result.Append("0000"); - result.Append(upceChars, 2, 3); - break; - case '3': - result.Append(upceChars, 0, 3); - result.Append("00000"); - result.Append(upceChars, 3, 2); - break; - case '4': - result.Append(upceChars, 0, 4); - result.Append("00000"); - result.Append(upceChars[4]); - break; - default: - result.Append(upceChars, 0, 5); - result.Append("0000"); - result.Append(lastChar); - break; - } - result.Append(upce[7]); - return result.ToString(); - } - - - } - - -} diff --git a/qrcode-scanner-live/qrcode/QRCodeReader.cs b/qrcode-scanner-live/qrcode/QRCodeReader.cs deleted file mode 100644 index b0b7c26..0000000 --- a/qrcode-scanner-live/qrcode/QRCodeReader.cs +++ /dev/null @@ -1,145 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.qrcode -{ - using System; - using System.Collections; - using com.google.zxing.common; - using com.google.zxing.qrcode.decoder; - using com.google.zxing.qrcode.detector; - - public sealed class QRCodeReader: Reader - { - private static ResultPoint[] NO_POINTS = new ResultPoint[0]; - private Decoder decoder = new Decoder(); - - /** - * Locates and decodes a QR code in an image. - * - * @return a String representing the content encoded by the QR code - * @throws ReaderException if a QR code cannot be found, or cannot be decoded - */ - public Result decode(MonochromeBitmapSource image) { - try{ - return decode(image, null); - } - catch(Exception e){ - throw new ReaderException(e.Message); - } - - } - - public Result decode(MonochromeBitmapSource image, Hashtable hints){ - try{ - DecoderResult decoderResult; - ResultPoint[] points; - if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) { - BitMatrix bits = extractPureBits(image); - decoderResult = decoder.decode(bits); - points = NO_POINTS; - } else { - DetectorResult detectorResult = new Detector(image).detect(hints); - decoderResult = decoder.decode(detectorResult.getBits()); - points = detectorResult.getPoints(); - } - - Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE); - if (decoderResult.getByteSegments() != null) { - result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.getByteSegments()); - } - return result; - }catch(Exception e){ - throw new ReaderException(e.Message); - } - - } - - /** - * This method detects a barcode in a "pure" image -- that is, pure monochrome image - * which contains only an unrotated, unskewed, image of a barcode, with some white border - * around it. This is a specialized method that works exceptionally fast in this special - * case. - */ - private static BitMatrix extractPureBits(MonochromeBitmapSource image){ - // Now need to determine module size in pixels - - int height = image.getHeight(); - int width = image.getWidth(); - int minDimension = Math.Min(height, width); - - // First, skip white border by tracking diagonally from the top left down and to the right: - int borderWidth = 0; - while (borderWidth < minDimension && !image.isBlack(borderWidth, borderWidth)) { - borderWidth++; - } - if (borderWidth == minDimension) { - throw new ReaderException(); - } - - // And then keep tracking across the top-left black module to determine module size - int moduleEnd = borderWidth; - while (moduleEnd < minDimension && image.isBlack(moduleEnd, moduleEnd)) { - moduleEnd++; - } - if (moduleEnd == minDimension) { - throw new ReaderException(); - } - - int moduleSize = moduleEnd - borderWidth; - - // And now find where the rightmost black module on the first row ends - int rowEndOfSymbol = width - 1; - while (rowEndOfSymbol >= 0 && !image.isBlack(rowEndOfSymbol, borderWidth)) { - rowEndOfSymbol--; - } - if (rowEndOfSymbol < 0) { - throw new ReaderException(); - } - rowEndOfSymbol++; - - // Make sure width of barcode is a multiple of module size - if ((rowEndOfSymbol - borderWidth) % moduleSize != 0) { - throw new ReaderException(); - } - int dimension = (rowEndOfSymbol - borderWidth) / moduleSize; - - // Push in the "border" by half the module width so that we start - // sampling in the middle of the module. Just in case the image is a - // little off, this will help recover. - borderWidth += moduleSize >> 1; - - int sampleDimension = borderWidth + (dimension - 1) * moduleSize; - if (sampleDimension >= width || sampleDimension >= height) { - throw new ReaderException(); - } - - // Now just read off the bits - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) { - int iOffset = borderWidth + i * moduleSize; - for (int j = 0; j < dimension; j++) { - if (image.isBlack(borderWidth + j * moduleSize, iOffset)) { - bits.set(i, j); - } - } - } - return bits; - } - - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/QRCodeWriter.cs b/qrcode-scanner-live/qrcode/QRCodeWriter.cs deleted file mode 100644 index 9b684cf..0000000 --- a/qrcode-scanner-live/qrcode/QRCodeWriter.cs +++ /dev/null @@ -1,143 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.qrcode -{ - using System; - using System.Collections; - using com.google.zxing.common; - using com.google.zxing.qrcode.decoder; - using com.google.zxing.qrcode.detector; - using com.google.zxing.qrcode.encoder; - - public sealed class QRCodeWriter : Writer - { - private static int QUIET_ZONE_SIZE = 4; - public ByteMatrix encode(String contents, BarcodeFormat format, int width, int height) - { - try{ - return encode(contents, format, width, height, null); - }catch(Exception e){ - throw new WriterException(e.Message); - } - } - - public ByteMatrix encode(String contents, BarcodeFormat format, int width, int height,Hashtable hints) { - - if (contents == null || contents.Length == 0) { - throw new ArgumentException("Found empty contents"); - } - - if (format != BarcodeFormat.QR_CODE) { - throw new ArgumentException("Can only encode QR_CODE, but got " + format); - } - - if (width < 0 || height < 0) { - throw new ArgumentException("Requested dimensions are too small: " + width + 'x' + - height); - } - - ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; - if (hints != null) { - ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints[EncodeHintType.ERROR_CORRECTION]; - if (requestedECLevel != null) { - errorCorrectionLevel = requestedECLevel; - } - } - - QRCode code = new QRCode(); - Encoder.encode(contents, errorCorrectionLevel, code); - return renderResult(code, width, height); - } - - // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses - // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap). - private static ByteMatrix renderResult(QRCode code, int width, int height) { - ByteMatrix input = code.getMatrix(); - int inputWidth = input.width(); - int inputHeight = input.height(); - int qrWidth = inputWidth + (QUIET_ZONE_SIZE << 1); - int qrHeight = inputHeight + (QUIET_ZONE_SIZE << 1); - int outputWidth = Math.Max(width, qrWidth); - int outputHeight = Math.Max(height, qrHeight); - - int multiple = Math.Min(outputWidth / qrWidth, outputHeight / qrHeight); - // Padding includes both the quiet zone and the extra white pixels to accomodate the requested - // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone. - // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will - // handle all the padding from 100x100 (the actual QR) up to 200x160. - int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; - int topPadding = (outputHeight - (inputHeight * multiple)) / 2; - - ByteMatrix output = new ByteMatrix(outputHeight, outputWidth); - sbyte[][] outputArray = output.getArray(); - - // We could be tricky and use the first row in each set of multiple as the temporary storage, - // instead of allocating this separate array. - sbyte[] row = new sbyte[outputWidth]; - - // 1. Write the white lines at the top - for (int y = 0; y < topPadding; y++) { - setRowColor(outputArray[y], unchecked((sbyte)255)); - } - - // 2. Expand the QR image to the multiple - sbyte[][] inputArray = input.getArray(); - for (int y = 0; y < inputHeight; y++) { - // a. Write the white pixels at the left of each row - for (int x = 0; x < leftPadding; x++) { - row[x] = unchecked((sbyte) 255); - } - - // b. Write the contents of this row of the barcode - int offset = leftPadding; - for (int x = 0; x < inputWidth; x++) { - sbyte value = (inputArray[y][x] == 1) ? (sbyte) 0 : unchecked((sbyte) 255); - for (int z = 0; z < multiple; z++) { - row[offset + z] = value; - } - offset += multiple; - } - - // c. Write the white pixels at the right of each row - offset = leftPadding + (inputWidth * multiple); - for (int x = offset; x < outputWidth; x++) { - row[x] = unchecked((sbyte) 255); - } - - // d. Write the completed row multiple times - offset = topPadding + (y * multiple); - for (int z = 0; z < multiple; z++) { - System.Array.Copy(row, 0, outputArray[offset + z], 0, outputWidth); - } - } - - // 3. Write the white lines at the bottom - int offset2 = topPadding + (inputHeight * multiple); - for (int y = offset2; y < outputHeight; y++) - { - setRowColor(outputArray[y], unchecked((sbyte) 255)); - } - return output; - } - - private static void setRowColor(sbyte[] row, sbyte value) { - for (int x = 0; x < row.Length; x++) { - row[x] = value; - } - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/decoder/BitMatrixParser.cs b/qrcode-scanner-live/qrcode/decoder/BitMatrixParser.cs deleted file mode 100644 index 7a2b643..0000000 --- a/qrcode-scanner-live/qrcode/decoder/BitMatrixParser.cs +++ /dev/null @@ -1,208 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class BitMatrixParser - { - private BitMatrix bitMatrix; - private Version parsedVersion; - private FormatInformation parsedFormatInfo; - - /** - * @param bitMatrix {@link BitMatrix} to parse - * @throws ReaderException if dimension is not >= 21 and 1 mod 4 - */ - public BitMatrixParser(BitMatrix bitMatrix){ - int dimension = bitMatrix.getDimension(); - if (dimension < 21 || (dimension & 0x03) != 1) { - throw new ReaderException(); - } - this.bitMatrix = bitMatrix; - } - - /** - *

Reads format information from one of its two locations within the QR Code.

- * - * @return {@link FormatInformation} encapsulating the QR Code's format info - * @throws ReaderException if both format information locations cannot be parsed as - * the valid encoding of format information - */ - public FormatInformation readFormatInformation(){ - - if (parsedFormatInfo != null) { - return parsedFormatInfo; - } - - // Read top-left format info bits - int formatInfoBits = 0; - for (int j = 0; j < 6; j++) { - formatInfoBits = copyBit(8, j, formatInfoBits); - } - // .. and skip a bit in the timing pattern ... - formatInfoBits = copyBit(8, 7, formatInfoBits); - formatInfoBits = copyBit(8, 8, formatInfoBits); - formatInfoBits = copyBit(7, 8, formatInfoBits); - // .. and skip a bit in the timing pattern ... - for (int i = 5; i >= 0; i--) { - formatInfoBits = copyBit(i, 8, formatInfoBits); - } - - parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); - if (parsedFormatInfo != null) { - return parsedFormatInfo; - } - - // Hmm, failed. Try the top-right/bottom-left pattern - int dimension = bitMatrix.getDimension(); - formatInfoBits = 0; - int iMin = dimension - 8; - for (int i = dimension - 1; i >= iMin; i--) { - formatInfoBits = copyBit(i, 8, formatInfoBits); - } - for (int j = dimension - 7; j < dimension; j++) { - formatInfoBits = copyBit(8, j, formatInfoBits); - } - - parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); - if (parsedFormatInfo != null) { - return parsedFormatInfo; - } - throw new ReaderException(); - } - - /** - *

Reads version information from one of its two locations within the QR Code.

- * - * @return {@link Version} encapsulating the QR Code's version - * @throws ReaderException if both version information locations cannot be parsed as - * the valid encoding of version information - */ - public Version readVersion(){ - - if (parsedVersion != null) { - return parsedVersion; - } - - int dimension = bitMatrix.getDimension(); - - int provisionalVersion = (dimension - 17) >> 2; - if (provisionalVersion <= 6) { - return Version.getVersionForNumber(provisionalVersion); - } - - // Read top-right version info: 3 wide by 6 tall - int versionBits = 0; - for (int i = 5; i >= 0; i--) { - int jMin = dimension - 11; - for (int j = dimension - 9; j >= jMin; j--) { - versionBits = copyBit(i, j, versionBits); - } - } - - parsedVersion = Version.decodeVersionInformation(versionBits); - if (parsedVersion != null) { - return parsedVersion; - } - - // Hmm, failed. Try bottom left: 6 wide by 3 tall - versionBits = 0; - for (int j = 5; j >= 0; j--) { - int iMin = dimension - 11; - for (int i = dimension - 11; i >= iMin; i--) { - versionBits = copyBit(i, j, versionBits); - } - } - - parsedVersion = Version.decodeVersionInformation(versionBits); - if (parsedVersion != null) { - return parsedVersion; - } - throw new ReaderException(); - } - - private int copyBit(int i, int j, int versionBits) { - return bitMatrix.get(i, j) ? (versionBits << 1) | 0x1 : versionBits << 1; - } - - /** - *

Reads the bits in the {@link BitMatrix} representing the finder pattern in the - * correct order in order to reconstitute the codewords bytes contained within the - * QR Code.

- * - * @return bytes encoded within the QR Code - * @throws ReaderException if the exact number of bytes expected is not read - */ - public sbyte[] readCodewords(){ - - FormatInformation formatInfo = readFormatInformation(); - Version version = readVersion(); - - // Get the data mask for the format used in this QR Code. This will exclude - // some bits from reading as we wind through the bit matrix. - DataMask dataMask = DataMask.forReference((int) formatInfo.getDataMask()); - int dimension = bitMatrix.getDimension(); - dataMask.unmaskBitMatrix(bitMatrix.getBits(), dimension); - - BitMatrix functionPattern = version.buildFunctionPattern(); - - bool readingUp = true; - sbyte[] result = new sbyte[version.getTotalCodewords()]; - int resultOffset = 0; - int currentByte = 0; - int bitsRead = 0; - // Read columns in pairs, from right to left - for (int j = dimension - 1; j > 0; j -= 2) { - if (j == 6) { - // Skip whole column with vertical alignment pattern; - // saves time and makes the other code proceed more cleanly - j--; - } - // Read alternatingly from bottom to top then top to bottom - for (int count = 0; count < dimension; count++) { - int i = readingUp ? dimension - 1 - count : count; - for (int col = 0; col < 2; col++) { - // Ignore bits covered by the function pattern - if (!functionPattern.get(i, j - col)) { - // Read a bit - bitsRead++; - currentByte <<= 1; - if (bitMatrix.get(i, j - col)) { - currentByte |= 1; - } - // If we've made a whole byte, save it off - if (bitsRead == 8) { - result[resultOffset++] = (sbyte) currentByte; - bitsRead = 0; - currentByte = 0; - } - } - } - } - readingUp = !readingUp; // switch directions - } - if (resultOffset != version.getTotalCodewords()) { - throw new ReaderException(); - } - return result; - } - - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/decoder/DataBlock.cs b/qrcode-scanner-live/qrcode/decoder/DataBlock.cs deleted file mode 100644 index 7fc4f5f..0000000 --- a/qrcode-scanner-live/qrcode/decoder/DataBlock.cs +++ /dev/null @@ -1,152 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.qrcode.decoder -{ - - ///

Encapsulates a block of data within a QR Code. QR Codes may split their data into - /// multiple blocks, each of which is a unit of data and error-correction codewords. Each - /// is represented by an instance of this class.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public sealed class DataBlock - { - internal int NumDataCodewords - { - get - { - return numDataCodewords; - } - - } - internal sbyte[] Codewords - { - get - { - return codewords; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'numDataCodewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int numDataCodewords; - //UPGRADE_NOTE: Final was removed from the declaration of 'codewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte[] codewords; - - public DataBlock(int numDataCodewords, sbyte[] codewords) - { - this.numDataCodewords = numDataCodewords; - this.codewords = codewords; - } - - ///

When QR Codes use multiple data blocks, they are actually interleave the bytes of each of them. - /// That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This - /// method will separate the data into original blocks.

- /// - ///
- /// bytes as read directly from the QR Code - /// - /// version of the QR Code - /// - /// error-correction level of the QR Code - /// - /// {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the - /// QR Code - /// - internal static DataBlock[] getDataBlocks(sbyte[] rawCodewords, Version version, ErrorCorrectionLevel ecLevel) - { - // Figure out the number and size of data blocks used by this version and - // error correction level - Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); - - // First count the total number of data blocks - int totalBlocks = 0; - Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); - for (int i = 0; i < ecBlockArray.Length; i++) - { - totalBlocks += ecBlockArray[i].getCount(); - } - - // Now establish DataBlocks of the appropriate size and number of data codewords - DataBlock[] result = new DataBlock[totalBlocks]; - int numResultBlocks = 0; - for (int j = 0; j < ecBlockArray.Length; j++) - { - Version.ECB ecBlock = ecBlockArray[j]; - for (int i = 0; i < ecBlock.getCount(); i++) - { - int numDataCodewords = ecBlock.getDataCodewords(); - int numBlockCodewords = ecBlocks.getTotalECCodewords() + numDataCodewords; - result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]); - } - } - - // All blocks have the same amount of data, except that the last n - // (where n may be 0) have 1 more byte. Figure out where these start. - int shorterBlocksTotalCodewords = result[0].codewords.Length; - int longerBlocksStartAt = result.Length - 1; - while (longerBlocksStartAt >= 0) - { - int numCodewords = result[longerBlocksStartAt].codewords.Length; - if (numCodewords == shorterBlocksTotalCodewords) - { - break; - } - if (numCodewords != shorterBlocksTotalCodewords + 1) - { - throw new System.SystemException("Data block sizes differ by more than 1"); - } - longerBlocksStartAt--; - } - longerBlocksStartAt++; - - int shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.getTotalECCodewords(); - // The last elements of result may be 1 element longer; - // first fill out as many elements as all of them have - int rawCodewordsOffset = 0; - for (int i = 0; i < shorterBlocksNumDataCodewords; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; - } - } - // Fill out the last data block in the longer ones - for (int j = longerBlocksStartAt; j < numResultBlocks; j++) - { - result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; - } - // Now add in error correction blocks - int max = result[0].codewords.Length; - for (int i = shorterBlocksNumDataCodewords; i < max; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - int iOffset = j < longerBlocksStartAt ? i : i + 1; - result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; - } - } - - if (rawCodewordsOffset != rawCodewords.Length) - { - throw new System.SystemException(); - } - - return result; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/decoder/DataMask.cs b/qrcode-scanner-live/qrcode/decoder/DataMask.cs deleted file mode 100644 index be25079..0000000 --- a/qrcode-scanner-live/qrcode/decoder/DataMask.cs +++ /dev/null @@ -1,282 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.qrcode.decoder -{ - - ///

Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations - /// of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix, - /// including areas used for finder patterns, timing patterns, etc. These areas should be unused - /// after the point they are unmasked anyway.

- /// - ///

Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position - /// and j is row position. In fact, as the text says, i is row position and j is column position.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - abstract class DataMask - { - - /// See ISO 18004:2006 6.8.1 - //UPGRADE_NOTE: Final was removed from the declaration of 'DATA_MASKS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly DataMask[] DATA_MASKS = new DataMask[] { new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111() }; - - private DataMask() - { - } - - ///

Implementations of this method reverse the data masking process applied to a QR Code and - /// make its bits ready to read.

- /// - ///
- /// representation of QR Code bits from {@link com.google.zxing.common.BitMatrix#getBits()} - /// - /// dimension of QR Code, represented by bits, being unmasked - /// - internal abstract void unmaskBitMatrix(int[] bits, int dimension); - - /// a value between 0 and 7 indicating one of the eight possible - /// data mask patterns a QR Code may use - /// - /// {@link DataMask} encapsulating the data mask pattern - /// - internal static DataMask forReference(int reference) - { - if (reference < 0 || reference > 7) - { - throw new System.ArgumentException(); - } - return DATA_MASKS[reference]; - } - - /// 000: mask bits for which (i + j) mod 2 == 0 - private class DataMask000 : DataMask - { - private const int BITMASK = 0x55555555; // = 010101... - - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - // This one's easy. Because the dimension of BitMatrix is always odd, - // we can merely flip every other bit - int max = bits.Length; - for (int i = 0; i < max; i++) - { - bits[i] ^= BITMASK; - } - } - } - - /// 001: mask bits for which i mod 2 == 0 - private class DataMask001 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - if ((i & 0x01) == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 010: mask bits for which j mod 3 == 0 - private class DataMask010 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - bool columnMasked = j % 3 == 0; - for (int i = 0; i < dimension; i++) - { - if (columnMasked) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 011: mask bits for which (i + j) mod 3 == 0 - private class DataMask011 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - if ((i + j) % 3 == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 100: mask bits for which (i/2 + j/3) mod 2 == 0 - private class DataMask100 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - int jComponentParity = (j / 3) & 0x01; - for (int i = 0; i < dimension; i++) - { - if (((i >> 1) & 0x01) == jComponentParity) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 101: mask bits for which ij mod 2 + ij mod 3 == 0 - private class DataMask101 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - int product = i * j; - if (((product & 0x01) == 0) && product % 3 == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 110: mask bits for which (ij mod 2 + ij mod 3) mod 2 == 0 - private class DataMask110 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - int product = i * j; - if ((((product & 0x01) + product % 3) & 0x01) == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 111: mask bits for which ((i+j)mod 2 + ij mod 3) mod 2 == 0 - private class DataMask111 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - if (((((i + j) & 0x01) + (i * j) % 3) & 0x01) == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/decoder/DecodedBitStreamParser.cs b/qrcode-scanner-live/qrcode/decoder/DecodedBitStreamParser.cs deleted file mode 100644 index dfe82fa..0000000 --- a/qrcode-scanner-live/qrcode/decoder/DecodedBitStreamParser.cs +++ /dev/null @@ -1,266 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using ReaderException = com.google.zxing.ReaderException; -using com.google.zxing.common; -namespace com.google.zxing.qrcode.decoder -{ - - ///

QR Codes can encode text as bits in one of several modes, and can use multiple modes - /// in one QR Code. This class decodes the bits back into text.

- /// - ///

See ISO 18004:2006, 6.4.3 - 6.4.7

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public sealed class DecodedBitStreamParser - { - - /// See ISO 18004:2006, 6.4.4 Table 5 - //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_CHARS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] ALPHANUMERIC_CHARS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' }; - private const System.String SHIFT_JIS = "Shift_JIS"; - private static bool ASSUME_SHIFT_JIS; - - private DecodedBitStreamParser() - { - } - - internal static System.String decode(sbyte[] bytes, Version version) - { - BitSource bits = new BitSource(bytes); - System.Text.StringBuilder result = new System.Text.StringBuilder(); - Mode mode; - do - { - // While still another segment to read... - mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits - if (!mode.Equals(Mode.TERMINATOR)) - { - // How many characters will follow, encoded in this mode? - int count = bits.readBits(mode.getCharacterCountBits(version)); - if (mode.Equals(Mode.NUMERIC)) - { - decodeNumericSegment(bits, result, count); - } - else if (mode.Equals(Mode.ALPHANUMERIC)) - { - decodeAlphanumericSegment(bits, result, count); - } - else if (mode.Equals(Mode.BYTE)) - { - decodeByteSegment(bits, result, count); - } - else if (mode.Equals(Mode.KANJI)) - { - decodeKanjiSegment(bits, result, count); - } - else - { - throw new ReaderException("Unsupported mode indicator"); - } - } - } - while (!mode.Equals(Mode.TERMINATOR)); - - // I thought it wasn't allowed to leave extra bytes after the terminator but it happens - /* - int bitsLeft = bits.available(); - if (bitsLeft > 0) { - if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) { - throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator"); - } - } - */ - return result.ToString(); - } - - private static void decodeKanjiSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - // Each character will require 2 bytes. Read the characters as 2-byte pairs - // and decode as Shift_JIS afterwards - sbyte[] buffer = new sbyte[2 * count]; - int offset = 0; - while (count > 0) - { - // Each 13 bits encodes a 2-byte character - int twoBytes = bits.readBits(13); - int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0); - if (assembledTwoBytes < 0x01F00) - { - // In the 0x8140 to 0x9FFC range - assembledTwoBytes += 0x08140; - } - else - { - // In the 0xE040 to 0xEBBF range - assembledTwoBytes += 0x0C140; - } - buffer[offset] = (sbyte)(assembledTwoBytes >> 8); - buffer[offset + 1] = (sbyte)assembledTwoBytes; - offset += 2; - count--; - } - // Shift_JIS may not be supported in some environments: - try - { - byte[] bytes = SupportClass.ToByteArray(buffer); - //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" - result.Append(System.Text.Encoding.GetEncoding("Shift_JIS").GetString(bytes, 0, bytes.Length)); - } - catch (System.IO.IOException uee) - { - throw new ReaderException("SHIFT_JIS encoding is not supported on this device"); - } - } - - private static void decodeByteSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - sbyte[] readBytes = new sbyte[count]; - if (count << 3 > bits.available()) - { - throw new ReaderException("Count too large: " + count); - } - for (int i = 0; i < count; i++) - { - readBytes[i] = (sbyte)bits.readBits(8); - } - // The spec isn't clear on this mode; see - // section 6.4.5: t does not say which encoding to assuming - // upon decoding. I have seen ISO-8859-1 used as well as - // Shift_JIS -- without anything like an ECI designator to - // give a hint. - System.String encoding = guessEncoding(readBytes); - try - { - byte[] bytes = SupportClass.ToByteArray(readBytes); - //System.Windows.Forms.MessageBox.Show("encodings: "+ System.Text.Encoding.()); - //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" - result.Append(System.Text.Encoding.GetEncoding(encoding).GetString(bytes, 0, bytes.Length)); - } - catch (System.IO.IOException uce) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new ReaderException(uce.ToString()); - } - } - - private static void decodeAlphanumericSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - // Read two characters at a time - while (count > 1) - { - int nextTwoCharsBits = bits.readBits(11); - result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]); - result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]); - count -= 2; - } - if (count == 1) - { - // special case: one character left - result.Append(ALPHANUMERIC_CHARS[bits.readBits(6)]); - } - } - - private static void decodeNumericSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - // Read three digits at a time - while (count >= 3) - { - // Each 10 bits encodes three digits - int threeDigitsBits = bits.readBits(10); - if (threeDigitsBits >= 1000) - { - throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits); - } - result.Append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]); - result.Append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]); - result.Append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]); - count -= 3; - } - if (count == 2) - { - // Two digits left over to read, encoded in 7 bits - int twoDigitsBits = bits.readBits(7); - if (twoDigitsBits >= 100) - { - throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits); - } - result.Append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]); - result.Append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]); - } - else if (count == 1) - { - // One digit left over to read - int digitBits = bits.readBits(4); - if (digitBits >= 10) - { - throw new ReaderException("Illegal value for digit unit: " + digitBits); - } - result.Append(ALPHANUMERIC_CHARS[digitBits]); - } - } - - private static System.String guessEncoding(sbyte[] bytes) - { - if (ASSUME_SHIFT_JIS) - { - return SHIFT_JIS; - } - // For now, merely tries to distinguish ISO-8859-1 and Shift_JIS, - // which should be by far the most common encodings. ISO-8859-1 - // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS - // uses this as a first byte of a two-byte character. If we see this - // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. - int length = bytes.Length; - for (int i = 0; i < length; i++) - { - int value_Renamed = bytes[i] & 0xFF; - if (value_Renamed >= 0x80 && value_Renamed <= 0x9F && i < length - 1) - { - // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS, - // just double check that it is followed by a byte that's valid in - // the Shift_JIS encoding - int nextValue = bytes[i + 1] & 0xFF; - if ((value_Renamed & 0x1) == 0) - { - // if even, - if (nextValue >= 0x40 && nextValue <= 0x9E) - { - return SHIFT_JIS; - } - } - else - { - if (nextValue >= 0x9F && nextValue <= 0x7C) - { - return SHIFT_JIS; - } - } - } - } - return "ASCII"; - } - //static DecodedBitStreamParser() - //{ - // { - // //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'" - // System.String platformDefault = System_Renamed.getProperty("file.encoding"); - // ASSUME_SHIFT_JIS = SHIFT_JIS.ToUpper().Equals(platformDefault.ToUpper()) || "EUC-JP".ToUpper().Equals(platformDefault.ToUpper()); - // } - //} - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/decoder/Decoder.cs b/qrcode-scanner-live/qrcode/decoder/Decoder.cs deleted file mode 100644 index 0e5993b..0000000 --- a/qrcode-scanner-live/qrcode/decoder/Decoder.cs +++ /dev/null @@ -1,140 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.qrcode.decoder -{ - using com.google.zxing.common; - using com.google.zxing.common.reedsolomon; - - public sealed class Decoder - { - private ReedSolomonDecoder rsDecoder; - - public Decoder() { - rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD); - } - - /** - *

Convenience method that can decode a QR Code represented as a 2D array of booleans. - * "true" is taken to mean a black module.

- * - * @param image booleans representing white/black QR Code modules - * @return text and bytes encoded within the QR Code - * @throws ReaderException if the QR Code cannot be decoded - */ - public DecoderResult decode(bool[][] image) { - try{ - int dimension = image.Length; - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - if (image[i][j]) { - bits.set(i, j); - } - } - } - return decode(bits); - }catch (Exception e){ - throw new ReaderException(e.Message); - } - } - - /** - *

Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.

- * - * @param bits booleans representing white/black QR Code modules - * @return text and bytes encoded within the QR Code - * @throws ReaderException if the QR Code cannot be decoded - */ - public DecoderResult decode(BitMatrix bits){ - try{ - // Construct a parser and read version, error-correction level - BitMatrixParser parser = new BitMatrixParser(bits); - Version version = parser.readVersion(); - ErrorCorrectionLevel ecLevel = parser.readFormatInformation().getErrorCorrectionLevel(); - - // Read codewords - sbyte[] codewords = parser.readCodewords(); - // Separate into data blocks - DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); - - // Count total number of data bytes - int totalBytes = 0; - for (int i = 0; i < dataBlocks.Length; i++) { - totalBytes += dataBlocks[i].NumDataCodewords; - } - sbyte[] resultBytes = new sbyte[totalBytes]; - int resultOffset = 0; - - // Error-correct and copy data blocks together into a stream of bytes - for (int j = 0; j < dataBlocks.Length; j++) { - DataBlock dataBlock = dataBlocks[j]; - sbyte[] codewordBytes = dataBlock.Codewords; - int numDataCodewords = dataBlock.NumDataCodewords; - correctErrors(codewordBytes, numDataCodewords); - for (int i = 0; i < numDataCodewords; i++) { - resultBytes[resultOffset++] = codewordBytes[i]; - } - } - - // Decode the contents of that stream of bytes - string sResult = DecodedBitStreamParser.decode(resultBytes, version); - return new DecoderResult(resultBytes, sResult, null); - }catch(Exception e){ - throw new ReaderException(e.Message); - } - - } - - /** - *

Given data and error-correction codewords received, possibly corrupted by errors, attempts to - * correct the errors in-place using Reed-Solomon error correction.

- * - * @param codewordBytes data and error correction codewords - * @param numDataCodewords number of codewords that are data bytes - * @throws ReaderException if error correction fails - */ - private void correctErrors(sbyte[] codewordBytes, int numDataCodewords){ - try - { - int numCodewords = codewordBytes.Length; - // First read into an array of ints - int[] codewordsInts = new int[numCodewords]; - for (int i = 0; i < numCodewords; i++) - { - codewordsInts[i] = codewordBytes[i] & 0xFF; - } - int numECCodewords = codewordBytes.Length - numDataCodewords; - try - { - rsDecoder.decode(codewordsInts, numECCodewords); - } - catch (ReedSolomonException rse) - { - throw new ReaderException(rse.Message); - } - // Copy back into array of bytes -- only need to worry about the bytes that were data - // We don't care about errors in the error-correction codewords - for (int i = 0; i < numDataCodewords; i++) - { - codewordBytes[i] = (sbyte)codewordsInts[i]; - } - } - catch (Exception e) { - throw new ReaderException(e.Message); - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/decoder/ErrorCorrectionLevel.cs b/qrcode-scanner-live/qrcode/decoder/ErrorCorrectionLevel.cs deleted file mode 100644 index c16e62f..0000000 --- a/qrcode-scanner-live/qrcode/decoder/ErrorCorrectionLevel.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class ErrorCorrectionLevel - { - // No, we can't use an enum here. J2ME doesn't support it. - /** - * L = ~7% correction - */ - public static ErrorCorrectionLevel L = new ErrorCorrectionLevel(0, 0x01, "L"); - /** - * M = ~15% correction - */ - public static ErrorCorrectionLevel M = new ErrorCorrectionLevel(1, 0x00, "M"); - /** - * Q = ~25% correction - */ - public static ErrorCorrectionLevel Q = new ErrorCorrectionLevel(2, 0x03, "Q"); - /** - * H = ~30% correction - */ - public static ErrorCorrectionLevel H = new ErrorCorrectionLevel(3, 0x02, "H"); - - private static ErrorCorrectionLevel[] FOR_BITS = {M, L, H, Q}; - - private int Ordinal; - private int bits; - private string name; - - private ErrorCorrectionLevel(int ordinal, int bits, string name) { - this.Ordinal = ordinal; - this.bits = bits; - this.name = name; - } - - public int ordinal() { - return Ordinal; - } - - public int getBits() { - return bits; - } - - public string getName() { - return name; - } - - public string toString() { - return name; - } - - /** - * @param bits int containing the two bits encoding a QR Code's error correction level - * @return {@link ErrorCorrectionLevel} representing the encoded error correction level - */ - public static ErrorCorrectionLevel forBits(int bits) { - if (bits < 0 || bits >= FOR_BITS.Length) { - throw new ArgumentException(); - } - return FOR_BITS[bits]; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/decoder/FormatInformation.cs b/qrcode-scanner-live/qrcode/decoder/FormatInformation.cs deleted file mode 100644 index 07aa37d..0000000 --- a/qrcode-scanner-live/qrcode/decoder/FormatInformation.cs +++ /dev/null @@ -1,118 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class FormatInformation - { - private static int FORMAT_INFO_MASK_QR = 0x5412; - /** - * See ISO 18004:2006, Annex C, Table C.1 - */ - private static readonly int[][] FORMAT_INFO_DECODE_LOOKUP = new int[][] { new int[] { 0x5412, 0x00 }, new int[] { 0x5125, 0x01 }, new int[] { 0x5E7C, 0x02 }, new int[] { 0x5B4B, 0x03 }, new int[] { 0x45F9, 0x04 }, new int[] { 0x40CE, 0x05 }, new int[] { 0x4F97, 0x06 }, new int[] { 0x4AA0, 0x07 }, new int[] { 0x77C4, 0x08 }, new int[] { 0x72F3, 0x09 }, new int[] { 0x7DAA, 0x0A }, new int[] { 0x789D, 0x0B }, new int[] { 0x662F, 0x0C }, new int[] { 0x6318, 0x0D }, new int[] { 0x6C41, 0x0E }, new int[] { 0x6976, 0x0F }, new int[] { 0x1689, 0x10 }, new int[] { 0x13BE, 0x11 }, new int[] { 0x1CE7, 0x12 }, new int[] { 0x19D0, 0x13 }, new int[] { 0x0762, 0x14 }, new int[] { 0x0255, 0x15 }, new int[] { 0x0D0C, 0x16 }, new int[] { 0x083B, 0x17 }, new int[] { 0x355F, 0x18 }, new int[] { 0x3068, 0x19 }, new int[] { 0x3F31, 0x1A }, new int[] { 0x3A06, 0x1B }, new int[] { 0x24B4, 0x1C }, new int[] { 0x2183, 0x1D }, new int[] { 0x2EDA, 0x1E }, new int[] { 0x2BED, 0x1F } }; - - /** - * Offset i holds the number of 1 bits in the binary representation of i - */ - private static int[] BITS_SET_IN_HALF_BYTE = - {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; - - private ErrorCorrectionLevel errorCorrectionLevel; - private byte dataMask; - - private FormatInformation(int formatInfo) { - // Bits 3,4 - errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); - // Bottom 3 bits - dataMask = (byte) (formatInfo & 0x07); - } - - public static int numBitsDiffering(int a, int b) { - a ^= b; // a now has a 1 bit exactly where its bit differs with b's - // Count bits set quickly with a series of lookups: - return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 28) & 0x0F)]; - } - - /** - * @param rawFormatInfo - * @return - */ - public static FormatInformation decodeFormatInformation(int rawFormatInfo){ - try{ - FormatInformation formatInfo = doDecodeFormatInformation(rawFormatInfo); - if (formatInfo != null) { - return formatInfo; - } - // Should return null, but, some QR codes apparently - // do not mask this info. Try again, first masking the raw bits so - // the function will unmask - return doDecodeFormatInformation(rawFormatInfo ^ FORMAT_INFO_MASK_QR); - }catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - private static FormatInformation doDecodeFormatInformation(int rawFormatInfo) { - // Unmask: - int unmaskedFormatInfo = rawFormatInfo ^ FORMAT_INFO_MASK_QR; - // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing - int bestDifference = int.MaxValue; - int bestFormatInfo = 0; - for (int i = 0; i < FORMAT_INFO_DECODE_LOOKUP.Length; i++) { - int[] decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; - int targetInfo = decodeInfo[0]; - if (targetInfo == unmaskedFormatInfo) { - // Found an exact match - return new FormatInformation(decodeInfo[1]); - } - int bitsDifference = numBitsDiffering(unmaskedFormatInfo, targetInfo); - if (bitsDifference < bestDifference) { - bestFormatInfo = decodeInfo[1]; - bestDifference = bitsDifference; - } - } - if (bestDifference <= 3) { - return new FormatInformation(bestFormatInfo); - } - return null; - } - - public ErrorCorrectionLevel getErrorCorrectionLevel() { - return errorCorrectionLevel; - } - - public byte getDataMask() { - return dataMask; - } - - public int hashCode() { - return (errorCorrectionLevel.ordinal() << 3) | (int) dataMask; - } - - public bool equals(Object o) { - if (!(o.GetType() == typeof(FormatInformation))){ - return false; - } - FormatInformation other = (FormatInformation) o; - return this.errorCorrectionLevel == other.errorCorrectionLevel && - this.dataMask == other.dataMask; - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/decoder/Mode.cs b/qrcode-scanner-live/qrcode/decoder/Mode.cs deleted file mode 100644 index f06f890..0000000 --- a/qrcode-scanner-live/qrcode/decoder/Mode.cs +++ /dev/null @@ -1,108 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class Mode - { - // No, we can't use an enum here. J2ME doesn't support it. - public static Mode TERMINATOR = new Mode(new int[]{0, 0, 0}, 0x00, "TERMINATOR"); // Not really a mode... - public static Mode NUMERIC = new Mode(new int[]{10, 12, 14}, 0x01, "NUMERIC"); - public static Mode ALPHANUMERIC = new Mode(new int[]{9, 11, 13}, 0x02, "ALPHANUMERIC"); - public static Mode BYTE = new Mode(new int[]{8, 16, 16}, 0x04, "BYTE"); - public static Mode ECI = new Mode(null, 0x07, "ECI"); // character counts don't apply - public static Mode KANJI = new Mode(new int[]{8, 10, 12}, 0x08, "KANJI"); - public static Mode FNC1_FIRST_POSITION = new Mode(null, 0x05, "FNC1_FIRST_POSITION"); - public static Mode FNC1_SECOND_POSITION = new Mode(null, 0x09, "FNC1_SECOND_POSITION"); - - private int[] characterCountBitsForVersions; - private int bits; - private string name; - - private Mode(int[] characterCountBitsForVersions, int bits, string name) { - this.characterCountBitsForVersions = characterCountBitsForVersions; - this.bits = bits; - this.name = name; - } - - /** - * @param bits four bits encoding a QR Code data mode - * @return {@link Mode} encoded by these bits - * @throws ArgumentException if bits do not correspond to a known mode - */ - public static Mode forBits(int bits) { - switch (bits) { - case 0x0: - return TERMINATOR; - case 0x1: - return NUMERIC; - case 0x2: - return ALPHANUMERIC; - case 0x4: - return BYTE; - case 0x5: - return FNC1_FIRST_POSITION; - case 0x7: - return ECI; - case 0x8: - return KANJI; - case 0x9: - return FNC1_SECOND_POSITION; - default: - throw new ArgumentException(); - } - } - - /** - * @param version version in question - * @return number of bits used, in this QR Code symbol {@link Version}, to encode the - * count of characters that will follow encoded in this {@link Mode} - */ - public int getCharacterCountBits(Version version) { - if (characterCountBitsForVersions == null) { - throw new ArgumentException("Character count doesn't apply to this mode"); - } - int number = version.getVersionNumber(); - int offset; - if (number <= 9) { - offset = 0; - } else if (number <= 26) { - offset = 1; - } else { - offset = 2; - } - return characterCountBitsForVersions[offset]; - } - - public int getBits() { - return bits; - } - - public string getName() { - return name; - } - - public string toString() { - return name; - } - - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/decoder/Version.cs b/qrcode-scanner-live/qrcode/decoder/Version.cs deleted file mode 100644 index 502b80a..0000000 --- a/qrcode-scanner-live/qrcode/decoder/Version.cs +++ /dev/null @@ -1,579 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class Version - { - /** - * See ISO 18004:2006 Annex D. - * Element i represents the raw version bits that specify version i + 7 - */ - private static int[] VERSION_DECODE_INFO = { - 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, - 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, - 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, - 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, - 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, - 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, - 0x2542E, 0x26A64, 0x27541, 0x28C69 - }; - - private static Version[] VERSIONS = buildVersions(); - - private int versionNumber; - private int[] alignmentPatternCenters; - private ECBlocks[] ecBlocks; - private int totalCodewords; - - private Version(int versionNumber, - int[] alignmentPatternCenters, - ECBlocks ecBlocks1, - ECBlocks ecBlocks2, - ECBlocks ecBlocks3, - ECBlocks ecBlocks4) { - this.versionNumber = versionNumber; - this.alignmentPatternCenters = alignmentPatternCenters; - this.ecBlocks = new ECBlocks[]{ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4}; - int total = 0; - int ecCodewords = ecBlocks1.getECCodewordsPerBlock(); - ECB[] ecbArray = ecBlocks1.getECBlocks(); - for (int i = 0; i < ecbArray.Length; i++) { - ECB ecBlock = ecbArray[i]; - total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords); - } - this.totalCodewords = total; - } - - public int getVersionNumber() { - return versionNumber; - } - - public int[] getAlignmentPatternCenters() { - return alignmentPatternCenters; - } - - public int getTotalCodewords() { - return totalCodewords; - } - - public int getDimensionForVersion() { - return 17 + 4 * versionNumber; - } - - public ECBlocks getECBlocksForLevel(ErrorCorrectionLevel ecLevel) { - return ecBlocks[ecLevel.ordinal()]; - } - - /** - *

Deduces version information purely from QR Code dimensions.

- * - * @param dimension dimension in modules - * @return {@link Version} for a QR Code of that dimension - * @throws ReaderException if dimension is not 1 mod 4 - */ - public static Version getProvisionalVersionForDimension(int dimension) { - if (dimension % 4 != 1) { - throw new ReaderException(); - } - return getVersionForNumber((dimension - 17) >> 2); - } - - public static Version getVersionForNumber(int versionNumber) { - if (versionNumber < 1 || versionNumber > 40) { - throw new ArgumentException(); - } - return VERSIONS[versionNumber - 1]; - } - - public static Version decodeVersionInformation(int versionBits) { - int bestDifference = int.MaxValue; - int bestVersion = 0; - for (int i = 0; i < VERSION_DECODE_INFO.Length; i++) { - int targetVersion = VERSION_DECODE_INFO[i]; - // Do the version info bits match exactly? done. - if (targetVersion == versionBits) { - return getVersionForNumber(i + 7); - } - // Otherwise see if this is the closest to a real version info bit string - // we have seen so far - int bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); - if (bitsDifference < bestDifference) { - bestVersion = i + 7; - } - } - // We can tolerate up to 3 bits of error since no two version info codewords will - // differ in less than 4 bits. - if (bestDifference <= 3) { - return getVersionForNumber(bestVersion); - } - // If we didn't find a close enough match, fail - return null; - } - - /** - * See ISO 18004:2006 Annex E - */ - public BitMatrix buildFunctionPattern() { - int dimension = getDimensionForVersion(); - BitMatrix bitMatrix = new BitMatrix(dimension); - - // Top left finder pattern + separator + format - bitMatrix.setRegion(0, 0, 9, 9); - // Top right finder pattern + separator + format - bitMatrix.setRegion(0, dimension - 8, 9, 8); - // Bottom left finder pattern + separator + format - bitMatrix.setRegion(dimension - 8, 0, 8, 9); - - // Alignment patterns - int max = alignmentPatternCenters.Length; - for (int x = 0; x < max; x++) { - int i = alignmentPatternCenters[x] - 2; - for (int y = 0; y < max; y++) { - if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) { - // No alignment patterns near the three finder paterns - continue; - } - bitMatrix.setRegion(i, alignmentPatternCenters[y] - 2, 5, 5); - } - } - - // Vertical timing pattern - bitMatrix.setRegion(9, 6, dimension - 17, 1); - // Horizontal timing pattern - bitMatrix.setRegion(6, 9, 1, dimension - 17); - - if (versionNumber > 6) { - // Version info, top right - bitMatrix.setRegion(0, dimension - 11, 6, 3); - // Version info, bottom left - bitMatrix.setRegion(dimension - 11, 0, 3, 6); - } - - return bitMatrix; - } - - /** - *

Encapsulates a set of error-correction blocks in one symbol version. Most versions will - * use blocks of differing sizes within one version, so, this encapsulates the parameters for - * each set of blocks. It also holds the number of error-correction codewords per block since it - * will be the same across all blocks within one version.

- */ - public class ECBlocks { - private int ecCodewordsPerBlock; - private ECB[] ecBlocks; - - public ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks) { - this.ecCodewordsPerBlock = ecCodewordsPerBlock; - this.ecBlocks = new ECB[]{ecBlocks}; - } - - public ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks1, ECB ecBlocks2) - { - this.ecCodewordsPerBlock = ecCodewordsPerBlock; - this.ecBlocks = new ECB[]{ecBlocks1, ecBlocks2}; - } - - public int getECCodewordsPerBlock() { - return ecCodewordsPerBlock; - } - - public int getNumBlocks() { - int total = 0; - for (int i = 0; i < ecBlocks.Length; i++) { - total += ecBlocks[i].getCount(); - } - return total; - } - - public int getTotalECCodewords() { - return ecCodewordsPerBlock * getNumBlocks(); - } - - public ECB[] getECBlocks() { - return ecBlocks; - } - } - - /** - *

Encapsualtes the parameters for one error-correction block in one symbol version. - * This includes the number of data codewords, and the number of times a block with these - * parameters is used consecutively in the QR code version's format.

- */ - public class ECB { - private int count; - private int dataCodewords; - - public ECB(int count, int dataCodewords) { - this.count = count; - this.dataCodewords = dataCodewords; - } - - public int getCount() { - return count; - } - - public int getDataCodewords() { - return dataCodewords; - } - } - - public String toString() { - return versionNumber.ToString(); - //return String.valueOf(versionNumber); - } - - /** - * See ISO 18004:2006 6.5.1 Table 9 - */ - private static Version[] buildVersions() { - return new Version[]{ - new Version(1, new int[]{}, - new ECBlocks(7, new ECB(1, 19)), - new ECBlocks(10, new ECB(1, 16)), - new ECBlocks(13, new ECB(1, 13)), - new ECBlocks(17, new ECB(1, 9))), - new Version(2, new int[]{6, 18}, - new ECBlocks(10, new ECB(1, 34)), - new ECBlocks(16, new ECB(1, 28)), - new ECBlocks(22, new ECB(1, 22)), - new ECBlocks(28, new ECB(1, 16))), - new Version(3, new int[]{6, 22}, - new ECBlocks(15, new ECB(1, 55)), - new ECBlocks(26, new ECB(1, 44)), - new ECBlocks(18, new ECB(2, 17)), - new ECBlocks(22, new ECB(2, 13))), - new Version(4, new int[]{6, 26}, - new ECBlocks(20, new ECB(1, 80)), - new ECBlocks(18, new ECB(2, 32)), - new ECBlocks(26, new ECB(2, 24)), - new ECBlocks(16, new ECB(4, 9))), - new Version(5, new int[]{6, 30}, - new ECBlocks(26, new ECB(1, 108)), - new ECBlocks(24, new ECB(2, 43)), - new ECBlocks(18, new ECB(2, 15), - new ECB(2, 16)), - new ECBlocks(22, new ECB(2, 11), - new ECB(2, 12))), - new Version(6, new int[]{6, 34}, - new ECBlocks(18, new ECB(2, 68)), - new ECBlocks(16, new ECB(4, 27)), - new ECBlocks(24, new ECB(4, 19)), - new ECBlocks(28, new ECB(4, 15))), - new Version(7, new int[]{6, 22, 38}, - new ECBlocks(20, new ECB(2, 78)), - new ECBlocks(18, new ECB(4, 31)), - new ECBlocks(18, new ECB(2, 14), - new ECB(4, 15)), - new ECBlocks(26, new ECB(4, 13), - new ECB(1, 14))), - new Version(8, new int[]{6, 24, 42}, - new ECBlocks(24, new ECB(2, 97)), - new ECBlocks(22, new ECB(2, 38), - new ECB(2, 39)), - new ECBlocks(22, new ECB(4, 18), - new ECB(2, 19)), - new ECBlocks(26, new ECB(4, 14), - new ECB(2, 15))), - new Version(9, new int[]{6, 26, 46}, - new ECBlocks(30, new ECB(2, 116)), - new ECBlocks(22, new ECB(3, 36), - new ECB(2, 37)), - new ECBlocks(20, new ECB(4, 16), - new ECB(4, 17)), - new ECBlocks(24, new ECB(4, 12), - new ECB(4, 13))), - new Version(10, new int[]{6, 28, 50}, - new ECBlocks(18, new ECB(2, 68), - new ECB(2, 69)), - new ECBlocks(26, new ECB(4, 43), - new ECB(1, 44)), - new ECBlocks(24, new ECB(6, 19), - new ECB(2, 20)), - new ECBlocks(28, new ECB(6, 15), - new ECB(2, 16))), - new Version(11, new int[]{6, 30, 54}, - new ECBlocks(20, new ECB(4, 81)), - new ECBlocks(30, new ECB(1, 50), - new ECB(4, 51)), - new ECBlocks(28, new ECB(4, 22), - new ECB(4, 23)), - new ECBlocks(24, new ECB(3, 12), - new ECB(8, 13))), - new Version(12, new int[]{6, 32, 58}, - new ECBlocks(24, new ECB(2, 92), - new ECB(2, 93)), - new ECBlocks(22, new ECB(6, 36), - new ECB(2, 37)), - new ECBlocks(26, new ECB(4, 20), - new ECB(6, 21)), - new ECBlocks(28, new ECB(7, 14), - new ECB(4, 15))), - new Version(13, new int[]{6, 34, 62}, - new ECBlocks(26, new ECB(4, 107)), - new ECBlocks(22, new ECB(8, 37), - new ECB(1, 38)), - new ECBlocks(24, new ECB(8, 20), - new ECB(4, 21)), - new ECBlocks(22, new ECB(12, 11), - new ECB(4, 12))), - new Version(14, new int[]{6, 26, 46, 66}, - new ECBlocks(30, new ECB(3, 115), - new ECB(1, 116)), - new ECBlocks(24, new ECB(4, 40), - new ECB(5, 41)), - new ECBlocks(20, new ECB(11, 16), - new ECB(5, 17)), - new ECBlocks(24, new ECB(11, 12), - new ECB(5, 13))), - new Version(15, new int[]{6, 26, 48, 70}, - new ECBlocks(22, new ECB(5, 87), - new ECB(1, 88)), - new ECBlocks(24, new ECB(5, 41), - new ECB(5, 42)), - new ECBlocks(30, new ECB(5, 24), - new ECB(7, 25)), - new ECBlocks(24, new ECB(11, 12), - new ECB(7, 13))), - new Version(16, new int[]{6, 26, 50, 74}, - new ECBlocks(24, new ECB(5, 98), - new ECB(1, 99)), - new ECBlocks(28, new ECB(7, 45), - new ECB(3, 46)), - new ECBlocks(24, new ECB(15, 19), - new ECB(2, 20)), - new ECBlocks(30, new ECB(3, 15), - new ECB(13, 16))), - new Version(17, new int[]{6, 30, 54, 78}, - new ECBlocks(28, new ECB(1, 107), - new ECB(5, 108)), - new ECBlocks(28, new ECB(10, 46), - new ECB(1, 47)), - new ECBlocks(28, new ECB(1, 22), - new ECB(15, 23)), - new ECBlocks(28, new ECB(2, 14), - new ECB(17, 15))), - new Version(18, new int[]{6, 30, 56, 82}, - new ECBlocks(30, new ECB(5, 120), - new ECB(1, 121)), - new ECBlocks(26, new ECB(9, 43), - new ECB(4, 44)), - new ECBlocks(28, new ECB(17, 22), - new ECB(1, 23)), - new ECBlocks(28, new ECB(2, 14), - new ECB(19, 15))), - new Version(19, new int[]{6, 30, 58, 86}, - new ECBlocks(28, new ECB(3, 113), - new ECB(4, 114)), - new ECBlocks(26, new ECB(3, 44), - new ECB(11, 45)), - new ECBlocks(26, new ECB(17, 21), - new ECB(4, 22)), - new ECBlocks(26, new ECB(9, 13), - new ECB(16, 14))), - new Version(20, new int[]{6, 34, 62, 90}, - new ECBlocks(28, new ECB(3, 107), - new ECB(5, 108)), - new ECBlocks(26, new ECB(3, 41), - new ECB(13, 42)), - new ECBlocks(30, new ECB(15, 24), - new ECB(5, 25)), - new ECBlocks(28, new ECB(15, 15), - new ECB(10, 16))), - new Version(21, new int[]{6, 28, 50, 72, 94}, - new ECBlocks(28, new ECB(4, 116), - new ECB(4, 117)), - new ECBlocks(26, new ECB(17, 42)), - new ECBlocks(28, new ECB(17, 22), - new ECB(6, 23)), - new ECBlocks(30, new ECB(19, 16), - new ECB(6, 17))), - new Version(22, new int[]{6, 26, 50, 74, 98}, - new ECBlocks(28, new ECB(2, 111), - new ECB(7, 112)), - new ECBlocks(28, new ECB(17, 46)), - new ECBlocks(30, new ECB(7, 24), - new ECB(16, 25)), - new ECBlocks(24, new ECB(34, 13))), - new Version(23, new int[]{6, 30, 54, 74, 102}, - new ECBlocks(30, new ECB(4, 121), - new ECB(5, 122)), - new ECBlocks(28, new ECB(4, 47), - new ECB(14, 48)), - new ECBlocks(30, new ECB(11, 24), - new ECB(14, 25)), - new ECBlocks(30, new ECB(16, 15), - new ECB(14, 16))), - new Version(24, new int[]{6, 28, 54, 80, 106}, - new ECBlocks(30, new ECB(6, 117), - new ECB(4, 118)), - new ECBlocks(28, new ECB(6, 45), - new ECB(14, 46)), - new ECBlocks(30, new ECB(11, 24), - new ECB(16, 25)), - new ECBlocks(30, new ECB(30, 16), - new ECB(2, 17))), - new Version(25, new int[]{6, 32, 58, 84, 110}, - new ECBlocks(26, new ECB(8, 106), - new ECB(4, 107)), - new ECBlocks(28, new ECB(8, 47), - new ECB(13, 48)), - new ECBlocks(30, new ECB(7, 24), - new ECB(22, 25)), - new ECBlocks(30, new ECB(22, 15), - new ECB(13, 16))), - new Version(26, new int[]{6, 30, 58, 86, 114}, - new ECBlocks(28, new ECB(10, 114), - new ECB(2, 115)), - new ECBlocks(28, new ECB(19, 46), - new ECB(4, 47)), - new ECBlocks(28, new ECB(28, 22), - new ECB(6, 23)), - new ECBlocks(30, new ECB(33, 16), - new ECB(4, 17))), - new Version(27, new int[]{6, 34, 62, 90, 118}, - new ECBlocks(30, new ECB(8, 122), - new ECB(4, 123)), - new ECBlocks(28, new ECB(22, 45), - new ECB(3, 46)), - new ECBlocks(30, new ECB(8, 23), - new ECB(26, 24)), - new ECBlocks(30, new ECB(12, 15), - new ECB(28, 16))), - new Version(28, new int[]{6, 26, 50, 74, 98, 122}, - new ECBlocks(30, new ECB(3, 117), - new ECB(10, 118)), - new ECBlocks(28, new ECB(3, 45), - new ECB(23, 46)), - new ECBlocks(30, new ECB(4, 24), - new ECB(31, 25)), - new ECBlocks(30, new ECB(11, 15), - new ECB(31, 16))), - new Version(29, new int[]{6, 30, 54, 78, 102, 126}, - new ECBlocks(30, new ECB(7, 116), - new ECB(7, 117)), - new ECBlocks(28, new ECB(21, 45), - new ECB(7, 46)), - new ECBlocks(30, new ECB(1, 23), - new ECB(37, 24)), - new ECBlocks(30, new ECB(19, 15), - new ECB(26, 16))), - new Version(30, new int[]{6, 26, 52, 78, 104, 130}, - new ECBlocks(30, new ECB(5, 115), - new ECB(10, 116)), - new ECBlocks(28, new ECB(19, 47), - new ECB(10, 48)), - new ECBlocks(30, new ECB(15, 24), - new ECB(25, 25)), - new ECBlocks(30, new ECB(23, 15), - new ECB(25, 16))), - new Version(31, new int[]{6, 30, 56, 82, 108, 134}, - new ECBlocks(30, new ECB(13, 115), - new ECB(3, 116)), - new ECBlocks(28, new ECB(2, 46), - new ECB(29, 47)), - new ECBlocks(30, new ECB(42, 24), - new ECB(1, 25)), - new ECBlocks(30, new ECB(23, 15), - new ECB(28, 16))), - new Version(32, new int[]{6, 34, 60, 86, 112, 138}, - new ECBlocks(30, new ECB(17, 115)), - new ECBlocks(28, new ECB(10, 46), - new ECB(23, 47)), - new ECBlocks(30, new ECB(10, 24), - new ECB(35, 25)), - new ECBlocks(30, new ECB(19, 15), - new ECB(35, 16))), - new Version(33, new int[]{6, 30, 58, 86, 114, 142}, - new ECBlocks(30, new ECB(17, 115), - new ECB(1, 116)), - new ECBlocks(28, new ECB(14, 46), - new ECB(21, 47)), - new ECBlocks(30, new ECB(29, 24), - new ECB(19, 25)), - new ECBlocks(30, new ECB(11, 15), - new ECB(46, 16))), - new Version(34, new int[]{6, 34, 62, 90, 118, 146}, - new ECBlocks(30, new ECB(13, 115), - new ECB(6, 116)), - new ECBlocks(28, new ECB(14, 46), - new ECB(23, 47)), - new ECBlocks(30, new ECB(44, 24), - new ECB(7, 25)), - new ECBlocks(30, new ECB(59, 16), - new ECB(1, 17))), - new Version(35, new int[]{6, 30, 54, 78, 102, 126, 150}, - new ECBlocks(30, new ECB(12, 121), - new ECB(7, 122)), - new ECBlocks(28, new ECB(12, 47), - new ECB(26, 48)), - new ECBlocks(30, new ECB(39, 24), - new ECB(14, 25)), - new ECBlocks(30, new ECB(22, 15), - new ECB(41, 16))), - new Version(36, new int[]{6, 24, 50, 76, 102, 128, 154}, - new ECBlocks(30, new ECB(6, 121), - new ECB(14, 122)), - new ECBlocks(28, new ECB(6, 47), - new ECB(34, 48)), - new ECBlocks(30, new ECB(46, 24), - new ECB(10, 25)), - new ECBlocks(30, new ECB(2, 15), - new ECB(64, 16))), - new Version(37, new int[]{6, 28, 54, 80, 106, 132, 158}, - new ECBlocks(30, new ECB(17, 122), - new ECB(4, 123)), - new ECBlocks(28, new ECB(29, 46), - new ECB(14, 47)), - new ECBlocks(30, new ECB(49, 24), - new ECB(10, 25)), - new ECBlocks(30, new ECB(24, 15), - new ECB(46, 16))), - new Version(38, new int[]{6, 32, 58, 84, 110, 136, 162}, - new ECBlocks(30, new ECB(4, 122), - new ECB(18, 123)), - new ECBlocks(28, new ECB(13, 46), - new ECB(32, 47)), - new ECBlocks(30, new ECB(48, 24), - new ECB(14, 25)), - new ECBlocks(30, new ECB(42, 15), - new ECB(32, 16))), - new Version(39, new int[]{6, 26, 54, 82, 110, 138, 166}, - new ECBlocks(30, new ECB(20, 117), - new ECB(4, 118)), - new ECBlocks(28, new ECB(40, 47), - new ECB(7, 48)), - new ECBlocks(30, new ECB(43, 24), - new ECB(22, 25)), - new ECBlocks(30, new ECB(10, 15), - new ECB(67, 16))), - new Version(40, new int[]{6, 30, 58, 86, 114, 142, 170}, - new ECBlocks(30, new ECB(19, 118), - new ECB(6, 119)), - new ECBlocks(28, new ECB(18, 47), - new ECB(31, 48)), - new ECBlocks(30, new ECB(34, 24), - new ECB(34, 25)), - new ECBlocks(30, new ECB(20, 15), - new ECB(61, 16))) - }; - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/detector/AlignmentPattern.cs b/qrcode-scanner-live/qrcode/detector/AlignmentPattern.cs deleted file mode 100644 index 562a1d2..0000000 --- a/qrcode-scanner-live/qrcode/detector/AlignmentPattern.cs +++ /dev/null @@ -1,56 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.detector -{ - public sealed class AlignmentPattern : ResultPoint - { - private float posX; - private float posY; - private float estimatedModuleSize; - - public AlignmentPattern(float posX, float posY, float estimatedModuleSize) { - this.posX = posX; - this.posY = posY; - this.estimatedModuleSize = estimatedModuleSize; - } - - public float getX() { - return posX; - } - - public float getY() { - return posY; - } - - /** - *

Determines if this alignment pattern "about equals" an alignment pattern at the stated - * position and size -- meaning, it is at nearly the same center with nearly the same size.

- */ - public bool aboutEquals(float moduleSize, float i, float j) { - return - Math.Abs(i - posY) <= moduleSize && - Math.Abs(j - posX) <= moduleSize && - (Math.Abs(moduleSize - estimatedModuleSize) <= 1.0f || - Math.Abs(moduleSize - estimatedModuleSize) / estimatedModuleSize <= 0.1f); - } - } - - -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/detector/AlignmentPatternFinder.cs b/qrcode-scanner-live/qrcode/detector/AlignmentPatternFinder.cs deleted file mode 100644 index ed7c41c..0000000 --- a/qrcode-scanner-live/qrcode/detector/AlignmentPatternFinder.cs +++ /dev/null @@ -1,258 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.detector -{ - public sealed class AlignmentPatternFinder - { - private MonochromeBitmapSource image; - private System.Collections.ArrayList possibleCenters; - private int startX; - private int startY; - private int width; - private int height; - private float moduleSize; - private int[] crossCheckStateCount; - - /** - *

Creates a finder that will look in a portion of the whole image.

- * - * @param image image to search - * @param startX left column from which to start searching - * @param startY top row from which to start searching - * @param width width of region to search - * @param height height of region to search - * @param moduleSize estimated module size so far - */ - public AlignmentPatternFinder(MonochromeBitmapSource image, - int startX, - int startY, - int width, - int height, - float moduleSize) { - this.image = image; - this.possibleCenters = new System.Collections.ArrayList(5); - this.startX = startX; - this.startY = startY; - this.width = width; - this.height = height; - this.moduleSize = moduleSize; - this.crossCheckStateCount = new int[3]; - } - - /** - *

This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since - * it's pretty performance-critical and so is written to be fast foremost.

- * - * @return {@link AlignmentPattern} if found - * @throws ReaderException if not found - */ - public AlignmentPattern find() { - int startX = this.startX; - int height = this.height; - int maxJ = startX + width; - int middleI = startY + (height >> 1); - BitArray luminanceRow = new BitArray(width); - // We are looking for black/white/black modules in 1:1:1 ratio; - // this tracks the number of black/white/black modules seen so far - int[] stateCount = new int[3]; - for (int iGen = 0; iGen < height; iGen++) { - // Search from middle outwards - int i = middleI + ((iGen & 0x01) == 0 ? ((iGen + 1) >> 1) : -((iGen + 1) >> 1)); - image.getBlackRow(i, luminanceRow, startX, width); - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - int j = startX; - // Burn off leading white pixels before anything else; if we start in the middle of - // a white run, it doesn't make sense to count its length, since we don't know if the - // white run continued to the left of the start point - while (j < maxJ && !luminanceRow.get(j - startX)) { - j++; - } - int currentState = 0; - while (j < maxJ) { - if (luminanceRow.get(j - startX)) { - // Black pixel - if (currentState == 1) { // Counting black pixels - stateCount[currentState]++; - } else { // Counting white pixels - if (currentState == 2) { // A winner? - if (foundPatternCross(stateCount)) { // Yes - AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j); - if (confirmed != null) { - return confirmed; - } - } - stateCount[0] = stateCount[2]; - stateCount[1] = 1; - stateCount[2] = 0; - currentState = 1; - } else { - stateCount[++currentState]++; - } - } - } else { // White pixel - if (currentState == 1) { // Counting black pixels - currentState++; - } - stateCount[currentState]++; - } - j++; - } - if (foundPatternCross(stateCount)) { - AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ); - if (confirmed != null) { - return confirmed; - } - } - - } - - // Hmm, nothing we saw was observed and confirmed twice. If we had - // any guess at all, return it. - if (!(possibleCenters.Count==0)) { - return (AlignmentPattern) possibleCenters[0]; - } - - throw new ReaderException(); - } - - /** - * Given a count of black/white/black pixels just seen and an end position, - * figures the location of the center of this black/white/black run. - */ - private static float centerFromEnd(int[] stateCount, int end) { - return (float) (end - stateCount[2]) - stateCount[1] / 2.0f; - } - - /** - * @param stateCount count of black/white/black pixels just read - * @return true iff the proportions of the counts is close enough to the 1/1/1 ratios - * used by alignment patterns to be considered a match - */ - private bool foundPatternCross(int[] stateCount) { - float moduleSize = this.moduleSize; - float maxVariance = moduleSize / 2.0f; - for (int i = 0; i < 3; i++) { - if (Math.Abs(moduleSize - stateCount[i]) >= maxVariance) { - return false; - } - } - return true; - } - - /** - *

After a horizontal scan finds a potential alignment pattern, this method - * "cross-checks" by scanning down vertically through the center of the possible - * alignment pattern to see if the same proportion is detected.

- * - * @param startI row where an alignment pattern was detected - * @param centerJ center of the section that appears to cross an alignment pattern - * @param maxCount maximum reasonable number of modules that should be - * observed in any reading state, based on the results of the horizontal scan - * @return vertical center of alignment pattern, or {@link Float#NaN} if not found - */ - private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { - MonochromeBitmapSource image = this.image; - - int maxI = image.getHeight(); - int[] stateCount = crossCheckStateCount; - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - - // Start counting up from center - int i = startI; - while (i >= 0 && image.isBlack(centerJ, i) && stateCount[1] <= maxCount) { - stateCount[1]++; - i--; - } - // If already too many modules in this state or ran off the edge: - if (i < 0 || stateCount[1] > maxCount) { - return float.NaN; - } - while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[0] <= maxCount) { - stateCount[0]++; - i--; - } - if (stateCount[0] > maxCount) { - return float.NaN; - } - - // Now also count down from center - i = startI + 1; - while (i < maxI && image.isBlack(centerJ, i) && stateCount[1] <= maxCount) { - stateCount[1]++; - i++; - } - if (i == maxI || stateCount[1] > maxCount) { - return float.NaN; - } - while (i < maxI && !image.isBlack(centerJ, i) && stateCount[2] <= maxCount) { - stateCount[2]++; - i++; - } - if (stateCount[2] > maxCount) { - return float.NaN; - } - - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; - if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { - return float.NaN; - } - - return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : float.NaN; - } - - /** - *

This is called when a horizontal scan finds a possible alignment pattern. It will - * cross check with a vertical scan, and if successful, will see if this pattern had been - * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have - * found the alignment pattern.

- * - * @param stateCount reading state module counts from horizontal scan - * @param i row where alignment pattern may be found - * @param j end of possible alignment pattern in row - * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not - */ - private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) { - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; - float centerJ = centerFromEnd(stateCount, j); - float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1], stateCountTotal); - if (!Single.IsNaN(centerI)) - { - float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f; - int max = possibleCenters.Count; - for (int index = 0; index < max; index++) { - AlignmentPattern center = (AlignmentPattern) possibleCenters[index]; - // Look for about the same center and module size: - if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { - return new AlignmentPattern(centerJ, centerI, estimatedModuleSize); - } - } - // Hadn't found this before; save it - possibleCenters.Add(new AlignmentPattern(centerJ, centerI, estimatedModuleSize)); - } - return null; - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/detector/Detector.cs b/qrcode-scanner-live/qrcode/detector/Detector.cs deleted file mode 100644 index 828aa85..0000000 --- a/qrcode-scanner-live/qrcode/detector/Detector.cs +++ /dev/null @@ -1,362 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.detector -{ - using Version = com.google.zxing.qrcode.decoder.Version; - - public sealed class Detector - { - private MonochromeBitmapSource image; - - public Detector(MonochromeBitmapSource image) { - this.image = image; - } - - /** - *

Detects a QR Code in an image, simply.

- * - * @return {@link DetectorResult} encapsulating results of detecting a QR Code - * @throws ReaderException if no QR Code can be found - */ - public DetectorResult detect(){ - try{ - return detect(null); - }catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - /** - *

Detects a QR Code in an image, simply.

- * - * @param hints optional hints to detector - * @return {@link DetectorResult} encapsulating results of detecting a QR Code - * @throws ReaderException if no QR Code can be found - */ - public DetectorResult detect(System.Collections.Hashtable hints) { - - MonochromeBitmapSource image = this.image; - if (!BlackPointEstimationMethod.TWO_D_SAMPLING.Equals(image.getLastEstimationMethod())) { - image.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0); - } - - FinderPatternFinder finder = new FinderPatternFinder(image); - FinderPatternInfo info = finder.find(hints); - - FinderPattern topLeft = info.getTopLeft(); - FinderPattern topRight = info.getTopRight(); - FinderPattern bottomLeft = info.getBottomLeft(); - - float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft); - if (moduleSize < 1.0f) { - throw new ReaderException(); - } - int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize); - - Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension); - int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7; - - AlignmentPattern alignmentPattern = null; - // Anything above version 1 has an alignment pattern - if (provisionalVersion.getAlignmentPatternCenters().Length > 0) { - - // Guess where a "bottom right" finder pattern would have been - float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX(); - float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY(); - - // Estimate that alignment pattern is closer by 3 modules - // from "bottom right" to known top left location - float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters; - int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX())); - int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY())); - - // Kind of arbitrary -- expand search radius before giving up - for (int i = 4; i <= 16; i <<= 1) { - try { - alignmentPattern = findAlignmentInRegion(moduleSize, - estAlignmentX, - estAlignmentY, - (float) i); - break; - } catch (ReaderException re) { - // try next round - } - } - if (alignmentPattern == null) { - throw new ReaderException(); - } - - } - - BitMatrix bits = sampleGrid(image, topLeft, topRight, bottomLeft, alignmentPattern, dimension); - - ResultPoint[] points; - if (alignmentPattern == null) { - points = new ResultPoint[]{bottomLeft, topLeft, topRight}; - } else { - points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern}; - } - return new DetectorResult(bits, points); - } - - private static BitMatrix sampleGrid(MonochromeBitmapSource image, - ResultPoint topLeft, - ResultPoint topRight, - ResultPoint bottomLeft, - ResultPoint alignmentPattern, - int dimension) { - float dimMinusThree = (float) dimension - 3.5f; - float bottomRightX; - float bottomRightY; - float sourceBottomRightX; - float sourceBottomRightY; - if (alignmentPattern != null) { - bottomRightX = alignmentPattern.getX(); - bottomRightY = alignmentPattern.getY(); - sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0f; - } else { - // Don't have an alignment pattern, just make up the bottom-right point - bottomRightX = (topRight.getX() - topLeft.getX()) + bottomLeft.getX(); - bottomRightY = (topRight.getY() - topLeft.getY()) + bottomLeft.getY(); - sourceBottomRightX = sourceBottomRightY = dimMinusThree; - } - - GridSampler sampler = GridSampler.Instance; - return sampler.sampleGrid( - image, - dimension, - 3.5f, - 3.5f, - dimMinusThree, - 3.5f, - sourceBottomRightX, - sourceBottomRightY, - 3.5f, - dimMinusThree, - topLeft.getX(), - topLeft.getY(), - topRight.getX(), - topRight.getY(), - bottomRightX, - bottomRightY, - bottomLeft.getX(), - bottomLeft.getY()); - } - - /** - *

Computes the dimension (number of modules on a size) of the QR Code based on the position - * of the finder patterns and estimated module size.

- */ - private static int computeDimension(ResultPoint topLeft, - ResultPoint topRight, - ResultPoint bottomLeft, - float moduleSize) { - int tltrCentersDimension = round(GenericResultPoint.distance(topLeft, topRight) / moduleSize); - int tlblCentersDimension = round(GenericResultPoint.distance(topLeft, bottomLeft) / moduleSize); - int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; - switch (dimension & 0x03) { // mod 4 - case 0: - dimension++; - break; - // 1? do nothing - case 2: - dimension--; - break; - case 3: - throw new ReaderException(); - } - return dimension; - } - - /** - *

Computes an average estimated module size based on estimated derived from the positions - * of the three finder patterns.

- */ - private float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) { - // Take the average - return (calculateModuleSizeOneWay(topLeft, topRight) + - calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f; - } - - /** - *

Estimates module size based on two finder patterns -- it uses - * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the - * width of each, measuring along the axis between their centers.

- */ - private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) { - float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(), - (int) pattern.getY(), - (int) otherPattern.getX(), - (int) otherPattern.getY()); - float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(), - (int) otherPattern.getY(), - (int) pattern.getX(), - (int) pattern.getY()); - if (Single.IsNaN(moduleSizeEst1)) { - return moduleSizeEst2; - } - if (Single.IsNaN(moduleSizeEst2)) - { - return moduleSizeEst1; - } - // Average them, and divide by 7 since we've counted the width of 3 black modules, - // and 1 white and 1 black module on either side. Ergo, divide sum by 14. - return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; - } - - /** - * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of - * a finder pattern by looking for a black-white-black run from the center in the direction - * of another point (another finder pattern center), and in the opposite direction too.

- */ - private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) { - - float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); - - // Now count other way -- don't run off image though of course - int otherToX = fromX - (toX - fromX); - if (otherToX < 0) { - // "to" should the be the first value not included, so, the first value off - // the edge is -1 - otherToX = -1; - } else if (otherToX >= image.getWidth()) { - otherToX = image.getWidth(); - } - int otherToY = fromY - (toY - fromY); - if (otherToY < 0) { - otherToY = -1; - } else if (otherToY >= image.getHeight()) { - otherToY = image.getHeight(); - } - result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); - return result - 1.0f; // -1 because we counted the middle pixel twice - } - - /** - *

This method traces a line from a point in the image, in the direction towards another point. - * It begins in a black region, and keeps going until it finds white, then black, then white again. - * It reports the distance from the start to this point.

- * - *

This is used when figuring out how wide a finder pattern is, when the finder pattern - * may be skewed or rotated.

- */ - private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) { - // Mild variant of Bresenham's algorithm; - // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm - bool steep = Math.Abs(toY - fromY) > Math.Abs(toX - fromX); - if (steep) { - int temp = fromX; - fromX = fromY; - fromY = temp; - temp = toX; - toX = toY; - toY = temp; - } - - int dx = Math.Abs(toX - fromX); - int dy = Math.Abs(toY - fromY); - int error = -dx >> 1; - int ystep = fromY < toY ? 1 : -1; - int xstep = fromX < toX ? 1 : -1; - int state = 0; // In black pixels, looking for white, first or second time - int diffX =0; - int diffY =0; - - for (int x = fromX, y = fromY; x != toX; x += xstep) { - - int realX = steep ? y : x; - int realY = steep ? x : y; - if (state == 1) { // In white pixels, looking for black - if (image.isBlack(realX, realY)) { - state++; - } - } else { - if (!image.isBlack(realX, realY)) { - state++; - } - } - - if (state == 3) { // Found black, white, black, and stumbled back onto white; done - diffX = x - fromX; - diffY = y - fromY; - return (float) Math.Sqrt((double) (diffX * diffX + diffY * diffY)); - } - error += dy; - if (error > 0) { - y += ystep; - error -= dx; - } - } - - diffX = toX - fromX; - diffY = toY - fromY; - return (float) Math.Sqrt((double) (diffX * diffX + diffY * diffY)); - } - - /** - *

Attempts to locate an alignment pattern in a limited region of the image, which is - * guessed to contain it. This method uses {@link AlignmentPattern}.

- * - * @param overallEstModuleSize estimated module size so far - * @param estAlignmentX x coordinate of center of area probably containing alignment pattern - * @param estAlignmentY y coordinate of above - * @param allowanceFactor number of pixels in all directons to search from the center - * @return {@link AlignmentPattern} if found, or null otherwise - * @throws ReaderException if an unexpected error occurs during detection - */ - private AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, - int estAlignmentX, - int estAlignmentY, - float allowanceFactor){ - // Look for an alignment pattern (3 modules in size) around where it - // should be - int allowance = (int) (allowanceFactor * overallEstModuleSize); - int alignmentAreaLeftX = Math.Max(0, estAlignmentX - allowance); - int alignmentAreaRightX = Math.Min(image.getWidth() - 1, estAlignmentX + allowance); - if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) { - throw new ReaderException(); - } - - int alignmentAreaTopY = Math.Max(0, estAlignmentY - allowance); - int alignmentAreaBottomY = Math.Min(image.getHeight() - 1, estAlignmentY + allowance); - - AlignmentPatternFinder alignmentFinder = - new AlignmentPatternFinder( - image, - alignmentAreaLeftX, - alignmentAreaTopY, - alignmentAreaRightX - alignmentAreaLeftX, - alignmentAreaBottomY - alignmentAreaTopY, - overallEstModuleSize); - return alignmentFinder.find(); - } - - /** - * Ends up being a bit faster than Math.round(). This merely rounds its argument to the nearest int, - * where x.5 rounds up. - */ - private static int round(float d) { - return (int) (d + 0.5f); - } - - } - - -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/detector/FinderPattern.cs b/qrcode-scanner-live/qrcode/detector/FinderPattern.cs deleted file mode 100644 index 601bcfb..0000000 --- a/qrcode-scanner-live/qrcode/detector/FinderPattern.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.detector -{ - public sealed class FinderPattern : ResultPoint - { - private float posX; - private float posY; - private float estimatedModuleSize; - private int count; - - public FinderPattern(float posX, float posY, float estimatedModuleSize) { - this.posX = posX; - this.posY = posY; - this.estimatedModuleSize = estimatedModuleSize; - this.count = 1; - } - - public float getX() { - return posX; - } - - public float getY() { - return posY; - } - - public float getEstimatedModuleSize() - { - return estimatedModuleSize; - } - - public int getCount() - { - return count; - } - - public void incrementCount() - { - this.count++; - } - - /** - *

Determines if this finder pattern "about equals" a finder pattern at the stated - * position and size -- meaning, it is at nearly the same center with nearly the same size.

- */ - public bool aboutEquals(float moduleSize, float i, float j) { - return Math.Abs(i - posY) <= moduleSize && - Math.Abs(j - posX) <= moduleSize && - (Math.Abs(moduleSize - estimatedModuleSize) <= 1.0f || - Math.Abs(moduleSize - estimatedModuleSize) / estimatedModuleSize <= 0.1f); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/detector/FinderPatternFinder.cs b/qrcode-scanner-live/qrcode/detector/FinderPatternFinder.cs deleted file mode 100644 index 6023ef0..0000000 --- a/qrcode-scanner-live/qrcode/detector/FinderPatternFinder.cs +++ /dev/null @@ -1,527 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.qrcode.detector -{ - using System; - using com.google.zxing; - using com.google.zxing.common; - - public sealed class FinderPatternFinder - { - private static int CENTER_QUORUM = 2; - private static int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center - private static int MAX_MODULES = 57; // support up to version 10 for mobile clients - private static int INTEGER_MATH_SHIFT = 8; - - private MonochromeBitmapSource image; - private System.Collections.ArrayList possibleCenters; - private bool hasSkipped; - private int[] crossCheckStateCount; - - /** - *

Creates a finder that will search the image for three finder patterns.

- * - * @param image image to search - */ - public FinderPatternFinder(MonochromeBitmapSource image) { - this.image = image; - this.possibleCenters = new System.Collections.ArrayList(); - this.crossCheckStateCount = new int[5]; - } - - public FinderPatternInfo find(System.Collections.Hashtable hints) { - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - int maxI = image.getHeight(); - int maxJ = image.getWidth(); - // We are looking for black/white/black/white/black modules in - // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far - - // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the - // image, and then account for the center being 3 modules in size. This gives the smallest - // number of pixels the center could be, so skip this often. When trying harder, look for all - // QR versions regardless of how dense they are. - int iSkip = (int) (maxI / (MAX_MODULES * 4.0f) * 3); - if (iSkip < MIN_SKIP || tryHarder) { - iSkip = MIN_SKIP; - } - - bool done = false; - int[] stateCount = new int[5]; - BitArray blackRow = new BitArray(maxJ); - for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { - // Get a row of black/white values - blackRow = image.getBlackRow(i, blackRow, 0, maxJ); - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - int currentState = 0; - for (int j = 0; j < maxJ; j++) { - if (blackRow.get(j)) { - // Black pixel - if ((currentState & 1) == 1) { // Counting white pixels - currentState++; - } - stateCount[currentState]++; - } else { // White pixel - if ((currentState & 1) == 0) { // Counting black pixels - if (currentState == 4) { // A winner? - if (foundPatternCross(stateCount)) { // Yes - bool confirmed = handlePossibleCenter(stateCount, i, j); - if (confirmed) { - // Start examining every other line. Checking each line turned out to be too - // expensive and didn't improve performance. - iSkip = 2; - if (hasSkipped) { - done = haveMulitplyConfirmedCenters(); - } else { - int rowSkip = findRowSkip(); - if (rowSkip > stateCount[2]) { - // Skip rows between row of lower confirmed center - // and top of presumed third confirmed center - // but back up a bit to get a full chance of detecting - // it, entire width of center of finder pattern - - // Skip by rowSkip, but back off by stateCount[2] (size of last center - // of pattern we saw) to be conservative, and also back off by iSkip which - // is about to be re-added - i += rowSkip - stateCount[2] - iSkip; - j = maxJ - 1; - } - } - } else { - // Advance to next black pixel - do { - j++; - } while (j < maxJ && !blackRow.get(j)); - j--; // back up to that last white pixel - } - // Clear state to start looking again - currentState = 0; - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - } else { // No, shift counts back by two - stateCount[0] = stateCount[2]; - stateCount[1] = stateCount[3]; - stateCount[2] = stateCount[4]; - stateCount[3] = 1; - stateCount[4] = 0; - currentState = 3; - } - } else { - stateCount[++currentState]++; - } - } else { // Counting white pixels - stateCount[currentState]++; - } - } - } - if (foundPatternCross(stateCount)) { - bool confirmed = handlePossibleCenter(stateCount, i, maxJ); - if (confirmed) { - iSkip = stateCount[0]; - if (hasSkipped) { - // Found a third one - done = haveMulitplyConfirmedCenters(); - } - } - } - } - - FinderPattern[] patternInfo = selectBestPatterns(); - GenericResultPoint.orderBestPatterns(patternInfo); - - return new FinderPatternInfo(patternInfo); - } - - /** - * Given a count of black/white/black/white/black pixels just seen and an end position, - * figures the location of the center of this run. - */ - private static float centerFromEnd(int[] stateCount, int end) { - return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; - } - - /** - * @param stateCount count of black/white/black/white/black pixels just read - * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios - * used by finder patterns to be considered a match - */ - private static bool foundPatternCross(int[] stateCount) { - int totalModuleSize = 0; - for (int i = 0; i < 5; i++) { - int count = stateCount[i]; - if (count == 0) { - return false; - } - totalModuleSize += count; - } - if (totalModuleSize < 7) { - return false; - } - int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; - int maxVariance = moduleSize / 2; - // Allow less than 50% variance from 1-1-3-1-1 proportions - return Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && - Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && - Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && - Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && - Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; - } - - private int[] getCrossCheckStateCount() { - crossCheckStateCount[0] = 0; - crossCheckStateCount[1] = 0; - crossCheckStateCount[2] = 0; - crossCheckStateCount[3] = 0; - crossCheckStateCount[4] = 0; - return crossCheckStateCount; - } - - /** - *

After a horizontal scan finds a potential finder pattern, this method - * "cross-checks" by scanning down vertically through the center of the possible - * finder pattern to see if the same proportion is detected.

- * - * @param startI row where a finder pattern was detected - * @param centerJ center of the section that appears to cross a finder pattern - * @param maxCount maximum reasonable number of modules that should be - * observed in any reading state, based on the results of the horizontal scan - * @return vertical center of finder pattern, or {@link Float#NaN} if not found - */ - private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { - MonochromeBitmapSource image = this.image; - - int maxI = image.getHeight(); - int[] stateCount = getCrossCheckStateCount(); - - // Start counting up from center - int i = startI; - while (i >= 0 && image.isBlack(centerJ, i)) { - stateCount[2]++; - i--; - } - if (i < 0) { - return float.NaN; - } - while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[1] <= maxCount) { - stateCount[1]++; - i--; - } - // If already too many modules in this state or ran off the edge: - if (i < 0 || stateCount[1] > maxCount) { - return float.NaN; - } - while (i >= 0 && image.isBlack(centerJ, i) && stateCount[0] <= maxCount) { - stateCount[0]++; - i--; - } - if (stateCount[0] > maxCount) { - return float.NaN; - } - - // Now also count down from center - i = startI + 1; - while (i < maxI && image.isBlack(centerJ, i)) { - stateCount[2]++; - i++; - } - if (i == maxI) { - return float.NaN; - } - while (i < maxI && !image.isBlack(centerJ, i) && stateCount[3] < maxCount) { - stateCount[3]++; - i++; - } - if (i == maxI || stateCount[3] >= maxCount) { - return float.NaN; - } - while (i < maxI && image.isBlack(centerJ, i) && stateCount[4] < maxCount) { - stateCount[4]++; - i++; - } - if (stateCount[4] >= maxCount) { - return float.NaN; - } - - // If we found a finder-pattern-like section, but its size is more than 20% different than - // the original, assume it's a false positive - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { - return float.NaN; - } - - return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : float.NaN; - } - - /** - *

Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical, - * except it reads horizontally instead of vertically. This is used to cross-cross - * check a vertical cross check and locate the real center of the alignment pattern.

- */ - private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) { - MonochromeBitmapSource image = this.image; - - int maxJ = image.getWidth(); - int[] stateCount = getCrossCheckStateCount(); - - int j = startJ; - while (j >= 0 && image.isBlack(j, centerI)) { - stateCount[2]++; - j--; - } - if (j < 0) { - return float.NaN; - } - while (j >= 0 && !image.isBlack(j, centerI) && stateCount[1] <= maxCount) { - stateCount[1]++; - j--; - } - if (j < 0 || stateCount[1] > maxCount) { - return float.NaN; - } - while (j >= 0 && image.isBlack(j, centerI) && stateCount[0] <= maxCount) { - stateCount[0]++; - j--; - } - if (stateCount[0] > maxCount) { - return float.NaN; - } - - j = startJ + 1; - while (j < maxJ && image.isBlack(j, centerI)) { - stateCount[2]++; - j++; - } - if (j == maxJ) { - return float.NaN; - } - while (j < maxJ && !image.isBlack(j, centerI) && stateCount[3] < maxCount) { - stateCount[3]++; - j++; - } - if (j == maxJ || stateCount[3] >= maxCount) { - return float.NaN; - } - while (j < maxJ && image.isBlack(j, centerI) && stateCount[4] < maxCount) { - stateCount[4]++; - j++; - } - if (stateCount[4] >= maxCount) { - return float.NaN; - } - - // If we found a finder-pattern-like section, but its size is significantly different than - // the original, assume it's a false positive - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { - return float.NaN; - } - - return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : float.NaN; - } - - /** - *

This is called when a horizontal scan finds a possible alignment pattern. It will - * cross check with a vertical scan, and if successful, will, ah, cross-cross-check - * with another horizontal scan. This is needed primarily to locate the real horizontal - * center of the pattern in cases of extreme skew.

- * - *

If that succeeds the finder pattern location is added to a list that tracks - * the number of times each location has been nearly-matched as a finder pattern. - * Each additional find is more evidence that the location is in fact a finder - * pattern center - * - * @param stateCount reading state module counts from horizontal scan - * @param i row where finder pattern may be found - * @param j end of possible finder pattern in row - * @return true if a finder pattern candidate was found this time - */ - private bool handlePossibleCenter(int[] stateCount, - int i, - int j) { - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - float centerJ = centerFromEnd(stateCount, j); - float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal); - if (!Single.IsNaN(centerI)) { - // Re-cross check - centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal); - if (!Single.IsNaN(centerJ)) - { - float estimatedModuleSize = (float) stateCountTotal / 7.0f; - bool found = false; - int max = possibleCenters.Count; - for (int index = 0; index < max; index++) { - FinderPattern center = (FinderPattern) possibleCenters[index]; - // Look for about the same center and module size: - if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { - center.incrementCount(); - found = true; - break; - } - } - if (!found) { - possibleCenters.Add(new FinderPattern(centerJ, centerI, estimatedModuleSize)); - } - return true; - } - } - return false; - } - - /** - * @return number of rows we could safely skip during scanning, based on the first - * two finder patterns that have been located. In some cases their position will - * allow us to infer that the third pattern must lie below a certain point farther - * down in the image. - */ - private int findRowSkip() { - int max = possibleCenters.Count; - if (max <= 1) { - return 0; - } - FinderPattern firstConfirmedCenter = null; - for (int i = 0; i < max; i++) { - FinderPattern center = (FinderPattern) possibleCenters[i]; - if (center.getCount() >= CENTER_QUORUM) { - if (firstConfirmedCenter == null) { - firstConfirmedCenter = center; - } else { - // We have two confirmed centers - // How far down can we skip before resuming looking for the next - // pattern? In the worst case, only the difference between the - // difference in the x / y coordinates of the two centers. - // This is the case where you find top left last. - hasSkipped = true; - return (int) (Math.Abs(firstConfirmedCenter.getX() - center.getX()) - - Math.Abs(firstConfirmedCenter.getY() - center.getY())) / 2; - } - } - } - return 0; - } - - /** - * @return true iff we have found at least 3 finder patterns that have been detected - * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the - * candidates is "pretty similar" - */ - private bool haveMulitplyConfirmedCenters() { - int confirmedCount = 0; - float totalModuleSize = 0.0f; - int max = possibleCenters.Count; - for (int i = 0; i < max; i++) { - FinderPattern pattern = (FinderPattern) possibleCenters[i]; - if (pattern.getCount() >= CENTER_QUORUM) { - confirmedCount++; - totalModuleSize += pattern.getEstimatedModuleSize(); - } - } - if (confirmedCount < 3) { - return false; - } - // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" - // and that we need to keep looking. We detect this by asking if the estimated module sizes - // vary too much. We arbitrarily say that when the total deviation from average exceeds - // 15% of the total module size estimates, it's too much. - float average = totalModuleSize / max; - float totalDeviation = 0.0f; - for (int i = 0; i < max; i++) { - FinderPattern pattern = (FinderPattern) possibleCenters[i]; - totalDeviation += Math.Abs(pattern.getEstimatedModuleSize() - average); - } - return totalDeviation <= 0.15f * totalModuleSize; - } - - /** - * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are - * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module - * size differs from the average among those patterns the least - * @throws ReaderException if 3 such finder patterns do not exist - */ - private FinderPattern[] selectBestPatterns(){ - Collections.insertionSort(possibleCenters, new CenterComparator()); - int size = 0; - int max = possibleCenters.Count; - while (size < max) { - if (((FinderPattern) possibleCenters[size]).getCount() < CENTER_QUORUM) { - break; - } - size++; - } - - if (size < 3) { - // Couldn't find enough finder patterns - throw new ReaderException(); - } - - if (size > 3) { - // Throw away all but those first size candidate points we found. - SupportClass.SetCapacity(possibleCenters, size); - // We need to pick the best three. Find the most - // popular ones whose module size is nearest the average - float averageModuleSize = 0.0f; - for (int i = 0; i < size; i++) { - averageModuleSize += ((FinderPattern) possibleCenters[i]).getEstimatedModuleSize(); - } - averageModuleSize /= (float) size; - // We don't have java.util.Collections in J2ME - Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize)); - } - - return new FinderPattern[]{ - (FinderPattern) possibleCenters[0], - (FinderPattern) possibleCenters[1], - (FinderPattern) possibleCenters[2] - }; - } - - /** - *

Orders by {@link FinderPattern#getCount()}, descending.

- */ - private class CenterComparator : Comparator { - public int compare(object center1, object center2) - { - return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount(); - } - } - - /** - *

Orders by variance from average module size, ascending.

- */ - private class ClosestToAverageComparator : Comparator { - private float averageModuleSize; - - public ClosestToAverageComparator(float averageModuleSize) { - this.averageModuleSize = averageModuleSize; - } - - public int compare(object center1, object center2) - { - return Math.Abs(((FinderPattern) center1).getEstimatedModuleSize() - averageModuleSize) < - Math.Abs(((FinderPattern) center2).getEstimatedModuleSize() - averageModuleSize) ? - -1 : - 1; - } - } - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/detector/FinderPatternInfo.cs b/qrcode-scanner-live/qrcode/detector/FinderPatternInfo.cs deleted file mode 100644 index 5faae93..0000000 --- a/qrcode-scanner-live/qrcode/detector/FinderPatternInfo.cs +++ /dev/null @@ -1,51 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.qrcode.detector -{ - using com.google.zxing; - using com.google.zxing.common; - - public sealed class FinderPatternInfo - { - private FinderPattern bottomLeft; - private FinderPattern topLeft; - private FinderPattern topRight; - - public FinderPatternInfo(FinderPattern[] patternCenters) { - this.bottomLeft = patternCenters[0]; - this.topLeft = patternCenters[1]; - this.topRight = patternCenters[2]; - } - - public FinderPattern getBottomLeft() - { - return bottomLeft; - } - - public FinderPattern getTopLeft() - { - return topLeft; - } - - public FinderPattern getTopRight() - { - return topRight; - } - - } - -} - diff --git a/qrcode-scanner-live/qrcode/encoder/BitVector.cs b/qrcode-scanner-live/qrcode/encoder/BitVector.cs deleted file mode 100644 index 32b5ea6..0000000 --- a/qrcode-scanner-live/qrcode/encoder/BitVector.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.encoder -{ - public sealed class BitVector { - - private int sizeInBits; - private sbyte[] array; - - // For efficiency, start out with some room to work. - private static int DEFAULT_SIZE_IN_BYTES = 32; - - public BitVector() { - sizeInBits = 0; - array = new sbyte[DEFAULT_SIZE_IN_BYTES]; - } - - // Return the bit value at "index". - public int at(int index) { - if (index < 0 || index >= sizeInBits) { - throw new ArgumentException("Bad index: " + index); - } - int value = array[index >> 3] & 0xff; - return (value >> (7 - (index & 0x7))) & 1; - } - - // Return the number of bits in the bit vector. - public int size() { - return sizeInBits; - } - - // Return the number of bytes in the bit vector. - public int sizeInBytes() { - return (sizeInBits + 7) >> 3; - } - - // Append one bit to the bit vector. - public void appendBit(int bit) { - if (!(bit == 0 || bit == 1)) { - throw new ArgumentException("Bad bit"); - } - int numBitsInLastByte = sizeInBits & 0x7; - // We'll expand array if we don't have bits in the last byte. - if (numBitsInLastByte == 0) { - appendByte(0); - sizeInBits -= 8; - } - // Modify the last byte. - array[sizeInBits >> 3] |= (sbyte)(bit << (7 - numBitsInLastByte)); - ++sizeInBits; - } - - // Append "numBits" bits in "value" to the bit vector. - // REQUIRES: 0<= numBits <= 32. - // - // Examples: - // - appendBits(0x00, 1) adds 0. - // - appendBits(0x00, 4) adds 0000. - // - appendBits(0xff, 8) adds 11111111. - public void appendBits(int value, int numBits) { - if (numBits < 0 || numBits > 32) { - throw new ArgumentException("Num bits must be between 0 and 32"); - } - int numBitsLeft = numBits; - while (numBitsLeft > 0) { - // Optimization for byte-oriented appending. - if ((sizeInBits & 0x7) == 0 && numBitsLeft >= 8) { - int newByte = (value >> (numBitsLeft - 8)) & 0xff; - appendByte(newByte); - numBitsLeft -= 8; - } else { - int bit = (value >> (numBitsLeft - 1)) & 1; - appendBit(bit); - --numBitsLeft; - } - } - } - - // Append "bits". - public void appendBitVector(BitVector bits) { - int size = bits.size(); - for (int i = 0; i < size; ++i) { - appendBit(bits.at(i)); - } - } - - // Modify the bit vector by XOR'ing with "other" - public void xor(BitVector other) { - if (sizeInBits != other.size()) { - throw new ArgumentException("BitVector sizes don't match"); - } - int sizeInBytes = (sizeInBits + 7) >> 3; - for (int i = 0; i < sizeInBytes; ++i) { - // The last byte could be incomplete (i.e. not have 8 bits in - // it) but there is no problem since 0 XOR 0 == 0. - array[i] ^= other.array[i]; - } - } - - // Return String like "01110111" for debugging. - public String toString() { - StringBuilder result = new StringBuilder(sizeInBits); - for (int i = 0; i < sizeInBits; ++i) { - if (at(i) == 0) { - result.Append('0'); - } else if (at(i) == 1) { - result.Append('1'); - } else { - throw new ArgumentException("Byte isn't 0 or 1"); - } - } - return result.ToString(); - } - - // Callers should not assume that array.length is the exact number of bytes needed to hold - // sizeInBits - it will typically be larger for efficiency. - public sbyte[] getArray() { - return array; - } - - // Add a new byte to the end, possibly reallocating and doubling the size of the array if we've - // run out of room. - private void appendByte(int value) { - if ((sizeInBits >> 3) == array.Length) { - sbyte[] newArray = new sbyte[(array.Length << 1)]; - System.Array.Copy (array, 0, newArray, 0, array.Length); - array = newArray; - } - array[sizeInBits >> 3] = (sbyte) value; - sizeInBits += 8; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/encoder/Encoder.cs b/qrcode-scanner-live/qrcode/encoder/Encoder.cs deleted file mode 100644 index df0b303..0000000 --- a/qrcode-scanner-live/qrcode/encoder/Encoder.cs +++ /dev/null @@ -1,511 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using System.Collections; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.common.reedsolomon; -using com.google.zxing.qrcode.decoder; -using com.google.zxing.qrcode; - -namespace com.google.zxing.qrcode.encoder -{ - using Version=com.google.zxing.qrcode.decoder.Version; - public sealed class Encoder - { - // The original table is defined in the table 5 of JISX0510:2004 (p.19). - private static int[] ALPHANUMERIC_TABLE = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f - 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f - -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f - }; - - private Encoder() { - } - - // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details. - // Basically it applies four rules and summate all penalties. - private static int calculateMaskPenalty(ByteMatrix matrix) { - int penalty = 0; - penalty += MaskUtil.applyMaskPenaltyRule1(matrix); - penalty += MaskUtil.applyMaskPenaltyRule2(matrix); - penalty += MaskUtil.applyMaskPenaltyRule3(matrix); - penalty += MaskUtil.applyMaskPenaltyRule4(matrix); - return penalty; - } - - private class BlockPair { - - private ByteArray dataBytes; - private ByteArray errorCorrectionBytes; - - public BlockPair(ByteArray data, ByteArray errorCorrection) { - dataBytes = data; - errorCorrectionBytes = errorCorrection; - } - - public ByteArray getDataBytes() { - return dataBytes; - } - - public ByteArray getErrorCorrectionBytes() { - return errorCorrectionBytes; - } - - } - - // Encode "bytes" with the error correction level "getECLevel". The encoding mode will be chosen - // internally by chooseMode(). On success, store the result in "qrCode" and return true. - // We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for - // "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very - // strong error correction for this purpose. - // - // Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode() - // with which clients can specify the encoding mode. For now, we don't need the functionality. - public static void encode(String content, ErrorCorrectionLevel ecLevel, QRCode qrCode) - { - // Step 1: Choose the mode (encoding). - Mode mode = chooseMode(content); - - // Step 2: Append "bytes" into "dataBits" in appropriate encoding. - BitVector dataBits = new BitVector(); - appendBytes(content, mode, dataBits); - // Step 3: Initialize QR code that can contain "dataBits". - int numInputBytes = dataBits.sizeInBytes(); - initQRCode(numInputBytes, ecLevel, mode, qrCode); - - // Step 4: Build another bit vector that contains header and data. - BitVector headerAndDataBits = new BitVector(); - appendModeInfo(qrCode.getMode(), headerAndDataBits); - appendLengthInfo(content.Length, qrCode.getVersion(), qrCode.getMode(), headerAndDataBits); - headerAndDataBits.appendBitVector(dataBits); - - // Step 5: Terminate the bits properly. - terminateBits(qrCode.getNumDataBytes(), headerAndDataBits); - - // Step 6: Interleave data bits with error correction code. - BitVector finalBits = new BitVector(); - interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(), - qrCode.getNumRSBlocks(), finalBits); - - // Step 7: Choose the mask pattern and set to "qrCode". - ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth()); - qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(), - matrix)); - - // Step 8. Build the matrix and set it to "qrCode". - MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(), - qrCode.getMaskPattern(), matrix); - qrCode.setMatrix(matrix); - // Step 9. Make sure we have a valid QR Code. - if (!qrCode.isValid()) { - throw new WriterException("Invalid QR code: " + qrCode.toString()); - } - } - - // Return the code point of the table used in alphanumeric mode. Return -1 if there is no - // corresponding code in the table. - static int getAlphanumericCode(int code) { - if (code < ALPHANUMERIC_TABLE.Length) { - return ALPHANUMERIC_TABLE[code]; - } - return -1; - } - - // Choose the best mode by examining the content. - // - // Note that this function does not return MODE_KANJI, as we cannot distinguish Shift_JIS from - // other encodings such as ISO-8859-1, from data bytes alone. For example "\xE0\xE0" can be - // interpreted as one character in Shift_JIS, but also two characters in ISO-8859-1. - // - // JAVAPORT: This MODE_KANJI limitation sounds like a problem for us. - public static Mode chooseMode(String content) { - bool hasNumeric = false; - bool hasAlphanumeric = false; - for (int i = 0; i < content.Length; ++i) { - char c = content[i]; - if (c >= '0' && c <= '9') { - hasNumeric = true; - } else if (getAlphanumericCode(c) != -1) { - hasAlphanumeric = true; - } else { - return Mode.BYTE; - } - } - if (hasAlphanumeric) { - return Mode.ALPHANUMERIC; - } else if (hasNumeric) { - return Mode.NUMERIC; - } - return Mode.BYTE; - } - - private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version,ByteMatrix matrix){ - try{ - int minPenalty = int.MaxValue; // Lower penalty is better. - int bestMaskPattern = -1; - // We try all mask patterns to choose the best one. - for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) - { - MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); - int penalty = calculateMaskPenalty(matrix); - if (penalty < minPenalty) - { - minPenalty = penalty; - bestMaskPattern = maskPattern; - } - } - return bestMaskPattern; - }catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - // Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success, modify - // "qrCode". - private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode) - { - try - { - qrCode.setECLevel(ecLevel); - qrCode.setMode(mode); - - // In the following comments, we use numbers of Version 7-H. - for (int versionNum = 1; versionNum <= 40; versionNum++) { - Version version = Version.getVersionForNumber(versionNum); - // numBytes = 196 - int numBytes = version.getTotalCodewords(); - // getNumECBytes = 130 - Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); - int numEcBytes = ecBlocks.getTotalECCodewords(); - // getNumRSBlocks = 5 - int numRSBlocks = ecBlocks.getNumBlocks(); - // getNumDataBytes = 196 - 130 = 66 - int numDataBytes = numBytes - numEcBytes; - // We want to choose the smallest version which can contain data of "numInputBytes" + some - // extra bits for the header (mode info and length info). The header can be three bytes - // (precisely 4 + 16 bits) at most. Hence we do +3 here. - if (numDataBytes >= numInputBytes + 3) { - // Yay, we found the proper rs block info! - qrCode.setVersion(versionNum); - qrCode.setNumTotalBytes(numBytes); - qrCode.setNumDataBytes(numDataBytes); - qrCode.setNumRSBlocks(numRSBlocks); - // getNumECBytes = 196 - 66 = 130 - qrCode.setNumECBytes(numEcBytes); - // matrix width = 21 + 6 * 4 = 45 - qrCode.setMatrixWidth(version.getDimensionForVersion()); - return; - } - } - throw new WriterException("Cannot find proper rs block info (input data too big?)"); - } - catch(Exception e){ - throw new WriterException(e.Message); - } - } - - // Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24). - static void terminateBits(int numDataBytes, BitVector bits){ - int capacity = numDataBytes << 3; - if (bits.size() > capacity) { - throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); - } - // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. - for (int i = 0; i < 4 && bits.size() < capacity; ++i) { - bits.appendBit(0); - } - int numBitsInLastByte = bits.size() % 8; - // If the last byte isn't 8-bit aligned, we'll add padding bits. - if (numBitsInLastByte > 0) { - int numPaddingBits = 8 - numBitsInLastByte; - for (int i = 0; i < numPaddingBits; ++i) { - bits.appendBit(0); - } - } - // Should be 8-bit aligned here. - if (bits.size() % 8 != 0) { - throw new WriterException("Number of bits is not a multiple of 8"); - } - // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). - int numPaddingBytes = numDataBytes - bits.sizeInBytes(); - for (int i = 0; i < numPaddingBytes; ++i) { - if (i % 2 == 0) { - bits.appendBits(0xec, 8); - } else { - bits.appendBits(0x11, 8); - } - } - if (bits.size() != capacity) { - throw new WriterException("Bits size does not equal capacity"); - } - } - - // Get number of data bytes and number of error correction bytes for block id "blockID". Store - // the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of - // JISX0510:2004 (p.30) - static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, - int numRSBlocks, int blockID, int[] numDataBytesInBlock,int[] numECBytesInBlock) { - if (blockID >= numRSBlocks) { - throw new WriterException("Block ID too large"); - } - // numRsBlocksInGroup2 = 196 % 5 = 1 - int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; - // numRsBlocksInGroup1 = 5 - 1 = 4 - int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; - // numTotalBytesInGroup1 = 196 / 5 = 39 - int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; - // numTotalBytesInGroup2 = 39 + 1 = 40 - int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; - // numDataBytesInGroup1 = 66 / 5 = 13 - int numDataBytesInGroup1 = numDataBytes / numRSBlocks; - // numDataBytesInGroup2 = 13 + 1 = 14 - int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; - // numEcBytesInGroup1 = 39 - 13 = 26 - int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; - // numEcBytesInGroup2 = 40 - 14 = 26 - int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; - // Sanity checks. - // 26 = 26 - if (numEcBytesInGroup1 != numEcBytesInGroup2) { - throw new WriterException("EC bytes mismatch"); - } - // 5 = 4 + 1. - if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { - throw new WriterException("RS blocks mismatch"); - } - // 196 = (13 + 26) * 4 + (14 + 26) * 1 - if (numTotalBytes != - ((numDataBytesInGroup1 + numEcBytesInGroup1) * - numRsBlocksInGroup1) + - ((numDataBytesInGroup2 + numEcBytesInGroup2) * - numRsBlocksInGroup2)) { - throw new WriterException("Total bytes mismatch"); - } - - if (blockID < numRsBlocksInGroup1) { - numDataBytesInBlock[0] = numDataBytesInGroup1; - numECBytesInBlock[0] = numEcBytesInGroup1; - } else { - numDataBytesInBlock[0] = numDataBytesInGroup2; - numECBytesInBlock[0] = numEcBytesInGroup2; - } - } - - // Interleave "bits" with corresponding error correction bytes. On success, store the result in - // "result" and return true. The interleave rule is complicated. See 8.6 - // of JISX0510:2004 (p.37) for details. - static void interleaveWithECBytes(BitVector bits, int numTotalBytes, - int numDataBytes, int numRSBlocks, BitVector result) { - - // "bits" must have "getNumDataBytes" bytes of data. - if (bits.sizeInBytes() != numDataBytes) { - throw new WriterException("Number of bits and data bytes does not match"); - } - - // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll - // store the divided data bytes blocks and error correction bytes blocks into "blocks". - int dataBytesOffset = 0; - int maxNumDataBytes = 0; - int maxNumEcBytes = 0; - - // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. - ArrayList blocks = new ArrayList(numRSBlocks); - - for (int i = 0; i < numRSBlocks; ++i) { - int[] numDataBytesInBlock = new int[1]; - int[] numEcBytesInBlock = new int[1]; - getNumDataBytesAndNumECBytesForBlockID( - numTotalBytes, numDataBytes, numRSBlocks, i, - numDataBytesInBlock, numEcBytesInBlock); - - ByteArray dataBytes = new ByteArray(); - dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]); - ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); - blocks.Add(new BlockPair(dataBytes, ecBytes)); - - maxNumDataBytes = Math.Max(maxNumDataBytes, dataBytes.size()); - maxNumEcBytes = Math.Max(maxNumEcBytes, ecBytes.size()); - dataBytesOffset += numDataBytesInBlock[0]; - } - if (numDataBytes != dataBytesOffset) { - throw new WriterException("Data bytes does not match offset"); - } - - // First, place data blocks. - for (int i = 0; i < maxNumDataBytes; ++i) { - for (int j = 0; j < blocks.Count; ++j) { - ByteArray dataBytes = ((BlockPair) blocks[j]).getDataBytes(); - if (i < dataBytes.size()) { - result.appendBits(dataBytes.at(i), 8); - } - } - } - // Then, place error correction blocks. - for (int i = 0; i < maxNumEcBytes; ++i) { - for (int j = 0; j < blocks.Count; ++j) { - ByteArray ecBytes = ((BlockPair) blocks[j]).getErrorCorrectionBytes(); - if (i < ecBytes.size()) { - result.appendBits(ecBytes.at(i), 8); - } - } - } - if (numTotalBytes != result.sizeInBytes()) { // Should be same. - throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + - " differ."); - } - } - - static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) { - int numDataBytes = dataBytes.size(); - int[] toEncode = new int[numDataBytes + numEcBytesInBlock]; - for (int i = 0; i < numDataBytes; i++) { - toEncode[i] = dataBytes.at(i); - } - new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock); - - ByteArray ecBytes = new ByteArray(numEcBytesInBlock); - for (int i = 0; i < numEcBytesInBlock; i++) { - ecBytes.set(i, toEncode[numDataBytes + i]); - } - return ecBytes; - } - - // Append mode info. On success, store the result in "bits" and return true. On error, return - // false. - static void appendModeInfo(Mode mode, BitVector bits) { - bits.appendBits(mode.getBits(), 4); - } - - - // Append length info. On success, store the result in "bits" and return true. On error, return - // false. - static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits){ - int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version)); - if (numLetters > ((1 << numBits) - 1)) { - throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1)); - } - bits.appendBits(numLetters, numBits); - } - - // Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits" - // and return true. - static void appendBytes(String content, Mode mode, BitVector bits) { - if (mode.Equals(Mode.NUMERIC)) { - appendNumericBytes(content, bits); - } else if (mode.Equals(Mode.ALPHANUMERIC)) { - appendAlphanumericBytes(content, bits); - } else if (mode.Equals(Mode.BYTE)) { - append8BitBytes(content, bits); - } else if (mode.Equals(Mode.KANJI)) { - appendKanjiBytes(content, bits); - } else { - throw new WriterException("Invalid mode: " + mode); - } - } - - static void appendNumericBytes(String content, BitVector bits) { - int length = content.Length; - int i = 0; - while (i < length) { - int num1 = content[i] - '0'; - if (i + 2 < length) { - // Encode three numeric letters in ten bits. - int num2 = content[i + 1] - '0'; - int num3 = content[i + 2] - '0'; - bits.appendBits(num1 * 100 + num2 * 10 + num3, 10); - i += 3; - } else if (i + 1 < length) { - // Encode two numeric letters in seven bits. - int num2 = content[i + 1] - '0'; - bits.appendBits(num1 * 10 + num2, 7); - i += 2; - } else { - // Encode one numeric letter in four bits. - bits.appendBits(num1, 4); - i++; - } - } - } - - static void appendAlphanumericBytes(String content, BitVector bits) { - int length = content.Length; - int i = 0; - while (i < length) { - int code1 = getAlphanumericCode(content[i]); - if (code1 == -1) { - throw new WriterException(); - } - if (i + 1 < length) { - int code2 = getAlphanumericCode(content[i + 1]); - if (code2 == -1) { - throw new WriterException(); - } - // Encode two alphanumeric letters in 11 bits. - bits.appendBits(code1 * 45 + code2, 11); - i += 2; - } else { - // Encode one alphanumeric letter in six bits. - bits.appendBits(code1, 6); - i++; - } - } - } - - static void append8BitBytes(String content, BitVector bits) { - byte[] bytes; - try { - bytes = System.Text.ASCIIEncoding.ASCII.GetBytes("ISO-8859-1"); - } catch (Exception uee) { - throw new WriterException(uee.ToString()); - } - for (int i = 0; i < bytes.Length; ++i) { - bits.appendBits(bytes[i], 8); - } - } - - static void appendKanjiBytes(String content, BitVector bits) { - byte[] bytes; - try { - bytes=System.Text.ASCIIEncoding.ASCII.GetBytes("Shift_JIS"); - } catch (Exception uee) { - throw new WriterException(uee.ToString()); - } - int length = bytes.Length; - for (int i = 0; i < length; i += 2) { - int byte1 = bytes[i] & 0xFF; - int byte2 = bytes[i + 1] & 0xFF; - int code = (byte1 << 8) | byte2; - int subtracted = -1; - if (code >= 0x8140 && code <= 0x9ffc) { - subtracted = code - 0x8140; - } else if (code >= 0xe040 && code <= 0xebbf) { - subtracted = code - 0xc140; - } - if (subtracted == -1) { - throw new WriterException("Invalid byte sequence"); - } - int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); - bits.appendBits(encoded, 13); - } - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/encoder/MaskUtil.cs b/qrcode-scanner-live/qrcode/encoder/MaskUtil.cs deleted file mode 100644 index 08f3a04..0000000 --- a/qrcode-scanner-live/qrcode/encoder/MaskUtil.cs +++ /dev/null @@ -1,233 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.qrcode.decoder; -using com.google.zxing.qrcode; - -namespace com.google.zxing.qrcode.encoder -{ - - public sealed class MaskUtil - { - private MaskUtil() - { - // do nothing - } - - // Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and - // give penalty to them. Example: 00000 or 11111. - public static int applyMaskPenaltyRule1(ByteMatrix matrix) - { - return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false); - } - - // Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give - // penalty to them. - public static int applyMaskPenaltyRule2(ByteMatrix matrix) - { - int penalty = 0; - sbyte[][] array = matrix.getArray(); - int width = matrix.width(); - int height = matrix.height(); - for (int y = 0; y < height - 1; ++y) - { - for (int x = 0; x < width - 1; ++x) - { - int value = array[y][x]; - if (value == array[y][x + 1] && value == array[y + 1][x] && value == array[y + 1][x + 1]) - { - penalty += 3; - } - } - } - return penalty; - } - - // Apply mask penalty rule 3 and return the penalty. Find consecutive cells of 00001011101 or - // 10111010000, and give penalty to them. If we find patterns like 000010111010000, we give - // penalties twice (i.e. 40 * 2). - public static int applyMaskPenaltyRule3(ByteMatrix matrix) - { - int penalty = 0; - sbyte[][] array = matrix.getArray(); - int width = matrix.width(); - int height = matrix.height(); - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - // Tried to simplify following conditions but failed. - if (x + 6 < width && - array[y][x] == 1 && - array[y][x + 1] == 0 && - array[y][x + 2] == 1 && - array[y][x + 3] == 1 && - array[y][x + 4] == 1 && - array[y][x + 5] == 0 && - array[y][x + 6] == 1 && - ((x + 10 < width && - array[y][x + 7] == 0 && - array[y][x + 8] == 0 && - array[y][x + 9] == 0 && - array[y][x + 10] == 0) || - (x - 4 >= 0 && - array[y][x - 1] == 0 && - array[y][x - 2] == 0 && - array[y][x - 3] == 0 && - array[y][x - 4] == 0))) - { - penalty += 40; - } - if (y + 6 < height && - array[y][x] == 1 && - array[y + 1][x] == 0 && - array[y + 2][x] == 1 && - array[y + 3][x] == 1 && - array[y + 4][x] == 1 && - array[y + 5][x] == 0 && - array[y + 6][x] == 1 && - ((y + 10 < height && - array[y + 7][x] == 0 && - array[y + 8][x] == 0 && - array[y + 9][x] == 0 && - array[y + 10][x] == 0) || - (y - 4 >= 0 && - array[y - 1][x] == 0 && - array[y - 2][x] == 0 && - array[y - 3][x] == 0 && - array[y - 4][x] == 0))) - { - penalty += 40; - } - } - } - return penalty; - } - - // Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give - // penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance. Examples: - // - 0% => 100 - // - 40% => 20 - // - 45% => 10 - // - 50% => 0 - // - 55% => 10 - // - 55% => 20 - // - 100% => 100 - public static int applyMaskPenaltyRule4(ByteMatrix matrix) - { - int numDarkCells = 0; - sbyte[][] array = matrix.getArray(); - int width = matrix.width(); - int height = matrix.height(); - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - if (array[y][x] == 1) - { - numDarkCells += 1; - } - } - } - int numTotalCells = matrix.height() * matrix.width(); - double darkRatio = (double)numDarkCells / numTotalCells; - return Math.Abs((int)(darkRatio * 100 - 50)) / 5 * 10; - } - - // Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask - // pattern conditions. - public static int getDataMaskBit(int maskPattern, int x, int y) - { - if (!QRCode.isValidMaskPattern(maskPattern)) - { - throw new ArgumentException("Invalid mask pattern"); - } - switch (maskPattern) - { - case 0: - return ((y + x) % 2 == 0) ? 1 : 0; - case 1: - return (y % 2 == 0) ? 1 : 0; - case 2: - return (x % 3 == 0) ? 1 : 0; - case 3: - return ((y + x) % 3 == 0) ? 1 : 0; - case 4: - return (((y / 2) + (x / 3)) % 2 == 0) ? 1 : 0; - case 5: - return (((y * x) % 2) + ((y * x) % 3) == 0) ? 1 : 0; - case 6: - return ((((y * x) % 2) + ((y * x) % 3)) % 2 == 0) ? 1 : 0; - case 7: - return ((((y * x) % 3) + ((y + x) % 2)) % 2 == 0) ? 1 : 0; - } - throw new ArgumentException("invalid mask pattern: " + maskPattern); - } - - // Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both - // vertical and horizontal orders respectively. - private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, bool isHorizontal) - { - int penalty = 0; - int numSameBitCells = 0; - int prevBit = -1; - // Horizontal mode: - // for (int i = 0; i < matrix.height(); ++i) { - // for (int j = 0; j < matrix.width(); ++j) { - // int bit = matrix.get(i, j); - // Vertical mode: - // for (int i = 0; i < matrix.width(); ++i) { - // for (int j = 0; j < matrix.height(); ++j) { - // int bit = matrix.get(j, i); - int iLimit = isHorizontal ? matrix.height() : matrix.width(); - int jLimit = isHorizontal ? matrix.width() : matrix.height(); - sbyte[][] array = matrix.getArray(); - for (int i = 0; i < iLimit; ++i) - { - for (int j = 0; j < jLimit; ++j) - { - int bit = isHorizontal ? array[i][j] : array[j][i]; - if (bit == prevBit) - { - numSameBitCells += 1; - // Found five repetitive cells with the same color (bit). - // We'll give penalty of 3. - if (numSameBitCells == 5) - { - penalty += 3; - } - else if (numSameBitCells > 5) - { - // After five repetitive cells, we'll add the penalty one - // by one. - penalty += 1; - } - } - else - { - numSameBitCells = 1; // Include the cell itself. - prevBit = bit; - } - } - numSameBitCells = 0; // Clear at each row/column. - } - return penalty; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/encoder/MatrixUtil.cs b/qrcode-scanner-live/qrcode/encoder/MatrixUtil.cs deleted file mode 100644 index eb763d1..0000000 --- a/qrcode-scanner-live/qrcode/encoder/MatrixUtil.cs +++ /dev/null @@ -1,531 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.qrcode.decoder; -using com.google.zxing.qrcode; - -namespace com.google.zxing.qrcode.encoder -{ - public sealed class MatrixUtil - { - private MatrixUtil() { - // do nothing - } - - private static int[][] POSITION_DETECTION_PATTERN = new int[][]{ - new int[]{1, 1, 1, 1, 1, 1, 1}, - new int[]{1, 0, 0, 0, 0, 0, 1}, - new int[]{1, 0, 1, 1, 1, 0, 1}, - new int[]{1, 0, 1, 1, 1, 0, 1}, - new int[]{1, 0, 1, 1, 1, 0, 1}, - new int[]{1, 0, 0, 0, 0, 0, 1}, - new int[]{1, 1, 1, 1, 1, 1, 1}, - }; - - private static int[][] HORIZONTAL_SEPARATION_PATTERN = new int[][]{ - new int[]{0, 0, 0, 0, 0, 0, 0, 0}, - }; - - private static int[][] VERTICAL_SEPARATION_PATTERN = new int[][]{ - new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, - }; - - private static int[][] POSITION_ADJUSTMENT_PATTERN = new int[][]{ - new int[]{1, 1, 1, 1, 1}, - new int[]{1, 0, 0, 0, 1}, - new int[]{1, 0, 1, 0, 1}, - new int[]{1, 0, 0, 0, 1}, - new int[]{1, 1, 1, 1, 1}, - }; - - // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu. - private static int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = new int[][]{ - new int[]{-1, -1, -1, -1, -1, -1, -1}, // Version 1 - new int[]{ 6, 18, -1, -1, -1, -1, -1}, // Version 2 - new int[]{ 6, 22, -1, -1, -1, -1, -1}, // Version 3 - new int[]{ 6, 26, -1, -1, -1, -1, -1}, // Version 4 - new int[]{ 6, 30, -1, -1, -1, -1, -1}, // Version 5 - new int[]{ 6, 34, -1, -1, -1, -1, -1}, // Version 6 - new int[]{ 6, 22, 38, -1, -1, -1, -1}, // Version 7 - new int[]{ 6, 24, 42, -1, -1, -1, -1}, // Version 8 - new int[]{ 6, 26, 46, -1, -1, -1, -1}, // Version 9 - new int[]{ 6, 28, 50, -1, -1, -1, -1}, // Version 10 - new int[]{ 6, 30, 54, -1, -1, -1, -1}, // Version 11 - new int[]{ 6, 32, 58, -1, -1, -1, -1}, // Version 12 - new int[]{ 6, 34, 62, -1, -1, -1, -1}, // Version 13 - new int[]{ 6, 26, 46, 66, -1, -1, -1}, // Version 14 - new int[]{ 6, 26, 48, 70, -1, -1, -1}, // Version 15 - new int[]{ 6, 26, 50, 74, -1, -1, -1}, // Version 16 - new int[]{ 6, 30, 54, 78, -1, -1, -1}, // Version 17 - new int[]{ 6, 30, 56, 82, -1, -1, -1}, // Version 18 - new int[]{ 6, 30, 58, 86, -1, -1, -1}, // Version 19 - new int[]{ 6, 34, 62, 90, -1, -1, -1}, // Version 20 - new int[]{ 6, 28, 50, 72, 94, -1, -1}, // Version 21 - new int[]{ 6, 26, 50, 74, 98, -1, -1}, // Version 22 - new int[]{ 6, 30, 54, 78, 102, -1, -1}, // Version 23 - new int[]{ 6, 28, 54, 80, 106, -1, -1}, // Version 24 - new int[]{ 6, 32, 58, 84, 110, -1, -1}, // Version 25 - new int[]{ 6, 30, 58, 86, 114, -1, -1}, // Version 26 - new int[]{ 6, 34, 62, 90, 118, -1, -1}, // Version 27 - new int[]{ 6, 26, 50, 74, 98, 122, -1}, // Version 28 - new int[]{ 6, 30, 54, 78, 102, 126, -1}, // Version 29 - new int[]{ 6, 26, 52, 78, 104, 130, -1}, // Version 30 - new int[]{ 6, 30, 56, 82, 108, 134, -1}, // Version 31 - new int[]{ 6, 34, 60, 86, 112, 138, -1}, // Version 32 - new int[]{ 6, 30, 58, 86, 114, 142, -1}, // Version 33 - new int[]{ 6, 34, 62, 90, 118, 146, -1}, // Version 34 - new int[]{ 6, 30, 54, 78, 102, 126, 150}, // Version 35 - new int[]{ 6, 24, 50, 76, 102, 128, 154}, // Version 36 - new int[]{ 6, 28, 54, 80, 106, 132, 158}, // Version 37 - new int[]{ 6, 32, 58, 84, 110, 136, 162}, // Version 38 - new int[]{ 6, 26, 54, 82, 110, 138, 166}, // Version 39 - new int[]{ 6, 30, 58, 86, 114, 142, 170}, // Version 40 - }; - - // Type info cells at the left top corner. - private static int[][] TYPE_INFO_COORDINATES = new int[][]{ - new int[]{8, 0}, - new int[]{8, 1}, - new int[]{8, 2}, - new int[]{8, 3}, - new int[]{8, 4}, - new int[]{8, 5}, - new int[]{8, 7}, - new int[]{8, 8}, - new int[]{7, 8}, - new int[]{5, 8}, - new int[]{4, 8}, - new int[]{3, 8}, - new int[]{2, 8}, - new int[]{1, 8}, - new int[]{0, 8}, - }; - - // From Appendix D in JISX0510:2004 (p. 67) - private static int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101 - - // From Appendix C in JISX0510:2004 (p.65). - private static int TYPE_INFO_POLY = 0x537; - private static int TYPE_INFO_MASK_PATTERN = 0x5412; - - // Set all cells to -1. -1 means that the cell is empty (not set yet). - // - // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding - // with the ByteMatrix initialized all to zero. - public static void clearMatrix(ByteMatrix matrix) { - matrix.clear((sbyte)(-1)); - } - - // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On - // success, store the result in "matrix" and return true. - public static void buildMatrix(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version,int maskPattern, ByteMatrix matrix) { - try{ - clearMatrix(matrix); - embedBasicPatterns(version, matrix); - // Type information appear with any version. - embedTypeInfo(ecLevel, maskPattern, matrix); - // Version info appear if version >= 7. - maybeEmbedVersionInfo(version, matrix); - // Data should be embedded at end. - embedDataBits(dataBits, maskPattern, matrix); - }catch(Exception e){ - throw new WriterException(e.Message); - } - - } - - // Embed basic patterns. On success, modify the matrix and return true. - // The basic patterns are: - // - Position detection patterns - // - Timing patterns - // - Dark dot at the left bottom corner - // - Position adjustment patterns, if need be - public static void embedBasicPatterns(int version, ByteMatrix matrix){ - try - { - // Let's get started with embedding big squares at corners. - embedPositionDetectionPatternsAndSeparators(matrix); - // Then, embed the dark dot at the left bottom corner. - embedDarkDotAtLeftBottomCorner(matrix); - - // Position adjustment patterns appear if version >= 2. - maybeEmbedPositionAdjustmentPatterns(version, matrix); - // Timing patterns should be embedded after position adj. patterns. - embedTimingPatterns(matrix); - }catch(Exception e){ - throw new WriterException (e.Message); - } - } - - // Embed type information. On success, modify the matrix. - public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) - { - BitVector typeInfoBits = new BitVector(); - makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); - - for (int i = 0; i < typeInfoBits.size(); ++i) { - // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in - // "typeInfoBits". - int bit = typeInfoBits.at(typeInfoBits.size() - 1 - i); - - // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). - int x1 = TYPE_INFO_COORDINATES[i][0]; - int y1 = TYPE_INFO_COORDINATES[i][1]; - matrix.set(y1, x1, bit); - - if (i < 8) { - // Right top corner. - int x2 = matrix.width() - i - 1; - int y2 = 8; - matrix.set(y2, x2, bit); - } else { - // Left bottom corner. - int x2 = 8; - int y2 = matrix.height() - 7 + (i - 8); - matrix.set(y2, x2, bit); - } - } - } - - // Embed version information if need be. On success, modify the matrix and return true. - // See 8.10 of JISX0510:2004 (p.47) for how to embed version information. - public static void maybeEmbedVersionInfo(int version, ByteMatrix matrix){ - if (version < 7) { // Version info is necessary if version >= 7. - return; // Don't need version info. - } - BitVector versionInfoBits = new BitVector(); - makeVersionInfoBits(version, versionInfoBits); - - int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. - for (int i = 0; i < 6; ++i) { - for (int j = 0; j < 3; ++j) { - // Place bits in LSB (least significant bit) to MSB order. - int bit = versionInfoBits.at(bitIndex); - bitIndex--; - // Left bottom corner. - matrix.set(matrix.height() - 11 + j, i, bit); - // Right bottom corner. - matrix.set(i, matrix.height() - 11 + j, bit); - } - } - } - - // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. - // For debugging purposes, it skips masking process if "getMaskPattern" is -1. - // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. - public static void embedDataBits(BitVector dataBits, int maskPattern, ByteMatrix matrix) - { - int bitIndex = 0; - int direction = -1; - // Start from the right bottom cell. - int x = matrix.width() - 1; - int y = matrix.height() - 1; - while (x > 0) { - // Skip the vertical timing pattern. - if (x == 6) { - x -= 1; - } - while (y >= 0 && y < matrix.height()) { - for (int i = 0; i < 2; ++i) { - int xx = x - i; - // Skip the cell if it's not empty. - if (!isEmpty(matrix.get(y, xx))) { - continue; - } - int bit; - if (bitIndex < dataBits.size()) { - bit = dataBits.at(bitIndex); - ++bitIndex; - } else { - // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described - // in 8.4.9 of JISX0510:2004 (p. 24). - bit = 0; - } - - // Skip masking if mask_pattern is -1. - if (maskPattern != -1) { - int mask = MaskUtil.getDataMaskBit(maskPattern, xx, y); - bit ^= mask; - } - matrix.set(y, xx, bit); - } - y += direction; - } - direction = -direction; // Reverse the direction. - y += direction; - x -= 2; // Move to the left. - } - // All bits should be consumed. - if (bitIndex != dataBits.size()) { - throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size()); - } - } - - // Return the position of the most significant bit set (to one) in the "value". The most - // significant bit is position 32. If there is no bit set, return 0. Examples: - // - findMSBSet(0) => 0 - // - findMSBSet(1) => 1 - // - findMSBSet(255) => 8 - public static int findMSBSet(int value) { - int numDigits = 0; - while (value != 0) { - value >>= 1; - ++numDigits; - } - return numDigits; - } - - // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH - // code is used for encoding type information and version information. - // Example: Calculation of version information of 7. - // f(x) is created from 7. - // - 7 = 000111 in 6 bits - // - f(x) = x^2 + x^2 + x^1 - // g(x) is given by the standard (p. 67) - // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 - // Multiply f(x) by x^(18 - 6) - // - f'(x) = f(x) * x^(18 - 6) - // - f'(x) = x^14 + x^13 + x^12 - // Calculate the remainder of f'(x) / g(x) - // x^2 - // __________________________________________________ - // g(x) )x^14 + x^13 + x^12 - // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2 - // -------------------------------------------------- - // x^11 + x^10 + x^7 + x^4 + x^2 - // - // The remainder is x^11 + x^10 + x^7 + x^4 + x^2 - // Encode it in binary: 110010010100 - // The return value is 0xc94 (1100 1001 0100) - // - // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit - // operations. We don't care if cofficients are positive or negative. - public static int calculateBCHCode(int value, int poly) { - // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 - // from 13 to make it 12. - int msbSetInPoly = findMSBSet(poly); - value <<= msbSetInPoly - 1; - // Do the division business using exclusive-or operations. - while (findMSBSet(value) >= msbSetInPoly) { - value ^= poly << (findMSBSet(value) - msbSetInPoly); - } - // Now the "value" is the remainder (i.e. the BCH code) - return value; - } - - // Make bit vector of type information. On success, store the result in "bits" and return true. - // Encode error correction level and mask pattern. See 8.9 of - // JISX0510:2004 (p.45) for details. - public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits) - { - if (!QRCode.isValidMaskPattern(maskPattern)) { - throw new WriterException("Invalid mask pattern"); - } - int typeInfo = (ecLevel.getBits() << 3) | maskPattern; - bits.appendBits(typeInfo, 5); - - int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); - bits.appendBits(bchCode, 10); - - BitVector maskBits = new BitVector(); - maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); - bits.xor(maskBits); - - if (bits.size() != 15) { // Just in case. - throw new WriterException("should not happen but we got: " + bits.size()); - } - } - - // Make bit vector of version information. On success, store the result in "bits" and return true. - // See 8.10 of JISX0510:2004 (p.45) for details. - public static void makeVersionInfoBits(int version, BitVector bits){ - bits.appendBits(version, 6); - int bchCode = calculateBCHCode(version, VERSION_INFO_POLY); - bits.appendBits(bchCode, 12); - - if (bits.size() != 18) { // Just in case. - throw new WriterException("should not happen but we got: " + bits.size()); - } - } - - // Check if "value" is empty. - private static bool isEmpty(int value) { - return value == -1; - } - - // Check if "value" is valid. - private static bool isValidValue(int value) { - return (value == -1 || // Empty. - value == 0 || // Light (white). - value == 1); // Dark (black). - } - - private static void embedTimingPatterns(ByteMatrix matrix) { - // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical - // separation patterns (size 1). Thus, 8 = 7 + 1. - for (int i = 8; i < matrix.width() - 8; ++i) { - int bit = (i + 1) % 2; - // Horizontal line. - if (!isValidValue(matrix.get(6, i))) { - throw new WriterException(); - } - if (isEmpty(matrix.get(6, i))) { - matrix.set(6, i, bit); - } - // Vertical line. - if (!isValidValue(matrix.get(i, 6))) { - throw new WriterException(); - } - if (isEmpty(matrix.get(i, 6))) { - matrix.set(i, 6, bit); - } - } - } - - // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) - private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix){ - if (matrix.get(matrix.height() - 8, 8) == 0) { - throw new WriterException(); - } - matrix.set(matrix.height() - 8, 8, 1); - } - - private static void embedHorizontalSeparationPattern(int xStart, int yStart,ByteMatrix matrix) { - // We know the width and height. - if (HORIZONTAL_SEPARATION_PATTERN[0].Length != 8 || HORIZONTAL_SEPARATION_PATTERN.Length != 1) { - throw new WriterException("Bad horizontal separation pattern"); - } - for (int x = 0; x < 8; ++x) { - if (!isEmpty(matrix.get(yStart, xStart + x))) { - throw new WriterException(); - } - matrix.set(yStart, xStart + x, HORIZONTAL_SEPARATION_PATTERN[0][x]); - } - } - - private static void embedVerticalSeparationPattern(int xStart, int yStart,ByteMatrix matrix){ - // We know the width and height. - if (VERTICAL_SEPARATION_PATTERN[0].Length != 1 || VERTICAL_SEPARATION_PATTERN.Length != 7) { - throw new WriterException("Bad vertical separation pattern"); - } - for (int y = 0; y < 7; ++y) { - if (!isEmpty(matrix.get(yStart + y, xStart))) { - throw new WriterException(); - } - matrix.set(yStart + y, xStart, VERTICAL_SEPARATION_PATTERN[y][0]); - } - } - - // Note that we cannot unify the function with embedPositionDetectionPattern() despite they are - // almost identical, since we cannot write a function that takes 2D arrays in different sizes in - // C/C++. We should live with the fact. - private static void embedPositionAdjustmentPattern(int xStart, int yStart,ByteMatrix matrix){ - // We know the width and height. - if (POSITION_ADJUSTMENT_PATTERN[0].Length != 5 || POSITION_ADJUSTMENT_PATTERN.Length != 5) { - throw new WriterException("Bad position adjustment"); - } - for (int y = 0; y < 5; ++y) { - for (int x = 0; x < 5; ++x) { - if (!isEmpty(matrix.get(yStart + y, xStart + x))) { - throw new WriterException(); - } - matrix.set(yStart + y, xStart + x, POSITION_ADJUSTMENT_PATTERN[y][x]); - } - } - } - - private static void embedPositionDetectionPattern(int xStart, int yStart,ByteMatrix matrix){ - // We know the width and height. - if (POSITION_DETECTION_PATTERN[0].Length != 7 || POSITION_DETECTION_PATTERN.Length != 7) { - throw new WriterException("Bad position detection pattern"); - } - for (int y = 0; y < 7; ++y) { - for (int x = 0; x < 7; ++x) { - if (!isEmpty(matrix.get(yStart + y, xStart + x))) { - throw new WriterException(); - } - matrix.set(yStart + y, xStart + x, POSITION_DETECTION_PATTERN[y][x]); - } - } - } - - // Embed position detection patterns and surrounding vertical/horizontal separators. - private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) { - // Embed three big squares at corners. - int pdpWidth = POSITION_DETECTION_PATTERN[0].Length; - // Left top corner. - embedPositionDetectionPattern(0, 0, matrix); - // Right top corner. - embedPositionDetectionPattern(matrix.width() - pdpWidth, 0, matrix); - // Left bottom corner. - embedPositionDetectionPattern(0, matrix.width() - pdpWidth, matrix); - - // Embed horizontal separation patterns around the squares. - int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].Length; - // Left top corner. - embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); - // Right top corner. - embedHorizontalSeparationPattern(matrix.width() - hspWidth, - hspWidth - 1, matrix); - // Left bottom corner. - embedHorizontalSeparationPattern(0, matrix.width() - hspWidth, matrix); - - // Embed vertical separation patterns around the squares. - int vspSize = VERTICAL_SEPARATION_PATTERN.Length; - // Left top corner. - embedVerticalSeparationPattern(vspSize, 0, matrix); - // Right top corner. - embedVerticalSeparationPattern(matrix.height() - vspSize - 1, 0, matrix); - // Left bottom corner. - embedVerticalSeparationPattern(vspSize, matrix.height() - vspSize, - matrix); - } - - // Embed position adjustment patterns if need be. - private static void maybeEmbedPositionAdjustmentPatterns(int version, ByteMatrix matrix) - { - if (version < 2) { // The patterns appear if version >= 2 - return; - } - int index = version - 1; - int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; - int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].Length; - for (int i = 0; i < numCoordinates; ++i) { - for (int j = 0; j < numCoordinates; ++j) { - int y = coordinates[i]; - int x = coordinates[j]; - if (x == -1 || y == -1) { - continue; - } - // If the cell is unset, we embed the position adjustment pattern here. - if (isEmpty(matrix.get(y, x))) { - // -2 is necessary since the x/y coordinates point to the center of the pattern, not the - // left top corner. - embedPositionAdjustmentPattern(x - 2, y - 2, matrix); - } - } - } - } - - - - } - - -} \ No newline at end of file diff --git a/qrcode-scanner-live/qrcode/encoder/QRCode.cs b/qrcode-scanner-live/qrcode/encoder/QRCode.cs deleted file mode 100644 index b4292c9..0000000 --- a/qrcode-scanner-live/qrcode/encoder/QRCode.cs +++ /dev/null @@ -1,242 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.qrcode.decoder; -using com.google.zxing.qrcode; - -namespace com.google.zxing.qrcode.encoder -{ - - public sealed class QRCode - { - - public static int NUM_MASK_PATTERNS = 8; - - private Mode mode; - private ErrorCorrectionLevel ecLevel; - private int version; - private int matrixWidth; - private int maskPattern; - private int numTotalBytes; - private int numDataBytes; - private int numECBytes; - private int numRSBlocks; - private ByteMatrix matrix; - - public QRCode() { - mode = null; - ecLevel = null; - version = -1; - matrixWidth = -1; - maskPattern = -1; - numTotalBytes = -1; - numDataBytes = -1; - numECBytes = -1; - numRSBlocks = -1; - matrix = null; - } - - // Mode of the QR Code. - public Mode getMode() { - return mode; - } - - // Error correction level of the QR Code. - public ErrorCorrectionLevel getECLevel() { - return ecLevel; - } - - // Version of the QR Code. The bigger size, the bigger version. - public int getVersion() { - return version; - } - - // ByteMatrix width of the QR Code. - public int getMatrixWidth() { - return matrixWidth; - } - - // Mask pattern of the QR Code. - public int getMaskPattern() { - return maskPattern; - } - - // Number of total bytes in the QR Code. - public int getNumTotalBytes() { - return numTotalBytes; - } - - // Number of data bytes in the QR Code. - public int getNumDataBytes() { - return numDataBytes; - } - - // Number of error correction bytes in the QR Code. - public int getNumECBytes() { - return numECBytes; - } - - // Number of Reedsolomon blocks in the QR Code. - public int getNumRSBlocks() { - return numRSBlocks; - } - - // ByteMatrix data of the QR Code. - public ByteMatrix getMatrix() { - return matrix; - } - - - // Return the value of the module (cell) pointed by "x" and "y" in the matrix of the QR Code. They - // call cells in the matrix "modules". 1 represents a black cell, and 0 represents a white cell. - public int at(int x, int y) { - // The value must be zero or one. - int value = matrix.get(y, x); - if (!(value == 0 || value == 1)) { - // this is really like an assert... not sure what better exception to use? - throw new Exception("Bad value"); - } - return value; - } - - // Checks all the member variables are set properly. Returns true on success. Otherwise, returns - // false. - public bool isValid() { - return - // First check if all version are not uninitialized. - mode != null && - ecLevel != null && - version != -1 && - matrixWidth != -1 && - maskPattern != -1 && - numTotalBytes != -1 && - numDataBytes != -1 && - numECBytes != -1 && - numRSBlocks != -1 && - // Then check them in other ways.. - isValidMaskPattern(maskPattern) && - numTotalBytes == numDataBytes + numECBytes && - // ByteMatrix stuff. - matrix != null && - matrixWidth == matrix.width() && - // See 7.3.1 of JISX0510:2004 (p.5). - matrix.width() == matrix.height(); // Must be square. - } - - // Return debug String. - public String toString() { - StringBuilder result = new StringBuilder(200); - result.Append("<<\n"); - result.Append(" mode: "); - result.Append(mode); - result.Append("\n ecLevel: "); - result.Append(ecLevel); - result.Append("\n version: "); - result.Append(version); - result.Append("\n matrixWidth: "); - result.Append(matrixWidth); - result.Append("\n maskPattern: "); - result.Append(maskPattern); - result.Append("\n numTotalBytes: "); - result.Append(numTotalBytes); - result.Append("\n numDataBytes: "); - result.Append(numDataBytes); - result.Append("\n numECBytes: "); - result.Append(numECBytes); - result.Append("\n numRSBlocks: "); - result.Append(numRSBlocks); - if (matrix == null) { - result.Append("\n matrix: null\n"); - } else { - result.Append("\n matrix:\n"); - result.Append(matrix.toString()); - } - result.Append(">>\n"); - return result.ToString(); - } - - public void setMode(Mode value) { - mode = value; - } - - public void setECLevel(ErrorCorrectionLevel value) { - ecLevel = value; - } - - public void setVersion(int value) { - version = value; - } - - public void setMatrixWidth(int value) { - matrixWidth = value; - } - - public void setMaskPattern(int value) { - maskPattern = value; - } - - public void setNumTotalBytes(int value) { - numTotalBytes = value; - } - - public void setNumDataBytes(int value) { - numDataBytes = value; - } - - public void setNumECBytes(int value) { - numECBytes = value; - } - - public void setNumRSBlocks(int value) { - numRSBlocks = value; - } - - // This takes ownership of the 2D array. - public void setMatrix(ByteMatrix value) { - matrix = value; - } - - // Check if "mask_pattern" is valid. - public static bool isValidMaskPattern(int maskPattern) { - return maskPattern >= 0 && maskPattern < NUM_MASK_PATTERNS; - } - - // Return true if the all values in the matrix are binary numbers. - // - // JAVAPORT: This is going to be super expensive and unnecessary, we should not call this in - // production. I'm leaving it because it may be useful for testing. It should be removed entirely - // if ByteMatrix is changed never to contain a -1. - /* - private static boolean EverythingIsBinary(final ByteMatrix matrix) { - for (int y = 0; y < matrix.height(); ++y) { - for (int x = 0; x < matrix.width(); ++x) { - int value = matrix.get(y, x); - if (!(value == 0 || value == 1)) { - // Found non zero/one value. - return false; - } - } - } - return true; - } - */ - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live/zxing.csproj b/qrcode-scanner-live/zxing.csproj deleted file mode 100644 index 179dfcc..0000000 --- a/qrcode-scanner-live/zxing.csproj +++ /dev/null @@ -1,139 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {22174889-87F2-4843-A5CE-99A4847D24EE} - Library - Properties - com.google.zxing - com.google.zxing - v3.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - 3.5 - - - - 3.5 - - - 3.5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qrcode-scanner-live/zxing.pidb b/qrcode-scanner-live/zxing.pidb deleted file mode 100644 index 7c7c4f8..0000000 Binary files a/qrcode-scanner-live/zxing.pidb and /dev/null differ diff --git a/qrcode-scanner-live/zxing.sln b/qrcode-scanner-live/zxing.sln deleted file mode 100644 index 350ef5f..0000000 --- a/qrcode-scanner-live/zxing.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual C# Express 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "zxing", "zxing.csproj", "{22174889-87F2-4843-A5CE-99A4847D24EE}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {22174889-87F2-4843-A5CE-99A4847D24EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {22174889-87F2-4843-A5CE-99A4847D24EE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {22174889-87F2-4843-A5CE-99A4847D24EE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {22174889-87F2-4843-A5CE-99A4847D24EE}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/qrcode-scanner-live/zxing.suo b/qrcode-scanner-live/zxing.suo deleted file mode 100644 index c662b2b..0000000 Binary files a/qrcode-scanner-live/zxing.suo and /dev/null differ diff --git a/qrcode-scanner-live/zxing.userprefs b/qrcode-scanner-live/zxing.userprefs deleted file mode 100644 index 94bcd4f..0000000 --- a/qrcode-scanner-live/zxing.userprefs +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/qrcode-scanner-live2/BarcodeFormat.cs b/qrcode-scanner-live2/BarcodeFormat.cs deleted file mode 100644 index 3cdf6bf..0000000 --- a/qrcode-scanner-live2/BarcodeFormat.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - - /// Enumerates barcode formats known to this package. - /// * - /// - /// Sean Owen - /// - /// - public sealed class BarcodeFormat - { - - // No, we can't use an enum here. J2ME doesn't support it. - - /// QR Code 2D barcode format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'QR_CODE '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat QR_CODE = new BarcodeFormat("QR_CODE"); - - /// DataMatrix 2D barcode format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'DATAMATRIX '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat DATAMATRIX = new BarcodeFormat("DATAMATRIX"); - - /// UPC-E 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'UPC_E '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat UPC_E = new BarcodeFormat("UPC_E"); - - /// UPC-A 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'UPC_A '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat UPC_A = new BarcodeFormat("UPC_A"); - - /// EAN-8 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'EAN_8 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat EAN_8 = new BarcodeFormat("EAN_8"); - - /// EAN-13 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'EAN_13 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat EAN_13 = new BarcodeFormat("EAN_13"); - - /// Code 128 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'CODE_128 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat CODE_128 = new BarcodeFormat("CODE_128"); - - /// Code 39 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'CODE_39 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat CODE_39 = new BarcodeFormat("CODE_39"); - - /// ITF (Interleaved Two of Five) 1D format. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'ITF '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - public static readonly BarcodeFormat ITF = new BarcodeFormat("ITF"); - - //UPGRADE_NOTE: Final was removed from the declaration of 'name '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - private System.String name; - - private BarcodeFormat(System.String name) - { - this.name = name; - } - - public override System.String ToString() - { - return name; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/BlackPointEstimationMethod.cs b/qrcode-scanner-live2/BlackPointEstimationMethod.cs deleted file mode 100644 index 5217afe..0000000 --- a/qrcode-scanner-live2/BlackPointEstimationMethod.cs +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing -{ - - ///

Enumerates different methods of sampling an imagine to estimate a black point.

- /// - ///
- /// srowen@google.com (Sean Owen), dswitkin@google.com (Daniel Switkin) - /// - public sealed class BlackPointEstimationMethod - { - /** - * Method probably most suitable for use with 2D barcdoe format. - */ - public static BlackPointEstimationMethod TWO_D_SAMPLING = new BlackPointEstimationMethod(); - /** - * Method probably most suitable for 1D barcode decoding, where one row at a time is sampled. - */ - public static BlackPointEstimationMethod ROW_SAMPLING = new BlackPointEstimationMethod(); - - private BlackPointEstimationMethod() { - // do nothing - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/BufferedImageMonochromeBitmapSource.cs b/qrcode-scanner-live2/BufferedImageMonochromeBitmapSource.cs deleted file mode 100644 index 5871022..0000000 --- a/qrcode-scanner-live2/BufferedImageMonochromeBitmapSource.cs +++ /dev/null @@ -1,181 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Drawing; -using MonochromeBitmapSource = com.google.zxing.MonochromeBitmapSource; -using BlackPointEstimationMethod = com.google.zxing.BlackPointEstimationMethod; -using BitArray = com.google.zxing.common.BitArray; -using BlackPointEstimator = com.google.zxing.common.BlackPointEstimator; - - -namespace com.google.zxing.client.j2se -{ - - ///

An implementation based upon {@link BufferedImage}. This provides access to the - /// underlying image as if it were a monochrome image. Behind the scenes, it is evaluating - /// the luminance of the underlying image by retrieving its pixels' RGB values.

- /// - ///
- /// srowen@google.com (Sean Owen), Daniel Switkin (dswitkin@google.com) - /// - public sealed class BufferedImageMonochromeBitmapSource : MonochromeBitmapSource - { - public bool iRotateSupported = false; - - public bool isRotateSupported() { - return iRotateSupported; - } - - public int getWidth() { - return (iRotateSupported ? image.Height : image.Width); - } - - public BlackPointEstimationMethod getLastEstimationMethod() { - return lastMethod; - } - - public int getHeight() - { - return (iRotateSupported ? image.Width : image.Height); - } - - - public MonochromeBitmapSource rotateCounterClockwise() { - return null; - } - - public BitArray getBlackColumn(int x, BitArray column, int startY, int getHeight) { - return null; - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Drawing.Bitmap image; - private int blackPoint; - private BlackPointEstimationMethod lastMethod; - private int lastArgument; - - private const int LUMINANCE_BITS = 5; - //UPGRADE_NOTE: Final was removed from the declaration of 'LUMINANCE_SHIFT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; - //UPGRADE_NOTE: Final was removed from the declaration of 'LUMINANCE_BUCKETS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; - - public BufferedImageMonochromeBitmapSource(System.Drawing.Bitmap image, bool rotated) - { - this.image = image; - blackPoint = 0x7F; - lastMethod = null; - lastArgument = 0; - iRotateSupported = rotated; - } - - public bool isBlack(int x, int y) - { - return (iRotateSupported ? computeRGBLuminance(image.GetPixel(y, x).ToArgb()) < blackPoint : computeRGBLuminance(image.GetPixel(x, y).ToArgb()) < blackPoint); - } - - int[] getRGB(int startx, int starty, int width) - { - int[] pixels = new int[width]; - for (int k = 0; k < width; k++) - { - Color c = (iRotateSupported ? image.GetPixel(starty, startx + k) : image.GetPixel(startx + k, starty)); - pixels[k] = ((int)c.R) << 16 | ((int)c.G) << 8 | ((int)c.B); - } - - return pixels; - } - - public BitArray getBlackRow(int y, BitArray row, int startX, int getWidth) - { - if (row == null) - { - row = new BitArray(getWidth); - } - else - { - row.clear(); - } - //UPGRADE_ISSUE: Method 'java.awt.image.BufferedImage.getRGB' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaawtimageBufferedImagegetRGB_int_int_int_int_int[]_int_int'" - int[] pixelRow = getRGB(startX, y, getWidth); - for (int i = 0; i < getWidth; i++) - { - if (computeRGBLuminance(pixelRow[i]) < blackPoint) - { - row.set(i); - } - } - return row; - } - - public void estimateBlackPoint(BlackPointEstimationMethod method, int argument) - { - if (!method.Equals(lastMethod) || argument != lastArgument) - { - int width = getWidth(); - int height = getHeight(); - int[] histogram = new int[LUMINANCE_BUCKETS]; - float biasTowardsWhite = 1.0f; - if (method.Equals(BlackPointEstimationMethod.TWO_D_SAMPLING)) - { - int minDimension = width < height?width:height; - int startI = height == minDimension?0:(height - width) >> 1; - int startJ = width == minDimension?0:(width - height) >> 1; - for (int n = 0; n < minDimension; n++) - { - int pixel = (iRotateSupported ? image.GetPixel(startI + n, startJ + n).ToArgb() : image.GetPixel(startJ + n, startI + n).ToArgb()); - histogram[computeRGBLuminance(pixel) >> LUMINANCE_SHIFT]++; - } - } - else if (method.Equals(BlackPointEstimationMethod.ROW_SAMPLING)) - { - if (argument < 0 || argument >= height) - { - throw new System.ArgumentException("Row is not within the image: " + argument); - } - biasTowardsWhite = 2.0f; - int[] rgbArray = getRGB(0, argument, width); - for (int x = 0; x < width; x++) - { - int l = computeRGBLuminance(rgbArray[x]); - histogram[l >> LUMINANCE_SHIFT]++; - } - } - else - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.ArgumentException("Unknown method: " + method); - } - blackPoint = BlackPointEstimator.estimate(histogram) << LUMINANCE_SHIFT; - lastMethod = method; - lastArgument = argument; - } - } - - /// Extracts luminance from a pixel from this source. By default, the source is assumed to use RGB, - /// so this implementation computes luminance is a function of a red, green and blue components as - /// follows: - /// - /// Y = 0.299R + 0.587G + 0.114B - /// - /// where R, G, and B are values in [0,1]. - /// - private static int computeRGBLuminance(int pixel) - { - // Coefficients add up to 1024 to make the divide into a fast shift - return (306 * ((pixel >> 16) & 0xFF) + 601 * ((pixel >> 8) & 0xFF) + 117 * (pixel & 0xFF)) >> 10; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/DecodeHintType.cs b/qrcode-scanner-live2/DecodeHintType.cs deleted file mode 100644 index 8bc3190..0000000 --- a/qrcode-scanner-live2/DecodeHintType.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class DecodeHintType - { - // No, we can't use an enum here. J2ME doesn't support it. - /** - * Unspecified, application-specific hint. Maps to an unspecified {@link Object}. - */ - public static DecodeHintType OTHER = new DecodeHintType(); - - /** - * Image is a pure monochrome image of a barcode. Doesn't matter what it maps to; - * use {@link Boolean#TRUE}. - */ - public static DecodeHintType PURE_BARCODE = new DecodeHintType(); - - /** - * Image is known to be of one of a few possible formats. - * Maps to a {@link java.util.Vector} of {@link BarcodeFormat}s. - */ - public static DecodeHintType POSSIBLE_FORMATS = new DecodeHintType(); - - /** - * Spend more time to try to find a barcode; optimize for accuracy, not speed. - * Doesn't matter what it maps to; use {@link Boolean#TRUE}. - */ - public static DecodeHintType TRY_HARDER = new DecodeHintType(); - - private DecodeHintType() { - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/EncodeHintType.cs b/qrcode-scanner-live2/EncodeHintType.cs deleted file mode 100644 index 3ee58a1..0000000 --- a/qrcode-scanner-live2/EncodeHintType.cs +++ /dev/null @@ -1,44 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class EncodeHintType - { - /** - * Specifies what degree of error correction to use, for example in QR Codes (type Integer). - */ - public static EncodeHintType ERROR_CORRECTION = new EncodeHintType(); - - private EncodeHintType() { - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/MonochromeBitmapSource.cs b/qrcode-scanner-live2/MonochromeBitmapSource.cs deleted file mode 100644 index 58dd985..0000000 --- a/qrcode-scanner-live2/MonochromeBitmapSource.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing -{ - - ///

Encapsulates a generic black-and-white bitmap -- a collection of pixels in two dimensions. - /// This unifies many possible representations, like AWT's BufferedImage.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public interface MonochromeBitmapSource - { - /** - * @param x horizontal offset, from left, of the pixel - * @param y vertical offset, from top, of the pixel - * @return true iff the pixel at (x,y) is black - */ - bool isBlack(int x, int y); - - /** - *

Returns an entire row of black/white pixels as an array of bits, where "true" means "black". - * This is a sort of "bulk get" operation intended to enable efficient access in - * certain situations.

- * - * @param y vertical offset, from top, of the row of pixels - * @param row if not null, {@link BitArray} to write pixels into. If null, a new {@link BitArray} - * is allocated and returned. - * @param startX horizontal offset, from left, from which to start getting pixels - * @param getWidth number of pixels to get from the row - * @return {@link BitArray} representing the (subset of the) row of pixels. If row parameter - * was not null, it is returned. - */ - BitArray getBlackRow(int y, BitArray row, int startX, int getWidth); - - /** - * Entirely analogous to {@link #getBlackRow(int, BitArray, int, int)} but gets a column. - */ - BitArray getBlackColumn(int x, BitArray column, int startY, int getHeight); - - /** - * @return height of underlying image - */ - int getHeight(); - - /** - * @return width of underlying image - */ - int getWidth(); - - /** - *

Estimates black point according to the given method, which is optionally parameterized by - * a single int argument. For {@link BlackPointEstimationMethod#ROW_SAMPLING}, this - * specifies the row to sample.

- * - *

The estimated value will be used in subsequent computations that rely on an estimated black - * point.

- * - * @param method black point estimation method - * @param argument method-specific argument - */ - void estimateBlackPoint(BlackPointEstimationMethod method, int argument); - - /** - * @return {@link BlackPointEstimationMethod} representing last sampling method used - */ - BlackPointEstimationMethod getLastEstimationMethod(); - - /** - *

Optional operation which returns an implementation based on the same underlying - * image, but which behaves as if the underlying image had been rotated 90 degrees - * counterclockwise. This is useful in the context of 1D barcodes and the - * {@link DecodeHintType#TRY_HARDER} decode hint, and is only intended to be - * used in non-resource-constrained environments. Hence, implementations - * of this class which are only used in resource-constrained mobile environments - * don't have a need to implement this.

- * - * @throws IllegalArgumentException if not supported - */ - MonochromeBitmapSource rotateCounterClockwise(); - - /** - * @return true iff rotation is supported - * @see #rotateCounterClockwise() - */ - bool isRotateSupported(); - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/MultiFormatReader.cs b/qrcode-scanner-live2/MultiFormatReader.cs deleted file mode 100644 index 74a04ed..0000000 --- a/qrcode-scanner-live2/MultiFormatReader.cs +++ /dev/null @@ -1,171 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; -using com.google.zxing.qrcode; -using com.google.zxing.oned; -using com.google.zxing.datamatrix; - -namespace com.google.zxing -{ - public sealed class MultiFormatReader : Reader - { - private Hashtable hints; - private ArrayList readers; - - /** - * This version of decode honors the intent of Reader.decode(MonochromeBitmapSource) in that it - * passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly. - * Use setHints() followed by decodeWithState() for continuous scan applications. - * - * @param image The pixel data to decode - * @return The contents of the image - * @throws ReaderException Any errors which occurred - */ - public Result decode(MonochromeBitmapSource image){ - try{ - setHints(null); - return decodeInternal(image); - } - catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - /** - * Decode an image using the hints provided. Does not honor existing state. - * - * @param image The pixel data to decode - * @param hints The hints to use, clearing the previous state. - * @return The contents of the image - * @throws ReaderException Any errors which occurred - */ - public Result decode(MonochromeBitmapSource image, Hashtable hints){ - try{ - setHints(hints); - return decodeInternal(image); - }catch(Exception e){ - throw new ReaderException (e.Message); - } - } - - /** - * Decode an image using the state set up by calling setHints() previously. Continuous scan - * clients will get a large speed increase by using this instead of decode(). - * - * @param image The pixel data to decode - * @return The contents of the image - * @throws ReaderException Any errors which occurred - */ - public Result decodeWithState(MonochromeBitmapSource image){ - try{ - // Make sure to set up the default state so we don't crash - if (readers == null) { - setHints(null); - } - return decodeInternal(image); - }catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - /** - * This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls - * to decodeWithState(image) can reuse the same set of readers without reallocating memory. This - * is important for performance in continuous scan clients. - * - * @param hints The set of hints to use for subsequent calls to decode(image) - */ - public void setHints(Hashtable hints) { - this.hints = hints; - - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - - ArrayList possibleFormats = hints == null ? null : (ArrayList)hints[(DecodeHintType.POSSIBLE_FORMATS)]; - readers = new ArrayList(); - if (possibleFormats != null) - { - bool addOneDReader = - possibleFormats.Contains(BarcodeFormat.UPC_A) || - possibleFormats.Contains(BarcodeFormat.UPC_E) || - possibleFormats.Contains(BarcodeFormat.EAN_13) || - possibleFormats.Contains(BarcodeFormat.EAN_8) || - possibleFormats.Contains(BarcodeFormat.CODE_39) || - possibleFormats.Contains(BarcodeFormat.CODE_128); - // Put 1D readers upfront in "normal" mode - - if (addOneDReader && !tryHarder) - { - readers.Add(new MultiFormatOneDReader(hints)); - } - - if (possibleFormats.Contains(BarcodeFormat.QR_CODE)) - { - readers.Add(new QRCodeReader()); - } - // TODO re-enable once Data Matrix is ready - if (possibleFormats.Contains(BarcodeFormat.DATAMATRIX)) { - readers.Add(new DataMatrixReader()); - } - // At end in "try harder" mode - if (addOneDReader && tryHarder) - { - readers.Add(new MultiFormatOneDReader(hints)); - } - } - - if (readers.Count == 0) - { - if (!tryHarder) - { - readers.Add(new MultiFormatOneDReader(hints)); - } - readers.Add(new QRCodeReader()); - // TODO re-enable once Data Matrix is ready - readers.Add(new DataMatrixReader()); - if (tryHarder) - { - readers.Add(new MultiFormatOneDReader(hints)); - } - } - } - - private Result decodeInternal(MonochromeBitmapSource image) { - try - { - int size = readers.Count; - for (int i = 0; i < size; i++) - { - Reader reader = (Reader)readers[i]; - try - { - return reader.decode(image, hints); - } - catch (ReaderException re) - { - // continue - } - } - - throw new ReaderException(""); - } - catch (Exception e) { - throw new ReaderException(e.Message); - } - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/MultiFormatWriter.cs b/qrcode-scanner-live2/MultiFormatWriter.cs deleted file mode 100644 index 42f244c..0000000 --- a/qrcode-scanner-live2/MultiFormatWriter.cs +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; -using com.google.zxing.qrcode; -using com.google.zxing.common; - -namespace com.google.zxing -{ - public sealed class MultiFormatWriter : Writer - { - public ByteMatrix encode(String contents, BarcodeFormat format, int width,int height) { - return encode(contents, format, width, height,null); - } - - public ByteMatrix encode(String contents, BarcodeFormat format, int width, int height,Hashtable hints){ - if (format == BarcodeFormat.QR_CODE) { - return new QRCodeWriter().encode(contents, format, width, height, hints); - } else { - throw new ArgumentException("No encoder available for format " + format); - } - } - } -} - - - diff --git a/qrcode-scanner-live2/Properties/AssemblyInfo.cs b/qrcode-scanner-live2/Properties/AssemblyInfo.cs deleted file mode 100644 index 672bae1..0000000 --- a/qrcode-scanner-live2/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("QRCodeLib3")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("QRCodeLib3")] -[assembly: AssemblyCopyright("Copyright © 2009")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("869eed67-0f3d-424a-8e40-d8bb61c8dc7b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/qrcode-scanner-live2/README b/qrcode-scanner-live2/README deleted file mode 100644 index 49dcb93..0000000 --- a/qrcode-scanner-live2/README +++ /dev/null @@ -1 +0,0 @@ -This port was contributed and is maintained by Mohamad Fairol. \ No newline at end of file diff --git a/qrcode-scanner-live2/Reader.cs b/qrcode-scanner-live2/Reader.cs deleted file mode 100644 index 631cab8..0000000 --- a/qrcode-scanner-live2/Reader.cs +++ /dev/null @@ -1,45 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; - -namespace com.google.zxing -{ - public interface Reader - { - /** - * Locates and decodes a barcode in some format within an image. - * - * @param image image of barcode to decode - * @return String which the barcode encodes - * @throws ReaderException if the barcode cannot be located or decoded for any reason - */ - Result decode(MonochromeBitmapSource image); - - /** - * Locates and decodes a barcode in some format within an image. This method also accepts - * hints, each possibly associated to some data, which may help the implementation decode. - * - * @param image image of barcode to decode - * @param hints passed as a {@link Hashtable} from {@link DecodeHintType} to aribtrary data. The - * meaning of the data depends upon the hint type. The implementation may or may not do - * anything with these hints. - * @return String which the barcode encodes - * @throws ReaderException if the barcode cannot be located or decoded for any reason - */ - Result decode(MonochromeBitmapSource image, Hashtable hints); - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/ReaderException.cs b/qrcode-scanner-live2/ReaderException.cs deleted file mode 100644 index c84928a..0000000 --- a/qrcode-scanner-live2/ReaderException.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing -{ - - /// The general exception class throw when something goes wrong during decoding of a barcode. - /// This includes, but is not limited to, failing checksums / error correction algorithms, being - /// unable to locate finder timing patterns, and so on. - /// - /// - /// srowen@google.com (Sean Owen) - /// - //[Serializable] - public sealed class ReaderException : System.Exception - { - - private static ReaderException instance = new ReaderException(); - - public ReaderException() { - // do nothing - } - - public ReaderException(System.String message): base(message) - { - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/Result.cs b/qrcode-scanner-live2/Result.cs deleted file mode 100644 index 1bc5841..0000000 --- a/qrcode-scanner-live2/Result.cs +++ /dev/null @@ -1,106 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; - -namespace com.google.zxing -{ - - /// The general exception class throw when something goes wrong during decoding of a barcode. - /// This includes, but is not limited to, failing checksums / error correction algorithms, being - /// unable to locate finder timing patterns, and so on. - /// - /// - /// srowen@google.com (Sean Owen) - /// - //[Serializable] - public sealed class Result - { - private String text; - private sbyte[] rawBytes; - private ResultPoint[] resultPoints; - private BarcodeFormat format; - private Hashtable resultMetadata; - - public Result(String text, - sbyte[] rawBytes, - ResultPoint[] resultPoints, - BarcodeFormat format) { - if (text == null && rawBytes == null) { - throw new ArgumentException("Text and bytes are null"); - } - this.text = text; - this.rawBytes = rawBytes; - this.resultPoints = resultPoints; - this.format = format; - this.resultMetadata = null; - } - - /** - * @return raw text encoded by the barcode, if applicable, otherwise null - */ - public String getText() { - return text; - } - - /** - * @return raw bytes encoded by the barcode, if applicable, otherwise null - */ - public sbyte[] getRawBytes() { - return rawBytes; - } - - /** - * @return points related to the barcode in the image. These are typically points - * identifying finder patterns or the corners of the barcode. The exact meaning is - * specific to the type of barcode that was decoded. - */ - public ResultPoint[] getResultPoints() { - return resultPoints; - } - - /** - * @return {@link BarcodeFormat} representing the format of the barcode that was recognized and decoded - */ - public BarcodeFormat getBarcodeFormat() { - return format; - } - - /** - * @return {@link Hashtable} mapping {@link ResultMetadataType} keys to values. May be null. - * This contains optional metadata about what was detected about the barcode, like orientation. - */ - public Hashtable getResultMetadata() { - return resultMetadata; - } - - public void putMetadata(ResultMetadataType type, Object value) { - if (resultMetadata == null) { - resultMetadata = new Hashtable(3); - } - resultMetadata.Add(type, value); - } - - public String toString() { - if (text == null) { - return "[" + rawBytes.Length + " bytes]"; - } else { - return text; - } - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/ResultMetadataType.cs b/qrcode-scanner-live2/ResultMetadataType.cs deleted file mode 100644 index 5a37130..0000000 --- a/qrcode-scanner-live2/ResultMetadataType.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; - -namespace com.google.zxing -{ - - /// The general exception class throw when something goes wrong during decoding of a barcode. - /// This includes, but is not limited to, failing checksums / error correction algorithms, being - /// unable to locate finder timing patterns, and so on. - /// - /// - /// srowen@google.com (Sean Owen) - /// - //[Serializable] - public sealed class ResultMetadataType - { - // No, we can't use an enum here. J2ME doesn't support it. - - /** - * Unspecified, application-specific metadata. Maps to an unspecified {@link Object}. - */ - public static ResultMetadataType OTHER = new ResultMetadataType(); - - /** - * Denotes the likely approximate orientation of the barcode in the image. This value - * is given as degrees rotated clockwise from the normal, upright orientation. - * For example a 1D barcode which was found by reading top-to-bottom would be - * said to have orientation "90". This key maps to an {@link Integer} whose - * value is in the range [0,360). - */ - public static ResultMetadataType ORIENTATION = new ResultMetadataType(); - - /** - *

2D barcode formats typically encode text, but allow for a sort of 'byte mode' - * which is sometimes used to encode binary data. While {@link Result} makes available - * the complete raw bytes in the barcode for these formats, it does not offer the bytes - * from the byte segments alone.

- * - *

This maps to a {@link java.util.Vector} of byte arrays corresponding to the - * raw bytes in the byte segments in the barcode, in order.

- */ - public static ResultMetadataType BYTE_SEGMENTS = new ResultMetadataType(); - - private ResultMetadataType() { - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/ResultPoint.cs b/qrcode-scanner-live2/ResultPoint.cs deleted file mode 100644 index 378c0cd..0000000 --- a/qrcode-scanner-live2/ResultPoint.cs +++ /dev/null @@ -1,38 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public interface ResultPoint - { - float getX(); - float getY(); - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/SupportClass.cs b/qrcode-scanner-live2/SupportClass.cs deleted file mode 100644 index 5058d7d..0000000 --- a/qrcode-scanner-live2/SupportClass.cs +++ /dev/null @@ -1,456 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; - - /// - /// This interface should be implemented by any class whose instances are intended - /// to be executed by a thread. - /// - public interface IThreadRunnable - { - /// - /// This method has to be implemented in order that starting of the thread causes the object's - /// run method to be called in that separately executing thread. - /// - void Run(); - } - -/// -/// Contains conversion support elements such as classes, interfaces and static methods. -/// -public class SupportClass -{ - - - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static int URShift(int number, int bits) - { - if ( number >= 0) - return number >> bits; - else - return (number >> bits) + (2 << ~bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static int URShift(int number, long bits) - { - return URShift(number, (int)bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static long URShift(long number, int bits) - { - if ( number >= 0) - return number >> bits; - else - return (number >> bits) + (2L << ~bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static long URShift(long number, long bits) - { - return URShift(number, (int)bits); - } - - /*******************************/ - /// - /// Copies an array of chars obtained from a String into a specified array of chars - /// - /// The String to get the chars from - /// Position of the String to start getting the chars - /// Position of the String to end getting the chars - /// Array to return the chars - /// Position of the destination array of chars to start storing the chars - /// An array of chars - public static void GetCharsFromString(System.String sourceString, int sourceStart, int sourceEnd, char[] destinationArray, int destinationStart) - { - int sourceCounter; - int destinationCounter; - sourceCounter = sourceStart; - destinationCounter = destinationStart; - while (sourceCounter < sourceEnd) - { - destinationArray[destinationCounter] = (char) sourceString[sourceCounter]; - sourceCounter++; - destinationCounter++; - } - } - - /*******************************/ - /// - /// Converts an array of sbytes to an array of bytes - /// - /// The array of sbytes to be converted - /// The new array of bytes - public static byte[] ToByteArray(sbyte[] sbyteArray) - { - byte[] byteArray = null; - - if (sbyteArray != null) - { - byteArray = new byte[sbyteArray.Length]; - for(int index=0; index < sbyteArray.Length; index++) - byteArray[index] = (byte) sbyteArray[index]; - } - return byteArray; - } - - /// - /// Converts a string to an array of bytes - /// - /// The string to be converted - /// The new array of bytes - public static byte[] ToByteArray(System.String sourceString) - { - return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); - } - - /// - /// Converts a array of object-type instances to a byte-type array. - /// - /// Array to convert. - /// An array of byte type elements. - public static byte[] ToByteArray(System.Object[] tempObjectArray) - { - byte[] byteArray = null; - if (tempObjectArray != null) - { - byteArray = new byte[tempObjectArray.Length]; - for (int index = 0; index < tempObjectArray.Length; index++) - byteArray[index] = (byte)tempObjectArray[index]; - } - return byteArray; - } - - /*******************************/ - /// - /// Sets the capacity for the specified ArrayList - /// - /// The ArrayList which capacity will be set - /// The new capacity value - public static void SetCapacity(System.Collections.ArrayList vector, int newCapacity) - { - if (newCapacity > vector.Count) - vector.AddRange(new Array[newCapacity-vector.Count]); - else if (newCapacity < vector.Count) - vector.RemoveRange(newCapacity, vector.Count - newCapacity); - vector.Capacity = newCapacity; - } - - - - /*******************************/ - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static long Identity(long literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static ulong Identity(ulong literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static float Identity(float literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static double Identity(double literal) - { - return literal; - } - - /*******************************/ - /// - /// Support class used to handle threads - /// - public class ThreadClass : IThreadRunnable - { - /// - /// The instance of System.Threading.Thread - /// - private System.Threading.Thread threadField; - - /// - /// Initializes a new instance of the ThreadClass class - /// - public ThreadClass() - { - threadField = new System.Threading.Thread(new System.Threading.ThreadStart(Run)); - } - - /// - /// Initializes a new instance of the Thread class. - /// - /// The name of the thread - public ThreadClass(System.String Name) - { - threadField = new System.Threading.Thread(new System.Threading.ThreadStart(Run)); - this.Name = Name; - } - - /// - /// Initializes a new instance of the Thread class. - /// - /// A ThreadStart delegate that references the methods to be invoked when this thread begins executing - public ThreadClass(System.Threading.ThreadStart Start) - { - threadField = new System.Threading.Thread(Start); - } - - /// - /// Initializes a new instance of the Thread class. - /// - /// A ThreadStart delegate that references the methods to be invoked when this thread begins executing - /// The name of the thread - public ThreadClass(System.Threading.ThreadStart Start, System.String Name) - { - threadField = new System.Threading.Thread(Start); - this.Name = Name; - } - - /// - /// This method has no functionality unless the method is overridden - /// - public virtual void Run() - { - } - - /// - /// Causes the operating system to change the state of the current thread instance to ThreadState.Running - /// - public virtual void Start() - { - threadField.Start(); - } - - ///// - ///// Interrupts a thread that is in the WaitSleepJoin thread state - ///// - //public virtual void Interrupt() - //{ - // threadField.Interrupt(); - //} - - /// - /// Gets the current thread instance - /// - public System.Threading.Thread Instance - { - get - { - return threadField; - } - set - { - threadField = value; - } - } - - /// - /// Gets or sets the name of the thread - /// - public System.String Name - { - get - { - return threadField.Name; - } - set - { - if (threadField.Name == null) - threadField.Name = value; - } - } - - /// - /// Gets or sets a value indicating the scheduling priority of a thread - /// - public System.Threading.ThreadPriority Priority - { - get - { - return threadField.Priority; - } - set - { - threadField.Priority = value; - } - } - - ///// - ///// Gets a value indicating the execution status of the current thread - ///// - //public bool IsAlive - //{ - // get - // { - // return threadField.IsAlive; - // } - //} - - /// - /// Gets or sets a value indicating whether or not a thread is a background thread. - /// - public bool IsBackground - { - get - { - return threadField.IsBackground; - } - set - { - threadField.IsBackground = value; - } - } - - /// - /// Blocks the calling thread until a thread terminates - /// - public void Join() - { - threadField.Join(); - } - - /// - /// Blocks the calling thread until a thread terminates or the specified time elapses - /// - /// Time of wait in milliseconds - public void Join(int MiliSeconds) - { - lock(this) - { - threadField.Join(MiliSeconds); - } - } - - ///// - ///// Blocks the calling thread until a thread terminates or the specified time elapses - ///// - ///// Time of wait in milliseconds - ///// Time of wait in nanoseconds - //public void Join(long MiliSeconds, int NanoSeconds) - //{ - // lock(this) - // { - // threadField.Join(new System.TimeSpan(MiliSeconds * 10000 + NanoSeconds * 100)); - // } - //} - - ///// - ///// Resumes a thread that has been suspended - ///// - //public void Resume() - //{ - // threadField.Resume(); - //} - - /// - /// Raises a ThreadAbortException in the thread on which it is invoked, - /// to begin the process of terminating the thread. Calling this method - /// usually terminates the thread - /// - public void Abort() - { - threadField.Abort(); - } - - /// - /// Raises a ThreadAbortException in the thread on which it is invoked, - /// to begin the process of terminating the thread while also providing - /// exception information about the thread termination. - /// Calling this method usually terminates the thread. - /// - /// An object that contains application-specific information, such as state, which can be used by the thread being aborted - public void Abort(System.Object stateInfo) - { - lock(this) - { - threadField.Abort(stateInfo); - } - } - - ///// - ///// Suspends the thread, if the thread is already suspended it has no effect - ///// - //public void Suspend() - //{ - // threadField.Suspend(); - //} - - /// - /// Obtain a String that represents the current Object - /// - /// A String that represents the current Object - public override System.String ToString() - { - return "Thread[" + Name + "," + Priority.ToString() + "," + "" + "]"; - } - - /// - /// Gets the currently running thread - /// - /// The currently running thread - public static ThreadClass Current() - { - ThreadClass CurrentThread = new ThreadClass(); - CurrentThread.Instance = System.Threading.Thread.CurrentThread; - return CurrentThread; - } - } - - -} diff --git a/qrcode-scanner-live2/Writer.cs b/qrcode-scanner-live2/Writer.cs deleted file mode 100644 index dcba9ec..0000000 --- a/qrcode-scanner-live2/Writer.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - using ByteMatrix = com.google.zxing.common.ByteMatrix; - /// The base class for all objects which encode/generate a barcode image. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public interface Writer - { - /// Encode a barcode using the default settings. - /// * - /// - /// The contents to encode in the barcode - /// - /// The barcode format to generate - /// - /// The preferred width in pixels - /// - /// The preferred height in pixels - /// - /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) - /// - /// - ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height); - /// * - /// - /// The contents to encode in the barcode - /// - /// The barcode format to generate - /// - /// The preferred width in pixels - /// - /// The preferred height in pixels - /// - /// Additional parameters to supply to the encoder - /// - /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) - /// - /// - ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height, System.Collections.Hashtable hints); - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/WriterException.cs b/qrcode-scanner-live2/WriterException.cs deleted file mode 100644 index 6148a1a..0000000 --- a/qrcode-scanner-live2/WriterException.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing -{ - using System; - - /// A base class which covers the range of exceptions which may occur when encoding a barcode using - /// the Writer framework. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class WriterException : System.Exception - { - - public WriterException() - : base() - { - } - - public WriterException(System.String message) - : base(message) - { - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/bin/Debug/com.google.zxing.dll b/qrcode-scanner-live2/bin/Debug/com.google.zxing.dll deleted file mode 100644 index 5c7572e..0000000 Binary files a/qrcode-scanner-live2/bin/Debug/com.google.zxing.dll and /dev/null differ diff --git a/qrcode-scanner-live2/bin/Debug/com.google.zxing.dll.mdb b/qrcode-scanner-live2/bin/Debug/com.google.zxing.dll.mdb deleted file mode 100644 index 2e8ecff..0000000 Binary files a/qrcode-scanner-live2/bin/Debug/com.google.zxing.dll.mdb and /dev/null differ diff --git a/qrcode-scanner-live2/bin/Release/com.google.zxing.dll b/qrcode-scanner-live2/bin/Release/com.google.zxing.dll deleted file mode 100644 index 107727e..0000000 Binary files a/qrcode-scanner-live2/bin/Release/com.google.zxing.dll and /dev/null differ diff --git a/qrcode-scanner-live2/bin/Release/com.google.zxing.pdb b/qrcode-scanner-live2/bin/Release/com.google.zxing.pdb deleted file mode 100644 index 3aef474..0000000 Binary files a/qrcode-scanner-live2/bin/Release/com.google.zxing.pdb and /dev/null differ diff --git a/qrcode-scanner-live2/common/BaseMonochromeBitmapSource.cs b/qrcode-scanner-live2/common/BaseMonochromeBitmapSource.cs deleted file mode 100644 index 9d2ad27..0000000 --- a/qrcode-scanner-live2/common/BaseMonochromeBitmapSource.cs +++ /dev/null @@ -1,196 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using BitArray = com.google.zxing.common.BitArray; -using com.google.zxing.common; -namespace com.google.zxing -{ - /** - * @author dswitkin@google.com (Daniel Switkin) - */ - public abstract class BaseMonochromeBitmapSource: MonochromeBitmapSource - { - private static int LUMINANCE_BITS = 5; - private static int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; - private static int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; - - private int blackPoint; - private BlackPointEstimationMethod lastMethod; - private int lastArgument; - private int[] luminances; - - protected BaseMonochromeBitmapSource() { - blackPoint = 0x7F; - lastMethod = null; - lastArgument = 0; - } - - private void initLuminances() { - if (luminances == null) { - int width = getWidth(); - int height = getHeight(); - int max = width > height ? width : height; - luminances = new int[max]; - } - } - - public bool isBlack(int x, int y) { - return getLuminance(x, y) < blackPoint; - } - - public BitArray getBlackRow(int y, BitArray row, int startX, int getWidth) { - if (row == null || row.getSize() < getWidth) { - row = new BitArray(getWidth); - } else { - row.clear(); - } - - // Reuse the same int array each time - initLuminances(); - luminances = getLuminanceRow(y, luminances); - - // If the current decoder calculated the blackPoint based on one row, assume we're trying to - // decode a 1D barcode, and apply some sharpening. - if (lastMethod.Equals(BlackPointEstimationMethod.ROW_SAMPLING)) { - int left = luminances[startX]; - int center = luminances[startX + 1]; - for (int x = 1; x < getWidth - 1; x++) { - int right = luminances[startX + x + 1]; - // Simple -1 4 -1 box filter with a weight of 2 - int luminance = ((center << 2) - left - right) >> 1; - if (luminance < blackPoint) { - row.set(x); - } - left = center; - center = right; - } - } else { - for (int x = 0; x < getWidth; x++) { - if (luminances[startX + x] < blackPoint) { - row.set(x); - } - } - } - return row; - } - - public BitArray getBlackColumn(int x, BitArray column, int startY, int getHeight) { - if (column == null || column.getSize() < getHeight) { - column = new BitArray(getHeight); - } else { - column.clear(); - } - - // Reuse the same int array each time - initLuminances(); - luminances = getLuminanceColumn(x, luminances); - - // We don't handle "row sampling" specially here - for (int y = 0; y < getHeight; y++) { - if (luminances[startY + y] < blackPoint) { - column.set(y); - } - } - return column; - } - - public void estimateBlackPoint(BlackPointEstimationMethod method, int argument){ - if (!method.Equals(lastMethod) || argument != lastArgument) { - int width = getWidth(); - int height = getHeight(); - int[] histogram = new int[LUMINANCE_BUCKETS]; - if (method.Equals(BlackPointEstimationMethod.TWO_D_SAMPLING)) { - int minDimension = width < height ? width : height; - int startX = (width - minDimension) >> 1; - int startY = (height - minDimension) >> 1; - for (int n = 0; n < minDimension; n++) { - int luminance = getLuminance(startX + n, startY + n); - histogram[luminance >> LUMINANCE_SHIFT]++; - } - } else if (method.Equals(BlackPointEstimationMethod.ROW_SAMPLING)) { - if (argument < 0 || argument >= height) { - throw new Exception("Row is not within the image: " + argument); - } - initLuminances(); - luminances = getLuminanceRow(argument, luminances); - for (int x = 0; x < width; x++) { - histogram[luminances[x] >> LUMINANCE_SHIFT]++; - } - } else { - throw new Exception("Unknown method: " + method); - } - blackPoint = BlackPointEstimator.estimate(histogram) << LUMINANCE_SHIFT; - lastMethod = method; - lastArgument = argument; - } - } - - public BlackPointEstimationMethod getLastEstimationMethod() { - return lastMethod; - } - - public MonochromeBitmapSource rotateCounterClockwise() { - throw new Exception("Rotate not supported"); - } - - public bool isRotateSupported() { - return false; - } - - // These two methods should not need to exist because they are defined in the interface that - // this abstract class implements. However this seems to cause problems on some Nokias. - // So we write these redundant declarations. - - public abstract int getHeight(); - - public abstract int getWidth(); - - /** - * Retrieves the luminance at the pixel x,y in the bitmap. This method is only used for estimating - * the black point and implementing getBlackRow() - it is not meant for decoding, hence it is not - * part of MonochromeBitmapSource itself, and is protected. - * - * @param x The x coordinate in the image. - * @param y The y coordinate in the image. - * @return The luminance value between 0 and 255. - */ - protected abstract int getLuminance(int x, int y); - - /** - * This is the main mechanism for retrieving luminance data. It is dramatically more efficient - * than repeatedly calling getLuminance(). As above, this is not meant for decoders. - * - * @param y The row to fetch - * @param row The array to write luminance values into. It is strongly suggested that you - * allocate this yourself, making sure row.length >= getWidth(), and reuse the same - * array on subsequent calls for performance. If you pass null, you will be flogged, - * but then I will take pity on you and allocate a sufficient array internally. - * @return The array containing the luminance data. This is the same as row if it was usable. - */ - protected abstract int[] getLuminanceRow(int y, int[] row); - - /** - * The same as getLuminanceRow(), but for columns. - * - * @param x The column to fetch - * @param column The array to write luminance values into. See above. - * @return The array containing the luminance data. - */ - protected abstract int[] getLuminanceColumn(int x, int[] column); - - } -} - - diff --git a/qrcode-scanner-live2/common/BitArray.cs b/qrcode-scanner-live2/common/BitArray.cs deleted file mode 100644 index 84a8fe4..0000000 --- a/qrcode-scanner-live2/common/BitArray.cs +++ /dev/null @@ -1,178 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class BitArray - { - // TODO: I have changed these members to be public so ProGuard can inline get() and set(). Ideally - // they'd be private and we'd use the -allowaccessmodification flag, but Dalvik rejects the - // resulting binary at runtime on Android. If we find a solution to this, these should be changed - // back to private. - public int[] bits; - public int Size; - - public BitArray(int size) { - if (size < 1) { - throw new Exception("size must be at least 1"); - } - this.Size = size; - this.bits = makeArray(size); - } - - public int getSize() { - return Size; - } - - /** - * @param i bit to get - * @return true iff bit i is set - */ - public bool get(int i) { - return (bits[i >> 5] & (1 << (i & 0x1F))) != 0; - } - - /** - * Sets bit i. - * - * @param i bit to set - */ - public void set(int i) { - bits[i >> 5] |= 1 << (i & 0x1F); - } - - /** - * Sets a block of 32 bits, starting at bit i. - * - * @param i first bit to set - * @param newBits the new value of the next 32 bits. Note again that the least-significant bit - * corresponds to bit i, the next-least-significant to i+1, and so on. - */ - public void setBulk(int i, int newBits) { - bits[i >> 5] = newBits; - } - - /** - * Clears all bits (sets to false). - */ - public void clear() { - int max = bits.Length; - for (int i = 0; i < max; i++) { - bits[i] = 0; - } - } - - /** - * Efficient method to check if a range of bits is set, or not set. - * - * @param start start of range, inclusive. - * @param end end of range, exclusive - * @param value if true, checks that bits in range are set, otherwise checks that they are not set - * @return true iff all bits are set or not set in range, according to value argument - * @throws IllegalArgumentException if end is less than or equal to start - */ - public bool isRange(int start, int end, bool value) { - if (end < start) { - throw new Exception(); - } - if (end == start) { - return true; // empty range matches - } - end--; // will be easier to treat this as the last actually set bit -- inclusive - int firstInt = start >> 5; - int lastInt = end >> 5; - for (int i = firstInt; i <= lastInt; i++) { - int firstBit = i > firstInt ? 0 : start & 0x1F; - int lastBit = i < lastInt ? 31 : end & 0x1F; - int mask; - if (firstBit == 0 && lastBit == 31) { - mask = -1; - } else { - mask = 0; - for (int j = firstBit; j <= lastBit; j++) { - mask |= 1 << j; - } - } - - // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, - // equals the mask, or we're looking for 0s and the masked portion is not all 0s - if ((bits[i] & mask) != (value ? mask : 0)) { - return false; - } - } - return true; - } - - /** - * @return underlying array of ints. The first element holds the first 32 bits, and the least - * significant bit is bit 0. - */ - public int[] getBitArray() { - return bits; - } - - /** - * Reverses all bits in the array. - */ - public void reverse() { - int[] newBits = makeArray(Size); - int max = newBits.Length; - for (int i = 0; i < max; i++) { - newBits[i] = 0; - } - int size = this.Size; - for (int i = 0; i < size; i++) { - if (get(size - i - 1)) { - newBits[i >> 5] |= 1 << (i & 0x1F); - } - } - bits = newBits; - } - - private static int[] makeArray(int size) { - int arraySize = size >> 5; - if ((size & 0x1F) != 0) { - arraySize++; - } - return new int[arraySize]; - } - - public String toString() { - StringBuilder result = new StringBuilder(Size); - for (int i = 0; i < Size; i++) { - if (i % 8 == 0) { - result.Append(' '); - } - result.Append(get(i) ? 'X' : '.'); - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/BitMatrix.cs b/qrcode-scanner-live2/common/BitMatrix.cs deleted file mode 100644 index 3d9a993..0000000 --- a/qrcode-scanner-live2/common/BitMatrix.cs +++ /dev/null @@ -1,129 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class BitMatrix - { - private int dimension; - private int[] bits; - - public BitMatrix(int dimension) { - if (dimension < 1) { - throw new Exception("dimension must be at least 1"); - } - this.dimension = dimension; - int numBits = dimension * dimension; - int arraySize = numBits >> 5; // one int per 32 bits - if ((numBits & 0x1F) != 0) { // plus one more if there are leftovers - arraySize++; - } - bits = new int[arraySize]; - } - - /** - * @param i row offset - * @param j column offset - * @return value of given bit in matrix - */ - public bool get(int i, int j) { - int offset = i + dimension * j; - //return ((bits[offset >> 5] >>> (offset & 0x1F)) & 0x01) != 0; - return ((SupportClass.URShift(bits[offset >> 5], (offset & 0x1F))) & 0x01) != 0; - } - - /** - *

Sets the given bit to true.

- * - * @param i row offset - * @param j column offset - */ - public void set(int i, int j) { - int offset = i + dimension * j; - bits[offset >> 5] |= 1 << (offset & 0x1F); - } - - /** - *

Sets a square region of the bit matrix to true.

- * - * @param topI row offset of region's top-left corner (inclusive) - * @param leftJ column offset of region's top-left corner (inclusive) - * @param height height of region - * @param width width of region - */ - public void setRegion(int topI, int leftJ, int height, int width) { - if (topI < 0 || leftJ < 0) { - throw new Exception("topI and leftJ must be nonnegative"); - } - if (height < 1 || width < 1) { - throw new Exception("height and width must be at least 1"); - } - int maxJ = leftJ + width; - int maxI = topI + height; - if (maxI > dimension || maxJ > dimension) { - throw new Exception( - "topI + height and leftJ + width must be <= matrix dimension"); - } - for (int j = leftJ; j < maxJ; j++) { - int jOffset = dimension * j; - for (int i = topI; i < maxI; i++) { - int offset = i + jOffset; - bits[offset >> 5] |= 1 << (offset & 0x1F); - } - } - } - - /** - * @return row/column dimension of this matrix - */ - public int getDimension() { - return dimension; - } - - /** - * @return array of ints holding internal representation of this matrix's bits - */ - public int[] getBits() { - return bits; - } - - public String toString() { - StringBuilder result = new StringBuilder(dimension * (dimension + 1)); - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - result.Append(get(i, j) ? "X " : " "); - } - result.Append('\n'); - } - return result.ToString(); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/BitSource.cs b/qrcode-scanner-live2/common/BitSource.cs deleted file mode 100644 index 91df66e..0000000 --- a/qrcode-scanner-live2/common/BitSource.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class BitSource - { - private sbyte[] bytes; - private int byteOffset; - private int bitOffset; - - /** - * @param bytes bytes from which this will read bits. Bits will be read from the first byte first. - * Bits are read within a byte from most-significant to least-significant bit. - */ - public BitSource(sbyte[] bytes) { - this.bytes = bytes; - } - - /** - * @param numBits number of bits to read - * @return int representing the bits read. The bits will appear as the least-significant - * bits of the int - * @throws IllegalArgumentException if numBits isn't in [1,32] - */ - public int readBits(int numBits) { - if (numBits < 1 || numBits > 32) { - throw new Exception(); - } - - int result = 0; - - // First, read remainder from current byte - if (bitOffset > 0) { - int bitsLeft = 8 - bitOffset; - int toRead = numBits < bitsLeft ? numBits : bitsLeft; - int bitsToNotRead = bitsLeft - toRead; - int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; - result = (bytes[byteOffset] & mask) >> bitsToNotRead; - numBits -= toRead; - bitOffset += toRead; - if (bitOffset == 8) { - bitOffset = 0; - byteOffset++; - } - } - - // Next read whole bytes - if (numBits > 0) { - while (numBits >= 8) { - result = (result << 8) | (bytes[byteOffset] & 0xFF); - byteOffset++; - numBits -= 8; - } - - // Finally read a partial byte - if (numBits > 0) { - int bitsToNotRead = 8 - numBits; - int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; - result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead); - bitOffset += numBits; - } - } - - return result; - } - - /** - * @return number of bits that can be read successfully - */ - public int available() { - return 8 * (bytes.Length - byteOffset) - bitOffset; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/BlackPointEstimator.cs b/qrcode-scanner-live2/common/BlackPointEstimator.cs deleted file mode 100644 index d922193..0000000 --- a/qrcode-scanner-live2/common/BlackPointEstimator.cs +++ /dev/null @@ -1,118 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common -{ - - ///

Encapsulates logic that estimates the optimal "black point", the luminance value - /// which is the best line between "white" and "black" in a grayscale image.

- /// - ///

For an interesting discussion of this issue, see - /// http://webdiis.unizar.es/~neira/12082/thresholding.pdf. - ///

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - /// dswitkin@google.com (Daniel Switkin) - /// - public sealed class BlackPointEstimator - { - private BlackPointEstimator() - { - } - - /** - *

Given an array of counts of luminance values (i.e. a histogram), this method - * decides which bucket of values corresponds to the black point -- which bucket contains the - * count of the brightest luminance values that should be considered "black".

- * - * @param histogram an array of counts of luminance values - * @return index within argument of bucket corresponding to brightest values which should be - * considered "black" - * @throws ReaderException if "black" and "white" appear to be very close in luminance in the image - */ - public static int estimate(int[] histogram) - { - try{ - - int numBuckets = histogram.Length; - int maxBucketCount = 0; - // Find tallest peak in histogram - int firstPeak = 0; - int firstPeakSize = 0; - for (int i = 0; i < numBuckets; i++) { - if (histogram[i] > firstPeakSize) { - firstPeak = i; - firstPeakSize = histogram[i]; - } - if (histogram[i] > maxBucketCount) { - maxBucketCount = histogram[i]; - } - } - - // Find second-tallest peak -- well, another peak that is tall and not - // so close to the first one - int secondPeak = 0; - int secondPeakScore = 0; - for (int i = 0; i < numBuckets; i++) { - int distanceToBiggest = i - firstPeak; - // Encourage more distant second peaks by multiplying by square of distance - int score = histogram[i] * distanceToBiggest * distanceToBiggest; - if (score > secondPeakScore) { - secondPeak = i; - secondPeakScore = score; - } - } - - // Put firstPeak first - if (firstPeak > secondPeak) { - int temp = firstPeak; - firstPeak = secondPeak; - secondPeak = temp; - } - - // Kind of aribtrary; if the two peaks are very close, then we figure there is so little - // dynamic range in the image, that discriminating black and white is too error-prone. - // Decoding the image/line is either pointless, or may in some cases lead to a false positive - // for 1D formats, which are relatively lenient. - // We arbitrarily say "close" is "<= 1/16 of the total histogram buckets apart" - if (secondPeak - firstPeak <= numBuckets >> 4) { - throw new ReaderException(""); - } - - // Find a valley between them that is low and closer to the white peak - int bestValley = secondPeak - 1; - int bestValleyScore = -1; - for (int i = secondPeak - 1; i > firstPeak; i--) { - int fromFirst = i - firstPeak; - // Favor a "valley" that is not too close to either peak -- especially not the black peak -- - // and that has a low value of course - int score = fromFirst * fromFirst * (secondPeak - i) * (maxBucketCount - histogram[i]); - if (score > bestValleyScore) { - bestValley = i; - bestValleyScore = score; - } - } - - return bestValley; - } - catch (Exception e) - { - throw (ReaderException) e; - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/ByteArray.cs b/qrcode-scanner-live2/common/ByteArray.cs deleted file mode 100644 index 5c4d828..0000000 --- a/qrcode-scanner-live2/common/ByteArray.cs +++ /dev/null @@ -1,117 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class ByteArray - { - private static int INITIAL_SIZE = 32; - private sbyte[] bytes; - private int Size; - - public ByteArray() - { - bytes = null; - this.Size = 0; - } - - public ByteArray(int size) - { - bytes = new sbyte[size]; - this.Size = size; - } - - public ByteArray(sbyte[] byteArray) - { - bytes = byteArray; - this.Size = bytes.Length; - } - - /** - * Access an unsigned byte at location index. - * @param index The index in the array to access. - * @return The unsigned value of the byte as an int. - */ - public int at(int index) - { - return bytes[index] & 0xff; - } - - public void set(int index, int value) - { - bytes[index] = (sbyte)value; - } - - public int size() - { - return Size; - } - - public bool empty() - { - return Size == 0; - } - - public void appendByte(int value) - { - if (Size == 0 || Size >= bytes.Length) - { - int newSize = Math.Max(INITIAL_SIZE, Size << 1); - reserve(newSize); - } - bytes[Size] = (sbyte)value; - Size++; - } - - public void reserve(int capacity) - { - if (bytes == null || bytes.Length < capacity) - { - sbyte[] newArray = new sbyte[capacity]; - if (bytes != null) - { - System.Array.Copy(bytes, 0, newArray, 0, bytes.Length); - } - bytes = newArray; - } - } - - // Copy count bytes from array source starting at offset. - public void set(sbyte[] source, int offset, int count) - { - bytes = new sbyte[count]; - Size = count; - for (int x = 0; x < count; x++) - { - bytes[x] = source[offset + x]; - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/ByteMatrix.cs b/qrcode-scanner-live2/common/ByteMatrix.cs deleted file mode 100644 index b1daa72..0000000 --- a/qrcode-scanner-live2/common/ByteMatrix.cs +++ /dev/null @@ -1,115 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class ByteMatrix - { - private sbyte[][] bytes; - private int Height; - private int Width; - - - public ByteMatrix(int height, int width) { - bytes = new sbyte[height][]; - for (int i = 0; i < height; i++) { - bytes[i] = new sbyte[width]; - } - this.Height = height; - this.Width = width; - } - - public int height() - { - return Height; - } - - public int width() - { - return Width; - } - - public sbyte get(int y, int x) - { - return bytes[y][x]; - } - - public sbyte[][] getArray() - { - return bytes; - } - - public void set(int y, int x, sbyte value) - { - bytes[y][x] = value; - } - - public void set(int y, int x, int value) - { - bytes[y][x] = (sbyte)value; - } - - public void clear(sbyte value) - { - for (int y = 0; y < Height; ++y) - { - for (int x = 0; x < Width; ++x) - { - bytes[y][x] = value; - } - } - } - - public String toString() - { - StringBuilder result = new StringBuilder(); - for (int y = 0; y < Height; ++y) - { - for (int x = 0; x < Width; ++x) - { - switch (bytes[y][x]) - { - case 0: - result.Append(" 0"); - break; - case 1: - result.Append(" 1"); - break; - default: - result.Append(" "); - break; - } - } - result.Append('\n'); - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/CharacterSetECI.cs b/qrcode-scanner-live2/common/CharacterSetECI.cs deleted file mode 100644 index 35e0e10..0000000 --- a/qrcode-scanner-live2/common/CharacterSetECI.cs +++ /dev/null @@ -1,101 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - using System.Collections; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class CharacterSetECI : ECI - { - private static Hashtable VALUE_TO_ECI=new Hashtable(29); - /*static VALUE_TO_ECI = new Hashtable(29){ - // TODO figure out if these values are even right! - addCharacterSet(0, "Cp437"); - addCharacterSet(1, "ISO8859_1"); - addCharacterSet(2, "Cp437"); - addCharacterSet(3, "ISO8859_1"); - addCharacterSet(4, "ISO8859_2"); - addCharacterSet(5, "ISO8859_3"); - addCharacterSet(6, "ISO8859_4"); - addCharacterSet(7, "ISO8859_5"); - addCharacterSet(8, "ISO8859_6"); - addCharacterSet(9, "ISO8859_7"); - addCharacterSet(10, "ISO8859_8"); - addCharacterSet(11, "ISO8859_9"); - addCharacterSet(12, "ISO8859_10"); - addCharacterSet(13, "ISO8859_11"); - addCharacterSet(15, "ISO8859_13"); - addCharacterSet(16, "ISO8859_14"); - addCharacterSet(17, "ISO8859_15"); - addCharacterSet(18, "ISO8859_16"); - addCharacterSet(20, "SJIS"); - }*/ - - private String encodingName; - - private CharacterSetECI(int value, String encodingName):base(value) { - addCharacterSet(0, "Cp437"); - addCharacterSet(1, "ISO8859_1"); - addCharacterSet(2, "Cp437"); - addCharacterSet(3, "ISO8859_1"); - addCharacterSet(4, "ISO8859_2"); - addCharacterSet(5, "ISO8859_3"); - addCharacterSet(6, "ISO8859_4"); - addCharacterSet(7, "ISO8859_5"); - addCharacterSet(8, "ISO8859_6"); - addCharacterSet(9, "ISO8859_7"); - addCharacterSet(10, "ISO8859_8"); - addCharacterSet(11, "ISO8859_9"); - addCharacterSet(12, "ISO8859_10"); - addCharacterSet(13, "ISO8859_11"); - addCharacterSet(15, "ISO8859_13"); - addCharacterSet(16, "ISO8859_14"); - addCharacterSet(17, "ISO8859_15"); - addCharacterSet(18, "ISO8859_16"); - addCharacterSet(20, "SJIS"); - this.encodingName = encodingName; - } - - public String getEncodingName() { - return encodingName; - } - - private static void addCharacterSet(int value, String encodingName) { - VALUE_TO_ECI.Add(value, new CharacterSetECI(value, encodingName)); - } - - public static CharacterSetECI getCharacterSetECIByValue(int value) { - CharacterSetECI eci = (CharacterSetECI) VALUE_TO_ECI[value]; - if (eci == null) { - throw new Exception("Unsupported value: " + value); - } - return eci; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/Collections.cs b/qrcode-scanner-live2/common/Collections.cs deleted file mode 100644 index 85e8c74..0000000 --- a/qrcode-scanner-live2/common/Collections.cs +++ /dev/null @@ -1,64 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class Collections - { - - private Collections() - { - } - - /** - * Sorts its argument (destructively) using insert sort; in the context of this package - * insertion sort is simple and efficient given its relatively small inputs. - * - * @param vector vector to sort - * @param comparator comparator to define sort ordering - */ - public static void insertionSort(System.Collections.ArrayList vector, Comparator comparator) - { - int max = vector.Count; - for (int i = 1; i < max; i++) - { - System.Object value_Renamed = vector[i]; - int j = i - 1; - System.Object valueB; - while (j >= 0 && comparator.compare((valueB = vector[j]), value_Renamed) > 0) - { - vector[j + 1] = valueB; - j--; - } - vector[j + 1] = value_Renamed; - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/Comparator.cs b/qrcode-scanner-live2/common/Comparator.cs deleted file mode 100644 index 4d8bc9f..0000000 --- a/qrcode-scanner-live2/common/Comparator.cs +++ /dev/null @@ -1,27 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common -{ - - /// This is merely a clone of Comparator since it is not available in - /// CLDC 1.1 / MIDP 2.0. - /// - public interface Comparator - { - - int compare(System.Object o1, System.Object o2); - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/DecoderResult.cs b/qrcode-scanner-live2/common/DecoderResult.cs deleted file mode 100644 index ad3c81a..0000000 --- a/qrcode-scanner-live2/common/DecoderResult.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class DecoderResult - { - private sbyte[] rawBytes; - private String text; - private System.Collections.ArrayList byteSegments; - - public DecoderResult(sbyte[] rawBytes, String text, System.Collections.ArrayList byteSegments) - { - if (rawBytes == null && text == null) { - throw new Exception(); - } - this.rawBytes = rawBytes; - this.text = text; - this.byteSegments = byteSegments; - } - - public sbyte[] getRawBytes() { - return this.rawBytes; - } - - public String getText() { - return text; - } - - public System.Collections.ArrayList getByteSegments() - { - return byteSegments; - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/DefaultGridSampler.cs b/qrcode-scanner-live2/common/DefaultGridSampler.cs deleted file mode 100644 index 95d1ee0..0000000 --- a/qrcode-scanner-live2/common/DefaultGridSampler.cs +++ /dev/null @@ -1,73 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using MonochromeBitmapSource = com.google.zxing.MonochromeBitmapSource; - using ReaderException = com.google.zxing.ReaderException; - /// Sean Owen - /// - /// - public sealed class DefaultGridSampler : GridSampler - { - - public override BitMatrix sampleGrid(MonochromeBitmapSource image, int dimension, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) - { - PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); - - BitMatrix bits = new BitMatrix(dimension); - float[] points = new float[dimension << 1]; - for (int i = 0; i < dimension; i++) - { - int max = points.Length; - float iValue = (float)i + 0.5f; - for (int j = 0; j < max; j += 2) - { - points[j] = (float)(j >> 1) + 0.5f; - points[j + 1] = iValue; - } - transform.transformPoints(points); - // Quick check to see if points transformed to something inside the image; - // sufficent to check the endpoints - checkAndNudgePoints(image, points); - try - { - for (int j = 0; j < max; j += 2) - { - //UPGRADE_WARNING: Narrowing conversions may produce unexpected results in C#. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1042"' - if (image.isBlack((int)points[j], (int)points[j + 1])) - { - // Black(-ish) pixel - bits.set(i, j >> 1); - } - } - } - catch (System.IndexOutOfRangeException aioobe) - { - // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting - // transform gets "twisted" such that it maps a straight line of points to a set of points - // whose endpoints are in bounds, but others are not. There is probably some mathematical - // way to detect this about the transformation that I don't know yet. - // This results in an ugly runtime exception despite our clever checks above -- can't have that. - // We could check each point's coordinates but that feels duplicative. We settle for - // catching and wrapping ArrayIndexOutOfBoundsException. - throw new ReaderException(aioobe.Message); - } - } - return bits; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/DetectorResult.cs b/qrcode-scanner-live2/common/DetectorResult.cs deleted file mode 100644 index bce786a..0000000 --- a/qrcode-scanner-live2/common/DetectorResult.cs +++ /dev/null @@ -1,51 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class DetectorResult - { - private BitMatrix bits; - private ResultPoint[] points; - - public DetectorResult(BitMatrix bits, ResultPoint[] points) { - this.bits = bits; - this.points = points; - } - - public BitMatrix getBits() { - return bits; - } - - public ResultPoint[] getPoints() { - return points; - } - } -} diff --git a/qrcode-scanner-live2/common/ECI.cs b/qrcode-scanner-live2/common/ECI.cs deleted file mode 100644 index 05f8dc6..0000000 --- a/qrcode-scanner-live2/common/ECI.cs +++ /dev/null @@ -1,56 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public abstract class ECI - { - private int value; - - public ECI(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - - public static ECI getECIByValue(int value) { - if (value < 0 || value > 999999) { - throw new Exception("Bad ECI value: " + value); - } - if (value < 900) { // Character set ECIs use 000000 - 000899 - return CharacterSetECI.getCharacterSetECIByValue(value); - } - throw new Exception("Unsupported ECI value: " + value); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/GenericResultPoint.cs b/qrcode-scanner-live2/common/GenericResultPoint.cs deleted file mode 100644 index 3a3c20a..0000000 --- a/qrcode-scanner-live2/common/GenericResultPoint.cs +++ /dev/null @@ -1,136 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using System.Text; - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// * - /// JAVAPORT: I'm not happy about the argument ordering throughout the file, as I always like to have - /// the horizontal component first, but this is for compatibility with the C++ code. The original - /// code was a 2D array of ints, but since it only ever gets assigned -1, 0, and 1, I'm going to use - /// less memory and go with bytes. - /// * - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// - public sealed class GenericResultPoint : ResultPoint - { - private float posX; - private float posY; - - public GenericResultPoint(float posX, float posY) { - this.posX = posX; - this.posY = posY; - } - - public float getX() { - return posX; - } - - public float getY() { - return posY; - } - - public String toString() { - StringBuilder result = new StringBuilder(25); - result.Append('('); - result.Append(posX); - result.Append(','); - result.Append(posY); - result.Append(')'); - return result.ToString(); - } - - public bool equals(Object other) { - - if (other.GetType() == typeof(GenericResultPoint)) { - GenericResultPoint otherPoint = (GenericResultPoint) other; - return posX == otherPoint.posX && posY == otherPoint.posY; - } - return false; - } - - public int hashCode() { - return 31 * posX.GetHashCode() + posY.GetHashCode(); - } - - /** - *

Orders an array of three ResultPoints in an order [A,B,C] such that AB < AC and - * BC < AC and the angle between BC and BA is less than 180 degrees. - */ - public static void orderBestPatterns(ResultPoint[] patterns) { - - // Find distances between pattern centers - float zeroOneDistance = distance(patterns[0], patterns[1]); - float oneTwoDistance = distance(patterns[1], patterns[2]); - float zeroTwoDistance = distance(patterns[0], patterns[2]); - - ResultPoint pointA, pointB, pointC; - // Assume one closest to other two is B; A and C will just be guesses at first - if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) { - pointB = patterns[0]; - pointA = patterns[1]; - pointC = patterns[2]; - } else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) { - pointB = patterns[1]; - pointA = patterns[0]; - pointC = patterns[2]; - } else { - pointB = patterns[2]; - pointA = patterns[0]; - pointC = patterns[1]; - } - - // Use cross product to figure out whether A and C are correct or flipped. - // This asks whether BC x BA has a positive z component, which is the arrangement - // we want for A, B, C. If it's negative, then we've got it flipped around and - // should swap A and C. - if (crossProductZ(pointA, pointB, pointC) < 0.0f) { - ResultPoint temp = pointA; - pointA = pointC; - pointC = temp; - } - - patterns[0] = pointA; - patterns[1] = pointB; - patterns[2] = pointC; - } - - - /** - * @return distance between two points - */ - public static float distance(ResultPoint pattern1, ResultPoint pattern2) { - float xDiff = pattern1.getX() - pattern2.getX(); - float yDiff = pattern1.getY() - pattern2.getY(); - return (float) Math.Sqrt((double) (xDiff * xDiff + yDiff * yDiff)); - } - - /** - * Returns the z component of the cross product between vectors BC and BA. - */ - public static float crossProductZ(ResultPoint pointA, ResultPoint pointB, ResultPoint pointC) { - float bX = pointB.getX(); - float bY = pointB.getY(); - return ((pointC.getX() - bX) * (pointA.getY() - bY)) - ((pointC.getY() - bY) * (pointA.getX() - bX)); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/GridSampler.cs b/qrcode-scanner-live2/common/GridSampler.cs deleted file mode 100644 index 1964708..0000000 --- a/qrcode-scanner-live2/common/GridSampler.cs +++ /dev/null @@ -1,168 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - using MonochromeBitmapSource = com.google.zxing.MonochromeBitmapSource; - using ReaderException = com.google.zxing.ReaderException; - ///

Implementations of this class can, given locations of finder patterns for a QR code in an - /// image, sample the right points in the image to reconstruct the QR code, accounting for - /// perspective distortion. It is abstracted since it is relatively expensive and should be allowed - /// to take advantage of platform-specific optimized implementations, like Sun's Java Advanced - /// Imaging library, but which may not be available in other environments such as J2ME, and vice - /// versa. - /// * - /// The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)} - /// with an instance of a class which implements this interface. - /// * - /// - /// Sean Owen - /// - /// - public abstract class GridSampler - { - public static GridSampler Instance - { - get - { - // No real point in trying to make this thread-safe; - // doesn't matter if a second instance is created - if (gridSampler == null) - { - gridSampler = new DefaultGridSampler(); - } - return gridSampler; - } - - } - - private static GridSampler gridSampler = null; - ///

Samples an image for a square matrix of bits of the given dimension. This is used to extract the - /// black/white modules of a 2D barcode like a QR Code found in an image. Because this barcode may be - /// rotated or perspective-distorted, the caller supplies four points in the source image that define - /// known points in the barcode, so that the image may be sampled appropriately.

- /// * - ///

The last eight "from" parameters are four X/Y coordinate pairs of locations of points in - /// the image that define some significant points in the image to be sample. For example, - /// these may be the location of finder pattern in a QR Code.

- /// * - ///

The first eight "to" parameters are four X/Y coordinate pairs measured in the destination - /// {@link BitMatrix}, from the top left, where the known points in the image given by the "from" parameters - /// map to.

- /// * - ///

These 16 parameters define the transformation needed to sample the image.

- /// * - ///
- /// image to sample - /// - /// width/height of {@link BitMatrix} to sample from iamge - /// - /// {@link BitMatrix} representing a grid of points sampled from the image within a region - /// defined by the "from" parameters - /// @throws ReaderException if image can't be sampled, for example, if the transformation defined by - /// the given points is invalid or results in sampling outside the image boundaries - /// - /// - public abstract BitMatrix sampleGrid(MonochromeBitmapSource image, int dimension, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY); - - ///

Checks a set of points that have been transformed to sample points on an image against - /// the image's dimensions to see if the point are even within the image.

- /// * - ///

This method will actually "nudge" the endpoints back onto the image if they are found to be barely - /// (less than 1 pixel) off the image. This accounts for imperfect detection of finder patterns in an image - /// where the QR Code runs all the way to the image border.

- /// * - ///

For efficiency, the method will check points from either end of the line until one is found - /// to be within the image. Because the set of points are assumed to be linear, this is valid.

- /// * - ///
- /// image into which the points should map - /// - /// actual points in x1,y1,...,xn,yn form - /// @throws ReaderException if an endpoint is lies outside the image boundaries - /// - /// - protected internal static void checkAndNudgePoints(MonochromeBitmapSource image, float[] points) - { - int width = image.getWidth(); - int height = image.getHeight(); - // Check and nudge points from start until we see some that are OK: - bool nudged = true; - for (int offset = 0; offset < points.Length && nudged; offset += 2) - { - int x = (int)points[offset]; - int y = (int)points[offset + 1]; - if (x < -1 || x > width || y < -1 || y > height) - { - throw new ReaderException(""); - } - nudged = false; - if (x == -1) - { - points[offset] = 0.0f; - nudged = true; - } - else if (x == width) - { - points[offset] = width - 1; - nudged = true; - } - if (y == -1) - { - points[offset + 1] = 0.0f; - nudged = true; - } - else if (y == height) - { - points[offset + 1] = height - 1; - nudged = true; - } - } - // Check and nudge points from end: - nudged = true; - for (int offset = points.Length - 2; offset >= 0 && nudged; offset -= 2) - { - int x = (int)points[offset]; - int y = (int)points[offset + 1]; - if (x < -1 || x > width || y < -1 || y > height) - { - throw new ReaderException(""); - } - nudged = false; - if (x == -1) - { - points[offset] = 0.0f; - nudged = true; - } - else if (x == width) - { - points[offset] = width - 1; - nudged = true; - } - if (y == -1) - { - points[offset + 1] = 0.0f; - nudged = true; - } - else if (y == height) - { - points[offset + 1] = height - 1; - nudged = true; - } - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/PerspectiveTransform.cs b/qrcode-scanner-live2/common/PerspectiveTransform.cs deleted file mode 100644 index a42a83e..0000000 --- a/qrcode-scanner-live2/common/PerspectiveTransform.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.common -{ - using System; - - ///

This class implements a perspective transform in two dimensions. Given four source and four destination - /// points, it will compute the transformation implied between them. The code is based directly upon section - /// 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.

- /// * - ///
- /// Sean Owen - /// - /// - sealed class PerspectiveTransform - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'a11 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a12 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a13 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a21 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a22 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a23 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a31 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a32 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - //UPGRADE_NOTE: Final was removed from the declaration of 'a33 '. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1003"' - private float a11; - private float a12; - private float a13; - private float a21; - private float a22; - private float a23; - private float a31; - private float a32; - private float a33; - - private PerspectiveTransform(float a11, float a21, float a31, float a12, float a22, float a32, float a13, float a23, float a33) - { - this.a11 = a11; - this.a12 = a12; - this.a13 = a13; - this.a21 = a21; - this.a22 = a22; - this.a23 = a23; - this.a31 = a31; - this.a32 = a32; - this.a33 = a33; - } - - internal static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x3p, float y3p) - { - - PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); - PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); - return sToQ.times(qToS); - } - - internal void transformPoints(float[] points) - { - int max = points.Length; - float a11 = this.a11; - float a12 = this.a12; - float a13 = this.a13; - float a21 = this.a21; - float a22 = this.a22; - float a23 = this.a23; - float a31 = this.a31; - float a32 = this.a32; - float a33 = this.a33; - for (int i = 0; i < max; i += 2) - { - float x = points[i]; - float y = points[i + 1]; - float denominator = a13 * x + a23 * y + a33; - points[i] = (a11 * x + a21 * y + a31) / denominator; - points[i + 1] = (a12 * x + a22 * y + a32) / denominator; - } - } - - internal static PerspectiveTransform squareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) - { - float dy2 = y3 - y2; - float dy3 = y0 - y1 + y2 - y3; - if (dy2 == 0.0f && dy3 == 0.0f) - { - return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0f, 0.0f, 1.0f); - } - else - { - float dx1 = x1 - x2; - float dx2 = x3 - x2; - float dx3 = x0 - x1 + x2 - x3; - float dy1 = y1 - y2; - float denominator = dx1 * dy2 - dx2 * dy1; - float a13 = (dx3 * dy2 - dx2 * dy3) / denominator; - float a23 = (dx1 * dy3 - dx3 * dy1) / denominator; - return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0f); - } - } - - private static PerspectiveTransform quadrilateralToSquare(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) - { - // Here, the adjoint serves as the inverse: - return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); - } - - internal PerspectiveTransform buildAdjoint() - { - // Adjoint is the transpose of the cofactor matrix: - return new PerspectiveTransform(a22 * a33 - a23 * a32, a23 * a31 - a21 * a33, a21 * a32 - a22 * a31, a13 * a32 - a12 * a33, a11 * a33 - a13 * a31, a12 * a31 - a11 * a32, a12 * a23 - a13 * a22, a13 * a21 - a11 * a23, a11 * a22 - a12 * a21); - } - - internal PerspectiveTransform times(PerspectiveTransform other) - { - return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13, a11 * other.a21 + a21 * other.a22 + a31 * other.a23, a11 * other.a31 + a21 * other.a32 + a31 * other.a33, a12 * other.a11 + a22 * other.a12 + a32 * other.a13, a12 * other.a21 + a22 * other.a22 + a32 * other.a23, a12 * other.a31 + a22 * other.a32 + a32 * other.a33, a13 * other.a11 + a23 * other.a12 + a33 * other.a13, a13 * other.a21 + a23 * other.a22 + a33 * other.a23, a13 * other.a31 + a23 * other.a32 + a33 * other.a33); - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/reedsolomon/GF256.cs b/qrcode-scanner-live2/common/reedsolomon/GF256.cs deleted file mode 100644 index f1aaeb3..0000000 --- a/qrcode-scanner-live2/common/reedsolomon/GF256.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

This class contains utility methods for performing mathematical operations over - /// the Galois Field GF(256). Operations use the primitive polynomial - /// x^8 + x^4 + x^3 + x^2 + 1 in calculations.

- /// - ///

Throughout this package, elements of GF(256) are represented as an int - /// for convenience and speed (but at the cost of memory). - /// Only the bottom 8 bits are really used.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public sealed class GF256 - { - public static GF256 QR_CODE_FIELD = new GF256(0x011D); // x^8 + x^4 + x^3 + x^2 + 1 - public static GF256 DATA_MATRIX_FIELD = new GF256(0x012D); // x^8 + x^5 + x^3 + x^2 + 1 - - private int[] expTable; - private int[] logTable; - private GF256Poly zero; - private GF256Poly one; - - /** - * Create a representation of GF(256) using the given primitive polynomial. - * - * @param primitive irreducible polynomial whose coefficients are represented by - * the bits of an int, where the least-significant bit represents the constant - * coefficient - */ - private GF256(int primitive) { - expTable = new int[256]; - logTable = new int[256]; - int x = 1; - for (int i = 0; i < 256; i++) { - expTable[i] = x; - x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 - if (x >= 0x100) { - x ^= primitive; - } - } - for (int i = 0; i < 255; i++) { - logTable[expTable[i]] = i; - } - // logTable[0] == 0 but this should never be used - zero = new GF256Poly(this, new int[]{0}); - one = new GF256Poly(this, new int[]{1}); - } - - public GF256Poly getZero() { - return zero; - } - - public GF256Poly getOne() - { - return one; - } - - /** - * @return the monomial representing coefficient * x^degree - */ - public GF256Poly buildMonomial(int degree, int coefficient) - { - if (degree < 0) { - throw new ArgumentException(); - } - if (coefficient == 0) { - return zero; - } - int[] coefficients = new int[degree + 1]; - coefficients[0] = coefficient; - return new GF256Poly(this, coefficients); - } - - /** - * Implements both addition and subtraction -- they are the same in GF(256). - * - * @return sum/difference of a and b - */ - public static int addOrSubtract(int a, int b) { - return a ^ b; - } - - /** - * @return 2 to the power of a in GF(256) - */ - public int exp(int a) - { - return expTable[a]; - } - - /** - * @return base 2 log of a in GF(256) - */ - public int log(int a) - { - if (a == 0) { - throw new ArgumentException(); - } - return logTable[a]; - } - - /** - * @return multiplicative inverse of a - */ - public int inverse(int a) - { - if (a == 0) { - throw new ArithmeticException(); - } - return expTable[255 - logTable[a]]; - } - - /** - * @param a - * @param b - * @return product of a and b in GF(256) - */ - public int multiply(int a, int b) - { - if (a == 0 || b == 0) { - return 0; - } - if (a == 1) { - return b; - } - if (b == 1) { - return a; - } - return expTable[(logTable[a] + logTable[b]) % 255]; - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/reedsolomon/GF256Poly.cs b/qrcode-scanner-live2/common/reedsolomon/GF256Poly.cs deleted file mode 100644 index 86eb3d3..0000000 --- a/qrcode-scanner-live2/common/reedsolomon/GF256Poly.cs +++ /dev/null @@ -1,274 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Text; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Represents a polynomial whose coefficients are elements of GF(256). - /// Instances of this class are immutable.

- /// - ///

Much credit is due to William Rucklidge since portions of this code are an indirect - /// port of his C++ Reed-Solomon implementation.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public sealed class GF256Poly - { - private GF256 field; - private int[] coefficients; - - /** - * @param field the {@link GF256} instance representing the field to use - * to perform computations - * @param coefficients coefficients as ints representing elements of GF(256), arranged - * from most significant (highest-power term) coefficient to least significant - * @throws ArgumentException if argument is null or empty, - * or if leading coefficient is 0 and this is not a - * constant polynomial (that is, it is not the monomial "0") - */ - public GF256Poly(GF256 field, int[] coefficients) { - if (coefficients == null || coefficients.Length == 0) { - throw new ArgumentException(); - } - this.field = field; - int coefficientsLength = coefficients.Length; - if (coefficientsLength > 1 && coefficients[0] == 0) { - // Leading term must be non-zero for anything except the constant polynomial "0" - int firstNonZero = 1; - while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) { - firstNonZero++; - } - if (firstNonZero == coefficientsLength) { - this.coefficients = field.getZero().coefficients; - } else { - this.coefficients = new int[coefficientsLength - firstNonZero]; - System.Array.Copy(coefficients,firstNonZero,this.coefficients,0,this.coefficients.Length); - } - } else { - this.coefficients = coefficients; - } - } - - public int[] getCoefficients() - { - return coefficients; - } - - /** - * @return degree of this polynomial - */ - public int getDegree() - { - return coefficients.Length - 1; - } - - /** - * @return true iff this polynomial is the monomial "0" - */ - public bool isZero() - { - return coefficients[0] == 0; - } - - /** - * @return coefficient of x^degree term in this polynomial - */ - public int getCoefficient(int degree) - { - return coefficients[coefficients.Length - 1 - degree]; - } - - /** - * @return evaluation of this polynomial at a given point - */ - public int evaluateAt(int a) - { - if (a == 0) { - // Just return the x^0 coefficient - return getCoefficient(0); - } - int size = coefficients.Length; - int result = 0; - - if (a == 1) { - // Just the sum of the coefficients - result = 0; - for (int i = 0; i < size; i++) { - result = GF256.addOrSubtract(result, coefficients[i]); - } - return result; - } - - result = coefficients[0]; - for (int i = 1; i < size; i++) { - result = GF256.addOrSubtract(field.multiply(a, result), coefficients[i]); - } - return result; - } - - public GF256Poly addOrSubtract(GF256Poly other) - { - if (!field.Equals(other.field)) { - throw new ArgumentException("GF256Polys do not have same GF256 field"); - } - if (isZero()) { - return other; - } - if (other.isZero()) { - return this; - } - - int[] smallerCoefficients = this.coefficients; - int[] largerCoefficients = other.coefficients; - if (smallerCoefficients.Length > largerCoefficients.Length) { - int[] temp = smallerCoefficients; - smallerCoefficients = largerCoefficients; - largerCoefficients = temp; - } - int[] sumDiff = new int[largerCoefficients.Length]; - int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length; - // Copy high-order terms only found in higher-degree polynomial's coefficients - System.Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); - - for (int i = lengthDiff; i < largerCoefficients.Length; i++) { - sumDiff[i] = GF256.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); - } - - return new GF256Poly(field, sumDiff); - } - - public GF256Poly multiply(GF256Poly other) - { - if (!field.Equals(other.field)) { - throw new ArgumentException("GF256Polys do not have same GF256 field"); - } - if (isZero() || other.isZero()) { - return field.getZero(); - } - int[] aCoefficients = this.coefficients; - int aLength = aCoefficients.Length; - int[] bCoefficients = other.coefficients; - int bLength = bCoefficients.Length; - int[] product = new int[aLength + bLength - 1]; - for (int i = 0; i < aLength; i++) { - int aCoeff = aCoefficients[i]; - for (int j = 0; j < bLength; j++) { - product[i + j] = GF256.addOrSubtract(product[i + j], - field.multiply(aCoeff, bCoefficients[j])); - } - } - return new GF256Poly(field, product); - } - - public GF256Poly multiply(int scalar) - { - if (scalar == 0) { - return field.getZero(); - } - if (scalar == 1) { - return this; - } - int size = coefficients.Length; - int[] product = new int[size]; - for (int i = 0; i < size; i++) { - product[i] = field.multiply(coefficients[i], scalar); - } - return new GF256Poly(field, product); - } - - public GF256Poly multiplyByMonomial(int degree, int coefficient) - { - if (degree < 0) { - throw new ArgumentException(); - } - if (coefficient == 0) { - return field.getZero(); - } - int size = coefficients.Length; - int[] product = new int[size + degree]; - for (int i = 0; i < size; i++) { - product[i] = field.multiply(coefficients[i], coefficient); - } - return new GF256Poly(field, product); - } - - public GF256Poly[] divide(GF256Poly other) - { - if (!field.Equals(other.field)) { - throw new ArgumentException("GF256Polys do not have same GF256 field"); - } - if (other.isZero()) { - throw new ArgumentException("Divide by 0"); - } - - GF256Poly quotient = field.getZero(); - GF256Poly remainder = this; - - int denominatorLeadingTerm = other.getCoefficient(other.getDegree()); - int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm); - - while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) { - int degreeDifference = remainder.getDegree() - other.getDegree(); - int scale = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm); - GF256Poly term = other.multiplyByMonomial(degreeDifference, scale); - GF256Poly iterationQuotient = field.buildMonomial(degreeDifference, scale); - quotient = quotient.addOrSubtract(iterationQuotient); - remainder = remainder.addOrSubtract(term); - } - - return new GF256Poly[] { quotient, remainder }; - } - - public String toString() { - StringBuilder result = new StringBuilder(8 * getDegree()); - for (int degree = getDegree(); degree >= 0; degree--) { - int coefficient = getCoefficient(degree); - if (coefficient != 0) { - if (coefficient < 0) { - result.Append(" - "); - coefficient = -coefficient; - } else { - if (result.Length > 0) { - result.Append(" + "); - } - } - if (degree == 0 || coefficient != 1) { - int alphaPower = field.log(coefficient); - if (alphaPower == 0) { - result.Append('1'); - } else if (alphaPower == 1) { - result.Append('a'); - } else { - result.Append("a^"); - result.Append(alphaPower); - } - } - if (degree != 0) { - if (degree == 1) { - result.Append('x'); - } else { - result.Append("x^"); - result.Append(degree); - } - } - } - } - return result.ToString(); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/reedsolomon/ReedSolomonDecoder.cs b/qrcode-scanner-live2/common/reedsolomon/ReedSolomonDecoder.cs deleted file mode 100644 index 0ab74eb..0000000 --- a/qrcode-scanner-live2/common/reedsolomon/ReedSolomonDecoder.cs +++ /dev/null @@ -1,195 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Implements Reed-Solomon decoding, as the name implies.

- /// - ///

The algorithm will not be explained here, but the following references were helpful - /// in creating this implementation:

- /// - /// - /// - ///

Much credit is due to William Rucklidge since portions of this code are an indirect - /// port of his C++ Reed-Solomon implementation.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - /// William Rucklidge - /// - public sealed class ReedSolomonDecoder - { - private GF256 field; - - public ReedSolomonDecoder(GF256 field) { - this.field = field; - } - - /** - *

Decodes given set of received codewords, which include both data and error-correction - * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place, - * in the input.

- * - * @param received data and error-correction codewords - * @param twoS number of error-correction codewords available - * @throws ReedSolomonException if decoding fails for any reason - */ - public void decode(int[] received, int twoS) { - try{ - - - GF256Poly poly = new GF256Poly(field, received); - int[] syndromeCoefficients = new int[twoS]; - bool dataMatrix = field.Equals(GF256.DATA_MATRIX_FIELD); - bool noError = true; - for (int i = 0; i < twoS; i++) { - // Thanks to sanfordsquires for this fix: - int eval = poly.evaluateAt(field.exp(dataMatrix ? i + 1 : i)); - syndromeCoefficients[syndromeCoefficients.Length - 1 - i] = eval; - if (eval != 0) { - noError = false; - } - } - if (noError) { - return; - } - GF256Poly syndrome = new GF256Poly(field, syndromeCoefficients); - GF256Poly[] sigmaOmega = - runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS); - GF256Poly sigma = sigmaOmega[0]; - GF256Poly omega = sigmaOmega[1]; - int[] errorLocations = findErrorLocations(sigma); - int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations, dataMatrix); - for (int i = 0; i < errorLocations.Length; i++) { - int position = received.Length - 1 - field.log(errorLocations[i]); - if (position < 0) { - throw new ReedSolomonException("Bad error location"); - } - received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]); - } - }catch(ReedSolomonException e){ - throw new ReedSolomonException(e.Message); - } - } - - private GF256Poly[] runEuclideanAlgorithm(GF256Poly a, GF256Poly b, int R){ - // Assume a's degree is >= b's - if (a.getDegree() < b.getDegree()) { - GF256Poly temp = a; - a = b; - b = temp; - } - - GF256Poly rLast = a; - GF256Poly r = b; - GF256Poly sLast = field.getOne(); - GF256Poly s = field.getZero(); - GF256Poly tLast = field.getZero(); - GF256Poly t = field.getOne(); - - // Run Euclidean algorithm until r's degree is less than R/2 - while (r.getDegree() >= R / 2) { - GF256Poly rLastLast = rLast; - GF256Poly sLastLast = sLast; - GF256Poly tLastLast = tLast; - rLast = r; - sLast = s; - tLast = t; - - // Divide rLastLast by rLast, with quotient in q and remainder in r - if (rLast.isZero()) { - // Oops, Euclidean algorithm already terminated? - throw new ReedSolomonException("r_{i-1} was zero"); - } - r = rLastLast; - GF256Poly q = field.getZero(); - int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree()); - int dltInverse = field.inverse(denominatorLeadingTerm); - while (r.getDegree() >= rLast.getDegree() && !r.isZero()) { - int degreeDiff = r.getDegree() - rLast.getDegree(); - int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse); - q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale)); - r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); - } - - s = q.multiply(sLast).addOrSubtract(sLastLast); - t = q.multiply(tLast).addOrSubtract(tLastLast); - } - - int sigmaTildeAtZero = t.getCoefficient(0); - if (sigmaTildeAtZero == 0) { - throw new ReedSolomonException("sigmaTilde(0) was zero"); - } - - int inverse = field.inverse(sigmaTildeAtZero); - GF256Poly sigma = t.multiply(inverse); - GF256Poly omega = r.multiply(inverse); - return new GF256Poly[]{sigma, omega}; - } - - private int[] findErrorLocations(GF256Poly errorLocator){ - // This is a direct application of Chien's search - int numErrors = errorLocator.getDegree(); - if (numErrors == 1) { // shortcut - return new int[] { errorLocator.getCoefficient(1) }; - } - int[] result = new int[numErrors]; - int e = 0; - for (int i = 1; i < 256 && e < numErrors; i++) { - if (errorLocator.evaluateAt(i) == 0) { - result[e] = field.inverse(i); - e++; - } - } - if (e != numErrors) { - throw new ReedSolomonException("Error locator degree does not match number of roots"); - } - return result; - } - - private int[] findErrorMagnitudes(GF256Poly errorEvaluator, int[] errorLocations, bool dataMatrix) { - // This is directly applying Forney's Formula - int s = errorLocations.Length; - int[] result = new int[s]; - for (int i = 0; i < s; i++) { - int xiInverse = field.inverse(errorLocations[i]); - int denominator = 1; - for (int j = 0; j < s; j++) { - if (i != j) { - denominator = field.multiply(denominator, - GF256.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse))); - } - } - result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), - field.inverse(denominator)); - // Thanks to sanfordsquires for this fix: - if (dataMatrix) { - result[i] = field.multiply(result[i], xiInverse); - } - } - return result; - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/reedsolomon/ReedSolomonEncoder.cs b/qrcode-scanner-live2/common/reedsolomon/ReedSolomonEncoder.cs deleted file mode 100644 index db76156..0000000 --- a/qrcode-scanner-live2/common/reedsolomon/ReedSolomonEncoder.cs +++ /dev/null @@ -1,70 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using System.Collections; - -namespace com.google.zxing.common.reedsolomon -{ - public sealed class ReedSolomonEncoder - { - private GF256 Field; - private ArrayList cachedGenerators; - - public ReedSolomonEncoder(GF256 field) { - if (!GF256.QR_CODE_FIELD.Equals(field)) { - throw new ArgumentException("Only QR Code is supported at this time"); - } - this.Field = field; - this.cachedGenerators = new ArrayList(); - cachedGenerators.Add(new GF256Poly(field, new int[] { 1 })); - } - - private GF256Poly buildGenerator(int degree) { - if (degree >= cachedGenerators.Count) { - GF256Poly lastGenerator = (GF256Poly)cachedGenerators[(cachedGenerators.Count - 1)]; - for (int d = cachedGenerators.Count; d <= degree; d++) - { - GF256Poly nextGenerator = lastGenerator.multiply(new GF256Poly(Field, new int[] { 1, Field.exp(d - 1) })); - cachedGenerators.Add(nextGenerator); - lastGenerator = nextGenerator; - } - } - return (GF256Poly) cachedGenerators[(degree)]; - } - - public void encode(int[] toEncode, int ecBytes) { - if (ecBytes == 0) { - throw new ArgumentException("No error correction bytes"); - } - int dataBytes = toEncode.Length - ecBytes; - if (dataBytes <= 0) { - throw new ArgumentException("No data bytes provided"); - } - GF256Poly generator = buildGenerator(ecBytes); - int[] infoCoefficients = new int[dataBytes]; - System.Array.Copy(toEncode, 0, infoCoefficients, 0, dataBytes); - GF256Poly info = new GF256Poly(this.Field, infoCoefficients); - info = info.multiplyByMonomial(ecBytes, 1); - GF256Poly remainder = info.divide(generator)[1]; - int[] coefficients = remainder.getCoefficients(); - int numZeroCoefficients = ecBytes - coefficients.Length; - for (int i = 0; i < numZeroCoefficients; i++) { - toEncode[dataBytes + i] = 0; - } - System.Array.Copy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.Length); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/common/reedsolomon/ReedSolomonException.cs b/qrcode-scanner-live2/common/reedsolomon/ReedSolomonException.cs deleted file mode 100644 index e965339..0000000 --- a/qrcode-scanner-live2/common/reedsolomon/ReedSolomonException.cs +++ /dev/null @@ -1,38 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Thrown when an exception occurs during Reed-Solomon decoding, such as when - /// there are too many errors to correct.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - //[Serializable] - public sealed class ReedSolomonException : System.Exception - { - - public ReedSolomonException() - { - } - - public ReedSolomonException(System.String message) - : base(message) - { - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/datamatrix/DataMatrixReader.cs b/qrcode-scanner-live2/datamatrix/DataMatrixReader.cs deleted file mode 100644 index 4c87612..0000000 --- a/qrcode-scanner-live2/datamatrix/DataMatrixReader.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.datamatrix.decoder; -using com.google.zxing.datamatrix.detector; - -namespace com.google.zxing.datamatrix -{ - public sealed class DataMatrixReader - { - private static ResultPoint[] NO_POINTS = new ResultPoint[0]; - private Decoder decoder = new Decoder(); - - /** - * Locates and decodes a Data Matrix code in an image. - * - * @return a String representing the content encoded by the Data Matrix code - * @throws ReaderException if a Data Matrix code cannot be found, or cannot be decoded - */ - public Result decode(MonochromeBitmapSource image) { - return decode(image, null); - } - - public Result decode(MonochromeBitmapSource image, System.Collections.Hashtable hints) - { - DecoderResult decoderResult; - ResultPoint[] points; - if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) { - BitMatrix bits = extractPureBits(image); - decoderResult = decoder.decode(bits); - points = NO_POINTS; - } else { - DetectorResult detectorResult = new Detector(image).detect(); - decoderResult = decoder.decode(detectorResult.getBits()); - points = detectorResult.getPoints(); - } - Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.DATAMATRIX); - if (decoderResult.getByteSegments() != null) { - result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.getByteSegments()); - } - return result; - } - - /** - * This method detects a Data Matrix code in a "pure" image -- that is, pure monochrome image - * which contains only an unrotated, unskewed, image of a Data Matrix code, with some white border - * around it. This is a specialized method that works exceptionally fast in this special - * case. - */ - private static BitMatrix extractPureBits(MonochromeBitmapSource image) { - // Now need to determine module size in pixels - - int height = image.getHeight(); - int width = image.getWidth(); - int minDimension = Math.Min(height, width); - - // First, skip white border by tracking diagonally from the top left down and to the right: - int borderWidth = 0; - while (borderWidth < minDimension && !image.isBlack(borderWidth, borderWidth)) { - borderWidth++; - } - if (borderWidth == minDimension) { - throw new ReaderException(); - } - - // And then keep tracking across the top-left black module to determine module size - int moduleEnd = borderWidth + 1; - while (moduleEnd < width && image.isBlack(moduleEnd, borderWidth)) { - moduleEnd++; - } - if (moduleEnd == width) { - throw new ReaderException(); - } - - int moduleSize = moduleEnd - borderWidth; - - // And now find where the bottommost black module on the first column ends - int columnEndOfSymbol = height - 1; - while (columnEndOfSymbol >= 0 && !image.isBlack(borderWidth, columnEndOfSymbol)) { - columnEndOfSymbol--; - } - if (columnEndOfSymbol < 0) { - throw new ReaderException(); - } - columnEndOfSymbol++; - - // Make sure width of barcode is a multiple of module size - if ((columnEndOfSymbol - borderWidth) % moduleSize != 0) { - throw new ReaderException(); - } - int dimension = (columnEndOfSymbol - borderWidth) / moduleSize; - - // Push in the "border" by half the module width so that we start - // sampling in the middle of the module. Just in case the image is a - // little off, this will help recover. - borderWidth += moduleSize >> 1; - - int sampleDimension = borderWidth + (dimension - 1) * moduleSize; - if (sampleDimension >= width || sampleDimension >= height) { - throw new ReaderException(); - } - - // Now just read off the bits - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) { - int iOffset = borderWidth + i * moduleSize; - for (int j = 0; j < dimension; j++) { - if (image.isBlack(borderWidth + j * moduleSize, iOffset)) { - bits.set(i, j); - } - } - } - return bits; - } - } -} diff --git a/qrcode-scanner-live2/datamatrix/decoder/BitMatrixParser.cs b/qrcode-scanner-live2/datamatrix/decoder/BitMatrixParser.cs deleted file mode 100644 index 653810a..0000000 --- a/qrcode-scanner-live2/datamatrix/decoder/BitMatrixParser.cs +++ /dev/null @@ -1,450 +0,0 @@ -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using com.google.zxing.common; - -namespace com.google.zxing.datamatrix.decoder -{ - /** - * @author bbrown@google.com (Brian Brown) - */ - public sealed class BitMatrixParser - { - - private BitMatrix mappingBitMatrix; - private BitMatrix readMappingMatrix; - private Version version; - - /** - * @param bitMatrix {@link BitMatrix} to parse - * @throws ReaderException if dimension is < 10 or > 144 or not 0 mod 2 - */ - public BitMatrixParser(BitMatrix bitMatrix) { - int dimension = bitMatrix.getDimension(); - if (dimension < 10 || dimension > 144 || (dimension & 0x01) != 0) { - throw new ReaderException(); - } - - version = readVersion(bitMatrix); - this.mappingBitMatrix = extractDataRegion(bitMatrix); - // TODO(bbrown): Make this work for rectangular symbols - this.readMappingMatrix = new BitMatrix(this.mappingBitMatrix.getDimension()); - } - - /** - *

Creates the version object based on the dimension of the original bit matrix from - * the datamatrix code.

- * - *

See ISO 16022:2006 Table 7 - ECC 200 symbol attributes

- * - * @param bitMatrix Original {@link BitMatrix} including alignment patterns - * @return {@link Version} encapsulating the Data Matrix Code's "version" - * @throws ReaderException if the dimensions of the mapping matrix are not valid - * Data Matrix dimensions. - */ - public Version readVersion(BitMatrix bitMatrix) { - - if (version != null) { - return version; - } - - // TODO(bbrown): make this work for rectangular dimensions as well. - int numRows = bitMatrix.getDimension(); - int numColumns = numRows; - - return Version.getVersionForDimensions(numRows, numColumns); - } - - /** - *

Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns) - * in the correct order in order to reconstitute the codewords bytes contained within the - * Data Matrix Code.

- * - * @return bytes encoded within the Data Matrix Code - * @throws ReaderException if the exact number of bytes expected is not read - */ - public sbyte[] readCodewords() { - - sbyte[] result = new sbyte[version.getTotalCodewords()]; - int resultOffset = 0; - - int row = 4; - int column = 0; - // TODO(bbrown): Data Matrix can be rectangular, assuming square for now - int numRows = mappingBitMatrix.getDimension(); - int numColumns = numRows; - - bool corner1Read = false; - bool corner2Read = false; - bool corner3Read = false; - bool corner4Read = false; - - // Read all of the codewords - do { - // Check the four corner cases - if ((row == numRows) && (column == 0) && !corner1Read) { - result[resultOffset++] = (sbyte) readCorner1(numRows, numColumns); - row -= 2; - column +=2; - corner1Read = true; - } else if ((row == numRows-2) && (column == 0) && ((numColumns & 0x03) != 0) && !corner2Read) { - result[resultOffset++] = (sbyte)readCorner2(numRows, numColumns); - row -= 2; - column +=2; - corner2Read = true; - } else if ((row == numRows+4) && (column == 2) && ((numColumns & 0x07) == 0) && !corner3Read) { - result[resultOffset++] = (sbyte)readCorner3(numRows, numColumns); - row -= 2; - column +=2; - corner3Read = true; - } else if ((row == numRows-2) && (column == 0) && ((numColumns & 0x07) == 4) && !corner4Read) { - result[resultOffset++] = (sbyte)readCorner4(numRows, numColumns); - row -= 2; - column +=2; - corner4Read = true; - } else { - // Sweep upward diagonally to the right - do { - if ((row < numRows) && (column >= 0) && !readMappingMatrix.get(row, column)) { - result[resultOffset++] = (sbyte)readUtah(row, column, numRows, numColumns); - } - row -= 2; - column +=2; - } while ((row >= 0) && (column < numColumns)); - row += 1; - column +=3; - - // Sweep downward diagonally to the left - do { - if ((row >= 0) && (column < numColumns) && !readMappingMatrix.get(row, column)) { - result[resultOffset++] = (sbyte) readUtah(row, column, numRows, numColumns); - } - row += 2; - column -=2; - } while ((row < numRows) && (column >= 0)); - row += 3; - column +=1; - } - } while ((row < numRows) || (column < numColumns)); - - if (resultOffset != version.getTotalCodewords()) { - throw new ReaderException(); - } - return result; - } - - /** - *

Reads a bit of the mapping matrix accounting for boundary wrapping.

- * - * @param row Row to read in the mapping matrix - * @param column Column to read in the mapping matrix - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return value of the given bit in the mapping matrix - */ - bool readModule(int row, int column, int numRows, int numColumns) { - // Adjust the row and column indices based on boundary wrapping - if (row < 0) { - row += numRows; - column += 4 - ((numRows + 4) & 0x07); - } - if (column < 0) { - column += numColumns; - row += 4 - ((numColumns + 4) & 0x07); - } - readMappingMatrix.set(row, column); - return mappingBitMatrix.get(row, column); - } - - /** - *

Reads the 8 bits of the standard utah shaped pattern.

- * - *

See ISO 16022:2006, 5.8.1 Figure 6

- * - * @param row Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern - * @param column Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the utah shape - */ - int readUtah(int row, int column, int numRows, int numColumns) { - int currentByte = 0; - if (readModule(row - 2, column - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 2, column - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 1, column - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 1, column - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 1, column, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row, column - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row, column - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row, column, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Reads the 8 bits of the special corner condition 1.

- * - *

See ISO 16022:2006, Figure F.3

- * - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the Corner condition 1 - */ - int readCorner1(int numRows, int numColumns) { - int currentByte = 0; - if (readModule(numRows - 1, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(2, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(3, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Reads the 8 bits of the special corner condition 2.

- * - *

See ISO 16022:2006, Figure F.4

- * - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the Corner condition 2 - */ - int readCorner2(int numRows, int numColumns) { - int currentByte = 0; - if (readModule(numRows - 3, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 2, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 4, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 3, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Reads the 8 bits of the special corner condition 3.

- * - *

See ISO 16022:2006, Figure F.5

- * - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the Corner condition 3 - */ - int readCorner3(int numRows, int numColumns) { - int currentByte = 0; - if (readModule(numRows - 1, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 3, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 3, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Reads the 8 bits of the special corner condition 4.

- * - *

See ISO 16022:2006, Figure F.6

- * - * @param numRows Number of rows in the mapping matrix - * @param numColumns Number of columns in the mapping matrix - * @return byte from the Corner condition 4 - */ - int readCorner4(int numRows, int numColumns) { - int currentByte = 0; - if (readModule(numRows - 3, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 2, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 0, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(2, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(3, numColumns - 1, numRows, numColumns)) { - currentByte |= 1; - } - return currentByte; - } - - /** - *

Extracts the data region from a {@link BitMatrix} that contains - * alignment patterns.

- * - * @param bitMatrix Original {@link BitMatrix} with alignment patterns - * @return BitMatrix that has the alignment patterns removed - */ - BitMatrix extractDataRegion(BitMatrix bitMatrix) { - int symbolSizeRows = version.getSymbolSizeRows(); - int symbolSizeColumns = version.getSymbolSizeColumns(); - - // TODO(bbrown): Make this work with rectangular codes - if (bitMatrix.getDimension() != symbolSizeRows) { - throw new ArgumentException("Dimension of bitMarix must match the version size"); - } - - int dataRegionSizeRows = version.getDataRegionSizeRows(); - int dataRegionSizeColumns = version.getDataRegionSizeColumns(); - - int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows; - int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns; - - int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows; - //int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns; - - // TODO(bbrown): Make this work with rectangular codes - BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionRow); - for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) { - int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows; - for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) { - int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns; - for (int i = 0; i < dataRegionSizeRows; ++i) { - int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i; - int writeRowOffset = dataRegionRowOffset + i; - for (int j = 0; j < dataRegionSizeColumns; ++j) { - int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j; - if (bitMatrix.get(readRowOffset, readColumnOffset)) { - int writeColumnOffset = dataRegionColumnOffset + j; - bitMatrixWithoutAlignment.set(writeRowOffset, writeColumnOffset); - } - } - } - } - } - return bitMatrixWithoutAlignment; - } - - } -} diff --git a/qrcode-scanner-live2/datamatrix/decoder/DataBlock.cs b/qrcode-scanner-live2/datamatrix/decoder/DataBlock.cs deleted file mode 100644 index 8e4893e..0000000 --- a/qrcode-scanner-live2/datamatrix/decoder/DataBlock.cs +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace com.google.zxing.datamatrix.decoder -{ - - /** - *

Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into - * multiple blocks, each of which is a unit of data and error-correction codewords. Each - * is represented by an instance of this class.

- * - * @author bbrown@google.com (Brian Brown) - */ - public sealed class DataBlock - { - private int numDataCodewords; - private sbyte[] codewords; - - private DataBlock(int numDataCodewords, sbyte[] codewords) { - this.numDataCodewords = numDataCodewords; - this.codewords = codewords; - } - - /** - *

When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them. - * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This - * method will separate the data into original blocks.

- * - * @param rawCodewords bytes as read directly from the Data Matrix Code - * @param version version of the Data Matrix Code - * @return {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the - * Data Matrix Code - */ - public static DataBlock[] getDataBlocks(sbyte[] rawCodewords, - Version version) { - // Figure out the number and size of data blocks used by this version - Version.ECBlocks ecBlocks = version.getECBlocks(); - - // First count the total number of data blocks - int totalBlocks = 0; - Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); - for (int i = 0; i < ecBlockArray.Length; i++) { - totalBlocks += ecBlockArray[i].getCount(); - } - - // Now establish DataBlocks of the appropriate size and number of data codewords - DataBlock[] result = new DataBlock[totalBlocks]; - int numResultBlocks = 0; - for (int j = 0; j < ecBlockArray.Length; j++) { - Version.ECB ecBlock = ecBlockArray[j]; - for (int i = 0; i < ecBlock.getCount(); i++) { - int numDataCodewords = ecBlock.getDataCodewords(); - int numBlockCodewords = ecBlocks.getECCodewords() + numDataCodewords; - result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]); - } - } - - // All blocks have the same amount of data, except that the last n - // (where n may be 0) have 1 less byte. Figure out where these start. - // TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144 - int longerBlocksTotalCodewords = result[0].codewords.Length; - //int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1; - - int longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.getECCodewords(); - int shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1; - // The last elements of result may be 1 element shorter for 144 matrix - // first fill out as many elements as all of them have minus 1 - int rawCodewordsOffset = 0; - for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { - for (int j = 0; j < numResultBlocks; j++) { - result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; - } - } - - // Fill out the last data block in the longer ones - bool specialVersion = version.getVersionNumber() == 24; - int numLongerBlocks = specialVersion ? 8 : numResultBlocks; - for (int j = 0; j < numLongerBlocks; j++) { - result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++]; - } - - // Now add in error correction blocks - int max = result[0].codewords.Length; - for (int i = longerBlocksNumDataCodewords; i < max; i++) { - for (int j = 0; j < numResultBlocks; j++) { - int iOffset = (specialVersion && j > 7) ? i - 1 : i; - result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; - } - } - - if (rawCodewordsOffset != rawCodewords.Length) { - throw new ArgumentException(); - } - - return result; - } - - public int getNumDataCodewords() { - return numDataCodewords; - } - - public sbyte[] getCodewords() { - return codewords; - } - } -} diff --git a/qrcode-scanner-live2/datamatrix/decoder/DecodedBitStreamParser.cs b/qrcode-scanner-live2/datamatrix/decoder/DecodedBitStreamParser.cs deleted file mode 100644 index 15bf322..0000000 --- a/qrcode-scanner-live2/datamatrix/decoder/DecodedBitStreamParser.cs +++ /dev/null @@ -1,449 +0,0 @@ -/* - * Copyright 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using com.google.zxing.common; - -namespace com.google.zxing.datamatrix.decoder -{ - /** - *

Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into - * multiple blocks, each of which is a unit of data and error-correction codewords. Each - * is represented by an instance of this class.

- * - * @author bbrown@google.com (Brian Brown) - */ - public sealed class DecodedBitStreamParser - { - /** - * See ISO 16022:2006, Annex C Table C.1 - * The C40 Basic Character Set (*'s used for placeholders for the shift values) - */ - private static char[] C40_BASIC_SET_CHARS = { - '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' - }; - - private static char[] C40_SHIFT2_SET_CHARS = { - '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', - '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_' - }; - - /** - * See ISO 16022:2006, Annex C Table C.2 - * The Text Basic Character Set (*'s used for placeholders for the shift values) - */ - private static char[] TEXT_BASIC_SET_CHARS = { - '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' - }; - - private static char[] TEXT_SHIFT3_SET_CHARS = { - '\'', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char) 127 - }; - - private const int PAD_ENCODE = 0; // Not really an encoding - private const int ASCII_ENCODE = 1; - private const int C40_ENCODE = 2; - private const int TEXT_ENCODE = 3; - private const int ANSIX12_ENCODE = 4; - private const int EDIFACT_ENCODE = 5; - private const int BASE256_ENCODE = 6; - - private DecodedBitStreamParser() { - } - - public static DecoderResult decode(sbyte[] bytes) { - BitSource bits = new BitSource(bytes); - StringBuilder result = new StringBuilder(); - StringBuilder resultTrailer = new StringBuilder(0); - System.Collections.ArrayList byteSegments = new System.Collections.ArrayList(1); - int mode = ASCII_ENCODE; - do { - if (mode == ASCII_ENCODE) { - mode = decodeAsciiSegment(bits, result, resultTrailer); - } else { - switch (mode) { - case C40_ENCODE: - decodeC40Segment(bits, result); - break; - case TEXT_ENCODE: - decodeTextSegment(bits, result); - break; - case ANSIX12_ENCODE: - decodeAnsiX12Segment(bits, result); - break; - case EDIFACT_ENCODE: - decodeEdifactSegment(bits, result); - break; - case BASE256_ENCODE: - decodeBase256Segment(bits, result, byteSegments); - break; - default: - throw new ReaderException(); - } - mode = ASCII_ENCODE; - } - } while (mode != PAD_ENCODE && bits.available() > 0); - if (resultTrailer.Length > 0) { - result.Append(resultTrailer); - } - return new DecoderResult(bytes, result.ToString(), int.Equals(byteSegments.Count,0) ? null : byteSegments); - } - - /** - * See ISO 16022:2006, 5.2.3 and Annex C, Table C.2 - */ - private static int decodeAsciiSegment(BitSource bits, StringBuilder result, StringBuilder resultTrailer) - { - bool upperShift = false; - do { - int oneByte = bits.readBits(8); - if (oneByte == 0) { - throw new ReaderException(); - } else if (oneByte <= 128) { // ASCII data (ASCII value + 1) - oneByte = upperShift ? (oneByte + 128) : oneByte; - upperShift = false; - result.Append((char) (oneByte - 1)); - return ASCII_ENCODE; - } else if (oneByte == 129) { // Pad - return PAD_ENCODE; - } else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130) - int value = oneByte - 130; - if (value < 10) { // padd with '0' for single digit values - result.Append('0'); - } - result.Append(value); - } else if (oneByte == 230) { // Latch to C40 encodation - return C40_ENCODE; - } else if (oneByte == 231) { // Latch to Base 256 encodation - return BASE256_ENCODE; - } else if (oneByte == 232) { // FNC1 - throw new ReaderException(); - } else if (oneByte == 233) { // Structured Append - throw new ReaderException(); - } else if (oneByte == 234) { // Reader Programming - throw new ReaderException(); - } else if (oneByte == 235) { // Upper Shift (shift to Extended ASCII) - upperShift = true; - } else if (oneByte == 236) { // 05 Macro - result.Append("[)>\u001E05\u001D"); - resultTrailer.Insert(0, "\u001E\u0004"); - } else if (oneByte == 237) { // 06 Macro - result.Append("[)>\u001E06\u001D"); - resultTrailer.Insert(0, "\u001E\u0004"); - } else if (oneByte == 238) { // Latch to ANSI X12 encodation - return ANSIX12_ENCODE; - } else if (oneByte == 239) { // Latch to Text encodation - return TEXT_ENCODE; - } else if (oneByte == 240) { // Latch to EDIFACT encodation - return EDIFACT_ENCODE; - } else if (oneByte == 241) { // ECI Character - // TODO(bbrown): I think we need to support ECI - throw new ReaderException(); - } else if (oneByte >= 242) { // Not to be used in ASCII encodation - throw new ReaderException(); - } - } while (bits.available() > 0); - return ASCII_ENCODE; - } - - /** - * See ISO 16022:2006, 5.2.5 and Annex C, Table C.1 - */ - private static void decodeC40Segment(BitSource bits, StringBuilder result) { - // Three C40 values are encoded in a 16-bit value as - // (1600 * C1) + (40 * C2) + C3 + 1 - // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time - bool upperShift = false; - - int[] cValues = new int[3]; - do { - // If there is only one byte left then it will be encoded as ASCII - if (bits.available() == 8) { - return; - } - int firstByte = bits.readBits(8); - if (firstByte == 254) { // Unlatch codeword - return; - } - - parseTwoBytes(firstByte, bits.readBits(8), cValues); - - int shift = 0; - for (int i = 0; i < 3; i++) { - int cValue = cValues[i]; - switch (shift) { - case 0: - if (cValue < 3) { - shift = cValue + 1; - } else { - if (upperShift) { - result.Append((char) (C40_BASIC_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(C40_BASIC_SET_CHARS[cValue]); - } - } - break; - case 1: - if (upperShift) { - result.Append((char) (cValue + 128)); - upperShift = false; - } else { - result.Append(cValue); - } - shift = 0; - break; - case 2: - if (cValue < 27) { - if (upperShift) { - result.Append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(C40_SHIFT2_SET_CHARS[cValue]); - } - } else if (cValue == 27) { // FNC1 - throw new ReaderException(); - } else if (cValue == 30) { // Upper Shift - upperShift = true; - } else { - throw new ReaderException(); - } - shift = 0; - break; - case 3: - if (upperShift) { - result.Append((char) (cValue + 224)); - upperShift = false; - } else { - result.Append((char) (cValue + 96)); - } - shift = 0; - break; - default: - throw new ReaderException(); - } - } - } while (bits.available() > 0); - } - - /** - * See ISO 16022:2006, 5.2.6 and Annex C, Table C.2 - */ - private static void decodeTextSegment(BitSource bits, StringBuilder result) { - // Three Text values are encoded in a 16-bit value as - // (1600 * C1) + (40 * C2) + C3 + 1 - // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time - bool upperShift = false; - - int[] cValues = new int[3]; - do { - // If there is only one byte left then it will be encoded as ASCII - if (bits.available() == 8) { - return; - } - int firstByte = bits.readBits(8); - if (firstByte == 254) { // Unlatch codeword - return; - } - - parseTwoBytes(firstByte, bits.readBits(8), cValues); - - int shift = 0; - for (int i = 0; i < 3; i++) { - int cValue = cValues[i]; - switch (shift) { - case 0: - if (cValue < 3) { - shift = cValue + 1; - } else { - if (upperShift) { - result.Append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(TEXT_BASIC_SET_CHARS[cValue]); - } - } - break; - case 1: - if (upperShift) { - result.Append((char) (cValue + 128)); - upperShift = false; - } else { - result.Append(cValue); - } - shift = 0; - break; - case 2: - // Shift 2 for Text is the same encoding as C40 - if (cValue < 27) { - if (upperShift) { - result.Append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(C40_SHIFT2_SET_CHARS[cValue]); - } - } else if (cValue == 27) { // FNC1 - throw new ReaderException(); - } else if (cValue == 30) { // Upper Shift - upperShift = true; - } else { - throw new ReaderException(); - } - shift = 0; - break; - case 3: - if (upperShift) { - result.Append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128)); - upperShift = false; - } else { - result.Append(TEXT_SHIFT3_SET_CHARS[cValue]); - } - shift = 0; - break; - default: - throw new ReaderException(); - } - } - } while (bits.available() > 0); - } - - /** - * See ISO 16022:2006, 5.2.7 - */ - private static void decodeAnsiX12Segment(BitSource bits, StringBuilder result) { - // Three ANSI X12 values are encoded in a 16-bit value as - // (1600 * C1) + (40 * C2) + C3 + 1 - - int[] cValues = new int[3]; - do { - // If there is only one byte left then it will be encoded as ASCII - if (bits.available() == 8) { - return; - } - int firstByte = bits.readBits(8); - if (firstByte == 254) { // Unlatch codeword - return; - } - - parseTwoBytes(firstByte, bits.readBits(8), cValues); - - for (int i = 0; i < 3; i++) { - int cValue = cValues[i]; - if (cValue == 0) { // X12 segment terminator - result.Append('\r'); - } else if (cValue == 1) { // X12 segment separator * - result.Append('*'); - } else if (cValue == 2) { // X12 sub-element separator > - result.Append('>'); - } else if (cValue == 3) { // space - result.Append(' '); - } else if (cValue < 14) { // 0 - 9 - result.Append((char) (cValue + 44)); - } else if (cValue < 40) { // A - Z - result.Append((char) (cValue + 51)); - } else { - throw new ReaderException(); - } - } - } while (bits.available() > 0); - } - - private static void parseTwoBytes(int firstByte, int secondByte, int[] result) { - int fullBitValue = (firstByte << 8) + secondByte - 1; - int temp = fullBitValue / 1600; - result[0] = temp; - fullBitValue -= temp * 1600; - temp = fullBitValue / 40; - result[1] = temp; - result[2] = fullBitValue - temp * 40; - } - - /** - * See ISO 16022:2006, 5.2.8 and Annex C Table C.3 - */ - private static void decodeEdifactSegment(BitSource bits, StringBuilder result) { - bool unlatch = false; - do { - // If there is only two or less bytes left then it will be encoded as ASCII - if (bits.available() <= 16) { - return; - } - - for (int i = 0; i < 4; i++) { - int edifactValue = bits.readBits(6); - - // Check for the unlatch character - if (edifactValue == 0x2B67) { // 011111 - unlatch = true; - // If we encounter the unlatch code then continue reading because the Codeword triple - // is padded with 0's - } - - if (!unlatch) { - if ((edifactValue & 32) == 0) { // no 1 in the leading (6th) bit - edifactValue |= 64; // Add a leading 01 to the 6 bit binary value - } - result.Append(edifactValue); - } - } - } while (!unlatch && bits.available() > 0); - } - - /** - * See ISO 16022:2006, 5.2.9 and Annex B, B.2 - */ - private static void decodeBase256Segment(BitSource bits, StringBuilder result, System.Collections.ArrayList byteSegments) { - // Figure out how long the Base 256 Segment is. - int d1 = bits.readBits(8); - int count; - if (d1 == 0) { // Read the remainder of the symbol - count = bits.available() / 8; - } else if (d1 < 250) { - count = d1; - } else { - count = 250 * (d1 - 249) + bits.readBits(8); - } - byte[] bytes = new byte[count]; - for (int i = 0; i < count; i++) { - bytes[i] = unrandomize255State(bits.readBits(8), i); - } - byteSegments.Add(bytes); - try { - result.Append(System.Text.Encoding.GetEncoding("iso-8859-1").GetString(bytes)); - } catch (Exception uee) { - throw new Exception("Platform does not support required encoding: " + uee); - } - } - - /** - * See ISO 16022:2006, Annex B, B.2 - */ - private static byte unrandomize255State(int randomizedBase256Codeword, - int base256CodewordPosition) { - int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1; - int tempVariable = randomizedBase256Codeword - pseudoRandomNumber; - return (byte) (tempVariable >= 0 ? tempVariable : (tempVariable + 256)); - } - } -} diff --git a/qrcode-scanner-live2/datamatrix/decoder/Decoder.cs b/qrcode-scanner-live2/datamatrix/decoder/Decoder.cs deleted file mode 100644 index d30b4be..0000000 --- a/qrcode-scanner-live2/datamatrix/decoder/Decoder.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2007 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using com.google.zxing.common; -using com.google.zxing.common.reedsolomon; - -namespace com.google.zxing.datamatrix.decoder -{ - - /** - *

The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting - * the Data Matrix Code from an image.

- * - * @author bbrown@google.com (Brian Brown) - */ - public sealed class Decoder - { - private ReedSolomonDecoder rsDecoder; - public Decoder() { - rsDecoder = new ReedSolomonDecoder(GF256.DATA_MATRIX_FIELD); - } - - /** - *

Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans. - * "true" is taken to mean a black module.

- * - * @param image booleans representing white/black Data Matrix Code modules - * @return text and bytes encoded within the Data Matrix Code - * @throws ReaderException if the Data Matrix Code cannot be decoded - */ - public DecoderResult decode(bool[][] image) { - int dimension = image.Length; - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - if (image[i][j]) { - bits.set(i, j); - } - } - } - return decode(bits); - } - - /** - *

Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken - * to mean a black module.

- * - * @param bits booleans representing white/black Data Matrix Code modules - * @return text and bytes encoded within the Data Matrix Code - * @throws ReaderException if the Data Matrix Code cannot be decoded - */ - public DecoderResult decode(BitMatrix bits) { - - // Construct a parser and read version, error-correction level - BitMatrixParser parser = new BitMatrixParser(bits); - Version version = parser.readVersion(bits); - - // Read codewords - sbyte[] codewords = parser.readCodewords(); - // Separate into data blocks - DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version); - - // Count total number of data bytes - int totalBytes = 0; - for (int i = 0; i < dataBlocks.Length; i++) { - totalBytes += dataBlocks[i].getNumDataCodewords(); - } - sbyte[] resultBytes = new sbyte[totalBytes]; - int resultOffset = 0; - - // Error-correct and copy data blocks together into a stream of bytes - for (int j = 0; j < dataBlocks.Length; j++) { - DataBlock dataBlock = dataBlocks[j]; - sbyte[] codewordBytes = dataBlock.getCodewords(); - int numDataCodewords = dataBlock.getNumDataCodewords(); - correctErrors(codewordBytes, numDataCodewords); - for (int i = 0; i < numDataCodewords; i++) { - resultBytes[resultOffset++] = codewordBytes[i]; - } - } - - // Decode the contents of that stream of bytes - return DecodedBitStreamParser.decode(resultBytes); - } - - /** - *

Given data and error-correction codewords received, possibly corrupted by errors, attempts to - * correct the errors in-place using Reed-Solomon error correction.

- * - * @param codewordBytes data and error correction codewords - * @param numDataCodewords number of codewords that are data bytes - * @throws ReaderException if error correction fails - */ - private void correctErrors(sbyte[] codewordBytes, int numDataCodewords) { - int numCodewords = codewordBytes.Length; - // First read into an array of ints - int[] codewordsInts = new int[numCodewords]; - for (int i = 0; i < numCodewords; i++) { - codewordsInts[i] = codewordBytes[i] & 0xFF; - } - int numECCodewords = codewordBytes.Length - numDataCodewords; - try { - rsDecoder.decode(codewordsInts, numECCodewords); - } catch (ReedSolomonException rse) { - throw new ReaderException(); - } - // Copy back into array of bytes -- only need to worry about the bytes that were data - // We don't care about errors in the error-correction codewords - for (int i = 0; i < numDataCodewords; i++) { - codewordBytes[i] = (sbyte) codewordsInts[i]; - } - } - - } -} diff --git a/qrcode-scanner-live2/datamatrix/decoder/Version.cs b/qrcode-scanner-live2/datamatrix/decoder/Version.cs deleted file mode 100644 index 25e3274..0000000 --- a/qrcode-scanner-live2/datamatrix/decoder/Version.cs +++ /dev/null @@ -1,222 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace com.google.zxing.datamatrix.decoder -{ - public sealed class Version - { - private static Version[] VERSIONS = buildVersions(); - private int versionNumber; - private int symbolSizeRows; - private int symbolSizeColumns; - private int dataRegionSizeRows; - private int dataRegionSizeColumns; - private ECBlocks ecBlocks; - private int totalCodewords; - - private Version(int versionNumber, - int symbolSizeRows, - int symbolSizeColumns, - int dataRegionSizeRows, - int dataRegionSizeColumns, - ECBlocks ecBlocks) { - this.versionNumber = versionNumber; - this.symbolSizeRows = symbolSizeRows; - this.symbolSizeColumns = symbolSizeColumns; - this.dataRegionSizeRows = dataRegionSizeRows; - this.dataRegionSizeColumns = dataRegionSizeColumns; - this.ecBlocks = ecBlocks; - - // Calculate the total number of codewords - int total = 0; - int ecCodewords = ecBlocks.getECCodewords(); - ECB[] ecbArray = ecBlocks.getECBlocks(); - for (int i = 0; i < ecbArray.Length; i++) { - ECB ecBlock = ecbArray[i]; - total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords); - } - this.totalCodewords = total; - } - - public int getVersionNumber() { - return versionNumber; - } - - public int getSymbolSizeRows() { - return symbolSizeRows; - } - - public int getSymbolSizeColumns() { - return symbolSizeColumns; - } - - public int getDataRegionSizeRows() { - return dataRegionSizeRows; - } - - public int getDataRegionSizeColumns() { - return dataRegionSizeColumns; - } - - public int getTotalCodewords() { - return totalCodewords; - } - - public ECBlocks getECBlocks() { - return ecBlocks; - } - - /** - *

Deduces version information from Data Matrix dimensions.

- * - * @param numRows Number of rows in modules - * @param numColumns Number of columns in modules - * @return {@link Version} for a Data Matrix Code of those dimensions - * @throws ReaderException if dimensions do correspond to a valid Data Matrix size - */ - public static Version getVersionForDimensions(int numRows, int numColumns) { - if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0) { - throw new ReaderException(); - } - - // TODO(bbrown): This is doing a linear search through the array of versions. - // If we interleave the rectangular versions with the square versions we could - // do a binary search. - int numVersions = VERSIONS.Length; - for (int i = 0; i < numVersions; ++i){ - Version version = VERSIONS[i]; - if (version.symbolSizeRows == numRows && version.symbolSizeColumns == numColumns) { - return version; - } - } - - throw new ReaderException(); - } - - /** - *

Encapsulates a set of error-correction blocks in one symbol version. Most versions will - * use blocks of differing sizes within one version, so, this encapsulates the parameters for - * each set of blocks. It also holds the number of error-correction codewords per block since it - * will be the same across all blocks within one version.

- */ - public class ECBlocks { - private int ecCodewords; - private ECB[] ecBlocks; - - public ECBlocks(int ecCodewords, ECB ecBlocks) { - this.ecCodewords = ecCodewords; - this.ecBlocks = new ECB[] { ecBlocks }; - } - - public ECBlocks(int ecCodewords, ECB ecBlocks1, ECB ecBlocks2) { - this.ecCodewords = ecCodewords; - this.ecBlocks = new ECB[] { ecBlocks1, ecBlocks2 }; - } - - public int getECCodewords() { - return ecCodewords; - } - - public ECB[] getECBlocks() { - return ecBlocks; - } - } - - /** - *

Encapsualtes the parameters for one error-correction block in one symbol version. - * This includes the number of data codewords, and the number of times a block with these - * parameters is used consecutively in the Data Matrix code version's format.

- */ - public class ECB { - private int count; - private int dataCodewords; - - public ECB(int count, int dataCodewords) { - this.count = count; - this.dataCodewords = dataCodewords; - } - - public int getCount() { - return count; - } - - public int getDataCodewords() { - return dataCodewords; - } - } - - public String toString() { - return versionNumber.ToString(); - } - - /** - * See ISO 16022:2006 5.5.1 Table 7 - */ - private static Version[] buildVersions() { - return new Version[]{ - new Version(1, 10, 10, 8, 8, - new ECBlocks(5, new ECB(1, 3))), - new Version(2, 12, 12, 10, 10, - new ECBlocks(7, new ECB(1, 5))), - new Version(3, 14, 14, 12, 12, - new ECBlocks(10, new ECB(1, 8))), - new Version(4, 16, 16, 14, 14, - new ECBlocks(12, new ECB(1, 12))), - new Version(5, 18, 18, 16, 16, - new ECBlocks(14, new ECB(1, 18))), - new Version(6, 20, 20, 18, 18, - new ECBlocks(18, new ECB(1, 22))), - new Version(7, 22, 22, 20, 20, - new ECBlocks(20, new ECB(1, 30))), - new Version(8, 24, 24, 22, 22, - new ECBlocks(24, new ECB(1, 36))), - new Version(9, 26, 26, 24, 24, - new ECBlocks(28, new ECB(1, 44))), - new Version(10, 32, 32, 14, 14, - new ECBlocks(36, new ECB(1, 62))), - new Version(11, 36, 36, 16, 16, - new ECBlocks(42, new ECB(1, 86))), - new Version(12, 40, 40, 18, 18, - new ECBlocks(48, new ECB(1, 114))), - new Version(13, 44, 44, 20, 20, - new ECBlocks(56, new ECB(1, 144))), - new Version(14, 48, 48, 22, 22, - new ECBlocks(68, new ECB(1, 174))), - new Version(15, 52, 52, 24, 24, - new ECBlocks(42, new ECB(2, 102))), - new Version(16, 64, 64, 14, 14, - new ECBlocks(56, new ECB(2, 140))), - new Version(17, 72, 72, 16, 16, - new ECBlocks(36, new ECB(4, 92))), - new Version(18, 80, 80, 18, 18, - new ECBlocks(48, new ECB(4, 114))), - new Version(19, 88, 88, 20, 20, - new ECBlocks(56, new ECB(4, 144))), - new Version(20, 96, 96, 22, 22, - new ECBlocks(68, new ECB(4, 174))), - new Version(21, 104, 104, 24, 24, - new ECBlocks(56, new ECB(6, 136))), - new Version(22, 120, 120, 18, 18, - new ECBlocks(68, new ECB(6, 175))), - new Version(23, 132, 132, 20, 20, - new ECBlocks(62, new ECB(8, 163))), - new Version(24, 144, 144, 22, 22, - new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))), - new Version(25, 8, 18, 6, 16, - new ECBlocks(7, new ECB(1, 5))), - new Version(26, 8, 32, 6, 14, - new ECBlocks(11, new ECB(1, 10))), - new Version(27, 12, 26, 10, 24, - new ECBlocks(14, new ECB(1, 16))), - new Version(28, 12, 36, 10, 16, - new ECBlocks(18, new ECB(1, 22))), - new Version(29, 16, 36, 10, 16, - new ECBlocks(24, new ECB(1, 32))), - new Version(30, 16, 48, 14, 22, - new ECBlocks(28, new ECB(1, 49))) - }; - } - } -} diff --git a/qrcode-scanner-live2/datamatrix/detector/Detector.cs b/qrcode-scanner-live2/datamatrix/detector/Detector.cs deleted file mode 100644 index 777d1ab..0000000 --- a/qrcode-scanner-live2/datamatrix/detector/Detector.cs +++ /dev/null @@ -1,424 +0,0 @@ -/* - * Copyright 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.datamatrix.detector -{ - /** - *

Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code - * is rotated or skewed, or partially obscured.

- * - * @author Sean Owen - */ - public sealed class Detector - { - private static int MAX_MODULES = 32; - - // Trick to avoid creating new int objects below -- a sort of crude copy of - // the int.valueOf(int) optimization added in Java 5, not in J2ME - private static int[] intS = - {0, 1, 2, 3, 4}; - - private MonochromeBitmapSource image; - - public Detector(MonochromeBitmapSource image) { - this.image = image; - } - - /** - *

Detects a Data Matrix Code in an image.

- * - * @return {@link DetectorResult} encapsulating results of detecting a QR Code - * @throws ReaderException if no Data Matrix Code can be found - */ - public DetectorResult detect() { - - if (!BlackPointEstimationMethod.TWO_D_SAMPLING.Equals(image.getLastEstimationMethod())) { - image.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0); - } - - int height = image.getHeight(); - int width = image.getWidth(); - int halfHeight = height >> 1; - int halfWidth = width >> 1; - int iSkip = Math.Max(1, height / (MAX_MODULES << 3)); - int jSkip = Math.Max(1, width / (MAX_MODULES << 3)); - - int minI = 0; - int maxI = height; - int minJ = 0; - int maxJ = width; - ResultPoint pointA = findCornerFromCenter(halfHeight, -iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 1); - minI = (int) pointA.getY() - 1; - ResultPoint pointB = findCornerFromCenter(halfHeight, 0, minI, maxI, halfWidth, -jSkip, minJ, maxJ, halfHeight >> 1); - minJ = (int) pointB.getX() - 1; - ResultPoint pointC = findCornerFromCenter(halfHeight, 0, minI, maxI, halfWidth, jSkip, minJ, maxJ, halfHeight >> 1); - maxJ = (int) pointC.getX() + 1; - ResultPoint pointD = findCornerFromCenter(halfHeight, iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 1); - maxI = (int) pointD.getY() + 1; - // Go try to find point A again with better information -- might have been off at first. - pointA = findCornerFromCenter(halfHeight, -iSkip, minI, maxI, halfWidth, 0, minJ, maxJ, halfWidth >> 2); - - // Point A and D are across the diagonal from one another, - // as are B and C. Figure out which are the solid black lines - // by counting transitions - System.Collections.ArrayList transitions = new System.Collections.ArrayList(4); - transitions.Add(transitionsBetween(pointA, pointB)); - transitions.Add(transitionsBetween(pointA, pointC)); - transitions.Add(transitionsBetween(pointB, pointD)); - transitions.Add(transitionsBetween(pointC, pointD)); - Collections.insertionSort(transitions, new ResultPointsAndTransitionsComparator()); - - // Sort by number of transitions. First two will be the two solid sides; last two - // will be the two alternating black/white sides - ResultPointsAndTransitions lSideOne = (ResultPointsAndTransitions) transitions[0]; - ResultPointsAndTransitions lSideTwo = (ResultPointsAndTransitions) transitions[1]; - - // Figure out which point is their intersection by tallying up the number of times we see the - // endpoints in the four endpoints. One will show up twice. - System.Collections.Hashtable pointCount = new System.Collections.Hashtable(); - increment(pointCount, lSideOne.getFrom()); - increment(pointCount, lSideOne.getTo()); - increment(pointCount, lSideTwo.getFrom()); - increment(pointCount, lSideTwo.getTo()); - - ResultPoint maybeTopLeft = null; - ResultPoint bottomLeft = null; - ResultPoint maybeBottomRight = null; - System.Collections.IEnumerator points = pointCount.GetEnumerator(); - - while (points.MoveNext()) { - ResultPoint point = (ResultPoint) points.Current; - int value = (int) pointCount[point]; - if (value == 2) { - bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides - } else { - // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now - if (maybeTopLeft == null) { - maybeTopLeft = point; - } else { - maybeBottomRight = point; - } - } - } - - if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null) { - throw new ReaderException(); - } - - // Bottom left is correct but top left and bottom right might be switched - ResultPoint[] corners = { maybeTopLeft, bottomLeft, maybeBottomRight }; - // Use the dot product trick to sort them out - GenericResultPoint.orderBestPatterns(corners); - - // Now we know which is which: - ResultPoint bottomRight = corners[0]; - bottomLeft = corners[1]; - ResultPoint topLeft = corners[2]; - - // Which point didn't we find in relation to the "L" sides? that's the top right corner - ResultPoint topRight; - if (!pointCount.ContainsKey(pointA)) { - topRight = pointA; - } else if (!pointCount.ContainsKey(pointB)) { - topRight = pointB; - } else if (!pointCount.ContainsKey(pointC)) { - topRight = pointC; - } else { - topRight = pointD; - } - - // Next determine the dimension by tracing along the top or right side and counting black/white - // transitions. Since we start inside a black module, we should see a number of transitions - // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to - // end on a black module: - - // The top right point is actually the corner of a module, which is one of the two black modules - // adjacent to the white module at the top right. Tracing to that corner from either the top left - // or bottom right should work here, but, one will be more reliable since it's traced straight - // up or across, rather than at a slight angle. We use dot products to figure out which is - // better to use: - int dimension; - if (GenericResultPoint.crossProductZ(bottomLeft, bottomRight, topRight) < - GenericResultPoint.crossProductZ(topRight, topLeft, bottomLeft)) { - dimension = transitionsBetween(topLeft, topRight).getTransitions(); - } else { - dimension = transitionsBetween(bottomRight, topRight).getTransitions(); - } - dimension += 2; - - BitMatrix bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, dimension); - return new DetectorResult(bits, new ResultPoint[] {pointA, pointB, pointC, pointD}); - } - - /** - * Attempts to locate a corner of the barcode by scanning up, down, left or right from a center - * point which should be within the barcode. - * - * @param centerI center's i componennt (vertical) - * @param di change in i per step. If scanning up this is negative; down, positive; left or right, 0 - * @param minI minimum value of i to search through (meaningless when di == 0) - * @param maxI maximum value of i - * @param centerJ center's j component (horizontal) - * @param dj same as di but change in j per step instead - * @param minJ see minI - * @param maxJ see minJ - * @param maxWhiteRun maximum run of white pixels that can still be considered to be within - * the barcode - * @return a {@link ResultPoint} encapsulating the corner that was found - * @throws ReaderException if such a point cannot be found - */ - private ResultPoint findCornerFromCenter(int centerI, int di, int minI, int maxI, - int centerJ, int dj, int minJ, int maxJ, - int maxWhiteRun) { - int[] lastRange = null; - for (int i = centerI, j = centerJ; - i < maxI && i >= minI && j < maxJ && j >= minJ; - i += di, j += dj) { - int[] range; - if (dj == 0) { - // horizontal slices, up and down - range = blackWhiteRange(i, maxWhiteRun, minJ, maxJ, true); - } else { - // vertical slices, left and right - range = blackWhiteRange(j, maxWhiteRun, minI, maxI, false); - } - if (range == null) { - if (lastRange == null) { - throw new ReaderException(); - } - // lastRange was found - if (dj == 0) { - int lastI = i - di; - if (lastRange[0] < centerJ) { - if (lastRange[1] > centerJ) { - // straddle, choose one or the other based on direction - return new GenericResultPoint(di > 0 ? lastRange[0] : lastRange[1], lastI); - } - return new GenericResultPoint(lastRange[0], lastI); - } else { - return new GenericResultPoint(lastRange[1], lastI); - } - } else { - int lastJ = j - dj; - if (lastRange[0] < centerI) { - if (lastRange[1] > centerI) { - return new GenericResultPoint(lastJ, dj < 0 ? lastRange[0] : lastRange[1]); - } - return new GenericResultPoint(lastJ, lastRange[0]); - } else { - return new GenericResultPoint(lastJ, lastRange[1]); - } - } - } - lastRange = range; - } - throw new ReaderException(); - } - - /** - * Increments the int associated with a key by one. - */ - private static void increment(System.Collections.Hashtable table, ResultPoint key) { - int value = (int) table[key]; - table[key] = value.Equals(null) ? intS[1] : intS[value + 1]; - //table.put(key, value == null ? intS[1] : intS[value.intValue() + 1]); - } - - /** - * Computes the start and end of a region of pixels, either horizontally or vertically, that could be - * part of a Data Matrix barcode. - * - * @param fixedDimension if scanning horizontally, this is the row (the fixed vertical location) where - * we are scanning. If scanning vertically it's the colummn, the fixed horizontal location - * @param maxWhiteRun largest run of white pixels that can still be considered part of the barcode region - * @param minDim minimum pixel location, horizontally or vertically, to consider - * @param maxDim maximum pixel location, horizontally or vertically, to consider - * @param horizontal if true, we're scanning left-right, instead of up-down - * @return int[] with start and end of found range, or null if no such range is found (e.g. only white was found) - */ - private int[] blackWhiteRange(int fixedDimension, int maxWhiteRun, int minDim, int maxDim, bool horizontal) { - - int center = (minDim + maxDim) / 2; - - BitArray rowOrColumn = horizontal ? image.getBlackRow(fixedDimension, null, 0, image.getWidth()) - : image.getBlackColumn(fixedDimension, null, 0, image.getHeight()); - - // Scan left/up first - int start = center; - while (start >= minDim) { - if (rowOrColumn.get(start)) { - start--; - } else { - int whiteRunStart = start; - do { - start--; - } while (start >= minDim && !rowOrColumn.get(start)); - int whiteRunSize = whiteRunStart - start; - if (start < minDim || whiteRunSize > maxWhiteRun) { - start = whiteRunStart + 1; // back up - break; - } - } - } - start++; - - // Then try right/down - int end = center; - while (end < maxDim) { - if (rowOrColumn.get(end)) { - end++; - } else { - int whiteRunStart = end; - do { - end++; - } while (end < maxDim && !rowOrColumn.get(end)); - int whiteRunSize = end - whiteRunStart; - if (end >= maxDim || whiteRunSize > maxWhiteRun) { - end = whiteRunStart - 1; - break; - } - } - } - end--; - - if (end > start) { - return new int[] { start, end }; - } else { - return null; - } - } - - private static BitMatrix sampleGrid(MonochromeBitmapSource image, - ResultPoint topLeft, - ResultPoint bottomLeft, - ResultPoint bottomRight, - int dimension) { - - // We make up the top right point for now, based on the others. - // TODO: we actually found a fourth corner above and figured out which of two modules - // it was the corner of. We could use that here and adjust for perspective distortion. - float topRightX = (bottomRight.getX() - bottomLeft.getX()) + topLeft.getX(); - float topRightY = (bottomRight.getY() - bottomLeft.getY()) + topLeft.getY(); - - // Note that unlike in the QR Code sampler, we didn't find the center of modules, but the - // very corners. So there is no 0.5f here; 0.0f is right. - GridSampler sampler = GridSampler.Instance; - return sampler.sampleGrid( - image, - dimension, - 0.0f, - 0.0f, - dimension, - 0.0f, - dimension, - dimension, - 0.0f, - dimension, - topLeft.getX(), - topLeft.getY(), - topRightX, - topRightY, - bottomRight.getX(), - bottomRight.getY(), - bottomLeft.getX(), - bottomLeft.getY()); - } - - /** - * Counts the number of black/white transitions between two points, using something like Bresenham's algorithm. - */ - private ResultPointsAndTransitions transitionsBetween(ResultPoint from, ResultPoint to) { - // See QR Code Detector, sizeOfBlackWhiteBlackRun() - int fromX = (int) from.getX(); - int fromY = (int) from.getY(); - int toX = (int) to.getX(); - int toY = (int) to.getY(); - bool steep = Math.Abs(toY - fromY) > Math.Abs(toX - fromX); - if (steep) { - int temp = fromX; - fromX = fromY; - fromY = temp; - temp = toX; - toX = toY; - toY = temp; - } - - int dx = Math.Abs(toX - fromX); - int dy = Math.Abs(toY - fromY); - int error = -dx >> 1; - int ystep = fromY < toY ? 1 : -1; - int xstep = fromX < toX ? 1 : -1; - int transitions = 0; - bool inBlack = image.isBlack(steep ? fromY : fromX, steep ? fromX : fromY); - for (int x = fromX, y = fromY; x != toX; x += xstep) { - bool isBlack = image.isBlack(steep ? y : x, steep ? x : y); - if (isBlack == !inBlack) { - transitions++; - inBlack = isBlack; - } - error += dy; - if (error > 0) { - y += ystep; - error -= dx; - } - } - return new ResultPointsAndTransitions(from, to, transitions); - } - - /** - * Simply encapsulates two points and a number of transitions between them. - */ - private class ResultPointsAndTransitions { - private ResultPoint from; - private ResultPoint to; - private int transitions; - - public ResultPointsAndTransitions(ResultPoint from, ResultPoint to, int transitions) { - this.from = from; - this.to = to; - this.transitions = transitions; - } - - public ResultPoint getFrom() { - return from; - } - public ResultPoint getTo() { - return to; - } - public int getTransitions() { - return transitions; - } - public String toString() { - return from + "/" + to + '/' + transitions; - } - } - - /** - * Orders ResultPointsAndTransitions by number of transitions, ascending. - */ - private class ResultPointsAndTransitionsComparator : Comparator { - public int compare(Object o1, Object o2) { - return ((ResultPointsAndTransitions) o1).getTransitions() - ((ResultPointsAndTransitions) o2).getTransitions(); - } - } - } -} diff --git a/qrcode-scanner-live2/obj/Release/com.google.zxing.dll b/qrcode-scanner-live2/obj/Release/com.google.zxing.dll deleted file mode 100644 index 107727e..0000000 Binary files a/qrcode-scanner-live2/obj/Release/com.google.zxing.dll and /dev/null differ diff --git a/qrcode-scanner-live2/obj/Release/com.google.zxing.pdb b/qrcode-scanner-live2/obj/Release/com.google.zxing.pdb deleted file mode 100644 index 3aef474..0000000 Binary files a/qrcode-scanner-live2/obj/Release/com.google.zxing.pdb and /dev/null differ diff --git a/qrcode-scanner-live2/obj/Release/zxing.csproj.FileListAbsolute.txt b/qrcode-scanner-live2/obj/Release/zxing.csproj.FileListAbsolute.txt deleted file mode 100644 index 2d04eed..0000000 --- a/qrcode-scanner-live2/obj/Release/zxing.csproj.FileListAbsolute.txt +++ /dev/null @@ -1,5 +0,0 @@ -C:\projects\my open source project\zxingsharp\obj\Release\ResolveAssemblyReference.cache -C:\projects\my open source project\zxingsharp\bin\Release\com.google.zxing.dll -C:\projects\my open source project\zxingsharp\bin\Release\com.google.zxing.pdb -C:\projects\my open source project\zxingsharp\obj\Release\com.google.zxing.dll -C:\projects\my open source project\zxingsharp\obj\Release\com.google.zxing.pdb diff --git a/qrcode-scanner-live2/oned/AbstractOneDReader.cs b/qrcode-scanner-live2/oned/AbstractOneDReader.cs deleted file mode 100644 index 4ffd611..0000000 --- a/qrcode-scanner-live2/oned/AbstractOneDReader.cs +++ /dev/null @@ -1,231 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using com.google.zxing.common; - - public abstract class AbstractOneDReader - { - private static int INTEGER_MATH_SHIFT = 8; - public static int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT; - - public Result decode(MonochromeBitmapSource image) { - return decode(image, null); - } - - public Result decode(MonochromeBitmapSource image, System.Collections.Hashtable hints) { - try { - return doDecode(image, hints); - } catch (ReaderException re) { - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - if (tryHarder && image.isRotateSupported()) { - MonochromeBitmapSource rotatedImage = image.rotateCounterClockwise(); - Result result = doDecode(rotatedImage, hints); - // Record that we found it rotated 90 degrees CCW / 270 degrees CW - System.Collections.Hashtable metadata = result.getResultMetadata(); - int orientation = 270; - if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION)) { - // But if we found it reversed in doDecode(), add in that result here: - orientation = (orientation + ((int) metadata[ResultMetadataType.ORIENTATION])) % 360; - } - result.putMetadata(ResultMetadataType.ORIENTATION, orientation); - return result; - } else { - throw re; - } - } - } - - /** - * We're going to examine rows from the middle outward, searching alternately above and below the - * middle, and farther out each time. rowStep is the number of rows between each successive - * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then - * middle + rowStep, then middle - (2 * rowStep), etc. - * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily - * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the - * image if "trying harder". - * - * @param image The image to decode - * @param hints Any hints that were requested - * @return The contents of the decoded barcode - * @throws ReaderException Any spontaneous errors which occur - */ - private Result doDecode(MonochromeBitmapSource image, System.Collections.Hashtable hints) { - int width = image.getWidth(); - int height = image.getHeight(); - BitArray row = new BitArray(width); - - int middle = height >> 1; - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - int rowStep = Math.Max(1, height >> (tryHarder ? 7 : 4)); - int MaxLines; - if (tryHarder) { - MaxLines = height; // Look at the whole image, not just the center - } else { - MaxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image - } - - for (int x = 0; x < MaxLines; x++) { - - // Scanning from the middle out. Determine which row we're looking at next: - int rowStepsAboveOrBelow = (x + 1) >> 1; - bool isAbove = (x & 0x01) == 0; // i.e. is x even? - int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); - if (rowNumber < 0 || rowNumber >= height) { - // Oops, if we run off the top or bottom, stop - break; - } - - // Estimate black point for this row and load it: - try { - image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber); - } catch (ReaderException re) { - continue; - } - - image.getBlackRow(rowNumber, row,0, width); - - // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to - // handle decoding upside down barcodes. - for (int attempt = 0; attempt < 2; attempt++) { - if (attempt == 1) { // trying again? - row.reverse(); // reverse the row and continue - } - try { - // Look for a barcode - Result result = decodeRow(rowNumber, row, hints); - // We found our barcode - if (attempt == 1) { - // But it was upside down, so note that - result.putMetadata(ResultMetadataType.ORIENTATION, 180); - // And remember to flip the result points horizontally. - ResultPoint[] points = result.getResultPoints(); - points[0] = (ResultPoint) new GenericResultPoint(width - points[0].getX() - 1, points[0].getY()); - points[1] = (ResultPoint)new GenericResultPoint(width - points[1].getX() - 1, points[1].getY()); - } - return result; - } catch (ReaderException re) { - // continue -- just couldn't decode this row - } - } - } - - throw new ReaderException(); - } - - /** - * Records the size of successive runs of white and black pixels in a row, starting at a given point. - * The values are recorded in the given array, and the number of runs recorded is equal to the size - * of the array. If the row starts on a white pixel at the given start point, then the first count - * recorded is the run of white pixels starting from that point; likewise it is the count of a run - * of black pixels if the row begin on a black pixels at that point. - * - * @param row row to count from - * @param start offset into row to start at - * @param counters array into which to record counts - * @throws ReaderException if counters cannot be filled entirely from row before running out of pixels - */ - public static void recordPattern(BitArray row, int start, int[] counters) { - int numCounters = counters.Length; - for (int i = 0; i < numCounters; i++) { - counters[i] = 0; - } - int end = row.getSize(); - if (start >= end) { - throw new ReaderException(); - } - bool isWhite = !row.get(start); - int counterPosition = 0; - - int k = start; - while (k < end) { - bool pixel = row.get(k); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - counterPosition++; - if (counterPosition == numCounters) { - break; - } else { - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - k++; - } - // If we read fully the last section of pixels and filled up our counters -- or filled - // the last counter but ran off the side of the image, OK. Otherwise, a problem. - if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && k == end))) { - throw new ReaderException(); - } - } - - /** - * Determines how closely a set of observed counts of runs of black/white values matches a given - * target pattern. This is reported as the ratio of the total variance from the expected pattern - * proportions across all pattern elements, to the length of the pattern. - * - * @param counters observed counters - * @param pattern expected pattern - * @param MaxIndividualVariance The most any counter can differ before we give up - * @return ratio of total variance between counters and pattern compared to total pattern size, - * where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means - * the total variance between counters and patterns equals the pattern length, higher values mean - * even more variance - */ - public static int patternMatchVariance(int[] counters, int[] pattern, int MaxIndividualVariance) { - int numCounters = counters.Length; - int total = 0; - int patternLength = 0; - for (int i = 0; i < numCounters; i++) { - total += counters[i]; - patternLength += pattern[i]; - } - if (total < patternLength) { - // If we don't even have one pixel per unit of bar width, assume this is too small - // to reliably match, so fail: - return int.MaxValue; - } - // We're going to fake floating-point math in integers. We just need to use more bits. - // Scale up patternLength so that intermediate values below like scaledCounter will have - // more "significant digits" - int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength; - MaxIndividualVariance = (MaxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT; - - int totalVariance = 0; - for (int x = 0; x < numCounters; x++) { - int counter = counters[x] << INTEGER_MATH_SHIFT; - int scaledPattern = pattern[x] * unitBarWidth; - int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter; - if (variance > MaxIndividualVariance) { - return int.MaxValue; - } - totalVariance += variance; - } - return totalVariance / total; - } - - // This declaration should not be necessary, since this class is - // abstract and so does not have to provide an implementation for every - // method of an interface it implements, but it is causing NoSuchMethodError - // issues on some Nokia JVMs. So we add this superfluous declaration: - - public abstract Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints); - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/AbstractUPCEANReader.cs b/qrcode-scanner-live2/oned/AbstractUPCEANReader.cs deleted file mode 100644 index ef18078..0000000 --- a/qrcode-scanner-live2/oned/AbstractUPCEANReader.cs +++ /dev/null @@ -1,295 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using System.Text; - using com.google.zxing.common; - - /** - *

Encapsulates functionality and implementation that is common to UPC and EAN families - * of one-dimensional barcodes.

- * - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - * @author alasdair@google.com (Alasdair Mackintosh) - */ - - public abstract class AbstractUPCEANReader : AbstractOneDReader,UPCEANReader - { - private static int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f); - private static int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); - - /** - * Start/end guard pattern. - */ - private static int[] START_END_PATTERN = {1, 1, 1,}; - - /** - * Pattern marking the middle of a UPC/EAN pattern, separating the two halves. - */ - public static int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1}; - - /** - * "Odd", or "L" patterns used to encode UPC/EAN digits. - */ - public static int[][] L_PATTERNS = new int[][]{ - new int[]{3, 2, 1, 1}, // 0 - new int[]{2, 2, 2, 1}, // 1 - new int[]{2, 1, 2, 2}, // 2 - new int[]{1, 4, 1, 1}, // 3 - new int[]{1, 1, 3, 2}, // 4 - new int[]{1, 2, 3, 1}, // 5 - new int[]{1, 1, 1, 4}, // 6 - new int[]{1, 3, 1, 2}, // 7 - new int[]{1, 2, 1, 3}, // 8 - new int[]{3, 1, 1, 2} // 9 - }; - - /** - * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits. - */ - public static int[][] L_AND_G_PATTERNS=new int[20][]; - - //static { - // L_AND_G_PATTERNS = new int[20][]; - // for (int i = 0; i < 10; i++) { - // L_AND_G_PATTERNS[i] = L_PATTERNS[i]; - // } - // for (int i = 10; i < 20; i++) { - // int[] widths = L_PATTERNS[i - 10]; - // int[] reversedWidths = new int[widths.length]; - // for (int j = 0; j < widths.length; j++) { - // reversedWidths[j] = widths[widths.length - j - 1]; - // } - // L_AND_G_PATTERNS[i] = reversedWidths; - // } - //} - - private StringBuilder decodeRowStringBuffer; - - protected AbstractUPCEANReader() { - for (int i = 0; i < 10; i++) { - L_AND_G_PATTERNS[i] = L_PATTERNS[i]; - } - for (int i = 10; i < 20; i++) { - int[] widths = L_PATTERNS[i - 10]; - int[] reversedWidths = new int[widths.Length]; - for (int j = 0; j < widths.Length; j++) { - reversedWidths[j] = widths[widths.Length - j - 1]; - } - L_AND_G_PATTERNS[i] = reversedWidths; - } - decodeRowStringBuffer = new StringBuilder(20); - } - - public static int[] findStartGuardPattern(BitArray row) { - bool foundStart = false; - int[] startRange = null; - int nextStart = 0; - while (!foundStart) { - startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN); - int start = startRange[0]; - nextStart = startRange[1]; - // Make sure there is a quiet zone at least as big as the start pattern before the barcode. If - // this check would run off the left edge of the image, do not accept this barcode, as it is - // very likely to be a false positive. - int quietStart = start - (nextStart - start); - if (quietStart >= 0) { - foundStart = row.isRange(quietStart, start, false); - } - } - return startRange; - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - return decodeRow(rowNumber, row, findStartGuardPattern(row)); - } - - public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange) { - StringBuilder result = decodeRowStringBuffer; - result.Length = 0; - int endStart = decodeMiddle(row, startGuardRange, result); - int[] endRange = decodeEnd(row, endStart); - - // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The - // spec might want more whitespace, but in practice this is the maximum we can count on. - int end = endRange[1]; - int quietEnd = end + (end - endRange[0]); - if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) { - throw new ReaderException(); - } - - String resultString = result.ToString(); - if (!checkChecksum(resultString)) { - throw new ReaderException(); - } - - float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f; - float right = (float) (endRange[1] + endRange[0]) / 2.0f; - return new Result(resultString, - null, // no natural byte representation for these barcodes - new ResultPoint[]{ - new GenericResultPoint(left, (float) rowNumber), - new GenericResultPoint(right, (float) rowNumber)}, - getBarcodeFormat()); - } - - public abstract BarcodeFormat getBarcodeFormat(); - - /** - * @return {@link #checkStandardUPCEANChecksum(String)} - */ - public bool checkChecksum(String s) { - return checkStandardUPCEANChecksum(s); - } - - /** - * Computes the UPC/EAN checksum on a string of digits, and reports - * whether the checksum is correct or not. - * - * @param s string of digits to check - * @return true iff string of digits passes the UPC/EAN checksum algorithm - * @throws ReaderException if the string does not contain only digits - */ - public static bool checkStandardUPCEANChecksum(String s) { - int length = s.Length; - if (length == 0) { - return false; - } - - int sum = 0; - for (int i = length - 2; i >= 0; i -= 2) { - int digit = (int) s[i] - (int) '0'; - if (digit < 0 || digit > 9) { - throw new ReaderException(); - } - sum += digit; - } - sum *= 3; - for (int i = length - 1; i >= 0; i -= 2) { - int digit = (int) s[i] - (int) '0'; - if (digit < 0 || digit > 9) { - throw new ReaderException(); - } - sum += digit; - } - return sum % 10 == 0; - } - - /** - * Subclasses override this to decode the portion of a barcode between the start and end guard patterns. - * - * @param row row of black/white values to search - * @param startRange start/end offset of start guard pattern - * @param resultString {@link StringBuffer} to append decoded chars to - * @return horizontal offset of first pixel after the "middle" that was decoded - * @throws ReaderException if decoding could not complete successfully - */ - protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString); - - int[] decodeEnd(BitArray row, int endStart) { - return findGuardPattern(row, endStart, false, START_END_PATTERN); - } - - /** - * @param row row of black/white values to search - * @param rowOffset position to start search - * @param whiteFirst if true, indicates that the pattern specifies white/black/white/... - * pixel counts, otherwise, it is interpreted as black/white/black/... - * @param pattern pattern of counts of number of black and white pixels that are being - * searched for as a pattern - * @return start/end horizontal offset of guard pattern, as an array of two ints - * @throws ReaderException if pattern is not found - */ - public static int[] findGuardPattern(BitArray row, int rowOffset, bool whiteFirst, int[] pattern) - { - int patternLength = pattern.Length; - int[] counters = new int[patternLength]; - int width = row.getSize(); - bool isWhite = false; - while (rowOffset < width) { - isWhite = !row.get(rowOffset); - if (whiteFirst == isWhite) { - break; - } - rowOffset++; - } - - int counterPosition = 0; - int patternStart = rowOffset; - for (int x = rowOffset; x < width; x++) { - bool pixel = row.get(x); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - if (counterPosition == patternLength - 1) { - if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { - return new int[]{patternStart, x}; - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } else { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw new ReaderException(); - } - - /** - * Attempts to decode a single UPC/EAN-encoded digit. - * - * @param row row of black/white values to decode - * @param counters the counts of runs of observed black/white/black/... values - * @param rowOffset horizontal offset to start decoding from - * @param patterns the set of patterns to use to decode -- sometimes different encodings - * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should - * be used - * @return horizontal offset of first pixel beyond the decoded digit - * @throws ReaderException if digit cannot be decoded - */ - public static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns) - { - recordPattern(row, rowOffset, counters); - int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept - int bestMatch = -1; - int max = patterns.Length; - for (int i = 0; i < max; i++) { - int[] pattern = patterns[i]; - int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) { - bestVariance = variance; - bestMatch = i; - } - } - if (bestMatch >= 0) { - return bestMatch; - } else { - throw new ReaderException(); - } - } - - - } - - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/Code128Reader.cs b/qrcode-scanner-live2/oned/Code128Reader.cs deleted file mode 100644 index 3be0c5a..0000000 --- a/qrcode-scanner-live2/oned/Code128Reader.cs +++ /dev/null @@ -1,459 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using System.Text; - using com.google.zxing.common; - - - public sealed class Code128Reader : AbstractOneDReader - { - private static int[][] CODE_PATTERNS = new int[][]{ - new int[]{2, 1, 2, 2, 2, 2}, // 0 - new int[]{2, 2, 2, 1, 2, 2}, - new int[]{2, 2, 2, 2, 2, 1}, - new int[]{1, 2, 1, 2, 2, 3}, - new int[]{1, 2, 1, 3, 2, 2}, - new int[]{1, 3, 1, 2, 2, 2}, // 5 - new int[]{1, 2, 2, 2, 1, 3}, - new int[]{1, 2, 2, 3, 1, 2}, - new int[]{1, 3, 2, 2, 1, 2}, - new int[]{2, 2, 1, 2, 1, 3}, - new int[]{2, 2, 1, 3, 1, 2}, // 10 - new int[]{2, 3, 1, 2, 1, 2}, - new int[]{1, 1, 2, 2, 3, 2}, - new int[]{1, 2, 2, 1, 3, 2}, - new int[]{1, 2, 2, 2, 3, 1}, - new int[]{1, 1, 3, 2, 2, 2}, // 15 - new int[]{1, 2, 3, 1, 2, 2}, - new int[]{1, 2, 3, 2, 2, 1}, - new int[]{2, 2, 3, 2, 1, 1}, - new int[]{2, 2, 1, 1, 3, 2}, - new int[]{2, 2, 1, 2, 3, 1}, // 20 - new int[]{2, 1, 3, 2, 1, 2}, - new int[]{2, 2, 3, 1, 1, 2}, - new int[]{3, 1, 2, 1, 3, 1}, - new int[]{3, 1, 1, 2, 2, 2}, - new int[]{3, 2, 1, 1, 2, 2}, // 25 - new int[]{3, 2, 1, 2, 2, 1}, - new int[]{3, 1, 2, 2, 1, 2}, - new int[]{3, 2, 2, 1, 1, 2}, - new int[]{3, 2, 2, 2, 1, 1}, - new int[]{2, 1, 2, 1, 2, 3}, // 30 - new int[]{2, 1, 2, 3, 2, 1}, - new int[]{2, 3, 2, 1, 2, 1}, - new int[]{1, 1, 1, 3, 2, 3}, - new int[]{1, 3, 1, 1, 2, 3}, - new int[]{1, 3, 1, 3, 2, 1}, // 35 - new int[]{1, 1, 2, 3, 1, 3}, - new int[]{1, 3, 2, 1, 1, 3}, - new int[]{1, 3, 2, 3, 1, 1}, - new int[]{2, 1, 1, 3, 1, 3}, - new int[]{2, 3, 1, 1, 1, 3}, // 40 - new int[]{2, 3, 1, 3, 1, 1}, - new int[]{1, 1, 2, 1, 3, 3}, - new int[]{1, 1, 2, 3, 3, 1}, - new int[]{1, 3, 2, 1, 3, 1}, - new int[]{1, 1, 3, 1, 2, 3}, // 45 - new int[]{1, 1, 3, 3, 2, 1}, - new int[]{1, 3, 3, 1, 2, 1}, - new int[]{3, 1, 3, 1, 2, 1}, - new int[]{2, 1, 1, 3, 3, 1}, - new int[]{2, 3, 1, 1, 3, 1}, // 50 - new int[]{2, 1, 3, 1, 1, 3}, - new int[]{2, 1, 3, 3, 1, 1}, - new int[]{2, 1, 3, 1, 3, 1}, - new int[]{3, 1, 1, 1, 2, 3}, - new int[]{3, 1, 1, 3, 2, 1}, // 55 - new int[]{3, 3, 1, 1, 2, 1}, - new int[]{3, 1, 2, 1, 1, 3}, - new int[]{3, 1, 2, 3, 1, 1}, - new int[]{3, 3, 2, 1, 1, 1}, - new int[]{3, 1, 4, 1, 1, 1}, // 60 - new int[]{2, 2, 1, 4, 1, 1}, - new int[]{4, 3, 1, 1, 1, 1}, - new int[]{1, 1, 1, 2, 2, 4}, - new int[]{1, 1, 1, 4, 2, 2}, - new int[] {1, 2, 1, 1, 2, 4}, // 65 - new int[]{1, 2, 1, 4, 2, 1}, - new int[]{1, 4, 1, 1, 2, 2}, - new int[]{1, 4, 1, 2, 2, 1}, - new int[]{1, 1, 2, 2, 1, 4}, - new int[]{1, 1, 2, 4, 1, 2}, // 70 - new int[]{1, 2, 2, 1, 1, 4}, - new int[]{1, 2, 2, 4, 1, 1}, - new int[]{1, 4, 2, 1, 1, 2}, - new int[]{1, 4, 2, 2, 1, 1}, - new int[]{2, 4, 1, 2, 1, 1}, // 75 - new int[]{2, 2, 1, 1, 1, 4}, - new int[]{4, 1, 3, 1, 1, 1}, - new int[]{2, 4, 1, 1, 1, 2}, - new int[]{1, 3, 4, 1, 1, 1}, - new int[]{1, 1, 1, 2, 4, 2}, // 80 - new int[]{1, 2, 1, 1, 4, 2}, - new int[]{1, 2, 1, 2, 4, 1}, - new int[]{1, 1, 4, 2, 1, 2}, - new int[]{1, 2, 4, 1, 1, 2}, - new int[]{1, 2, 4, 2, 1, 1}, // 85 - new int[]{4, 1, 1, 2, 1, 2}, - new int[]{4, 2, 1, 1, 1, 2}, - new int[]{4, 2, 1, 2, 1, 1}, - new int[]{2, 1, 2, 1, 4, 1}, - new int[]{2, 1, 4, 1, 2, 1}, // 90 - new int[]{4, 1, 2, 1, 2, 1}, - new int[]{1, 1, 1, 1, 4, 3}, - new int[]{1, 1, 1, 3, 4, 1}, - new int[]{1, 3, 1, 1, 4, 1}, - new int[]{1, 1, 4, 1, 1, 3}, // 95 - new int[]{1, 1, 4, 3, 1, 1}, - new int[]{4, 1, 1, 1, 1, 3}, - new int[]{4, 1, 1, 3, 1, 1}, - new int[]{1, 1, 3, 1, 4, 1}, - new int[]{1, 1, 4, 1, 3, 1}, // 100 - new int[]{3, 1, 1, 1, 4, 1}, - new int[]{4, 1, 1, 1, 3, 1}, - new int[]{2, 1, 1, 4, 1, 2}, - new int[]{2, 1, 1, 2, 1, 4}, - new int[]{2, 1, 1, 2, 3, 2}, // 105 - new int[]{2, 3, 3, 1, 1, 1, 2} - }; - - private static int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f); - private static int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); - - private const int CODE_SHIFT = 98; - - private const int CODE_CODE_C = 99; - private const int CODE_CODE_B = 100; - private const int CODE_CODE_A = 101; - - private const int CODE_FNC_1 = 102; - private const int CODE_FNC_2 = 97; - private const int CODE_FNC_3 = 96; - private const int CODE_FNC_4_A = 101; - private const int CODE_FNC_4_B = 100; - - private const int CODE_START_A = 103; - private const int CODE_START_B = 104; - private const int CODE_START_C = 105; - private const int CODE_STOP = 106; - - private static int[] findStartPattern(BitArray row) { - int width = row.getSize(); - int rowOffset = 0; - while (rowOffset < width) { - if (row.get(rowOffset)) { - break; - } - rowOffset++; - } - - int counterPosition = 0; - int[] counters = new int[6]; - int patternStart = rowOffset; - bool isWhite = false; - int patternLength = counters.Length; - - for (int i = rowOffset; i < width; i++) { - bool pixel = row.get(i); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - if (counterPosition == patternLength - 1) { - int bestVariance = MAX_AVG_VARIANCE; - int bestMatch = -1; - for (int startCode = CODE_START_A; startCode <= CODE_START_C; startCode++) { - int variance = patternMatchVariance(counters, CODE_PATTERNS[startCode], MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) { - bestVariance = variance; - bestMatch = startCode; - } - } - if (bestMatch >= 0) { - // Look for whitespace before start pattern, >= 50% of width of start pattern - if (row.isRange(Math.Max(0, patternStart - (i - patternStart) / 2), patternStart, false)) { - return new int[]{patternStart, i, bestMatch}; - } - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } else { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw new ReaderException(); - } - - private static int decodeCode(BitArray row, int[] counters, int rowOffset) { - recordPattern(row, rowOffset, counters); - int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept - int bestMatch = -1; - for (int d = 0; d < CODE_PATTERNS.Length; d++) { - int[] pattern = CODE_PATTERNS[d]; - int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) { - bestVariance = variance; - bestMatch = d; - } - } - // TODO We're overlooking the fact that the STOP pattern has 7 values, not 6 - if (bestMatch >= 0) { - return bestMatch; - } else { - throw new ReaderException(); - } - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - - int[] startPatternInfo = findStartPattern(row); - int startCode = startPatternInfo[2]; - int codeSet; - switch (startCode) { - case CODE_START_A: - codeSet = CODE_CODE_A; - break; - case CODE_START_B: - codeSet = CODE_CODE_B; - break; - case CODE_START_C: - codeSet = CODE_CODE_C; - break; - default: - throw new ReaderException(); - } - - bool done = false; - bool isNextShifted = false; - - StringBuilder result = new StringBuilder(); - int lastStart = startPatternInfo[0]; - int nextStart = startPatternInfo[1]; - int[] counters = new int[6]; - - int lastCode = 0; - int code = 0; - int checksumTotal = startCode; - int multiplier = 0; - bool lastCharacterWasPrintable = true; - - while (!done) { - - bool unshift = isNextShifted; - isNextShifted = false; - - // Save off last code - lastCode = code; - - // Decode another code from image - code = decodeCode(row, counters, nextStart); - - // Remember whether the last code was printable or not (excluding CODE_STOP) - if (code != CODE_STOP) { - lastCharacterWasPrintable = true; - } - - // Add to checksum computation (if not CODE_STOP of course) - if (code != CODE_STOP) { - multiplier++; - checksumTotal += multiplier * code; - } - - // Advance to where the next code will to start - lastStart = nextStart; - for (int i = 0; i < counters.Length; i++) { - nextStart += counters[i]; - } - - // Take care of illegal start codes - switch (code) { - case CODE_START_A: - case CODE_START_B: - case CODE_START_C: - throw new ReaderException(); - } - - switch (codeSet) { - - case CODE_CODE_A: - if (code < 64) { - result.Append((char) (' ' + code)); - } else if (code < 96) { - result.Append((char) (code - 64)); - } else { - // Don't let CODE_STOP, which always appears, affect whether whether we think the last code - // was printable or not - if (code != CODE_STOP) { - lastCharacterWasPrintable = false; - } - switch (code) { - case CODE_FNC_1: - case CODE_FNC_2: - case CODE_FNC_3: - case CODE_FNC_4_A: - // do nothing? - break; - case CODE_SHIFT: - isNextShifted = true; - codeSet = CODE_CODE_B; - break; - case CODE_CODE_B: - codeSet = CODE_CODE_B; - break; - case CODE_CODE_C: - codeSet = CODE_CODE_C; - break; - case CODE_STOP: - done = true; - break; - } - } - break; - case CODE_CODE_B: - if (code < 96) { - result.Append((char) (' ' + code)); - } else { - if (code != CODE_STOP) { - lastCharacterWasPrintable = false; - } - switch (code) { - case CODE_FNC_1: - case CODE_FNC_2: - case CODE_FNC_3: - case CODE_FNC_4_B: - // do nothing? - break; - case CODE_SHIFT: - isNextShifted = true; - codeSet = CODE_CODE_C; - break; - case CODE_CODE_A: - codeSet = CODE_CODE_A; - break; - case CODE_CODE_C: - codeSet = CODE_CODE_C; - break; - case CODE_STOP: - done = true; - break; - } - } - break; - case CODE_CODE_C: - if (code < 100) { - if (code < 10) { - result.Append('0'); - } - result.Append(code); - } else { - if (code != CODE_STOP) { - lastCharacterWasPrintable = false; - } - switch (code) { - case CODE_FNC_1: - // do nothing? - break; - case CODE_CODE_A: - codeSet = CODE_CODE_A; - break; - case CODE_CODE_B: - codeSet = CODE_CODE_B; - break; - case CODE_STOP: - done = true; - break; - } - } - break; - } - - // Unshift back to another code set if we were shifted - if (unshift) { - switch (codeSet) { - case CODE_CODE_A: - codeSet = CODE_CODE_C; - break; - case CODE_CODE_B: - codeSet = CODE_CODE_A; - break; - case CODE_CODE_C: - codeSet = CODE_CODE_B; - break; - } - } - - } - - // Check for ample whitespice following pattern, but, to do this we first need to remember that we - // fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left to read off. - // Would be slightly better to properly read. Here we just skip it: - while (row.get(nextStart)) { - nextStart++; - } - if (!row.isRange(nextStart, Math.Min(row.getSize(), nextStart + (nextStart - lastStart) / 2), false)) { - throw new ReaderException(); - } - - // Pull out from sum the value of the penultimate check code - checksumTotal -= multiplier * lastCode; - // lastCode is the checksum then: - if (checksumTotal % 103 != lastCode) { - throw new ReaderException(); - } - - // Need to pull out the check digits from string - int resultLength = result.Length; - // Only bother if, well, the result had at least one character, and if the checksum digit happened - // to be a printable character. If it was just interpreted as a control code, nothing to remove - if (resultLength > 0 && lastCharacterWasPrintable) { - if (codeSet == CODE_CODE_C) { - result.Remove(resultLength - 2, 2); - } else { - result.Remove(resultLength - 1, 1); - } - } - - String resultString = result.ToString(); - - if (resultString.Length == 0) { - // Almost surely a false positive - throw new ReaderException(); - } - - float left = (float) (startPatternInfo[1] + startPatternInfo[0]) / 2.0f; - float right = (float) (nextStart + lastStart) / 2.0f; - return new Result( - resultString, - null, - new ResultPoint[]{ - new GenericResultPoint(left, (float) rowNumber), - new GenericResultPoint(right, (float) rowNumber)}, - BarcodeFormat.CODE_128); - - } - - } - - - -} diff --git a/qrcode-scanner-live2/oned/Code39Reader.cs b/qrcode-scanner-live2/oned/Code39Reader.cs deleted file mode 100644 index ebddc97..0000000 --- a/qrcode-scanner-live2/oned/Code39Reader.cs +++ /dev/null @@ -1,319 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using System.Text; - using com.google.zxing.common; - - - public sealed class Code39Reader : AbstractOneDReader - { - private static String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; - private static char[] ALPHABET = ALPHABET_STRING.ToCharArray(); - - /** - * These represent the encodings of characters, as patterns of wide and narrow bars. - * The 9 least-significant bits of each int correspond to the pattern of wide and narrow, - * with 1s representing "wide" and 0s representing narrow. - */ - private static int[] CHARACTER_ENCODINGS = { - 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, // 0-9 - 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, // A-J - 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, // K-T - 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, // U-* - 0x0A8, 0x0A2, 0x08A, 0x02A // $-% - }; - - private static int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; - - private bool usingCheckDigit; - private bool extendedMode; - - /** - * Creates a reader that assumes all encoded data is data, and does not treat the - * character as a check digit. It will not decoded "extended Code 39" sequences. - */ - public Code39Reader() { - usingCheckDigit = false; - extendedMode = false; - } - - /** - * Creates a reader that can be configured to check the last character as a check digit. - * It will not decoded "extended Code 39" sequences. - * - * @param usingCheckDigit if true, treat the last data character as a check digit, not - * data, and verify that the checksum passes. - */ - public Code39Reader(bool usingCheckDigit) { - this.usingCheckDigit = usingCheckDigit; - this.extendedMode = false; - } - - /** - * Creates a reader that can be configured to check the last character as a check digit, - * or optionally attempt to decode "extended Code 39" sequences that are used to encode - * the full ASCII character set. - * - * @param usingCheckDigit if true, treat the last data character as a check digit, not - * data, and verify that the checksum passes. - * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the - * text. - */ - public Code39Reader(bool usingCheckDigit, bool extendedMode) { - this.usingCheckDigit = usingCheckDigit; - this.extendedMode = extendedMode; - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - - int[] start = findAsteriskPattern(row); - int nextStart = start[1]; - int end = row.getSize(); - - // Read off white space - while (nextStart < end && !row.get(nextStart)) { - nextStart++; - } - - StringBuilder result = new StringBuilder(); - int[] counters = new int[9]; - char decodedChar; - int lastStart; - do { - recordPattern(row, nextStart, counters); - int pattern = toNarrowWidePattern(counters); - decodedChar = patternToChar(pattern); - result.Append(decodedChar); - lastStart = nextStart; - for (int i = 0; i < counters.Length; i++) { - nextStart += counters[i]; - } - // Read off white space - while (nextStart < end && !row.get(nextStart)) { - nextStart++; - } - } while (decodedChar != '*'); - - result.Remove(result.Length - 1, 1); // remove asterisk - - // Look for whitespace after pattern: - int lastPatternSize = 0; - for (int i = 0; i < counters.Length; i++) { - lastPatternSize += counters[i]; - } - int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; - // If 50% of last pattern size, following last pattern, is not whitespace, fail - // (but if it's whitespace to the very end of the image, that's OK) - if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) { - throw new ReaderException(); - } - - if (usingCheckDigit) { - int max = result.Length - 1; - int total = 0; - for (int i = 0; i < max; i++) { - total += ALPHABET_STRING.IndexOf(result[i]); - } - if (total % 43 != ALPHABET_STRING.IndexOf(result[max])) - { - throw new ReaderException(); - } - result.Remove(max,1); - } - - String resultString = result.ToString(); - if (extendedMode) { - resultString = decodeExtended(resultString); - } - - if (resultString.Length == 0) { - // Almost surely a false positive - throw new ReaderException(); - } - - float left = (float) (start[1] + start[0]) / 2.0f; - float right = (float) (nextStart + lastStart) / 2.0f; - return new Result( - resultString, - null, - new ResultPoint[]{ - new GenericResultPoint(left, (float) rowNumber), - new GenericResultPoint(right, (float) rowNumber)}, - BarcodeFormat.CODE_39); - - } - - private static int[] findAsteriskPattern(BitArray row) { - int width = row.getSize(); - int rowOffset = 0; - while (rowOffset < width) { - if (row.get(rowOffset)) { - break; - } - rowOffset++; - } - - int counterPosition = 0; - int[] counters = new int[9]; - int patternStart = rowOffset; - bool isWhite = false; - int patternLength = counters.Length; - - for (int i = rowOffset; i < width; i++) { - bool pixel = row.get(i); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - if (counterPosition == patternLength - 1) { - try { - if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) { - // Look for whitespace before start pattern, >= 50% of width of start pattern - if (row.isRange(Math.Max(0, patternStart - (i - patternStart) / 2), patternStart, false)) { - return new int[]{patternStart, i}; - } - } - } catch (ReaderException re) { - // no match, continue - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } else { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw new ReaderException(); - } - - private static int toNarrowWidePattern(int[] counters) { - int numCounters = counters.Length; - int maxNarrowCounter = 0; - int wideCounters; - do { - int minCounter = int.MaxValue; - for (int i = 0; i < numCounters; i++) { - int counter = counters[i]; - if (counter < minCounter && counter > maxNarrowCounter) { - minCounter = counter; - } - } - maxNarrowCounter = minCounter; - wideCounters = 0; - int totalWideCountersWidth = 0; - int pattern = 0; - for (int i = 0; i < numCounters; i++) { - int counter = counters[i]; - if (counters[i] > maxNarrowCounter) { - pattern |= 1 << (numCounters - 1 - i); - wideCounters++; - totalWideCountersWidth += counter; - } - } - if (wideCounters == 3) { - // Found 3 wide counters, but are they close enough in width? - // We can perform a cheap, conservative check to see if any individual - // counter is more than 1.5 times the average: - for (int i = 0; i < numCounters && wideCounters > 0; i++) { - int counter = counters[i]; - if (counters[i] > maxNarrowCounter) { - wideCounters--; - // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average - if ((counter << 1) >= totalWideCountersWidth) { - throw new ReaderException(); - } - } - } - return pattern; - } - } while (wideCounters > 3); - throw new ReaderException(); - } - - private static char patternToChar(int pattern) { - for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++) { - if (CHARACTER_ENCODINGS[i] == pattern) { - return ALPHABET[i]; - } - } - throw new ReaderException(); - } - - private static String decodeExtended(String encoded) { - int Length = encoded.Length; - StringBuilder decoded = new StringBuilder(Length); - for (int i = 0; i < Length; i++) { - char c = encoded[i]; - if (c == '+' || c == '$' || c == '%' || c == '/') { - char next = encoded[i + 1]; - char decodedChar = '\0'; - switch (c) { - case '+': - // +A to +Z map to a to z - if (next >= 'A' && next <= 'Z') { - decodedChar = (char) (next + 32); - } else { - throw new ReaderException(); - } - break; - case '$': - // $A to $Z map to control codes SH to SB - if (next >= 'A' && next <= 'Z') { - decodedChar = (char) (next - 64); - } else { - throw new ReaderException(); - } - break; - case '%': - // %A to %E map to control codes ESC to US - if (next >= 'A' && next <= 'E') { - decodedChar = (char) (next - 38); - } else if (next >= 'F' && next <= 'W') { - decodedChar = (char) (next - 11); - } else { - throw new ReaderException(); - } - break; - case '/': - // /A to /O map to ! to , and /Z maps to : - if (next >= 'A' && next <= 'O') { - decodedChar = (char) (next - 32); - } else if (next == 'Z') { - decodedChar = ':'; - } else { - throw new ReaderException(); - } - break; - } - decoded.Append(decodedChar); - // bump up i again since we read two characters - i++; - } else { - decoded.Append(c); - } - } - return decoded.ToString(); - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/EAN13Reader.cs b/qrcode-scanner-live2/oned/EAN13Reader.cs deleted file mode 100644 index 0dda005..0000000 --- a/qrcode-scanner-live2/oned/EAN13Reader.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - *

Implements decoding of the EAN-13 format.

- * - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - * @author alasdair@google.com (Alasdair Mackintosh) - */ - - using System.Text; - using com.google.zxing.common; - - public sealed class EAN13Reader : AbstractUPCEANReader - { - // For an EAN-13 barcode, the first digit is represented by the parities used - // to encode the next six digits, according to the table below. For example, - // if the barcode is 5 123456 789012 then the value of the first digit is - // signified by using odd for '1', even for '2', even for '3', odd for '4', - // odd for '5', and even for '6'. See http://en.wikipedia.org/wiki/EAN-13 - // - // Parity of next 6 digits - // Digit 0 1 2 3 4 5 - // 0 Odd Odd Odd Odd Odd Odd - // 1 Odd Odd Even Odd Even Even - // 2 Odd Odd Even Even Odd Even - // 3 Odd Odd Even Even Even Odd - // 4 Odd Even Odd Odd Even Even - // 5 Odd Even Even Odd Odd Even - // 6 Odd Even Even Even Odd Odd - // 7 Odd Even Odd Even Odd Even - // 8 Odd Even Odd Even Even Odd - // 9 Odd Even Even Odd Even Odd - // - // Note that the encoding for '0' uses the same parity as a UPC barcode. Hence - // a UPC barcode can be converted to an EAN-13 barcode by prepending a 0. - // - // The encodong is represented by the following array, which is a bit pattern - // using Odd = 0 and Even = 1. For example, 5 is represented by: - // - // Odd Even Even Odd Odd Even - // in binary: - // 0 1 1 0 0 1 == 0x19 - // - private static int[] FIRST_DIGIT_ENCODINGS = { - 0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A - }; - - private int[] decodeMiddleCounters; - - public EAN13Reader() { - decodeMiddleCounters = new int[4]; - } - - protected override int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) { - int[] counters = decodeMiddleCounters; - counters[0] = 0; - counters[1] = 0; - counters[2] = 0; - counters[3] = 0; - int end = row.getSize(); - int rowOffset = startRange[1]; - - int lgPatternFound = 0; - - for (int x = 0; x < 6 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); - resultString.Append((char) ('0' + bestMatch % 10)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - if (bestMatch >= 10) { - lgPatternFound |= 1 << (5 - x); - } - } - - determineFirstDigit(resultString, lgPatternFound); - - int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); - rowOffset = middleRange[1]; - - for (int x = 0; x < 6 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); - resultString.Append((char) ('0' + bestMatch)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - } - - return rowOffset; - } - - public override BarcodeFormat getBarcodeFormat() { - return BarcodeFormat.EAN_13; - } - - /** - * Based on pattern of odd-even ('L' and 'G') patterns used to encoded the explicitly-encoded digits - * in a barcode, determines the implicitly encoded first digit and adds it to the result string. - * - * @param resultString string to insert decoded first digit into - * @param lgPatternFound int whose bits indicates the pattern of odd/even L/G patterns used to - * encode digits - * @throws ReaderException if first digit cannot be determined - */ - private static void determineFirstDigit(StringBuilder resultString, int lgPatternFound) { - for (int d = 0; d < 10; d++) { - if (lgPatternFound == FIRST_DIGIT_ENCODINGS[d]) { - resultString.Insert(0, (char) ('0' + d)); - return; - } - } - throw new ReaderException(); - } - - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/EAN8Reader.cs b/qrcode-scanner-live2/oned/EAN8Reader.cs deleted file mode 100644 index 6a21b19..0000000 --- a/qrcode-scanner-live2/oned/EAN8Reader.cs +++ /dev/null @@ -1,64 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System; - using System.Text; - using com.google.zxing.common; - - public sealed class EAN8Reader : AbstractUPCEANReader - { - private int[] decodeMiddleCounters; - public EAN8Reader() { - decodeMiddleCounters = new int[4]; - } - - protected override int decodeMiddle(BitArray row, int[] startRange, StringBuilder result) { - int[] counters = decodeMiddleCounters; - counters[0] = 0; - counters[1] = 0; - counters[2] = 0; - counters[3] = 0; - int end = row.getSize(); - int rowOffset = startRange[1]; - - for (int x = 0; x < 4 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); - result.Append((char) ('0' + bestMatch)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - } - - int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); - rowOffset = middleRange[1]; - - for (int x = 0; x < 4 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); - result.Append((char) ('0' + bestMatch)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - } - - return rowOffset; - } - - public override BarcodeFormat getBarcodeFormat() { - return BarcodeFormat.EAN_8; - } - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/ITFReader.cs b/qrcode-scanner-live2/oned/ITFReader.cs deleted file mode 100644 index 264e234..0000000 --- a/qrcode-scanner-live2/oned/ITFReader.cs +++ /dev/null @@ -1,323 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - *

Implements decoding of the EAN-13 format.

- * - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - * @author alasdair@google.com (Alasdair Mackintosh) - */ - - using System.Text; - using com.google.zxing.common; - - public sealed class ITFReader : AbstractOneDReader - { - private static int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f); - private static int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.8f); - - private static int W = 3; // Pixel width of a wide line - private static int N = 1; // Pixed width of a narrow line - - // Stores the actual narrow line width of the image being decoded. - private int narrowLineWidth = -1; - - /** - * Start/end guard pattern. - * - * Note: The end pattern is reversed because the row is reversed before - * searching for the END_PATTERN - */ - private static int[] START_PATTERN = {N, N, N, N}; - private static int[] END_PATTERN_REVERSED = {N, N, W}; - - /** - * Patterns of Wide / Narrow lines to indicate each digit - */ - private static int[][] PATTERNS = new int[][]{ - new int[]{N, N, W, W, N}, // 0 - new int[]{W, N, N, N, W}, // 1 - new int[]{N, W, N, N, W}, // 2 - new int[]{W, W, N, N, N}, // 3 - new int[]{N, N, W, N, W}, // 4 - new int[]{W, N, W, N, N}, // 5 - new int[]{N, W, W, N, N}, // 6 - new int[]{N, N, N, W, W}, // 7 - new int[]{W, N, N, W, N}, // 8 - new int[]{N, W, N, W, N} // 9 - }; - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - - StringBuilder result = new StringBuilder(20); - - // Find out where the Middle section (payload) starts & ends - int[] startRange = decodeStart(row); - int[] endRange = decodeEnd(row); - - decodeMiddle(row, startRange[1], endRange[0], result); - - string resultString = result.ToString(); - - // To avoid false positives with 2D barcodes (and other patterns), make - // an assumption that the decoded string must be 6, 10 or 14 digits. - int length = resultString.Length; - if (length != 6 && length != 10 && length != 14) { - throw new ReaderException(); - } - - return new Result( - resultString, - null, // no natural byte representation for these barcodes - new ResultPoint[] { new GenericResultPoint(startRange[1], (float) rowNumber), - new GenericResultPoint(startRange[0], (float) rowNumber)}, - BarcodeFormat.ITF); - } - - /** - * @param row row of black/white values to search - * @param payloadStart offset of start pattern - * @param resultString {@link StringBuilder} to Append decoded chars to - * @throws ReaderException if decoding could not complete successfully - */ - static void decodeMiddle(BitArray row, int payloadStart, int payloadEnd, StringBuilder resultString) { - - // Digits are interleaved in pairs - 5 black lines for one digit, and the - // 5 - // interleaved white lines for the second digit. - // Therefore, need to scan 10 lines and then - // split these into two arrays - int[] counterDigitPair = new int[10]; - int[] counterBlack = new int[5]; - int[] counterWhite = new int[5]; - - while (payloadStart < payloadEnd) { - - // Get 10 runs of black/white. - recordPattern(row, payloadStart, counterDigitPair); - // Split them into each array - for (int k = 0; k < 5; k++) { - int twoK = k << 1; - counterBlack[k] = counterDigitPair[twoK]; - counterWhite[k] = counterDigitPair[twoK + 1]; - } - - int bestMatch = decodeDigit(counterBlack); - resultString.Append((char) ('0' + bestMatch)); - bestMatch = decodeDigit(counterWhite); - resultString.Append((char) ('0' + bestMatch)); - - for (int i = 0; i < counterDigitPair.Length; i++) { - payloadStart += counterDigitPair[i]; - } - } - } - - /** - * Identify where the start of the middle / payload section starts. - * - * @param row row of black/white values to search - * @return Array, containing index of start of 'start block' and end of - * 'start block' - * @throws ReaderException - */ - int[] decodeStart(BitArray row) { - int endStart = skipWhiteSpace(row); - int[] startPattern = findGuardPattern(row, endStart, START_PATTERN); - - // Determine the width of a narrow line in pixels. We can do this by - // getting the width of the start pattern and dividing by 4 because its - // made up of 4 narrow lines. - this.narrowLineWidth = (startPattern[1] - startPattern[0]) >> 2; - - validateQuietZone(row, startPattern[0]); - - return startPattern; - } - - /** - * The start & end patterns must be pre/post fixed by a quiet zone. This - * zone must be at least 10 times the width of a narrow line. Scan back until - * we either get to the start of the barcode or match the necessary number of - * quiet zone pixels. - * - * Note: Its assumed the row is reversed when using this method to find - * quiet zone after the end pattern. - * - * ref: http://www.barcode-1.net/i25code.html - * - * @param row bit array representing the scanned barcode. - * @param startPattern index into row of the start or end pattern. - * @throws ReaderException if the quiet zone cannot be found, a ReaderException is thrown. - */ - private void validateQuietZone(BitArray row, int startPattern) { - - int quietCount = this.narrowLineWidth * 10; // expect to find this many pixels of quiet zone - - for (int i = startPattern - 1; quietCount > 0 && i >= 0; i--) { - if (row.get(i)) { - break; - } - quietCount--; - } - if (quietCount != 0) { - // Unable to find the necessary number of quiet zone pixels. - throw new ReaderException(); - } - } - - /** - * Skip all whitespace until we get to the first black line. - * - * @param row row of black/white values to search - * @return index of the first black line. - * @throws ReaderException Throws exception if no black lines are found in the row - */ - private int skipWhiteSpace(BitArray row) { - int width = row.getSize(); - int endStart = 0; - while (endStart < width) { - if (row.get(endStart)) { - break; - } - endStart++; - } - if (endStart == width) { - throw new ReaderException(); - } - - return endStart; - } - - /** - * Identify where the end of the middle / payload section ends. - * - * @param row row of black/white values to search - * @return Array, containing index of start of 'end block' and end of 'end - * block' - * @throws ReaderException - */ - - int[] decodeEnd(BitArray row) { - - // For convenience, reverse the row and then - // search from 'the start' for the end block - row.reverse(); - - int endStart = skipWhiteSpace(row); - int[] endPattern; - try { - endPattern = findGuardPattern(row, endStart, END_PATTERN_REVERSED); - } catch (ReaderException e) { - // Put our row of data back the right way before throwing - row.reverse(); - throw e; - } - - // The start & end patterns must be pre/post fixed by a quiet zone. This - // zone must be at least 10 times the width of a narrow line. - // ref: http://www.barcode-1.net/i25code.html - validateQuietZone(row, endPattern[0]); - - // Now recalc the indicies of where the 'endblock' starts & stops to - // accomodate - // the reversed nature of the search - int temp = endPattern[0]; - endPattern[0] = row.getSize() - endPattern[1]; - endPattern[1] = row.getSize() - temp; - - // Put the row back the righ way. - row.reverse(); - return endPattern; - } - - /** - * @param row row of black/white values to search - * @param rowOffset position to start search - * @param pattern pattern of counts of number of black and white pixels that are - * being searched for as a pattern - * @return start/end horizontal offset of guard pattern, as an array of two - * ints - * @throws ReaderException if pattern is not found - */ - int[] findGuardPattern(BitArray row, int rowOffset, int[] pattern) { - - // TODO: This is very similar to implementation in AbstractUPCEANReader. Consider if they can be merged to - // a single method. - - int patternLength = pattern.Length; - int[] counters = new int[patternLength]; - int width = row.getSize(); - bool isWhite = false; - - int counterPosition = 0; - int patternStart = rowOffset; - for (int x = rowOffset; x < width; x++) { - bool pixel = row.get(x); - if ((!pixel && isWhite) || (pixel && !isWhite)) { - counters[counterPosition]++; - } else { - if (counterPosition == patternLength - 1) { - if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { - return new int[]{patternStart, x}; - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } else { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw new ReaderException(); - } - - /** - * Attempts to decode a sequence of ITF black/white lines into single - * digit. - * - * @param counters the counts of runs of observed black/white/black/... values - * @return The decoded digit - * @throws ReaderException if digit cannot be decoded - */ - private static int decodeDigit(int[] counters) { - - int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept - int bestMatch = -1; - int max = PATTERNS.Length; - for (int i = 0; i < max; i++) { - int[] pattern = PATTERNS[i]; - int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) { - bestVariance = variance; - bestMatch = i; - } - } - if (bestMatch >= 0) { - return bestMatch; - } else { - throw new ReaderException(); - } - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/MultiFormatOneDReader.cs b/qrcode-scanner-live2/oned/MultiFormatOneDReader.cs deleted file mode 100644 index b421435..0000000 --- a/qrcode-scanner-live2/oned/MultiFormatOneDReader.cs +++ /dev/null @@ -1,76 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - */ - using System.Text; - using com.google.zxing.common; - - public sealed class MultiFormatOneDReader : AbstractOneDReader - { - private System.Collections.ArrayList readers; - - public MultiFormatOneDReader(System.Collections.Hashtable hints) - { - System.Collections.ArrayList possibleFormats = hints == null ? null : (System.Collections.ArrayList) hints[DecodeHintType.POSSIBLE_FORMATS]; - readers = new System.Collections.ArrayList(); - if (possibleFormats != null) { - if (possibleFormats.Contains(BarcodeFormat.EAN_13) || - possibleFormats.Contains(BarcodeFormat.UPC_A) || - possibleFormats.Contains(BarcodeFormat.EAN_8) || - possibleFormats.Contains(BarcodeFormat.UPC_E)) - { - readers.Add(new MultiFormatUPCEANReader(hints)); - } - if (possibleFormats.Contains(BarcodeFormat.CODE_39)) { - readers.Add(new Code39Reader()); - } - if (possibleFormats.Contains(BarcodeFormat.CODE_128)) - { - readers.Add(new Code128Reader()); - } - if (possibleFormats.Contains(BarcodeFormat.ITF)) - { - readers.Add(new ITFReader()); - } - } - if (readers.Count==0) { - readers.Contains(new MultiFormatUPCEANReader(hints)); - readers.Contains(new Code39Reader()); - readers.Contains(new Code128Reader()); - // TODO: Add ITFReader once it is validated as production ready, and tested for performance. - //readers.addElement(new ITFReader()); - } - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) - { - int size = readers.Count; - for (int i = 0; i < size; i++) { - OneDReader reader = (OneDReader) readers[i]; - try { - return reader.decodeRow(rowNumber, row, hints); - } catch (ReaderException re) { - // continue - } - } - - throw new ReaderException(); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/MultiFormatUPCEANReader.cs b/qrcode-scanner-live2/oned/MultiFormatUPCEANReader.cs deleted file mode 100644 index 98dbf79..0000000 --- a/qrcode-scanner-live2/oned/MultiFormatUPCEANReader.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - */ - using System.Text; - using com.google.zxing.common; - - public sealed class MultiFormatUPCEANReader : AbstractOneDReader - { - private System.Collections.ArrayList readers; - public MultiFormatUPCEANReader(System.Collections.Hashtable hints) { - System.Collections.ArrayList possibleFormats = hints == null ? null : (System.Collections.ArrayList) hints[DecodeHintType.POSSIBLE_FORMATS]; - readers = new System.Collections.ArrayList(); - if (possibleFormats != null) { - if (possibleFormats.Contains(BarcodeFormat.EAN_13)) { - readers.Add(new EAN13Reader()); - } else if (possibleFormats.Contains(BarcodeFormat.UPC_A)) { - readers.Add(new UPCAReader()); - } - if (possibleFormats.Contains(BarcodeFormat.EAN_8)) { - readers.Add(new EAN8Reader()); - } - if (possibleFormats.Contains(BarcodeFormat.UPC_E)) { - readers.Add(new UPCEReader()); - } - } - if (readers.Count==0) { - readers.Add(new EAN13Reader()); - // UPC-A is covered by EAN-13 - readers.Add(new EAN8Reader()); - readers.Add(new UPCEReader()); - } - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - // Compute this location once and reuse it on multiple implementations - int[] startGuardPattern = AbstractUPCEANReader.findStartGuardPattern(row); - int size = readers.Count; - for (int i = 0; i < size; i++) { - UPCEANReader reader = (UPCEANReader) readers[i]; - Result result; - try { - result = reader.decodeRow(rowNumber, row, startGuardPattern); - } catch (ReaderException re) { - continue; - } - // Special case: a 12-digit code encoded in UPC-A is identical to a "0" - // followed by those 12 digits encoded as EAN-13. Each will recognize such a code, - // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0". - // Individually these are correct and their readers will both read such a code - // and correctly call it EAN-13, or UPC-A, respectively. - // - // In this case, if we've been looking for both types, we'd like to call it - // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read - // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A - // result if appropriate. - if (result.getBarcodeFormat().Equals(BarcodeFormat.EAN_13) && result.getText()[0] == '0') { - return new Result(result.getText().Substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A); - } - return result; - } - - throw new ReaderException(); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/OneDReader.cs b/qrcode-scanner-live2/oned/OneDReader.cs deleted file mode 100644 index d7d0ae4..0000000 --- a/qrcode-scanner-live2/oned/OneDReader.cs +++ /dev/null @@ -1,41 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - *

{@link Reader}s which also implement this interface read one-dimensional barcode - * formats, and expose additional functionality that is specific to this type of barcode.

- * - * @author Sean Owen - */ - - using com.google.zxing.common; - - public interface OneDReader :Reader - { - /** - *

Attempts to decode a one-dimensional barcode format given a single row of - * an image.

- * - * @param rowNumber row number from top of the row - * @param row the black/white pixel data of the row - * @param hints decode hints - * @return {@link Result} containing encoded string and start/end of barcode - * @throws ReaderException if an error occurs or barcode cannot be found - */ - Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints); - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/UPCAReader.cs b/qrcode-scanner-live2/oned/UPCAReader.cs deleted file mode 100644 index 257e4c2..0000000 --- a/qrcode-scanner-live2/oned/UPCAReader.cs +++ /dev/null @@ -1,54 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - /** - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - */ - using System.Text; - using com.google.zxing.common; - - public sealed class UPCAReader : UPCEANReader - { - private UPCEANReader ean13Reader = new EAN13Reader(); - - public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange) { - return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange)); - } - - public Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) { - return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, hints)); - } - - public Result decode(MonochromeBitmapSource image) { - return maybeReturnResult(ean13Reader.decode(image)); - } - - public Result decode(MonochromeBitmapSource image, System.Collections.Hashtable hints) { - return maybeReturnResult(ean13Reader.decode(image, hints)); - } - - private static Result maybeReturnResult(Result result) { - string text = result.getText(); - if (text[0] == '0') { - return new Result(text.Substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A); - } else { - throw new ReaderException(); - } - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/UPCEANReader.cs b/qrcode-scanner-live2/oned/UPCEANReader.cs deleted file mode 100644 index c4af834..0000000 --- a/qrcode-scanner-live2/oned/UPCEANReader.cs +++ /dev/null @@ -1,34 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using com.google.zxing.common; - /** - *

This interfaces captures addtional functionality that readers of - * UPC/EAN family of barcodes should expose.

- * - * @author Sean Owen - */ - - public interface UPCEANReader : OneDReader - { - /** - *

Like {@link #decodeRow(int, BitArray, java.util.Hashtable)}, but - * allows caller to inform method about where the UPC/EAN start pattern is - * found. This allows this to be computed once and reused across many implementations.

- */ - Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange); - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/oned/UPCEReader.cs b/qrcode-scanner-live2/oned/UPCEReader.cs deleted file mode 100644 index bed8653..0000000 --- a/qrcode-scanner-live2/oned/UPCEReader.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.oned -{ - using System.Text; - using com.google.zxing.common; - /** - *

Implements decoding of the UPC-E format.

- *

- *

This is a great reference for - * UPC-E information.

- * - * @author Sean Owen - */ - - - public sealed class UPCEReader : AbstractUPCEANReader - { - /** - * The pattern that marks the middle, and end, of a UPC-E pattern. - * There is no "second half" to a UPC-E barcode. - */ - private int[] MIDDLE_END_PATTERN = new int[]{1, 1, 1, 1, 1, 1}; - - /** - * See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of - * even-odd parity encodings of digits that imply both the number system (0 or 1) - * used, and the check digit. - */ - private static int[][] NUMSYS_AND_CHECK_DIGIT_PATTERNS = new int[][]{ - new int[]{0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25}, - new int[]{0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A} - }; - - private int[] decodeMiddleCounters; - - public UPCEReader() { - decodeMiddleCounters = new int[4]; - } - - protected override int decodeMiddle(BitArray row, int[] startRange, StringBuilder result) { - int[] counters = decodeMiddleCounters; - counters[0] = 0; - counters[1] = 0; - counters[2] = 0; - counters[3] = 0; - int end = row.getSize(); - int rowOffset = startRange[1]; - - int lgPatternFound = 0; - - for (int x = 0; x < 6 && rowOffset < end; x++) { - int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); - result.Append((char) ('0' + bestMatch % 10)); - for (int i = 0; i < counters.Length; i++) { - rowOffset += counters[i]; - } - if (bestMatch >= 10) { - lgPatternFound |= 1 << (5 - x); - } - } - - determineNumSysAndCheckDigit(result, lgPatternFound); - - return rowOffset; - } - - public int[] decodeEnd(BitArray row, int endStart) { - return findGuardPattern(row, endStart, true, MIDDLE_END_PATTERN); - } - - public bool checkChecksum(string s) { - return base.checkChecksum(convertUPCEtoUPCA(s)); - } - - private static void determineNumSysAndCheckDigit(StringBuilder resultString, int lgPatternFound) - { - - for (int numSys = 0; numSys <= 1; numSys++) { - for (int d = 0; d < 10; d++) { - if (lgPatternFound == NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]) { - resultString.Insert(0, (char) ('0' + numSys)); - resultString.Append((char) ('0' + d)); - return; - } - } - } - throw new ReaderException(); - } - - public override BarcodeFormat getBarcodeFormat() { - return BarcodeFormat.UPC_E; - } - - /** - * Expands a UPC-E value back into its full, equivalent UPC-A code value. - * - * @param upce UPC-E code as string of digits - * @return equivalent UPC-A code as string of digits - */ - public static string convertUPCEtoUPCA(string upce) { - char[] upceChars = new char[6]; - SupportClass.GetCharsFromString(upce, 1, 7, upceChars, 0); - StringBuilder result = new StringBuilder(12); - result.Append(upce[0]); - char lastChar = upceChars[5]; - switch (lastChar) { - case '0': - case '1': - case '2': - result.Append(upceChars, 0, 2); - result.Append(lastChar); - result.Append("0000"); - result.Append(upceChars, 2, 3); - break; - case '3': - result.Append(upceChars, 0, 3); - result.Append("00000"); - result.Append(upceChars, 3, 2); - break; - case '4': - result.Append(upceChars, 0, 4); - result.Append("00000"); - result.Append(upceChars[4]); - break; - default: - result.Append(upceChars, 0, 5); - result.Append("0000"); - result.Append(lastChar); - break; - } - result.Append(upce[7]); - return result.ToString(); - } - - - } - - -} diff --git a/qrcode-scanner-live2/qrcode/QRCodeReader.cs b/qrcode-scanner-live2/qrcode/QRCodeReader.cs deleted file mode 100644 index b0b7c26..0000000 --- a/qrcode-scanner-live2/qrcode/QRCodeReader.cs +++ /dev/null @@ -1,145 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.qrcode -{ - using System; - using System.Collections; - using com.google.zxing.common; - using com.google.zxing.qrcode.decoder; - using com.google.zxing.qrcode.detector; - - public sealed class QRCodeReader: Reader - { - private static ResultPoint[] NO_POINTS = new ResultPoint[0]; - private Decoder decoder = new Decoder(); - - /** - * Locates and decodes a QR code in an image. - * - * @return a String representing the content encoded by the QR code - * @throws ReaderException if a QR code cannot be found, or cannot be decoded - */ - public Result decode(MonochromeBitmapSource image) { - try{ - return decode(image, null); - } - catch(Exception e){ - throw new ReaderException(e.Message); - } - - } - - public Result decode(MonochromeBitmapSource image, Hashtable hints){ - try{ - DecoderResult decoderResult; - ResultPoint[] points; - if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) { - BitMatrix bits = extractPureBits(image); - decoderResult = decoder.decode(bits); - points = NO_POINTS; - } else { - DetectorResult detectorResult = new Detector(image).detect(hints); - decoderResult = decoder.decode(detectorResult.getBits()); - points = detectorResult.getPoints(); - } - - Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE); - if (decoderResult.getByteSegments() != null) { - result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.getByteSegments()); - } - return result; - }catch(Exception e){ - throw new ReaderException(e.Message); - } - - } - - /** - * This method detects a barcode in a "pure" image -- that is, pure monochrome image - * which contains only an unrotated, unskewed, image of a barcode, with some white border - * around it. This is a specialized method that works exceptionally fast in this special - * case. - */ - private static BitMatrix extractPureBits(MonochromeBitmapSource image){ - // Now need to determine module size in pixels - - int height = image.getHeight(); - int width = image.getWidth(); - int minDimension = Math.Min(height, width); - - // First, skip white border by tracking diagonally from the top left down and to the right: - int borderWidth = 0; - while (borderWidth < minDimension && !image.isBlack(borderWidth, borderWidth)) { - borderWidth++; - } - if (borderWidth == minDimension) { - throw new ReaderException(); - } - - // And then keep tracking across the top-left black module to determine module size - int moduleEnd = borderWidth; - while (moduleEnd < minDimension && image.isBlack(moduleEnd, moduleEnd)) { - moduleEnd++; - } - if (moduleEnd == minDimension) { - throw new ReaderException(); - } - - int moduleSize = moduleEnd - borderWidth; - - // And now find where the rightmost black module on the first row ends - int rowEndOfSymbol = width - 1; - while (rowEndOfSymbol >= 0 && !image.isBlack(rowEndOfSymbol, borderWidth)) { - rowEndOfSymbol--; - } - if (rowEndOfSymbol < 0) { - throw new ReaderException(); - } - rowEndOfSymbol++; - - // Make sure width of barcode is a multiple of module size - if ((rowEndOfSymbol - borderWidth) % moduleSize != 0) { - throw new ReaderException(); - } - int dimension = (rowEndOfSymbol - borderWidth) / moduleSize; - - // Push in the "border" by half the module width so that we start - // sampling in the middle of the module. Just in case the image is a - // little off, this will help recover. - borderWidth += moduleSize >> 1; - - int sampleDimension = borderWidth + (dimension - 1) * moduleSize; - if (sampleDimension >= width || sampleDimension >= height) { - throw new ReaderException(); - } - - // Now just read off the bits - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) { - int iOffset = borderWidth + i * moduleSize; - for (int j = 0; j < dimension; j++) { - if (image.isBlack(borderWidth + j * moduleSize, iOffset)) { - bits.set(i, j); - } - } - } - return bits; - } - - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/QRCodeWriter.cs b/qrcode-scanner-live2/qrcode/QRCodeWriter.cs deleted file mode 100644 index 9b684cf..0000000 --- a/qrcode-scanner-live2/qrcode/QRCodeWriter.cs +++ /dev/null @@ -1,143 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.qrcode -{ - using System; - using System.Collections; - using com.google.zxing.common; - using com.google.zxing.qrcode.decoder; - using com.google.zxing.qrcode.detector; - using com.google.zxing.qrcode.encoder; - - public sealed class QRCodeWriter : Writer - { - private static int QUIET_ZONE_SIZE = 4; - public ByteMatrix encode(String contents, BarcodeFormat format, int width, int height) - { - try{ - return encode(contents, format, width, height, null); - }catch(Exception e){ - throw new WriterException(e.Message); - } - } - - public ByteMatrix encode(String contents, BarcodeFormat format, int width, int height,Hashtable hints) { - - if (contents == null || contents.Length == 0) { - throw new ArgumentException("Found empty contents"); - } - - if (format != BarcodeFormat.QR_CODE) { - throw new ArgumentException("Can only encode QR_CODE, but got " + format); - } - - if (width < 0 || height < 0) { - throw new ArgumentException("Requested dimensions are too small: " + width + 'x' + - height); - } - - ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; - if (hints != null) { - ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints[EncodeHintType.ERROR_CORRECTION]; - if (requestedECLevel != null) { - errorCorrectionLevel = requestedECLevel; - } - } - - QRCode code = new QRCode(); - Encoder.encode(contents, errorCorrectionLevel, code); - return renderResult(code, width, height); - } - - // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses - // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap). - private static ByteMatrix renderResult(QRCode code, int width, int height) { - ByteMatrix input = code.getMatrix(); - int inputWidth = input.width(); - int inputHeight = input.height(); - int qrWidth = inputWidth + (QUIET_ZONE_SIZE << 1); - int qrHeight = inputHeight + (QUIET_ZONE_SIZE << 1); - int outputWidth = Math.Max(width, qrWidth); - int outputHeight = Math.Max(height, qrHeight); - - int multiple = Math.Min(outputWidth / qrWidth, outputHeight / qrHeight); - // Padding includes both the quiet zone and the extra white pixels to accomodate the requested - // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone. - // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will - // handle all the padding from 100x100 (the actual QR) up to 200x160. - int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; - int topPadding = (outputHeight - (inputHeight * multiple)) / 2; - - ByteMatrix output = new ByteMatrix(outputHeight, outputWidth); - sbyte[][] outputArray = output.getArray(); - - // We could be tricky and use the first row in each set of multiple as the temporary storage, - // instead of allocating this separate array. - sbyte[] row = new sbyte[outputWidth]; - - // 1. Write the white lines at the top - for (int y = 0; y < topPadding; y++) { - setRowColor(outputArray[y], unchecked((sbyte)255)); - } - - // 2. Expand the QR image to the multiple - sbyte[][] inputArray = input.getArray(); - for (int y = 0; y < inputHeight; y++) { - // a. Write the white pixels at the left of each row - for (int x = 0; x < leftPadding; x++) { - row[x] = unchecked((sbyte) 255); - } - - // b. Write the contents of this row of the barcode - int offset = leftPadding; - for (int x = 0; x < inputWidth; x++) { - sbyte value = (inputArray[y][x] == 1) ? (sbyte) 0 : unchecked((sbyte) 255); - for (int z = 0; z < multiple; z++) { - row[offset + z] = value; - } - offset += multiple; - } - - // c. Write the white pixels at the right of each row - offset = leftPadding + (inputWidth * multiple); - for (int x = offset; x < outputWidth; x++) { - row[x] = unchecked((sbyte) 255); - } - - // d. Write the completed row multiple times - offset = topPadding + (y * multiple); - for (int z = 0; z < multiple; z++) { - System.Array.Copy(row, 0, outputArray[offset + z], 0, outputWidth); - } - } - - // 3. Write the white lines at the bottom - int offset2 = topPadding + (inputHeight * multiple); - for (int y = offset2; y < outputHeight; y++) - { - setRowColor(outputArray[y], unchecked((sbyte) 255)); - } - return output; - } - - private static void setRowColor(sbyte[] row, sbyte value) { - for (int x = 0; x < row.Length; x++) { - row[x] = value; - } - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/decoder/BitMatrixParser.cs b/qrcode-scanner-live2/qrcode/decoder/BitMatrixParser.cs deleted file mode 100644 index 7a2b643..0000000 --- a/qrcode-scanner-live2/qrcode/decoder/BitMatrixParser.cs +++ /dev/null @@ -1,208 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class BitMatrixParser - { - private BitMatrix bitMatrix; - private Version parsedVersion; - private FormatInformation parsedFormatInfo; - - /** - * @param bitMatrix {@link BitMatrix} to parse - * @throws ReaderException if dimension is not >= 21 and 1 mod 4 - */ - public BitMatrixParser(BitMatrix bitMatrix){ - int dimension = bitMatrix.getDimension(); - if (dimension < 21 || (dimension & 0x03) != 1) { - throw new ReaderException(); - } - this.bitMatrix = bitMatrix; - } - - /** - *

Reads format information from one of its two locations within the QR Code.

- * - * @return {@link FormatInformation} encapsulating the QR Code's format info - * @throws ReaderException if both format information locations cannot be parsed as - * the valid encoding of format information - */ - public FormatInformation readFormatInformation(){ - - if (parsedFormatInfo != null) { - return parsedFormatInfo; - } - - // Read top-left format info bits - int formatInfoBits = 0; - for (int j = 0; j < 6; j++) { - formatInfoBits = copyBit(8, j, formatInfoBits); - } - // .. and skip a bit in the timing pattern ... - formatInfoBits = copyBit(8, 7, formatInfoBits); - formatInfoBits = copyBit(8, 8, formatInfoBits); - formatInfoBits = copyBit(7, 8, formatInfoBits); - // .. and skip a bit in the timing pattern ... - for (int i = 5; i >= 0; i--) { - formatInfoBits = copyBit(i, 8, formatInfoBits); - } - - parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); - if (parsedFormatInfo != null) { - return parsedFormatInfo; - } - - // Hmm, failed. Try the top-right/bottom-left pattern - int dimension = bitMatrix.getDimension(); - formatInfoBits = 0; - int iMin = dimension - 8; - for (int i = dimension - 1; i >= iMin; i--) { - formatInfoBits = copyBit(i, 8, formatInfoBits); - } - for (int j = dimension - 7; j < dimension; j++) { - formatInfoBits = copyBit(8, j, formatInfoBits); - } - - parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); - if (parsedFormatInfo != null) { - return parsedFormatInfo; - } - throw new ReaderException(); - } - - /** - *

Reads version information from one of its two locations within the QR Code.

- * - * @return {@link Version} encapsulating the QR Code's version - * @throws ReaderException if both version information locations cannot be parsed as - * the valid encoding of version information - */ - public Version readVersion(){ - - if (parsedVersion != null) { - return parsedVersion; - } - - int dimension = bitMatrix.getDimension(); - - int provisionalVersion = (dimension - 17) >> 2; - if (provisionalVersion <= 6) { - return Version.getVersionForNumber(provisionalVersion); - } - - // Read top-right version info: 3 wide by 6 tall - int versionBits = 0; - for (int i = 5; i >= 0; i--) { - int jMin = dimension - 11; - for (int j = dimension - 9; j >= jMin; j--) { - versionBits = copyBit(i, j, versionBits); - } - } - - parsedVersion = Version.decodeVersionInformation(versionBits); - if (parsedVersion != null) { - return parsedVersion; - } - - // Hmm, failed. Try bottom left: 6 wide by 3 tall - versionBits = 0; - for (int j = 5; j >= 0; j--) { - int iMin = dimension - 11; - for (int i = dimension - 11; i >= iMin; i--) { - versionBits = copyBit(i, j, versionBits); - } - } - - parsedVersion = Version.decodeVersionInformation(versionBits); - if (parsedVersion != null) { - return parsedVersion; - } - throw new ReaderException(); - } - - private int copyBit(int i, int j, int versionBits) { - return bitMatrix.get(i, j) ? (versionBits << 1) | 0x1 : versionBits << 1; - } - - /** - *

Reads the bits in the {@link BitMatrix} representing the finder pattern in the - * correct order in order to reconstitute the codewords bytes contained within the - * QR Code.

- * - * @return bytes encoded within the QR Code - * @throws ReaderException if the exact number of bytes expected is not read - */ - public sbyte[] readCodewords(){ - - FormatInformation formatInfo = readFormatInformation(); - Version version = readVersion(); - - // Get the data mask for the format used in this QR Code. This will exclude - // some bits from reading as we wind through the bit matrix. - DataMask dataMask = DataMask.forReference((int) formatInfo.getDataMask()); - int dimension = bitMatrix.getDimension(); - dataMask.unmaskBitMatrix(bitMatrix.getBits(), dimension); - - BitMatrix functionPattern = version.buildFunctionPattern(); - - bool readingUp = true; - sbyte[] result = new sbyte[version.getTotalCodewords()]; - int resultOffset = 0; - int currentByte = 0; - int bitsRead = 0; - // Read columns in pairs, from right to left - for (int j = dimension - 1; j > 0; j -= 2) { - if (j == 6) { - // Skip whole column with vertical alignment pattern; - // saves time and makes the other code proceed more cleanly - j--; - } - // Read alternatingly from bottom to top then top to bottom - for (int count = 0; count < dimension; count++) { - int i = readingUp ? dimension - 1 - count : count; - for (int col = 0; col < 2; col++) { - // Ignore bits covered by the function pattern - if (!functionPattern.get(i, j - col)) { - // Read a bit - bitsRead++; - currentByte <<= 1; - if (bitMatrix.get(i, j - col)) { - currentByte |= 1; - } - // If we've made a whole byte, save it off - if (bitsRead == 8) { - result[resultOffset++] = (sbyte) currentByte; - bitsRead = 0; - currentByte = 0; - } - } - } - } - readingUp = !readingUp; // switch directions - } - if (resultOffset != version.getTotalCodewords()) { - throw new ReaderException(); - } - return result; - } - - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/decoder/DataBlock.cs b/qrcode-scanner-live2/qrcode/decoder/DataBlock.cs deleted file mode 100644 index 7fc4f5f..0000000 --- a/qrcode-scanner-live2/qrcode/decoder/DataBlock.cs +++ /dev/null @@ -1,152 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.qrcode.decoder -{ - - ///

Encapsulates a block of data within a QR Code. QR Codes may split their data into - /// multiple blocks, each of which is a unit of data and error-correction codewords. Each - /// is represented by an instance of this class.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public sealed class DataBlock - { - internal int NumDataCodewords - { - get - { - return numDataCodewords; - } - - } - internal sbyte[] Codewords - { - get - { - return codewords; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'numDataCodewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int numDataCodewords; - //UPGRADE_NOTE: Final was removed from the declaration of 'codewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte[] codewords; - - public DataBlock(int numDataCodewords, sbyte[] codewords) - { - this.numDataCodewords = numDataCodewords; - this.codewords = codewords; - } - - ///

When QR Codes use multiple data blocks, they are actually interleave the bytes of each of them. - /// That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This - /// method will separate the data into original blocks.

- /// - ///
- /// bytes as read directly from the QR Code - /// - /// version of the QR Code - /// - /// error-correction level of the QR Code - /// - /// {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the - /// QR Code - /// - internal static DataBlock[] getDataBlocks(sbyte[] rawCodewords, Version version, ErrorCorrectionLevel ecLevel) - { - // Figure out the number and size of data blocks used by this version and - // error correction level - Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); - - // First count the total number of data blocks - int totalBlocks = 0; - Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); - for (int i = 0; i < ecBlockArray.Length; i++) - { - totalBlocks += ecBlockArray[i].getCount(); - } - - // Now establish DataBlocks of the appropriate size and number of data codewords - DataBlock[] result = new DataBlock[totalBlocks]; - int numResultBlocks = 0; - for (int j = 0; j < ecBlockArray.Length; j++) - { - Version.ECB ecBlock = ecBlockArray[j]; - for (int i = 0; i < ecBlock.getCount(); i++) - { - int numDataCodewords = ecBlock.getDataCodewords(); - int numBlockCodewords = ecBlocks.getTotalECCodewords() + numDataCodewords; - result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]); - } - } - - // All blocks have the same amount of data, except that the last n - // (where n may be 0) have 1 more byte. Figure out where these start. - int shorterBlocksTotalCodewords = result[0].codewords.Length; - int longerBlocksStartAt = result.Length - 1; - while (longerBlocksStartAt >= 0) - { - int numCodewords = result[longerBlocksStartAt].codewords.Length; - if (numCodewords == shorterBlocksTotalCodewords) - { - break; - } - if (numCodewords != shorterBlocksTotalCodewords + 1) - { - throw new System.SystemException("Data block sizes differ by more than 1"); - } - longerBlocksStartAt--; - } - longerBlocksStartAt++; - - int shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.getTotalECCodewords(); - // The last elements of result may be 1 element longer; - // first fill out as many elements as all of them have - int rawCodewordsOffset = 0; - for (int i = 0; i < shorterBlocksNumDataCodewords; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; - } - } - // Fill out the last data block in the longer ones - for (int j = longerBlocksStartAt; j < numResultBlocks; j++) - { - result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; - } - // Now add in error correction blocks - int max = result[0].codewords.Length; - for (int i = shorterBlocksNumDataCodewords; i < max; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - int iOffset = j < longerBlocksStartAt ? i : i + 1; - result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; - } - } - - if (rawCodewordsOffset != rawCodewords.Length) - { - throw new System.SystemException(); - } - - return result; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/decoder/DataMask.cs b/qrcode-scanner-live2/qrcode/decoder/DataMask.cs deleted file mode 100644 index be25079..0000000 --- a/qrcode-scanner-live2/qrcode/decoder/DataMask.cs +++ /dev/null @@ -1,282 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.qrcode.decoder -{ - - ///

Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations - /// of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix, - /// including areas used for finder patterns, timing patterns, etc. These areas should be unused - /// after the point they are unmasked anyway.

- /// - ///

Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position - /// and j is row position. In fact, as the text says, i is row position and j is column position.

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - abstract class DataMask - { - - /// See ISO 18004:2006 6.8.1 - //UPGRADE_NOTE: Final was removed from the declaration of 'DATA_MASKS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly DataMask[] DATA_MASKS = new DataMask[] { new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111() }; - - private DataMask() - { - } - - ///

Implementations of this method reverse the data masking process applied to a QR Code and - /// make its bits ready to read.

- /// - ///
- /// representation of QR Code bits from {@link com.google.zxing.common.BitMatrix#getBits()} - /// - /// dimension of QR Code, represented by bits, being unmasked - /// - internal abstract void unmaskBitMatrix(int[] bits, int dimension); - - /// a value between 0 and 7 indicating one of the eight possible - /// data mask patterns a QR Code may use - /// - /// {@link DataMask} encapsulating the data mask pattern - /// - internal static DataMask forReference(int reference) - { - if (reference < 0 || reference > 7) - { - throw new System.ArgumentException(); - } - return DATA_MASKS[reference]; - } - - /// 000: mask bits for which (i + j) mod 2 == 0 - private class DataMask000 : DataMask - { - private const int BITMASK = 0x55555555; // = 010101... - - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - // This one's easy. Because the dimension of BitMatrix is always odd, - // we can merely flip every other bit - int max = bits.Length; - for (int i = 0; i < max; i++) - { - bits[i] ^= BITMASK; - } - } - } - - /// 001: mask bits for which i mod 2 == 0 - private class DataMask001 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - if ((i & 0x01) == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 010: mask bits for which j mod 3 == 0 - private class DataMask010 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - bool columnMasked = j % 3 == 0; - for (int i = 0; i < dimension; i++) - { - if (columnMasked) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 011: mask bits for which (i + j) mod 3 == 0 - private class DataMask011 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - if ((i + j) % 3 == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 100: mask bits for which (i/2 + j/3) mod 2 == 0 - private class DataMask100 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - int jComponentParity = (j / 3) & 0x01; - for (int i = 0; i < dimension; i++) - { - if (((i >> 1) & 0x01) == jComponentParity) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 101: mask bits for which ij mod 2 + ij mod 3 == 0 - private class DataMask101 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - int product = i * j; - if (((product & 0x01) == 0) && product % 3 == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 110: mask bits for which (ij mod 2 + ij mod 3) mod 2 == 0 - private class DataMask110 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - int product = i * j; - if ((((product & 0x01) + product % 3) & 0x01) == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - - /// 111: mask bits for which ((i+j)mod 2 + ij mod 3) mod 2 == 0 - private class DataMask111 : DataMask - { - internal override void unmaskBitMatrix(int[] bits, int dimension) - { - int bitMask = 0; - int count = 0; - int offset = 0; - for (int j = 0; j < dimension; j++) - { - for (int i = 0; i < dimension; i++) - { - if (((((i + j) & 0x01) + (i * j) % 3) & 0x01) == 0) - { - bitMask |= 1 << count; - } - if (++count == 32) - { - bits[offset++] ^= bitMask; - count = 0; - bitMask = 0; - } - } - } - bits[offset] ^= bitMask; - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/decoder/DecodedBitStreamParser.cs b/qrcode-scanner-live2/qrcode/decoder/DecodedBitStreamParser.cs deleted file mode 100644 index dfe82fa..0000000 --- a/qrcode-scanner-live2/qrcode/decoder/DecodedBitStreamParser.cs +++ /dev/null @@ -1,266 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -using ReaderException = com.google.zxing.ReaderException; -using com.google.zxing.common; -namespace com.google.zxing.qrcode.decoder -{ - - ///

QR Codes can encode text as bits in one of several modes, and can use multiple modes - /// in one QR Code. This class decodes the bits back into text.

- /// - ///

See ISO 18004:2006, 6.4.3 - 6.4.7

- /// - ///
- /// srowen@google.com (Sean Owen) - /// - public sealed class DecodedBitStreamParser - { - - /// See ISO 18004:2006, 6.4.4 Table 5 - //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_CHARS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] ALPHANUMERIC_CHARS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' }; - private const System.String SHIFT_JIS = "Shift_JIS"; - private static bool ASSUME_SHIFT_JIS; - - private DecodedBitStreamParser() - { - } - - internal static System.String decode(sbyte[] bytes, Version version) - { - BitSource bits = new BitSource(bytes); - System.Text.StringBuilder result = new System.Text.StringBuilder(); - Mode mode; - do - { - // While still another segment to read... - mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits - if (!mode.Equals(Mode.TERMINATOR)) - { - // How many characters will follow, encoded in this mode? - int count = bits.readBits(mode.getCharacterCountBits(version)); - if (mode.Equals(Mode.NUMERIC)) - { - decodeNumericSegment(bits, result, count); - } - else if (mode.Equals(Mode.ALPHANUMERIC)) - { - decodeAlphanumericSegment(bits, result, count); - } - else if (mode.Equals(Mode.BYTE)) - { - decodeByteSegment(bits, result, count); - } - else if (mode.Equals(Mode.KANJI)) - { - decodeKanjiSegment(bits, result, count); - } - else - { - throw new ReaderException("Unsupported mode indicator"); - } - } - } - while (!mode.Equals(Mode.TERMINATOR)); - - // I thought it wasn't allowed to leave extra bytes after the terminator but it happens - /* - int bitsLeft = bits.available(); - if (bitsLeft > 0) { - if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) { - throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator"); - } - } - */ - return result.ToString(); - } - - private static void decodeKanjiSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - // Each character will require 2 bytes. Read the characters as 2-byte pairs - // and decode as Shift_JIS afterwards - sbyte[] buffer = new sbyte[2 * count]; - int offset = 0; - while (count > 0) - { - // Each 13 bits encodes a 2-byte character - int twoBytes = bits.readBits(13); - int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0); - if (assembledTwoBytes < 0x01F00) - { - // In the 0x8140 to 0x9FFC range - assembledTwoBytes += 0x08140; - } - else - { - // In the 0xE040 to 0xEBBF range - assembledTwoBytes += 0x0C140; - } - buffer[offset] = (sbyte)(assembledTwoBytes >> 8); - buffer[offset + 1] = (sbyte)assembledTwoBytes; - offset += 2; - count--; - } - // Shift_JIS may not be supported in some environments: - try - { - byte[] bytes = SupportClass.ToByteArray(buffer); - //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" - result.Append(System.Text.Encoding.GetEncoding("Shift_JIS").GetString(bytes, 0, bytes.Length)); - } - catch (System.IO.IOException uee) - { - throw new ReaderException("SHIFT_JIS encoding is not supported on this device"); - } - } - - private static void decodeByteSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - sbyte[] readBytes = new sbyte[count]; - if (count << 3 > bits.available()) - { - throw new ReaderException("Count too large: " + count); - } - for (int i = 0; i < count; i++) - { - readBytes[i] = (sbyte)bits.readBits(8); - } - // The spec isn't clear on this mode; see - // section 6.4.5: t does not say which encoding to assuming - // upon decoding. I have seen ISO-8859-1 used as well as - // Shift_JIS -- without anything like an ECI designator to - // give a hint. - System.String encoding = guessEncoding(readBytes); - try - { - byte[] bytes = SupportClass.ToByteArray(readBytes); - //System.Windows.Forms.MessageBox.Show("encodings: "+ System.Text.Encoding.()); - //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" - result.Append(System.Text.Encoding.GetEncoding(encoding).GetString(bytes, 0, bytes.Length)); - } - catch (System.IO.IOException uce) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new ReaderException(uce.ToString()); - } - } - - private static void decodeAlphanumericSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - // Read two characters at a time - while (count > 1) - { - int nextTwoCharsBits = bits.readBits(11); - result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]); - result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]); - count -= 2; - } - if (count == 1) - { - // special case: one character left - result.Append(ALPHANUMERIC_CHARS[bits.readBits(6)]); - } - } - - private static void decodeNumericSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - // Read three digits at a time - while (count >= 3) - { - // Each 10 bits encodes three digits - int threeDigitsBits = bits.readBits(10); - if (threeDigitsBits >= 1000) - { - throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits); - } - result.Append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]); - result.Append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]); - result.Append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]); - count -= 3; - } - if (count == 2) - { - // Two digits left over to read, encoded in 7 bits - int twoDigitsBits = bits.readBits(7); - if (twoDigitsBits >= 100) - { - throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits); - } - result.Append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]); - result.Append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]); - } - else if (count == 1) - { - // One digit left over to read - int digitBits = bits.readBits(4); - if (digitBits >= 10) - { - throw new ReaderException("Illegal value for digit unit: " + digitBits); - } - result.Append(ALPHANUMERIC_CHARS[digitBits]); - } - } - - private static System.String guessEncoding(sbyte[] bytes) - { - if (ASSUME_SHIFT_JIS) - { - return SHIFT_JIS; - } - // For now, merely tries to distinguish ISO-8859-1 and Shift_JIS, - // which should be by far the most common encodings. ISO-8859-1 - // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS - // uses this as a first byte of a two-byte character. If we see this - // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. - int length = bytes.Length; - for (int i = 0; i < length; i++) - { - int value_Renamed = bytes[i] & 0xFF; - if (value_Renamed >= 0x80 && value_Renamed <= 0x9F && i < length - 1) - { - // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS, - // just double check that it is followed by a byte that's valid in - // the Shift_JIS encoding - int nextValue = bytes[i + 1] & 0xFF; - if ((value_Renamed & 0x1) == 0) - { - // if even, - if (nextValue >= 0x40 && nextValue <= 0x9E) - { - return SHIFT_JIS; - } - } - else - { - if (nextValue >= 0x9F && nextValue <= 0x7C) - { - return SHIFT_JIS; - } - } - } - } - return "ASCII"; - } - //static DecodedBitStreamParser() - //{ - // { - // //UPGRADE_ISSUE: Method 'java.lang.System.getProperty' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'" - // System.String platformDefault = System_Renamed.getProperty("file.encoding"); - // ASSUME_SHIFT_JIS = SHIFT_JIS.ToUpper().Equals(platformDefault.ToUpper()) || "EUC-JP".ToUpper().Equals(platformDefault.ToUpper()); - // } - //} - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/decoder/Decoder.cs b/qrcode-scanner-live2/qrcode/decoder/Decoder.cs deleted file mode 100644 index 0e5993b..0000000 --- a/qrcode-scanner-live2/qrcode/decoder/Decoder.cs +++ /dev/null @@ -1,140 +0,0 @@ -/* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -using System; -namespace com.google.zxing.qrcode.decoder -{ - using com.google.zxing.common; - using com.google.zxing.common.reedsolomon; - - public sealed class Decoder - { - private ReedSolomonDecoder rsDecoder; - - public Decoder() { - rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD); - } - - /** - *

Convenience method that can decode a QR Code represented as a 2D array of booleans. - * "true" is taken to mean a black module.

- * - * @param image booleans representing white/black QR Code modules - * @return text and bytes encoded within the QR Code - * @throws ReaderException if the QR Code cannot be decoded - */ - public DecoderResult decode(bool[][] image) { - try{ - int dimension = image.Length; - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) { - for (int j = 0; j < dimension; j++) { - if (image[i][j]) { - bits.set(i, j); - } - } - } - return decode(bits); - }catch (Exception e){ - throw new ReaderException(e.Message); - } - } - - /** - *

Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.

- * - * @param bits booleans representing white/black QR Code modules - * @return text and bytes encoded within the QR Code - * @throws ReaderException if the QR Code cannot be decoded - */ - public DecoderResult decode(BitMatrix bits){ - try{ - // Construct a parser and read version, error-correction level - BitMatrixParser parser = new BitMatrixParser(bits); - Version version = parser.readVersion(); - ErrorCorrectionLevel ecLevel = parser.readFormatInformation().getErrorCorrectionLevel(); - - // Read codewords - sbyte[] codewords = parser.readCodewords(); - // Separate into data blocks - DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); - - // Count total number of data bytes - int totalBytes = 0; - for (int i = 0; i < dataBlocks.Length; i++) { - totalBytes += dataBlocks[i].NumDataCodewords; - } - sbyte[] resultBytes = new sbyte[totalBytes]; - int resultOffset = 0; - - // Error-correct and copy data blocks together into a stream of bytes - for (int j = 0; j < dataBlocks.Length; j++) { - DataBlock dataBlock = dataBlocks[j]; - sbyte[] codewordBytes = dataBlock.Codewords; - int numDataCodewords = dataBlock.NumDataCodewords; - correctErrors(codewordBytes, numDataCodewords); - for (int i = 0; i < numDataCodewords; i++) { - resultBytes[resultOffset++] = codewordBytes[i]; - } - } - - // Decode the contents of that stream of bytes - string sResult = DecodedBitStreamParser.decode(resultBytes, version); - return new DecoderResult(resultBytes, sResult, null); - }catch(Exception e){ - throw new ReaderException(e.Message); - } - - } - - /** - *

Given data and error-correction codewords received, possibly corrupted by errors, attempts to - * correct the errors in-place using Reed-Solomon error correction.

- * - * @param codewordBytes data and error correction codewords - * @param numDataCodewords number of codewords that are data bytes - * @throws ReaderException if error correction fails - */ - private void correctErrors(sbyte[] codewordBytes, int numDataCodewords){ - try - { - int numCodewords = codewordBytes.Length; - // First read into an array of ints - int[] codewordsInts = new int[numCodewords]; - for (int i = 0; i < numCodewords; i++) - { - codewordsInts[i] = codewordBytes[i] & 0xFF; - } - int numECCodewords = codewordBytes.Length - numDataCodewords; - try - { - rsDecoder.decode(codewordsInts, numECCodewords); - } - catch (ReedSolomonException rse) - { - throw new ReaderException(rse.Message); - } - // Copy back into array of bytes -- only need to worry about the bytes that were data - // We don't care about errors in the error-correction codewords - for (int i = 0; i < numDataCodewords; i++) - { - codewordBytes[i] = (sbyte)codewordsInts[i]; - } - } - catch (Exception e) { - throw new ReaderException(e.Message); - } - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/decoder/ErrorCorrectionLevel.cs b/qrcode-scanner-live2/qrcode/decoder/ErrorCorrectionLevel.cs deleted file mode 100644 index c16e62f..0000000 --- a/qrcode-scanner-live2/qrcode/decoder/ErrorCorrectionLevel.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class ErrorCorrectionLevel - { - // No, we can't use an enum here. J2ME doesn't support it. - /** - * L = ~7% correction - */ - public static ErrorCorrectionLevel L = new ErrorCorrectionLevel(0, 0x01, "L"); - /** - * M = ~15% correction - */ - public static ErrorCorrectionLevel M = new ErrorCorrectionLevel(1, 0x00, "M"); - /** - * Q = ~25% correction - */ - public static ErrorCorrectionLevel Q = new ErrorCorrectionLevel(2, 0x03, "Q"); - /** - * H = ~30% correction - */ - public static ErrorCorrectionLevel H = new ErrorCorrectionLevel(3, 0x02, "H"); - - private static ErrorCorrectionLevel[] FOR_BITS = {M, L, H, Q}; - - private int Ordinal; - private int bits; - private string name; - - private ErrorCorrectionLevel(int ordinal, int bits, string name) { - this.Ordinal = ordinal; - this.bits = bits; - this.name = name; - } - - public int ordinal() { - return Ordinal; - } - - public int getBits() { - return bits; - } - - public string getName() { - return name; - } - - public string toString() { - return name; - } - - /** - * @param bits int containing the two bits encoding a QR Code's error correction level - * @return {@link ErrorCorrectionLevel} representing the encoded error correction level - */ - public static ErrorCorrectionLevel forBits(int bits) { - if (bits < 0 || bits >= FOR_BITS.Length) { - throw new ArgumentException(); - } - return FOR_BITS[bits]; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/decoder/FormatInformation.cs b/qrcode-scanner-live2/qrcode/decoder/FormatInformation.cs deleted file mode 100644 index 07aa37d..0000000 --- a/qrcode-scanner-live2/qrcode/decoder/FormatInformation.cs +++ /dev/null @@ -1,118 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class FormatInformation - { - private static int FORMAT_INFO_MASK_QR = 0x5412; - /** - * See ISO 18004:2006, Annex C, Table C.1 - */ - private static readonly int[][] FORMAT_INFO_DECODE_LOOKUP = new int[][] { new int[] { 0x5412, 0x00 }, new int[] { 0x5125, 0x01 }, new int[] { 0x5E7C, 0x02 }, new int[] { 0x5B4B, 0x03 }, new int[] { 0x45F9, 0x04 }, new int[] { 0x40CE, 0x05 }, new int[] { 0x4F97, 0x06 }, new int[] { 0x4AA0, 0x07 }, new int[] { 0x77C4, 0x08 }, new int[] { 0x72F3, 0x09 }, new int[] { 0x7DAA, 0x0A }, new int[] { 0x789D, 0x0B }, new int[] { 0x662F, 0x0C }, new int[] { 0x6318, 0x0D }, new int[] { 0x6C41, 0x0E }, new int[] { 0x6976, 0x0F }, new int[] { 0x1689, 0x10 }, new int[] { 0x13BE, 0x11 }, new int[] { 0x1CE7, 0x12 }, new int[] { 0x19D0, 0x13 }, new int[] { 0x0762, 0x14 }, new int[] { 0x0255, 0x15 }, new int[] { 0x0D0C, 0x16 }, new int[] { 0x083B, 0x17 }, new int[] { 0x355F, 0x18 }, new int[] { 0x3068, 0x19 }, new int[] { 0x3F31, 0x1A }, new int[] { 0x3A06, 0x1B }, new int[] { 0x24B4, 0x1C }, new int[] { 0x2183, 0x1D }, new int[] { 0x2EDA, 0x1E }, new int[] { 0x2BED, 0x1F } }; - - /** - * Offset i holds the number of 1 bits in the binary representation of i - */ - private static int[] BITS_SET_IN_HALF_BYTE = - {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; - - private ErrorCorrectionLevel errorCorrectionLevel; - private byte dataMask; - - private FormatInformation(int formatInfo) { - // Bits 3,4 - errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); - // Bottom 3 bits - dataMask = (byte) (formatInfo & 0x07); - } - - public static int numBitsDiffering(int a, int b) { - a ^= b; // a now has a 1 bit exactly where its bit differs with b's - // Count bits set quickly with a series of lookups: - return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 28) & 0x0F)]; - } - - /** - * @param rawFormatInfo - * @return - */ - public static FormatInformation decodeFormatInformation(int rawFormatInfo){ - try{ - FormatInformation formatInfo = doDecodeFormatInformation(rawFormatInfo); - if (formatInfo != null) { - return formatInfo; - } - // Should return null, but, some QR codes apparently - // do not mask this info. Try again, first masking the raw bits so - // the function will unmask - return doDecodeFormatInformation(rawFormatInfo ^ FORMAT_INFO_MASK_QR); - }catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - private static FormatInformation doDecodeFormatInformation(int rawFormatInfo) { - // Unmask: - int unmaskedFormatInfo = rawFormatInfo ^ FORMAT_INFO_MASK_QR; - // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing - int bestDifference = int.MaxValue; - int bestFormatInfo = 0; - for (int i = 0; i < FORMAT_INFO_DECODE_LOOKUP.Length; i++) { - int[] decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; - int targetInfo = decodeInfo[0]; - if (targetInfo == unmaskedFormatInfo) { - // Found an exact match - return new FormatInformation(decodeInfo[1]); - } - int bitsDifference = numBitsDiffering(unmaskedFormatInfo, targetInfo); - if (bitsDifference < bestDifference) { - bestFormatInfo = decodeInfo[1]; - bestDifference = bitsDifference; - } - } - if (bestDifference <= 3) { - return new FormatInformation(bestFormatInfo); - } - return null; - } - - public ErrorCorrectionLevel getErrorCorrectionLevel() { - return errorCorrectionLevel; - } - - public byte getDataMask() { - return dataMask; - } - - public int hashCode() { - return (errorCorrectionLevel.ordinal() << 3) | (int) dataMask; - } - - public bool equals(Object o) { - if (!(o.GetType() == typeof(FormatInformation))){ - return false; - } - FormatInformation other = (FormatInformation) o; - return this.errorCorrectionLevel == other.errorCorrectionLevel && - this.dataMask == other.dataMask; - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/decoder/Mode.cs b/qrcode-scanner-live2/qrcode/decoder/Mode.cs deleted file mode 100644 index f06f890..0000000 --- a/qrcode-scanner-live2/qrcode/decoder/Mode.cs +++ /dev/null @@ -1,108 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class Mode - { - // No, we can't use an enum here. J2ME doesn't support it. - public static Mode TERMINATOR = new Mode(new int[]{0, 0, 0}, 0x00, "TERMINATOR"); // Not really a mode... - public static Mode NUMERIC = new Mode(new int[]{10, 12, 14}, 0x01, "NUMERIC"); - public static Mode ALPHANUMERIC = new Mode(new int[]{9, 11, 13}, 0x02, "ALPHANUMERIC"); - public static Mode BYTE = new Mode(new int[]{8, 16, 16}, 0x04, "BYTE"); - public static Mode ECI = new Mode(null, 0x07, "ECI"); // character counts don't apply - public static Mode KANJI = new Mode(new int[]{8, 10, 12}, 0x08, "KANJI"); - public static Mode FNC1_FIRST_POSITION = new Mode(null, 0x05, "FNC1_FIRST_POSITION"); - public static Mode FNC1_SECOND_POSITION = new Mode(null, 0x09, "FNC1_SECOND_POSITION"); - - private int[] characterCountBitsForVersions; - private int bits; - private string name; - - private Mode(int[] characterCountBitsForVersions, int bits, string name) { - this.characterCountBitsForVersions = characterCountBitsForVersions; - this.bits = bits; - this.name = name; - } - - /** - * @param bits four bits encoding a QR Code data mode - * @return {@link Mode} encoded by these bits - * @throws ArgumentException if bits do not correspond to a known mode - */ - public static Mode forBits(int bits) { - switch (bits) { - case 0x0: - return TERMINATOR; - case 0x1: - return NUMERIC; - case 0x2: - return ALPHANUMERIC; - case 0x4: - return BYTE; - case 0x5: - return FNC1_FIRST_POSITION; - case 0x7: - return ECI; - case 0x8: - return KANJI; - case 0x9: - return FNC1_SECOND_POSITION; - default: - throw new ArgumentException(); - } - } - - /** - * @param version version in question - * @return number of bits used, in this QR Code symbol {@link Version}, to encode the - * count of characters that will follow encoded in this {@link Mode} - */ - public int getCharacterCountBits(Version version) { - if (characterCountBitsForVersions == null) { - throw new ArgumentException("Character count doesn't apply to this mode"); - } - int number = version.getVersionNumber(); - int offset; - if (number <= 9) { - offset = 0; - } else if (number <= 26) { - offset = 1; - } else { - offset = 2; - } - return characterCountBitsForVersions[offset]; - } - - public int getBits() { - return bits; - } - - public string getName() { - return name; - } - - public string toString() { - return name; - } - - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/decoder/Version.cs b/qrcode-scanner-live2/qrcode/decoder/Version.cs deleted file mode 100644 index 502b80a..0000000 --- a/qrcode-scanner-live2/qrcode/decoder/Version.cs +++ /dev/null @@ -1,579 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.decoder -{ - public sealed class Version - { - /** - * See ISO 18004:2006 Annex D. - * Element i represents the raw version bits that specify version i + 7 - */ - private static int[] VERSION_DECODE_INFO = { - 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, - 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, - 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, - 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, - 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, - 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, - 0x2542E, 0x26A64, 0x27541, 0x28C69 - }; - - private static Version[] VERSIONS = buildVersions(); - - private int versionNumber; - private int[] alignmentPatternCenters; - private ECBlocks[] ecBlocks; - private int totalCodewords; - - private Version(int versionNumber, - int[] alignmentPatternCenters, - ECBlocks ecBlocks1, - ECBlocks ecBlocks2, - ECBlocks ecBlocks3, - ECBlocks ecBlocks4) { - this.versionNumber = versionNumber; - this.alignmentPatternCenters = alignmentPatternCenters; - this.ecBlocks = new ECBlocks[]{ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4}; - int total = 0; - int ecCodewords = ecBlocks1.getECCodewordsPerBlock(); - ECB[] ecbArray = ecBlocks1.getECBlocks(); - for (int i = 0; i < ecbArray.Length; i++) { - ECB ecBlock = ecbArray[i]; - total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords); - } - this.totalCodewords = total; - } - - public int getVersionNumber() { - return versionNumber; - } - - public int[] getAlignmentPatternCenters() { - return alignmentPatternCenters; - } - - public int getTotalCodewords() { - return totalCodewords; - } - - public int getDimensionForVersion() { - return 17 + 4 * versionNumber; - } - - public ECBlocks getECBlocksForLevel(ErrorCorrectionLevel ecLevel) { - return ecBlocks[ecLevel.ordinal()]; - } - - /** - *

Deduces version information purely from QR Code dimensions.

- * - * @param dimension dimension in modules - * @return {@link Version} for a QR Code of that dimension - * @throws ReaderException if dimension is not 1 mod 4 - */ - public static Version getProvisionalVersionForDimension(int dimension) { - if (dimension % 4 != 1) { - throw new ReaderException(); - } - return getVersionForNumber((dimension - 17) >> 2); - } - - public static Version getVersionForNumber(int versionNumber) { - if (versionNumber < 1 || versionNumber > 40) { - throw new ArgumentException(); - } - return VERSIONS[versionNumber - 1]; - } - - public static Version decodeVersionInformation(int versionBits) { - int bestDifference = int.MaxValue; - int bestVersion = 0; - for (int i = 0; i < VERSION_DECODE_INFO.Length; i++) { - int targetVersion = VERSION_DECODE_INFO[i]; - // Do the version info bits match exactly? done. - if (targetVersion == versionBits) { - return getVersionForNumber(i + 7); - } - // Otherwise see if this is the closest to a real version info bit string - // we have seen so far - int bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); - if (bitsDifference < bestDifference) { - bestVersion = i + 7; - } - } - // We can tolerate up to 3 bits of error since no two version info codewords will - // differ in less than 4 bits. - if (bestDifference <= 3) { - return getVersionForNumber(bestVersion); - } - // If we didn't find a close enough match, fail - return null; - } - - /** - * See ISO 18004:2006 Annex E - */ - public BitMatrix buildFunctionPattern() { - int dimension = getDimensionForVersion(); - BitMatrix bitMatrix = new BitMatrix(dimension); - - // Top left finder pattern + separator + format - bitMatrix.setRegion(0, 0, 9, 9); - // Top right finder pattern + separator + format - bitMatrix.setRegion(0, dimension - 8, 9, 8); - // Bottom left finder pattern + separator + format - bitMatrix.setRegion(dimension - 8, 0, 8, 9); - - // Alignment patterns - int max = alignmentPatternCenters.Length; - for (int x = 0; x < max; x++) { - int i = alignmentPatternCenters[x] - 2; - for (int y = 0; y < max; y++) { - if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) { - // No alignment patterns near the three finder paterns - continue; - } - bitMatrix.setRegion(i, alignmentPatternCenters[y] - 2, 5, 5); - } - } - - // Vertical timing pattern - bitMatrix.setRegion(9, 6, dimension - 17, 1); - // Horizontal timing pattern - bitMatrix.setRegion(6, 9, 1, dimension - 17); - - if (versionNumber > 6) { - // Version info, top right - bitMatrix.setRegion(0, dimension - 11, 6, 3); - // Version info, bottom left - bitMatrix.setRegion(dimension - 11, 0, 3, 6); - } - - return bitMatrix; - } - - /** - *

Encapsulates a set of error-correction blocks in one symbol version. Most versions will - * use blocks of differing sizes within one version, so, this encapsulates the parameters for - * each set of blocks. It also holds the number of error-correction codewords per block since it - * will be the same across all blocks within one version.

- */ - public class ECBlocks { - private int ecCodewordsPerBlock; - private ECB[] ecBlocks; - - public ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks) { - this.ecCodewordsPerBlock = ecCodewordsPerBlock; - this.ecBlocks = new ECB[]{ecBlocks}; - } - - public ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks1, ECB ecBlocks2) - { - this.ecCodewordsPerBlock = ecCodewordsPerBlock; - this.ecBlocks = new ECB[]{ecBlocks1, ecBlocks2}; - } - - public int getECCodewordsPerBlock() { - return ecCodewordsPerBlock; - } - - public int getNumBlocks() { - int total = 0; - for (int i = 0; i < ecBlocks.Length; i++) { - total += ecBlocks[i].getCount(); - } - return total; - } - - public int getTotalECCodewords() { - return ecCodewordsPerBlock * getNumBlocks(); - } - - public ECB[] getECBlocks() { - return ecBlocks; - } - } - - /** - *

Encapsualtes the parameters for one error-correction block in one symbol version. - * This includes the number of data codewords, and the number of times a block with these - * parameters is used consecutively in the QR code version's format.

- */ - public class ECB { - private int count; - private int dataCodewords; - - public ECB(int count, int dataCodewords) { - this.count = count; - this.dataCodewords = dataCodewords; - } - - public int getCount() { - return count; - } - - public int getDataCodewords() { - return dataCodewords; - } - } - - public String toString() { - return versionNumber.ToString(); - //return String.valueOf(versionNumber); - } - - /** - * See ISO 18004:2006 6.5.1 Table 9 - */ - private static Version[] buildVersions() { - return new Version[]{ - new Version(1, new int[]{}, - new ECBlocks(7, new ECB(1, 19)), - new ECBlocks(10, new ECB(1, 16)), - new ECBlocks(13, new ECB(1, 13)), - new ECBlocks(17, new ECB(1, 9))), - new Version(2, new int[]{6, 18}, - new ECBlocks(10, new ECB(1, 34)), - new ECBlocks(16, new ECB(1, 28)), - new ECBlocks(22, new ECB(1, 22)), - new ECBlocks(28, new ECB(1, 16))), - new Version(3, new int[]{6, 22}, - new ECBlocks(15, new ECB(1, 55)), - new ECBlocks(26, new ECB(1, 44)), - new ECBlocks(18, new ECB(2, 17)), - new ECBlocks(22, new ECB(2, 13))), - new Version(4, new int[]{6, 26}, - new ECBlocks(20, new ECB(1, 80)), - new ECBlocks(18, new ECB(2, 32)), - new ECBlocks(26, new ECB(2, 24)), - new ECBlocks(16, new ECB(4, 9))), - new Version(5, new int[]{6, 30}, - new ECBlocks(26, new ECB(1, 108)), - new ECBlocks(24, new ECB(2, 43)), - new ECBlocks(18, new ECB(2, 15), - new ECB(2, 16)), - new ECBlocks(22, new ECB(2, 11), - new ECB(2, 12))), - new Version(6, new int[]{6, 34}, - new ECBlocks(18, new ECB(2, 68)), - new ECBlocks(16, new ECB(4, 27)), - new ECBlocks(24, new ECB(4, 19)), - new ECBlocks(28, new ECB(4, 15))), - new Version(7, new int[]{6, 22, 38}, - new ECBlocks(20, new ECB(2, 78)), - new ECBlocks(18, new ECB(4, 31)), - new ECBlocks(18, new ECB(2, 14), - new ECB(4, 15)), - new ECBlocks(26, new ECB(4, 13), - new ECB(1, 14))), - new Version(8, new int[]{6, 24, 42}, - new ECBlocks(24, new ECB(2, 97)), - new ECBlocks(22, new ECB(2, 38), - new ECB(2, 39)), - new ECBlocks(22, new ECB(4, 18), - new ECB(2, 19)), - new ECBlocks(26, new ECB(4, 14), - new ECB(2, 15))), - new Version(9, new int[]{6, 26, 46}, - new ECBlocks(30, new ECB(2, 116)), - new ECBlocks(22, new ECB(3, 36), - new ECB(2, 37)), - new ECBlocks(20, new ECB(4, 16), - new ECB(4, 17)), - new ECBlocks(24, new ECB(4, 12), - new ECB(4, 13))), - new Version(10, new int[]{6, 28, 50}, - new ECBlocks(18, new ECB(2, 68), - new ECB(2, 69)), - new ECBlocks(26, new ECB(4, 43), - new ECB(1, 44)), - new ECBlocks(24, new ECB(6, 19), - new ECB(2, 20)), - new ECBlocks(28, new ECB(6, 15), - new ECB(2, 16))), - new Version(11, new int[]{6, 30, 54}, - new ECBlocks(20, new ECB(4, 81)), - new ECBlocks(30, new ECB(1, 50), - new ECB(4, 51)), - new ECBlocks(28, new ECB(4, 22), - new ECB(4, 23)), - new ECBlocks(24, new ECB(3, 12), - new ECB(8, 13))), - new Version(12, new int[]{6, 32, 58}, - new ECBlocks(24, new ECB(2, 92), - new ECB(2, 93)), - new ECBlocks(22, new ECB(6, 36), - new ECB(2, 37)), - new ECBlocks(26, new ECB(4, 20), - new ECB(6, 21)), - new ECBlocks(28, new ECB(7, 14), - new ECB(4, 15))), - new Version(13, new int[]{6, 34, 62}, - new ECBlocks(26, new ECB(4, 107)), - new ECBlocks(22, new ECB(8, 37), - new ECB(1, 38)), - new ECBlocks(24, new ECB(8, 20), - new ECB(4, 21)), - new ECBlocks(22, new ECB(12, 11), - new ECB(4, 12))), - new Version(14, new int[]{6, 26, 46, 66}, - new ECBlocks(30, new ECB(3, 115), - new ECB(1, 116)), - new ECBlocks(24, new ECB(4, 40), - new ECB(5, 41)), - new ECBlocks(20, new ECB(11, 16), - new ECB(5, 17)), - new ECBlocks(24, new ECB(11, 12), - new ECB(5, 13))), - new Version(15, new int[]{6, 26, 48, 70}, - new ECBlocks(22, new ECB(5, 87), - new ECB(1, 88)), - new ECBlocks(24, new ECB(5, 41), - new ECB(5, 42)), - new ECBlocks(30, new ECB(5, 24), - new ECB(7, 25)), - new ECBlocks(24, new ECB(11, 12), - new ECB(7, 13))), - new Version(16, new int[]{6, 26, 50, 74}, - new ECBlocks(24, new ECB(5, 98), - new ECB(1, 99)), - new ECBlocks(28, new ECB(7, 45), - new ECB(3, 46)), - new ECBlocks(24, new ECB(15, 19), - new ECB(2, 20)), - new ECBlocks(30, new ECB(3, 15), - new ECB(13, 16))), - new Version(17, new int[]{6, 30, 54, 78}, - new ECBlocks(28, new ECB(1, 107), - new ECB(5, 108)), - new ECBlocks(28, new ECB(10, 46), - new ECB(1, 47)), - new ECBlocks(28, new ECB(1, 22), - new ECB(15, 23)), - new ECBlocks(28, new ECB(2, 14), - new ECB(17, 15))), - new Version(18, new int[]{6, 30, 56, 82}, - new ECBlocks(30, new ECB(5, 120), - new ECB(1, 121)), - new ECBlocks(26, new ECB(9, 43), - new ECB(4, 44)), - new ECBlocks(28, new ECB(17, 22), - new ECB(1, 23)), - new ECBlocks(28, new ECB(2, 14), - new ECB(19, 15))), - new Version(19, new int[]{6, 30, 58, 86}, - new ECBlocks(28, new ECB(3, 113), - new ECB(4, 114)), - new ECBlocks(26, new ECB(3, 44), - new ECB(11, 45)), - new ECBlocks(26, new ECB(17, 21), - new ECB(4, 22)), - new ECBlocks(26, new ECB(9, 13), - new ECB(16, 14))), - new Version(20, new int[]{6, 34, 62, 90}, - new ECBlocks(28, new ECB(3, 107), - new ECB(5, 108)), - new ECBlocks(26, new ECB(3, 41), - new ECB(13, 42)), - new ECBlocks(30, new ECB(15, 24), - new ECB(5, 25)), - new ECBlocks(28, new ECB(15, 15), - new ECB(10, 16))), - new Version(21, new int[]{6, 28, 50, 72, 94}, - new ECBlocks(28, new ECB(4, 116), - new ECB(4, 117)), - new ECBlocks(26, new ECB(17, 42)), - new ECBlocks(28, new ECB(17, 22), - new ECB(6, 23)), - new ECBlocks(30, new ECB(19, 16), - new ECB(6, 17))), - new Version(22, new int[]{6, 26, 50, 74, 98}, - new ECBlocks(28, new ECB(2, 111), - new ECB(7, 112)), - new ECBlocks(28, new ECB(17, 46)), - new ECBlocks(30, new ECB(7, 24), - new ECB(16, 25)), - new ECBlocks(24, new ECB(34, 13))), - new Version(23, new int[]{6, 30, 54, 74, 102}, - new ECBlocks(30, new ECB(4, 121), - new ECB(5, 122)), - new ECBlocks(28, new ECB(4, 47), - new ECB(14, 48)), - new ECBlocks(30, new ECB(11, 24), - new ECB(14, 25)), - new ECBlocks(30, new ECB(16, 15), - new ECB(14, 16))), - new Version(24, new int[]{6, 28, 54, 80, 106}, - new ECBlocks(30, new ECB(6, 117), - new ECB(4, 118)), - new ECBlocks(28, new ECB(6, 45), - new ECB(14, 46)), - new ECBlocks(30, new ECB(11, 24), - new ECB(16, 25)), - new ECBlocks(30, new ECB(30, 16), - new ECB(2, 17))), - new Version(25, new int[]{6, 32, 58, 84, 110}, - new ECBlocks(26, new ECB(8, 106), - new ECB(4, 107)), - new ECBlocks(28, new ECB(8, 47), - new ECB(13, 48)), - new ECBlocks(30, new ECB(7, 24), - new ECB(22, 25)), - new ECBlocks(30, new ECB(22, 15), - new ECB(13, 16))), - new Version(26, new int[]{6, 30, 58, 86, 114}, - new ECBlocks(28, new ECB(10, 114), - new ECB(2, 115)), - new ECBlocks(28, new ECB(19, 46), - new ECB(4, 47)), - new ECBlocks(28, new ECB(28, 22), - new ECB(6, 23)), - new ECBlocks(30, new ECB(33, 16), - new ECB(4, 17))), - new Version(27, new int[]{6, 34, 62, 90, 118}, - new ECBlocks(30, new ECB(8, 122), - new ECB(4, 123)), - new ECBlocks(28, new ECB(22, 45), - new ECB(3, 46)), - new ECBlocks(30, new ECB(8, 23), - new ECB(26, 24)), - new ECBlocks(30, new ECB(12, 15), - new ECB(28, 16))), - new Version(28, new int[]{6, 26, 50, 74, 98, 122}, - new ECBlocks(30, new ECB(3, 117), - new ECB(10, 118)), - new ECBlocks(28, new ECB(3, 45), - new ECB(23, 46)), - new ECBlocks(30, new ECB(4, 24), - new ECB(31, 25)), - new ECBlocks(30, new ECB(11, 15), - new ECB(31, 16))), - new Version(29, new int[]{6, 30, 54, 78, 102, 126}, - new ECBlocks(30, new ECB(7, 116), - new ECB(7, 117)), - new ECBlocks(28, new ECB(21, 45), - new ECB(7, 46)), - new ECBlocks(30, new ECB(1, 23), - new ECB(37, 24)), - new ECBlocks(30, new ECB(19, 15), - new ECB(26, 16))), - new Version(30, new int[]{6, 26, 52, 78, 104, 130}, - new ECBlocks(30, new ECB(5, 115), - new ECB(10, 116)), - new ECBlocks(28, new ECB(19, 47), - new ECB(10, 48)), - new ECBlocks(30, new ECB(15, 24), - new ECB(25, 25)), - new ECBlocks(30, new ECB(23, 15), - new ECB(25, 16))), - new Version(31, new int[]{6, 30, 56, 82, 108, 134}, - new ECBlocks(30, new ECB(13, 115), - new ECB(3, 116)), - new ECBlocks(28, new ECB(2, 46), - new ECB(29, 47)), - new ECBlocks(30, new ECB(42, 24), - new ECB(1, 25)), - new ECBlocks(30, new ECB(23, 15), - new ECB(28, 16))), - new Version(32, new int[]{6, 34, 60, 86, 112, 138}, - new ECBlocks(30, new ECB(17, 115)), - new ECBlocks(28, new ECB(10, 46), - new ECB(23, 47)), - new ECBlocks(30, new ECB(10, 24), - new ECB(35, 25)), - new ECBlocks(30, new ECB(19, 15), - new ECB(35, 16))), - new Version(33, new int[]{6, 30, 58, 86, 114, 142}, - new ECBlocks(30, new ECB(17, 115), - new ECB(1, 116)), - new ECBlocks(28, new ECB(14, 46), - new ECB(21, 47)), - new ECBlocks(30, new ECB(29, 24), - new ECB(19, 25)), - new ECBlocks(30, new ECB(11, 15), - new ECB(46, 16))), - new Version(34, new int[]{6, 34, 62, 90, 118, 146}, - new ECBlocks(30, new ECB(13, 115), - new ECB(6, 116)), - new ECBlocks(28, new ECB(14, 46), - new ECB(23, 47)), - new ECBlocks(30, new ECB(44, 24), - new ECB(7, 25)), - new ECBlocks(30, new ECB(59, 16), - new ECB(1, 17))), - new Version(35, new int[]{6, 30, 54, 78, 102, 126, 150}, - new ECBlocks(30, new ECB(12, 121), - new ECB(7, 122)), - new ECBlocks(28, new ECB(12, 47), - new ECB(26, 48)), - new ECBlocks(30, new ECB(39, 24), - new ECB(14, 25)), - new ECBlocks(30, new ECB(22, 15), - new ECB(41, 16))), - new Version(36, new int[]{6, 24, 50, 76, 102, 128, 154}, - new ECBlocks(30, new ECB(6, 121), - new ECB(14, 122)), - new ECBlocks(28, new ECB(6, 47), - new ECB(34, 48)), - new ECBlocks(30, new ECB(46, 24), - new ECB(10, 25)), - new ECBlocks(30, new ECB(2, 15), - new ECB(64, 16))), - new Version(37, new int[]{6, 28, 54, 80, 106, 132, 158}, - new ECBlocks(30, new ECB(17, 122), - new ECB(4, 123)), - new ECBlocks(28, new ECB(29, 46), - new ECB(14, 47)), - new ECBlocks(30, new ECB(49, 24), - new ECB(10, 25)), - new ECBlocks(30, new ECB(24, 15), - new ECB(46, 16))), - new Version(38, new int[]{6, 32, 58, 84, 110, 136, 162}, - new ECBlocks(30, new ECB(4, 122), - new ECB(18, 123)), - new ECBlocks(28, new ECB(13, 46), - new ECB(32, 47)), - new ECBlocks(30, new ECB(48, 24), - new ECB(14, 25)), - new ECBlocks(30, new ECB(42, 15), - new ECB(32, 16))), - new Version(39, new int[]{6, 26, 54, 82, 110, 138, 166}, - new ECBlocks(30, new ECB(20, 117), - new ECB(4, 118)), - new ECBlocks(28, new ECB(40, 47), - new ECB(7, 48)), - new ECBlocks(30, new ECB(43, 24), - new ECB(22, 25)), - new ECBlocks(30, new ECB(10, 15), - new ECB(67, 16))), - new Version(40, new int[]{6, 30, 58, 86, 114, 142, 170}, - new ECBlocks(30, new ECB(19, 118), - new ECB(6, 119)), - new ECBlocks(28, new ECB(18, 47), - new ECB(31, 48)), - new ECBlocks(30, new ECB(34, 24), - new ECB(34, 25)), - new ECBlocks(30, new ECB(20, 15), - new ECB(61, 16))) - }; - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/detector/AlignmentPattern.cs b/qrcode-scanner-live2/qrcode/detector/AlignmentPattern.cs deleted file mode 100644 index 562a1d2..0000000 --- a/qrcode-scanner-live2/qrcode/detector/AlignmentPattern.cs +++ /dev/null @@ -1,56 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.detector -{ - public sealed class AlignmentPattern : ResultPoint - { - private float posX; - private float posY; - private float estimatedModuleSize; - - public AlignmentPattern(float posX, float posY, float estimatedModuleSize) { - this.posX = posX; - this.posY = posY; - this.estimatedModuleSize = estimatedModuleSize; - } - - public float getX() { - return posX; - } - - public float getY() { - return posY; - } - - /** - *

Determines if this alignment pattern "about equals" an alignment pattern at the stated - * position and size -- meaning, it is at nearly the same center with nearly the same size.

- */ - public bool aboutEquals(float moduleSize, float i, float j) { - return - Math.Abs(i - posY) <= moduleSize && - Math.Abs(j - posX) <= moduleSize && - (Math.Abs(moduleSize - estimatedModuleSize) <= 1.0f || - Math.Abs(moduleSize - estimatedModuleSize) / estimatedModuleSize <= 0.1f); - } - } - - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/detector/AlignmentPatternFinder.cs b/qrcode-scanner-live2/qrcode/detector/AlignmentPatternFinder.cs deleted file mode 100644 index ed7c41c..0000000 --- a/qrcode-scanner-live2/qrcode/detector/AlignmentPatternFinder.cs +++ /dev/null @@ -1,258 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.detector -{ - public sealed class AlignmentPatternFinder - { - private MonochromeBitmapSource image; - private System.Collections.ArrayList possibleCenters; - private int startX; - private int startY; - private int width; - private int height; - private float moduleSize; - private int[] crossCheckStateCount; - - /** - *

Creates a finder that will look in a portion of the whole image.

- * - * @param image image to search - * @param startX left column from which to start searching - * @param startY top row from which to start searching - * @param width width of region to search - * @param height height of region to search - * @param moduleSize estimated module size so far - */ - public AlignmentPatternFinder(MonochromeBitmapSource image, - int startX, - int startY, - int width, - int height, - float moduleSize) { - this.image = image; - this.possibleCenters = new System.Collections.ArrayList(5); - this.startX = startX; - this.startY = startY; - this.width = width; - this.height = height; - this.moduleSize = moduleSize; - this.crossCheckStateCount = new int[3]; - } - - /** - *

This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since - * it's pretty performance-critical and so is written to be fast foremost.

- * - * @return {@link AlignmentPattern} if found - * @throws ReaderException if not found - */ - public AlignmentPattern find() { - int startX = this.startX; - int height = this.height; - int maxJ = startX + width; - int middleI = startY + (height >> 1); - BitArray luminanceRow = new BitArray(width); - // We are looking for black/white/black modules in 1:1:1 ratio; - // this tracks the number of black/white/black modules seen so far - int[] stateCount = new int[3]; - for (int iGen = 0; iGen < height; iGen++) { - // Search from middle outwards - int i = middleI + ((iGen & 0x01) == 0 ? ((iGen + 1) >> 1) : -((iGen + 1) >> 1)); - image.getBlackRow(i, luminanceRow, startX, width); - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - int j = startX; - // Burn off leading white pixels before anything else; if we start in the middle of - // a white run, it doesn't make sense to count its length, since we don't know if the - // white run continued to the left of the start point - while (j < maxJ && !luminanceRow.get(j - startX)) { - j++; - } - int currentState = 0; - while (j < maxJ) { - if (luminanceRow.get(j - startX)) { - // Black pixel - if (currentState == 1) { // Counting black pixels - stateCount[currentState]++; - } else { // Counting white pixels - if (currentState == 2) { // A winner? - if (foundPatternCross(stateCount)) { // Yes - AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j); - if (confirmed != null) { - return confirmed; - } - } - stateCount[0] = stateCount[2]; - stateCount[1] = 1; - stateCount[2] = 0; - currentState = 1; - } else { - stateCount[++currentState]++; - } - } - } else { // White pixel - if (currentState == 1) { // Counting black pixels - currentState++; - } - stateCount[currentState]++; - } - j++; - } - if (foundPatternCross(stateCount)) { - AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ); - if (confirmed != null) { - return confirmed; - } - } - - } - - // Hmm, nothing we saw was observed and confirmed twice. If we had - // any guess at all, return it. - if (!(possibleCenters.Count==0)) { - return (AlignmentPattern) possibleCenters[0]; - } - - throw new ReaderException(); - } - - /** - * Given a count of black/white/black pixels just seen and an end position, - * figures the location of the center of this black/white/black run. - */ - private static float centerFromEnd(int[] stateCount, int end) { - return (float) (end - stateCount[2]) - stateCount[1] / 2.0f; - } - - /** - * @param stateCount count of black/white/black pixels just read - * @return true iff the proportions of the counts is close enough to the 1/1/1 ratios - * used by alignment patterns to be considered a match - */ - private bool foundPatternCross(int[] stateCount) { - float moduleSize = this.moduleSize; - float maxVariance = moduleSize / 2.0f; - for (int i = 0; i < 3; i++) { - if (Math.Abs(moduleSize - stateCount[i]) >= maxVariance) { - return false; - } - } - return true; - } - - /** - *

After a horizontal scan finds a potential alignment pattern, this method - * "cross-checks" by scanning down vertically through the center of the possible - * alignment pattern to see if the same proportion is detected.

- * - * @param startI row where an alignment pattern was detected - * @param centerJ center of the section that appears to cross an alignment pattern - * @param maxCount maximum reasonable number of modules that should be - * observed in any reading state, based on the results of the horizontal scan - * @return vertical center of alignment pattern, or {@link Float#NaN} if not found - */ - private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { - MonochromeBitmapSource image = this.image; - - int maxI = image.getHeight(); - int[] stateCount = crossCheckStateCount; - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - - // Start counting up from center - int i = startI; - while (i >= 0 && image.isBlack(centerJ, i) && stateCount[1] <= maxCount) { - stateCount[1]++; - i--; - } - // If already too many modules in this state or ran off the edge: - if (i < 0 || stateCount[1] > maxCount) { - return float.NaN; - } - while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[0] <= maxCount) { - stateCount[0]++; - i--; - } - if (stateCount[0] > maxCount) { - return float.NaN; - } - - // Now also count down from center - i = startI + 1; - while (i < maxI && image.isBlack(centerJ, i) && stateCount[1] <= maxCount) { - stateCount[1]++; - i++; - } - if (i == maxI || stateCount[1] > maxCount) { - return float.NaN; - } - while (i < maxI && !image.isBlack(centerJ, i) && stateCount[2] <= maxCount) { - stateCount[2]++; - i++; - } - if (stateCount[2] > maxCount) { - return float.NaN; - } - - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; - if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { - return float.NaN; - } - - return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : float.NaN; - } - - /** - *

This is called when a horizontal scan finds a possible alignment pattern. It will - * cross check with a vertical scan, and if successful, will see if this pattern had been - * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have - * found the alignment pattern.

- * - * @param stateCount reading state module counts from horizontal scan - * @param i row where alignment pattern may be found - * @param j end of possible alignment pattern in row - * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not - */ - private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) { - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; - float centerJ = centerFromEnd(stateCount, j); - float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1], stateCountTotal); - if (!Single.IsNaN(centerI)) - { - float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f; - int max = possibleCenters.Count; - for (int index = 0; index < max; index++) { - AlignmentPattern center = (AlignmentPattern) possibleCenters[index]; - // Look for about the same center and module size: - if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { - return new AlignmentPattern(centerJ, centerI, estimatedModuleSize); - } - } - // Hadn't found this before; save it - possibleCenters.Add(new AlignmentPattern(centerJ, centerI, estimatedModuleSize)); - } - return null; - } - - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/detector/Detector.cs b/qrcode-scanner-live2/qrcode/detector/Detector.cs deleted file mode 100644 index 828aa85..0000000 --- a/qrcode-scanner-live2/qrcode/detector/Detector.cs +++ /dev/null @@ -1,362 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.detector -{ - using Version = com.google.zxing.qrcode.decoder.Version; - - public sealed class Detector - { - private MonochromeBitmapSource image; - - public Detector(MonochromeBitmapSource image) { - this.image = image; - } - - /** - *

Detects a QR Code in an image, simply.

- * - * @return {@link DetectorResult} encapsulating results of detecting a QR Code - * @throws ReaderException if no QR Code can be found - */ - public DetectorResult detect(){ - try{ - return detect(null); - }catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - /** - *

Detects a QR Code in an image, simply.

- * - * @param hints optional hints to detector - * @return {@link DetectorResult} encapsulating results of detecting a QR Code - * @throws ReaderException if no QR Code can be found - */ - public DetectorResult detect(System.Collections.Hashtable hints) { - - MonochromeBitmapSource image = this.image; - if (!BlackPointEstimationMethod.TWO_D_SAMPLING.Equals(image.getLastEstimationMethod())) { - image.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0); - } - - FinderPatternFinder finder = new FinderPatternFinder(image); - FinderPatternInfo info = finder.find(hints); - - FinderPattern topLeft = info.getTopLeft(); - FinderPattern topRight = info.getTopRight(); - FinderPattern bottomLeft = info.getBottomLeft(); - - float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft); - if (moduleSize < 1.0f) { - throw new ReaderException(); - } - int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize); - - Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension); - int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7; - - AlignmentPattern alignmentPattern = null; - // Anything above version 1 has an alignment pattern - if (provisionalVersion.getAlignmentPatternCenters().Length > 0) { - - // Guess where a "bottom right" finder pattern would have been - float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX(); - float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY(); - - // Estimate that alignment pattern is closer by 3 modules - // from "bottom right" to known top left location - float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters; - int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX())); - int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY())); - - // Kind of arbitrary -- expand search radius before giving up - for (int i = 4; i <= 16; i <<= 1) { - try { - alignmentPattern = findAlignmentInRegion(moduleSize, - estAlignmentX, - estAlignmentY, - (float) i); - break; - } catch (ReaderException re) { - // try next round - } - } - if (alignmentPattern == null) { - throw new ReaderException(); - } - - } - - BitMatrix bits = sampleGrid(image, topLeft, topRight, bottomLeft, alignmentPattern, dimension); - - ResultPoint[] points; - if (alignmentPattern == null) { - points = new ResultPoint[]{bottomLeft, topLeft, topRight}; - } else { - points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern}; - } - return new DetectorResult(bits, points); - } - - private static BitMatrix sampleGrid(MonochromeBitmapSource image, - ResultPoint topLeft, - ResultPoint topRight, - ResultPoint bottomLeft, - ResultPoint alignmentPattern, - int dimension) { - float dimMinusThree = (float) dimension - 3.5f; - float bottomRightX; - float bottomRightY; - float sourceBottomRightX; - float sourceBottomRightY; - if (alignmentPattern != null) { - bottomRightX = alignmentPattern.getX(); - bottomRightY = alignmentPattern.getY(); - sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0f; - } else { - // Don't have an alignment pattern, just make up the bottom-right point - bottomRightX = (topRight.getX() - topLeft.getX()) + bottomLeft.getX(); - bottomRightY = (topRight.getY() - topLeft.getY()) + bottomLeft.getY(); - sourceBottomRightX = sourceBottomRightY = dimMinusThree; - } - - GridSampler sampler = GridSampler.Instance; - return sampler.sampleGrid( - image, - dimension, - 3.5f, - 3.5f, - dimMinusThree, - 3.5f, - sourceBottomRightX, - sourceBottomRightY, - 3.5f, - dimMinusThree, - topLeft.getX(), - topLeft.getY(), - topRight.getX(), - topRight.getY(), - bottomRightX, - bottomRightY, - bottomLeft.getX(), - bottomLeft.getY()); - } - - /** - *

Computes the dimension (number of modules on a size) of the QR Code based on the position - * of the finder patterns and estimated module size.

- */ - private static int computeDimension(ResultPoint topLeft, - ResultPoint topRight, - ResultPoint bottomLeft, - float moduleSize) { - int tltrCentersDimension = round(GenericResultPoint.distance(topLeft, topRight) / moduleSize); - int tlblCentersDimension = round(GenericResultPoint.distance(topLeft, bottomLeft) / moduleSize); - int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; - switch (dimension & 0x03) { // mod 4 - case 0: - dimension++; - break; - // 1? do nothing - case 2: - dimension--; - break; - case 3: - throw new ReaderException(); - } - return dimension; - } - - /** - *

Computes an average estimated module size based on estimated derived from the positions - * of the three finder patterns.

- */ - private float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) { - // Take the average - return (calculateModuleSizeOneWay(topLeft, topRight) + - calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f; - } - - /** - *

Estimates module size based on two finder patterns -- it uses - * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the - * width of each, measuring along the axis between their centers.

- */ - private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) { - float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(), - (int) pattern.getY(), - (int) otherPattern.getX(), - (int) otherPattern.getY()); - float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(), - (int) otherPattern.getY(), - (int) pattern.getX(), - (int) pattern.getY()); - if (Single.IsNaN(moduleSizeEst1)) { - return moduleSizeEst2; - } - if (Single.IsNaN(moduleSizeEst2)) - { - return moduleSizeEst1; - } - // Average them, and divide by 7 since we've counted the width of 3 black modules, - // and 1 white and 1 black module on either side. Ergo, divide sum by 14. - return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; - } - - /** - * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of - * a finder pattern by looking for a black-white-black run from the center in the direction - * of another point (another finder pattern center), and in the opposite direction too.

- */ - private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) { - - float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); - - // Now count other way -- don't run off image though of course - int otherToX = fromX - (toX - fromX); - if (otherToX < 0) { - // "to" should the be the first value not included, so, the first value off - // the edge is -1 - otherToX = -1; - } else if (otherToX >= image.getWidth()) { - otherToX = image.getWidth(); - } - int otherToY = fromY - (toY - fromY); - if (otherToY < 0) { - otherToY = -1; - } else if (otherToY >= image.getHeight()) { - otherToY = image.getHeight(); - } - result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); - return result - 1.0f; // -1 because we counted the middle pixel twice - } - - /** - *

This method traces a line from a point in the image, in the direction towards another point. - * It begins in a black region, and keeps going until it finds white, then black, then white again. - * It reports the distance from the start to this point.

- * - *

This is used when figuring out how wide a finder pattern is, when the finder pattern - * may be skewed or rotated.

- */ - private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) { - // Mild variant of Bresenham's algorithm; - // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm - bool steep = Math.Abs(toY - fromY) > Math.Abs(toX - fromX); - if (steep) { - int temp = fromX; - fromX = fromY; - fromY = temp; - temp = toX; - toX = toY; - toY = temp; - } - - int dx = Math.Abs(toX - fromX); - int dy = Math.Abs(toY - fromY); - int error = -dx >> 1; - int ystep = fromY < toY ? 1 : -1; - int xstep = fromX < toX ? 1 : -1; - int state = 0; // In black pixels, looking for white, first or second time - int diffX =0; - int diffY =0; - - for (int x = fromX, y = fromY; x != toX; x += xstep) { - - int realX = steep ? y : x; - int realY = steep ? x : y; - if (state == 1) { // In white pixels, looking for black - if (image.isBlack(realX, realY)) { - state++; - } - } else { - if (!image.isBlack(realX, realY)) { - state++; - } - } - - if (state == 3) { // Found black, white, black, and stumbled back onto white; done - diffX = x - fromX; - diffY = y - fromY; - return (float) Math.Sqrt((double) (diffX * diffX + diffY * diffY)); - } - error += dy; - if (error > 0) { - y += ystep; - error -= dx; - } - } - - diffX = toX - fromX; - diffY = toY - fromY; - return (float) Math.Sqrt((double) (diffX * diffX + diffY * diffY)); - } - - /** - *

Attempts to locate an alignment pattern in a limited region of the image, which is - * guessed to contain it. This method uses {@link AlignmentPattern}.

- * - * @param overallEstModuleSize estimated module size so far - * @param estAlignmentX x coordinate of center of area probably containing alignment pattern - * @param estAlignmentY y coordinate of above - * @param allowanceFactor number of pixels in all directons to search from the center - * @return {@link AlignmentPattern} if found, or null otherwise - * @throws ReaderException if an unexpected error occurs during detection - */ - private AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, - int estAlignmentX, - int estAlignmentY, - float allowanceFactor){ - // Look for an alignment pattern (3 modules in size) around where it - // should be - int allowance = (int) (allowanceFactor * overallEstModuleSize); - int alignmentAreaLeftX = Math.Max(0, estAlignmentX - allowance); - int alignmentAreaRightX = Math.Min(image.getWidth() - 1, estAlignmentX + allowance); - if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) { - throw new ReaderException(); - } - - int alignmentAreaTopY = Math.Max(0, estAlignmentY - allowance); - int alignmentAreaBottomY = Math.Min(image.getHeight() - 1, estAlignmentY + allowance); - - AlignmentPatternFinder alignmentFinder = - new AlignmentPatternFinder( - image, - alignmentAreaLeftX, - alignmentAreaTopY, - alignmentAreaRightX - alignmentAreaLeftX, - alignmentAreaBottomY - alignmentAreaTopY, - overallEstModuleSize); - return alignmentFinder.find(); - } - - /** - * Ends up being a bit faster than Math.round(). This merely rounds its argument to the nearest int, - * where x.5 rounds up. - */ - private static int round(float d) { - return (int) (d + 0.5f); - } - - } - - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/detector/FinderPattern.cs b/qrcode-scanner-live2/qrcode/detector/FinderPattern.cs deleted file mode 100644 index 601bcfb..0000000 --- a/qrcode-scanner-live2/qrcode/detector/FinderPattern.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.detector -{ - public sealed class FinderPattern : ResultPoint - { - private float posX; - private float posY; - private float estimatedModuleSize; - private int count; - - public FinderPattern(float posX, float posY, float estimatedModuleSize) { - this.posX = posX; - this.posY = posY; - this.estimatedModuleSize = estimatedModuleSize; - this.count = 1; - } - - public float getX() { - return posX; - } - - public float getY() { - return posY; - } - - public float getEstimatedModuleSize() - { - return estimatedModuleSize; - } - - public int getCount() - { - return count; - } - - public void incrementCount() - { - this.count++; - } - - /** - *

Determines if this finder pattern "about equals" a finder pattern at the stated - * position and size -- meaning, it is at nearly the same center with nearly the same size.

- */ - public bool aboutEquals(float moduleSize, float i, float j) { - return Math.Abs(i - posY) <= moduleSize && - Math.Abs(j - posX) <= moduleSize && - (Math.Abs(moduleSize - estimatedModuleSize) <= 1.0f || - Math.Abs(moduleSize - estimatedModuleSize) / estimatedModuleSize <= 0.1f); - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/detector/FinderPatternFinder.cs b/qrcode-scanner-live2/qrcode/detector/FinderPatternFinder.cs deleted file mode 100644 index 6023ef0..0000000 --- a/qrcode-scanner-live2/qrcode/detector/FinderPatternFinder.cs +++ /dev/null @@ -1,527 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.qrcode.detector -{ - using System; - using com.google.zxing; - using com.google.zxing.common; - - public sealed class FinderPatternFinder - { - private static int CENTER_QUORUM = 2; - private static int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center - private static int MAX_MODULES = 57; // support up to version 10 for mobile clients - private static int INTEGER_MATH_SHIFT = 8; - - private MonochromeBitmapSource image; - private System.Collections.ArrayList possibleCenters; - private bool hasSkipped; - private int[] crossCheckStateCount; - - /** - *

Creates a finder that will search the image for three finder patterns.

- * - * @param image image to search - */ - public FinderPatternFinder(MonochromeBitmapSource image) { - this.image = image; - this.possibleCenters = new System.Collections.ArrayList(); - this.crossCheckStateCount = new int[5]; - } - - public FinderPatternInfo find(System.Collections.Hashtable hints) { - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - int maxI = image.getHeight(); - int maxJ = image.getWidth(); - // We are looking for black/white/black/white/black modules in - // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far - - // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the - // image, and then account for the center being 3 modules in size. This gives the smallest - // number of pixels the center could be, so skip this often. When trying harder, look for all - // QR versions regardless of how dense they are. - int iSkip = (int) (maxI / (MAX_MODULES * 4.0f) * 3); - if (iSkip < MIN_SKIP || tryHarder) { - iSkip = MIN_SKIP; - } - - bool done = false; - int[] stateCount = new int[5]; - BitArray blackRow = new BitArray(maxJ); - for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { - // Get a row of black/white values - blackRow = image.getBlackRow(i, blackRow, 0, maxJ); - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - int currentState = 0; - for (int j = 0; j < maxJ; j++) { - if (blackRow.get(j)) { - // Black pixel - if ((currentState & 1) == 1) { // Counting white pixels - currentState++; - } - stateCount[currentState]++; - } else { // White pixel - if ((currentState & 1) == 0) { // Counting black pixels - if (currentState == 4) { // A winner? - if (foundPatternCross(stateCount)) { // Yes - bool confirmed = handlePossibleCenter(stateCount, i, j); - if (confirmed) { - // Start examining every other line. Checking each line turned out to be too - // expensive and didn't improve performance. - iSkip = 2; - if (hasSkipped) { - done = haveMulitplyConfirmedCenters(); - } else { - int rowSkip = findRowSkip(); - if (rowSkip > stateCount[2]) { - // Skip rows between row of lower confirmed center - // and top of presumed third confirmed center - // but back up a bit to get a full chance of detecting - // it, entire width of center of finder pattern - - // Skip by rowSkip, but back off by stateCount[2] (size of last center - // of pattern we saw) to be conservative, and also back off by iSkip which - // is about to be re-added - i += rowSkip - stateCount[2] - iSkip; - j = maxJ - 1; - } - } - } else { - // Advance to next black pixel - do { - j++; - } while (j < maxJ && !blackRow.get(j)); - j--; // back up to that last white pixel - } - // Clear state to start looking again - currentState = 0; - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - } else { // No, shift counts back by two - stateCount[0] = stateCount[2]; - stateCount[1] = stateCount[3]; - stateCount[2] = stateCount[4]; - stateCount[3] = 1; - stateCount[4] = 0; - currentState = 3; - } - } else { - stateCount[++currentState]++; - } - } else { // Counting white pixels - stateCount[currentState]++; - } - } - } - if (foundPatternCross(stateCount)) { - bool confirmed = handlePossibleCenter(stateCount, i, maxJ); - if (confirmed) { - iSkip = stateCount[0]; - if (hasSkipped) { - // Found a third one - done = haveMulitplyConfirmedCenters(); - } - } - } - } - - FinderPattern[] patternInfo = selectBestPatterns(); - GenericResultPoint.orderBestPatterns(patternInfo); - - return new FinderPatternInfo(patternInfo); - } - - /** - * Given a count of black/white/black/white/black pixels just seen and an end position, - * figures the location of the center of this run. - */ - private static float centerFromEnd(int[] stateCount, int end) { - return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; - } - - /** - * @param stateCount count of black/white/black/white/black pixels just read - * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios - * used by finder patterns to be considered a match - */ - private static bool foundPatternCross(int[] stateCount) { - int totalModuleSize = 0; - for (int i = 0; i < 5; i++) { - int count = stateCount[i]; - if (count == 0) { - return false; - } - totalModuleSize += count; - } - if (totalModuleSize < 7) { - return false; - } - int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; - int maxVariance = moduleSize / 2; - // Allow less than 50% variance from 1-1-3-1-1 proportions - return Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && - Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && - Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && - Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && - Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; - } - - private int[] getCrossCheckStateCount() { - crossCheckStateCount[0] = 0; - crossCheckStateCount[1] = 0; - crossCheckStateCount[2] = 0; - crossCheckStateCount[3] = 0; - crossCheckStateCount[4] = 0; - return crossCheckStateCount; - } - - /** - *

After a horizontal scan finds a potential finder pattern, this method - * "cross-checks" by scanning down vertically through the center of the possible - * finder pattern to see if the same proportion is detected.

- * - * @param startI row where a finder pattern was detected - * @param centerJ center of the section that appears to cross a finder pattern - * @param maxCount maximum reasonable number of modules that should be - * observed in any reading state, based on the results of the horizontal scan - * @return vertical center of finder pattern, or {@link Float#NaN} if not found - */ - private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { - MonochromeBitmapSource image = this.image; - - int maxI = image.getHeight(); - int[] stateCount = getCrossCheckStateCount(); - - // Start counting up from center - int i = startI; - while (i >= 0 && image.isBlack(centerJ, i)) { - stateCount[2]++; - i--; - } - if (i < 0) { - return float.NaN; - } - while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[1] <= maxCount) { - stateCount[1]++; - i--; - } - // If already too many modules in this state or ran off the edge: - if (i < 0 || stateCount[1] > maxCount) { - return float.NaN; - } - while (i >= 0 && image.isBlack(centerJ, i) && stateCount[0] <= maxCount) { - stateCount[0]++; - i--; - } - if (stateCount[0] > maxCount) { - return float.NaN; - } - - // Now also count down from center - i = startI + 1; - while (i < maxI && image.isBlack(centerJ, i)) { - stateCount[2]++; - i++; - } - if (i == maxI) { - return float.NaN; - } - while (i < maxI && !image.isBlack(centerJ, i) && stateCount[3] < maxCount) { - stateCount[3]++; - i++; - } - if (i == maxI || stateCount[3] >= maxCount) { - return float.NaN; - } - while (i < maxI && image.isBlack(centerJ, i) && stateCount[4] < maxCount) { - stateCount[4]++; - i++; - } - if (stateCount[4] >= maxCount) { - return float.NaN; - } - - // If we found a finder-pattern-like section, but its size is more than 20% different than - // the original, assume it's a false positive - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { - return float.NaN; - } - - return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : float.NaN; - } - - /** - *

Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical, - * except it reads horizontally instead of vertically. This is used to cross-cross - * check a vertical cross check and locate the real center of the alignment pattern.

- */ - private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) { - MonochromeBitmapSource image = this.image; - - int maxJ = image.getWidth(); - int[] stateCount = getCrossCheckStateCount(); - - int j = startJ; - while (j >= 0 && image.isBlack(j, centerI)) { - stateCount[2]++; - j--; - } - if (j < 0) { - return float.NaN; - } - while (j >= 0 && !image.isBlack(j, centerI) && stateCount[1] <= maxCount) { - stateCount[1]++; - j--; - } - if (j < 0 || stateCount[1] > maxCount) { - return float.NaN; - } - while (j >= 0 && image.isBlack(j, centerI) && stateCount[0] <= maxCount) { - stateCount[0]++; - j--; - } - if (stateCount[0] > maxCount) { - return float.NaN; - } - - j = startJ + 1; - while (j < maxJ && image.isBlack(j, centerI)) { - stateCount[2]++; - j++; - } - if (j == maxJ) { - return float.NaN; - } - while (j < maxJ && !image.isBlack(j, centerI) && stateCount[3] < maxCount) { - stateCount[3]++; - j++; - } - if (j == maxJ || stateCount[3] >= maxCount) { - return float.NaN; - } - while (j < maxJ && image.isBlack(j, centerI) && stateCount[4] < maxCount) { - stateCount[4]++; - j++; - } - if (stateCount[4] >= maxCount) { - return float.NaN; - } - - // If we found a finder-pattern-like section, but its size is significantly different than - // the original, assume it's a false positive - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { - return float.NaN; - } - - return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : float.NaN; - } - - /** - *

This is called when a horizontal scan finds a possible alignment pattern. It will - * cross check with a vertical scan, and if successful, will, ah, cross-cross-check - * with another horizontal scan. This is needed primarily to locate the real horizontal - * center of the pattern in cases of extreme skew.

- * - *

If that succeeds the finder pattern location is added to a list that tracks - * the number of times each location has been nearly-matched as a finder pattern. - * Each additional find is more evidence that the location is in fact a finder - * pattern center - * - * @param stateCount reading state module counts from horizontal scan - * @param i row where finder pattern may be found - * @param j end of possible finder pattern in row - * @return true if a finder pattern candidate was found this time - */ - private bool handlePossibleCenter(int[] stateCount, - int i, - int j) { - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - float centerJ = centerFromEnd(stateCount, j); - float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal); - if (!Single.IsNaN(centerI)) { - // Re-cross check - centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal); - if (!Single.IsNaN(centerJ)) - { - float estimatedModuleSize = (float) stateCountTotal / 7.0f; - bool found = false; - int max = possibleCenters.Count; - for (int index = 0; index < max; index++) { - FinderPattern center = (FinderPattern) possibleCenters[index]; - // Look for about the same center and module size: - if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { - center.incrementCount(); - found = true; - break; - } - } - if (!found) { - possibleCenters.Add(new FinderPattern(centerJ, centerI, estimatedModuleSize)); - } - return true; - } - } - return false; - } - - /** - * @return number of rows we could safely skip during scanning, based on the first - * two finder patterns that have been located. In some cases their position will - * allow us to infer that the third pattern must lie below a certain point farther - * down in the image. - */ - private int findRowSkip() { - int max = possibleCenters.Count; - if (max <= 1) { - return 0; - } - FinderPattern firstConfirmedCenter = null; - for (int i = 0; i < max; i++) { - FinderPattern center = (FinderPattern) possibleCenters[i]; - if (center.getCount() >= CENTER_QUORUM) { - if (firstConfirmedCenter == null) { - firstConfirmedCenter = center; - } else { - // We have two confirmed centers - // How far down can we skip before resuming looking for the next - // pattern? In the worst case, only the difference between the - // difference in the x / y coordinates of the two centers. - // This is the case where you find top left last. - hasSkipped = true; - return (int) (Math.Abs(firstConfirmedCenter.getX() - center.getX()) - - Math.Abs(firstConfirmedCenter.getY() - center.getY())) / 2; - } - } - } - return 0; - } - - /** - * @return true iff we have found at least 3 finder patterns that have been detected - * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the - * candidates is "pretty similar" - */ - private bool haveMulitplyConfirmedCenters() { - int confirmedCount = 0; - float totalModuleSize = 0.0f; - int max = possibleCenters.Count; - for (int i = 0; i < max; i++) { - FinderPattern pattern = (FinderPattern) possibleCenters[i]; - if (pattern.getCount() >= CENTER_QUORUM) { - confirmedCount++; - totalModuleSize += pattern.getEstimatedModuleSize(); - } - } - if (confirmedCount < 3) { - return false; - } - // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" - // and that we need to keep looking. We detect this by asking if the estimated module sizes - // vary too much. We arbitrarily say that when the total deviation from average exceeds - // 15% of the total module size estimates, it's too much. - float average = totalModuleSize / max; - float totalDeviation = 0.0f; - for (int i = 0; i < max; i++) { - FinderPattern pattern = (FinderPattern) possibleCenters[i]; - totalDeviation += Math.Abs(pattern.getEstimatedModuleSize() - average); - } - return totalDeviation <= 0.15f * totalModuleSize; - } - - /** - * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are - * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module - * size differs from the average among those patterns the least - * @throws ReaderException if 3 such finder patterns do not exist - */ - private FinderPattern[] selectBestPatterns(){ - Collections.insertionSort(possibleCenters, new CenterComparator()); - int size = 0; - int max = possibleCenters.Count; - while (size < max) { - if (((FinderPattern) possibleCenters[size]).getCount() < CENTER_QUORUM) { - break; - } - size++; - } - - if (size < 3) { - // Couldn't find enough finder patterns - throw new ReaderException(); - } - - if (size > 3) { - // Throw away all but those first size candidate points we found. - SupportClass.SetCapacity(possibleCenters, size); - // We need to pick the best three. Find the most - // popular ones whose module size is nearest the average - float averageModuleSize = 0.0f; - for (int i = 0; i < size; i++) { - averageModuleSize += ((FinderPattern) possibleCenters[i]).getEstimatedModuleSize(); - } - averageModuleSize /= (float) size; - // We don't have java.util.Collections in J2ME - Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize)); - } - - return new FinderPattern[]{ - (FinderPattern) possibleCenters[0], - (FinderPattern) possibleCenters[1], - (FinderPattern) possibleCenters[2] - }; - } - - /** - *

Orders by {@link FinderPattern#getCount()}, descending.

- */ - private class CenterComparator : Comparator { - public int compare(object center1, object center2) - { - return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount(); - } - } - - /** - *

Orders by variance from average module size, ascending.

- */ - private class ClosestToAverageComparator : Comparator { - private float averageModuleSize; - - public ClosestToAverageComparator(float averageModuleSize) { - this.averageModuleSize = averageModuleSize; - } - - public int compare(object center1, object center2) - { - return Math.Abs(((FinderPattern) center1).getEstimatedModuleSize() - averageModuleSize) < - Math.Abs(((FinderPattern) center2).getEstimatedModuleSize() - averageModuleSize) ? - -1 : - 1; - } - } - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/detector/FinderPatternInfo.cs b/qrcode-scanner-live2/qrcode/detector/FinderPatternInfo.cs deleted file mode 100644 index 5faae93..0000000 --- a/qrcode-scanner-live2/qrcode/detector/FinderPatternInfo.cs +++ /dev/null @@ -1,51 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -namespace com.google.zxing.qrcode.detector -{ - using com.google.zxing; - using com.google.zxing.common; - - public sealed class FinderPatternInfo - { - private FinderPattern bottomLeft; - private FinderPattern topLeft; - private FinderPattern topRight; - - public FinderPatternInfo(FinderPattern[] patternCenters) { - this.bottomLeft = patternCenters[0]; - this.topLeft = patternCenters[1]; - this.topRight = patternCenters[2]; - } - - public FinderPattern getBottomLeft() - { - return bottomLeft; - } - - public FinderPattern getTopLeft() - { - return topLeft; - } - - public FinderPattern getTopRight() - { - return topRight; - } - - } - -} - diff --git a/qrcode-scanner-live2/qrcode/encoder/BitVector.cs b/qrcode-scanner-live2/qrcode/encoder/BitVector.cs deleted file mode 100644 index 32b5ea6..0000000 --- a/qrcode-scanner-live2/qrcode/encoder/BitVector.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; - -namespace com.google.zxing.qrcode.encoder -{ - public sealed class BitVector { - - private int sizeInBits; - private sbyte[] array; - - // For efficiency, start out with some room to work. - private static int DEFAULT_SIZE_IN_BYTES = 32; - - public BitVector() { - sizeInBits = 0; - array = new sbyte[DEFAULT_SIZE_IN_BYTES]; - } - - // Return the bit value at "index". - public int at(int index) { - if (index < 0 || index >= sizeInBits) { - throw new ArgumentException("Bad index: " + index); - } - int value = array[index >> 3] & 0xff; - return (value >> (7 - (index & 0x7))) & 1; - } - - // Return the number of bits in the bit vector. - public int size() { - return sizeInBits; - } - - // Return the number of bytes in the bit vector. - public int sizeInBytes() { - return (sizeInBits + 7) >> 3; - } - - // Append one bit to the bit vector. - public void appendBit(int bit) { - if (!(bit == 0 || bit == 1)) { - throw new ArgumentException("Bad bit"); - } - int numBitsInLastByte = sizeInBits & 0x7; - // We'll expand array if we don't have bits in the last byte. - if (numBitsInLastByte == 0) { - appendByte(0); - sizeInBits -= 8; - } - // Modify the last byte. - array[sizeInBits >> 3] |= (sbyte)(bit << (7 - numBitsInLastByte)); - ++sizeInBits; - } - - // Append "numBits" bits in "value" to the bit vector. - // REQUIRES: 0<= numBits <= 32. - // - // Examples: - // - appendBits(0x00, 1) adds 0. - // - appendBits(0x00, 4) adds 0000. - // - appendBits(0xff, 8) adds 11111111. - public void appendBits(int value, int numBits) { - if (numBits < 0 || numBits > 32) { - throw new ArgumentException("Num bits must be between 0 and 32"); - } - int numBitsLeft = numBits; - while (numBitsLeft > 0) { - // Optimization for byte-oriented appending. - if ((sizeInBits & 0x7) == 0 && numBitsLeft >= 8) { - int newByte = (value >> (numBitsLeft - 8)) & 0xff; - appendByte(newByte); - numBitsLeft -= 8; - } else { - int bit = (value >> (numBitsLeft - 1)) & 1; - appendBit(bit); - --numBitsLeft; - } - } - } - - // Append "bits". - public void appendBitVector(BitVector bits) { - int size = bits.size(); - for (int i = 0; i < size; ++i) { - appendBit(bits.at(i)); - } - } - - // Modify the bit vector by XOR'ing with "other" - public void xor(BitVector other) { - if (sizeInBits != other.size()) { - throw new ArgumentException("BitVector sizes don't match"); - } - int sizeInBytes = (sizeInBits + 7) >> 3; - for (int i = 0; i < sizeInBytes; ++i) { - // The last byte could be incomplete (i.e. not have 8 bits in - // it) but there is no problem since 0 XOR 0 == 0. - array[i] ^= other.array[i]; - } - } - - // Return String like "01110111" for debugging. - public String toString() { - StringBuilder result = new StringBuilder(sizeInBits); - for (int i = 0; i < sizeInBits; ++i) { - if (at(i) == 0) { - result.Append('0'); - } else if (at(i) == 1) { - result.Append('1'); - } else { - throw new ArgumentException("Byte isn't 0 or 1"); - } - } - return result.ToString(); - } - - // Callers should not assume that array.length is the exact number of bytes needed to hold - // sizeInBits - it will typically be larger for efficiency. - public sbyte[] getArray() { - return array; - } - - // Add a new byte to the end, possibly reallocating and doubling the size of the array if we've - // run out of room. - private void appendByte(int value) { - if ((sizeInBits >> 3) == array.Length) { - sbyte[] newArray = new sbyte[(array.Length << 1)]; - System.Array.Copy (array, 0, newArray, 0, array.Length); - array = newArray; - } - array[sizeInBits >> 3] = (sbyte) value; - sizeInBits += 8; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/encoder/Encoder.cs b/qrcode-scanner-live2/qrcode/encoder/Encoder.cs deleted file mode 100644 index df0b303..0000000 --- a/qrcode-scanner-live2/qrcode/encoder/Encoder.cs +++ /dev/null @@ -1,511 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using System.Collections; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.common.reedsolomon; -using com.google.zxing.qrcode.decoder; -using com.google.zxing.qrcode; - -namespace com.google.zxing.qrcode.encoder -{ - using Version=com.google.zxing.qrcode.decoder.Version; - public sealed class Encoder - { - // The original table is defined in the table 5 of JISX0510:2004 (p.19). - private static int[] ALPHANUMERIC_TABLE = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f - 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f - -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f - }; - - private Encoder() { - } - - // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details. - // Basically it applies four rules and summate all penalties. - private static int calculateMaskPenalty(ByteMatrix matrix) { - int penalty = 0; - penalty += MaskUtil.applyMaskPenaltyRule1(matrix); - penalty += MaskUtil.applyMaskPenaltyRule2(matrix); - penalty += MaskUtil.applyMaskPenaltyRule3(matrix); - penalty += MaskUtil.applyMaskPenaltyRule4(matrix); - return penalty; - } - - private class BlockPair { - - private ByteArray dataBytes; - private ByteArray errorCorrectionBytes; - - public BlockPair(ByteArray data, ByteArray errorCorrection) { - dataBytes = data; - errorCorrectionBytes = errorCorrection; - } - - public ByteArray getDataBytes() { - return dataBytes; - } - - public ByteArray getErrorCorrectionBytes() { - return errorCorrectionBytes; - } - - } - - // Encode "bytes" with the error correction level "getECLevel". The encoding mode will be chosen - // internally by chooseMode(). On success, store the result in "qrCode" and return true. - // We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for - // "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very - // strong error correction for this purpose. - // - // Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode() - // with which clients can specify the encoding mode. For now, we don't need the functionality. - public static void encode(String content, ErrorCorrectionLevel ecLevel, QRCode qrCode) - { - // Step 1: Choose the mode (encoding). - Mode mode = chooseMode(content); - - // Step 2: Append "bytes" into "dataBits" in appropriate encoding. - BitVector dataBits = new BitVector(); - appendBytes(content, mode, dataBits); - // Step 3: Initialize QR code that can contain "dataBits". - int numInputBytes = dataBits.sizeInBytes(); - initQRCode(numInputBytes, ecLevel, mode, qrCode); - - // Step 4: Build another bit vector that contains header and data. - BitVector headerAndDataBits = new BitVector(); - appendModeInfo(qrCode.getMode(), headerAndDataBits); - appendLengthInfo(content.Length, qrCode.getVersion(), qrCode.getMode(), headerAndDataBits); - headerAndDataBits.appendBitVector(dataBits); - - // Step 5: Terminate the bits properly. - terminateBits(qrCode.getNumDataBytes(), headerAndDataBits); - - // Step 6: Interleave data bits with error correction code. - BitVector finalBits = new BitVector(); - interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(), - qrCode.getNumRSBlocks(), finalBits); - - // Step 7: Choose the mask pattern and set to "qrCode". - ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth()); - qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(), - matrix)); - - // Step 8. Build the matrix and set it to "qrCode". - MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(), - qrCode.getMaskPattern(), matrix); - qrCode.setMatrix(matrix); - // Step 9. Make sure we have a valid QR Code. - if (!qrCode.isValid()) { - throw new WriterException("Invalid QR code: " + qrCode.toString()); - } - } - - // Return the code point of the table used in alphanumeric mode. Return -1 if there is no - // corresponding code in the table. - static int getAlphanumericCode(int code) { - if (code < ALPHANUMERIC_TABLE.Length) { - return ALPHANUMERIC_TABLE[code]; - } - return -1; - } - - // Choose the best mode by examining the content. - // - // Note that this function does not return MODE_KANJI, as we cannot distinguish Shift_JIS from - // other encodings such as ISO-8859-1, from data bytes alone. For example "\xE0\xE0" can be - // interpreted as one character in Shift_JIS, but also two characters in ISO-8859-1. - // - // JAVAPORT: This MODE_KANJI limitation sounds like a problem for us. - public static Mode chooseMode(String content) { - bool hasNumeric = false; - bool hasAlphanumeric = false; - for (int i = 0; i < content.Length; ++i) { - char c = content[i]; - if (c >= '0' && c <= '9') { - hasNumeric = true; - } else if (getAlphanumericCode(c) != -1) { - hasAlphanumeric = true; - } else { - return Mode.BYTE; - } - } - if (hasAlphanumeric) { - return Mode.ALPHANUMERIC; - } else if (hasNumeric) { - return Mode.NUMERIC; - } - return Mode.BYTE; - } - - private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version,ByteMatrix matrix){ - try{ - int minPenalty = int.MaxValue; // Lower penalty is better. - int bestMaskPattern = -1; - // We try all mask patterns to choose the best one. - for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) - { - MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); - int penalty = calculateMaskPenalty(matrix); - if (penalty < minPenalty) - { - minPenalty = penalty; - bestMaskPattern = maskPattern; - } - } - return bestMaskPattern; - }catch(Exception e){ - throw new ReaderException(e.Message); - } - } - - // Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success, modify - // "qrCode". - private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode) - { - try - { - qrCode.setECLevel(ecLevel); - qrCode.setMode(mode); - - // In the following comments, we use numbers of Version 7-H. - for (int versionNum = 1; versionNum <= 40; versionNum++) { - Version version = Version.getVersionForNumber(versionNum); - // numBytes = 196 - int numBytes = version.getTotalCodewords(); - // getNumECBytes = 130 - Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); - int numEcBytes = ecBlocks.getTotalECCodewords(); - // getNumRSBlocks = 5 - int numRSBlocks = ecBlocks.getNumBlocks(); - // getNumDataBytes = 196 - 130 = 66 - int numDataBytes = numBytes - numEcBytes; - // We want to choose the smallest version which can contain data of "numInputBytes" + some - // extra bits for the header (mode info and length info). The header can be three bytes - // (precisely 4 + 16 bits) at most. Hence we do +3 here. - if (numDataBytes >= numInputBytes + 3) { - // Yay, we found the proper rs block info! - qrCode.setVersion(versionNum); - qrCode.setNumTotalBytes(numBytes); - qrCode.setNumDataBytes(numDataBytes); - qrCode.setNumRSBlocks(numRSBlocks); - // getNumECBytes = 196 - 66 = 130 - qrCode.setNumECBytes(numEcBytes); - // matrix width = 21 + 6 * 4 = 45 - qrCode.setMatrixWidth(version.getDimensionForVersion()); - return; - } - } - throw new WriterException("Cannot find proper rs block info (input data too big?)"); - } - catch(Exception e){ - throw new WriterException(e.Message); - } - } - - // Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24). - static void terminateBits(int numDataBytes, BitVector bits){ - int capacity = numDataBytes << 3; - if (bits.size() > capacity) { - throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); - } - // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. - for (int i = 0; i < 4 && bits.size() < capacity; ++i) { - bits.appendBit(0); - } - int numBitsInLastByte = bits.size() % 8; - // If the last byte isn't 8-bit aligned, we'll add padding bits. - if (numBitsInLastByte > 0) { - int numPaddingBits = 8 - numBitsInLastByte; - for (int i = 0; i < numPaddingBits; ++i) { - bits.appendBit(0); - } - } - // Should be 8-bit aligned here. - if (bits.size() % 8 != 0) { - throw new WriterException("Number of bits is not a multiple of 8"); - } - // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). - int numPaddingBytes = numDataBytes - bits.sizeInBytes(); - for (int i = 0; i < numPaddingBytes; ++i) { - if (i % 2 == 0) { - bits.appendBits(0xec, 8); - } else { - bits.appendBits(0x11, 8); - } - } - if (bits.size() != capacity) { - throw new WriterException("Bits size does not equal capacity"); - } - } - - // Get number of data bytes and number of error correction bytes for block id "blockID". Store - // the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of - // JISX0510:2004 (p.30) - static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, - int numRSBlocks, int blockID, int[] numDataBytesInBlock,int[] numECBytesInBlock) { - if (blockID >= numRSBlocks) { - throw new WriterException("Block ID too large"); - } - // numRsBlocksInGroup2 = 196 % 5 = 1 - int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; - // numRsBlocksInGroup1 = 5 - 1 = 4 - int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; - // numTotalBytesInGroup1 = 196 / 5 = 39 - int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; - // numTotalBytesInGroup2 = 39 + 1 = 40 - int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; - // numDataBytesInGroup1 = 66 / 5 = 13 - int numDataBytesInGroup1 = numDataBytes / numRSBlocks; - // numDataBytesInGroup2 = 13 + 1 = 14 - int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; - // numEcBytesInGroup1 = 39 - 13 = 26 - int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; - // numEcBytesInGroup2 = 40 - 14 = 26 - int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; - // Sanity checks. - // 26 = 26 - if (numEcBytesInGroup1 != numEcBytesInGroup2) { - throw new WriterException("EC bytes mismatch"); - } - // 5 = 4 + 1. - if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { - throw new WriterException("RS blocks mismatch"); - } - // 196 = (13 + 26) * 4 + (14 + 26) * 1 - if (numTotalBytes != - ((numDataBytesInGroup1 + numEcBytesInGroup1) * - numRsBlocksInGroup1) + - ((numDataBytesInGroup2 + numEcBytesInGroup2) * - numRsBlocksInGroup2)) { - throw new WriterException("Total bytes mismatch"); - } - - if (blockID < numRsBlocksInGroup1) { - numDataBytesInBlock[0] = numDataBytesInGroup1; - numECBytesInBlock[0] = numEcBytesInGroup1; - } else { - numDataBytesInBlock[0] = numDataBytesInGroup2; - numECBytesInBlock[0] = numEcBytesInGroup2; - } - } - - // Interleave "bits" with corresponding error correction bytes. On success, store the result in - // "result" and return true. The interleave rule is complicated. See 8.6 - // of JISX0510:2004 (p.37) for details. - static void interleaveWithECBytes(BitVector bits, int numTotalBytes, - int numDataBytes, int numRSBlocks, BitVector result) { - - // "bits" must have "getNumDataBytes" bytes of data. - if (bits.sizeInBytes() != numDataBytes) { - throw new WriterException("Number of bits and data bytes does not match"); - } - - // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll - // store the divided data bytes blocks and error correction bytes blocks into "blocks". - int dataBytesOffset = 0; - int maxNumDataBytes = 0; - int maxNumEcBytes = 0; - - // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. - ArrayList blocks = new ArrayList(numRSBlocks); - - for (int i = 0; i < numRSBlocks; ++i) { - int[] numDataBytesInBlock = new int[1]; - int[] numEcBytesInBlock = new int[1]; - getNumDataBytesAndNumECBytesForBlockID( - numTotalBytes, numDataBytes, numRSBlocks, i, - numDataBytesInBlock, numEcBytesInBlock); - - ByteArray dataBytes = new ByteArray(); - dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]); - ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); - blocks.Add(new BlockPair(dataBytes, ecBytes)); - - maxNumDataBytes = Math.Max(maxNumDataBytes, dataBytes.size()); - maxNumEcBytes = Math.Max(maxNumEcBytes, ecBytes.size()); - dataBytesOffset += numDataBytesInBlock[0]; - } - if (numDataBytes != dataBytesOffset) { - throw new WriterException("Data bytes does not match offset"); - } - - // First, place data blocks. - for (int i = 0; i < maxNumDataBytes; ++i) { - for (int j = 0; j < blocks.Count; ++j) { - ByteArray dataBytes = ((BlockPair) blocks[j]).getDataBytes(); - if (i < dataBytes.size()) { - result.appendBits(dataBytes.at(i), 8); - } - } - } - // Then, place error correction blocks. - for (int i = 0; i < maxNumEcBytes; ++i) { - for (int j = 0; j < blocks.Count; ++j) { - ByteArray ecBytes = ((BlockPair) blocks[j]).getErrorCorrectionBytes(); - if (i < ecBytes.size()) { - result.appendBits(ecBytes.at(i), 8); - } - } - } - if (numTotalBytes != result.sizeInBytes()) { // Should be same. - throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + - " differ."); - } - } - - static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) { - int numDataBytes = dataBytes.size(); - int[] toEncode = new int[numDataBytes + numEcBytesInBlock]; - for (int i = 0; i < numDataBytes; i++) { - toEncode[i] = dataBytes.at(i); - } - new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock); - - ByteArray ecBytes = new ByteArray(numEcBytesInBlock); - for (int i = 0; i < numEcBytesInBlock; i++) { - ecBytes.set(i, toEncode[numDataBytes + i]); - } - return ecBytes; - } - - // Append mode info. On success, store the result in "bits" and return true. On error, return - // false. - static void appendModeInfo(Mode mode, BitVector bits) { - bits.appendBits(mode.getBits(), 4); - } - - - // Append length info. On success, store the result in "bits" and return true. On error, return - // false. - static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits){ - int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version)); - if (numLetters > ((1 << numBits) - 1)) { - throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1)); - } - bits.appendBits(numLetters, numBits); - } - - // Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits" - // and return true. - static void appendBytes(String content, Mode mode, BitVector bits) { - if (mode.Equals(Mode.NUMERIC)) { - appendNumericBytes(content, bits); - } else if (mode.Equals(Mode.ALPHANUMERIC)) { - appendAlphanumericBytes(content, bits); - } else if (mode.Equals(Mode.BYTE)) { - append8BitBytes(content, bits); - } else if (mode.Equals(Mode.KANJI)) { - appendKanjiBytes(content, bits); - } else { - throw new WriterException("Invalid mode: " + mode); - } - } - - static void appendNumericBytes(String content, BitVector bits) { - int length = content.Length; - int i = 0; - while (i < length) { - int num1 = content[i] - '0'; - if (i + 2 < length) { - // Encode three numeric letters in ten bits. - int num2 = content[i + 1] - '0'; - int num3 = content[i + 2] - '0'; - bits.appendBits(num1 * 100 + num2 * 10 + num3, 10); - i += 3; - } else if (i + 1 < length) { - // Encode two numeric letters in seven bits. - int num2 = content[i + 1] - '0'; - bits.appendBits(num1 * 10 + num2, 7); - i += 2; - } else { - // Encode one numeric letter in four bits. - bits.appendBits(num1, 4); - i++; - } - } - } - - static void appendAlphanumericBytes(String content, BitVector bits) { - int length = content.Length; - int i = 0; - while (i < length) { - int code1 = getAlphanumericCode(content[i]); - if (code1 == -1) { - throw new WriterException(); - } - if (i + 1 < length) { - int code2 = getAlphanumericCode(content[i + 1]); - if (code2 == -1) { - throw new WriterException(); - } - // Encode two alphanumeric letters in 11 bits. - bits.appendBits(code1 * 45 + code2, 11); - i += 2; - } else { - // Encode one alphanumeric letter in six bits. - bits.appendBits(code1, 6); - i++; - } - } - } - - static void append8BitBytes(String content, BitVector bits) { - byte[] bytes; - try { - bytes = System.Text.ASCIIEncoding.ASCII.GetBytes("ISO-8859-1"); - } catch (Exception uee) { - throw new WriterException(uee.ToString()); - } - for (int i = 0; i < bytes.Length; ++i) { - bits.appendBits(bytes[i], 8); - } - } - - static void appendKanjiBytes(String content, BitVector bits) { - byte[] bytes; - try { - bytes=System.Text.ASCIIEncoding.ASCII.GetBytes("Shift_JIS"); - } catch (Exception uee) { - throw new WriterException(uee.ToString()); - } - int length = bytes.Length; - for (int i = 0; i < length; i += 2) { - int byte1 = bytes[i] & 0xFF; - int byte2 = bytes[i + 1] & 0xFF; - int code = (byte1 << 8) | byte2; - int subtracted = -1; - if (code >= 0x8140 && code <= 0x9ffc) { - subtracted = code - 0x8140; - } else if (code >= 0xe040 && code <= 0xebbf) { - subtracted = code - 0xc140; - } - if (subtracted == -1) { - throw new WriterException("Invalid byte sequence"); - } - int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); - bits.appendBits(encoded, 13); - } - } - - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/encoder/MaskUtil.cs b/qrcode-scanner-live2/qrcode/encoder/MaskUtil.cs deleted file mode 100644 index 08f3a04..0000000 --- a/qrcode-scanner-live2/qrcode/encoder/MaskUtil.cs +++ /dev/null @@ -1,233 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.qrcode.decoder; -using com.google.zxing.qrcode; - -namespace com.google.zxing.qrcode.encoder -{ - - public sealed class MaskUtil - { - private MaskUtil() - { - // do nothing - } - - // Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and - // give penalty to them. Example: 00000 or 11111. - public static int applyMaskPenaltyRule1(ByteMatrix matrix) - { - return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false); - } - - // Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give - // penalty to them. - public static int applyMaskPenaltyRule2(ByteMatrix matrix) - { - int penalty = 0; - sbyte[][] array = matrix.getArray(); - int width = matrix.width(); - int height = matrix.height(); - for (int y = 0; y < height - 1; ++y) - { - for (int x = 0; x < width - 1; ++x) - { - int value = array[y][x]; - if (value == array[y][x + 1] && value == array[y + 1][x] && value == array[y + 1][x + 1]) - { - penalty += 3; - } - } - } - return penalty; - } - - // Apply mask penalty rule 3 and return the penalty. Find consecutive cells of 00001011101 or - // 10111010000, and give penalty to them. If we find patterns like 000010111010000, we give - // penalties twice (i.e. 40 * 2). - public static int applyMaskPenaltyRule3(ByteMatrix matrix) - { - int penalty = 0; - sbyte[][] array = matrix.getArray(); - int width = matrix.width(); - int height = matrix.height(); - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - // Tried to simplify following conditions but failed. - if (x + 6 < width && - array[y][x] == 1 && - array[y][x + 1] == 0 && - array[y][x + 2] == 1 && - array[y][x + 3] == 1 && - array[y][x + 4] == 1 && - array[y][x + 5] == 0 && - array[y][x + 6] == 1 && - ((x + 10 < width && - array[y][x + 7] == 0 && - array[y][x + 8] == 0 && - array[y][x + 9] == 0 && - array[y][x + 10] == 0) || - (x - 4 >= 0 && - array[y][x - 1] == 0 && - array[y][x - 2] == 0 && - array[y][x - 3] == 0 && - array[y][x - 4] == 0))) - { - penalty += 40; - } - if (y + 6 < height && - array[y][x] == 1 && - array[y + 1][x] == 0 && - array[y + 2][x] == 1 && - array[y + 3][x] == 1 && - array[y + 4][x] == 1 && - array[y + 5][x] == 0 && - array[y + 6][x] == 1 && - ((y + 10 < height && - array[y + 7][x] == 0 && - array[y + 8][x] == 0 && - array[y + 9][x] == 0 && - array[y + 10][x] == 0) || - (y - 4 >= 0 && - array[y - 1][x] == 0 && - array[y - 2][x] == 0 && - array[y - 3][x] == 0 && - array[y - 4][x] == 0))) - { - penalty += 40; - } - } - } - return penalty; - } - - // Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give - // penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance. Examples: - // - 0% => 100 - // - 40% => 20 - // - 45% => 10 - // - 50% => 0 - // - 55% => 10 - // - 55% => 20 - // - 100% => 100 - public static int applyMaskPenaltyRule4(ByteMatrix matrix) - { - int numDarkCells = 0; - sbyte[][] array = matrix.getArray(); - int width = matrix.width(); - int height = matrix.height(); - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - if (array[y][x] == 1) - { - numDarkCells += 1; - } - } - } - int numTotalCells = matrix.height() * matrix.width(); - double darkRatio = (double)numDarkCells / numTotalCells; - return Math.Abs((int)(darkRatio * 100 - 50)) / 5 * 10; - } - - // Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask - // pattern conditions. - public static int getDataMaskBit(int maskPattern, int x, int y) - { - if (!QRCode.isValidMaskPattern(maskPattern)) - { - throw new ArgumentException("Invalid mask pattern"); - } - switch (maskPattern) - { - case 0: - return ((y + x) % 2 == 0) ? 1 : 0; - case 1: - return (y % 2 == 0) ? 1 : 0; - case 2: - return (x % 3 == 0) ? 1 : 0; - case 3: - return ((y + x) % 3 == 0) ? 1 : 0; - case 4: - return (((y / 2) + (x / 3)) % 2 == 0) ? 1 : 0; - case 5: - return (((y * x) % 2) + ((y * x) % 3) == 0) ? 1 : 0; - case 6: - return ((((y * x) % 2) + ((y * x) % 3)) % 2 == 0) ? 1 : 0; - case 7: - return ((((y * x) % 3) + ((y + x) % 2)) % 2 == 0) ? 1 : 0; - } - throw new ArgumentException("invalid mask pattern: " + maskPattern); - } - - // Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both - // vertical and horizontal orders respectively. - private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, bool isHorizontal) - { - int penalty = 0; - int numSameBitCells = 0; - int prevBit = -1; - // Horizontal mode: - // for (int i = 0; i < matrix.height(); ++i) { - // for (int j = 0; j < matrix.width(); ++j) { - // int bit = matrix.get(i, j); - // Vertical mode: - // for (int i = 0; i < matrix.width(); ++i) { - // for (int j = 0; j < matrix.height(); ++j) { - // int bit = matrix.get(j, i); - int iLimit = isHorizontal ? matrix.height() : matrix.width(); - int jLimit = isHorizontal ? matrix.width() : matrix.height(); - sbyte[][] array = matrix.getArray(); - for (int i = 0; i < iLimit; ++i) - { - for (int j = 0; j < jLimit; ++j) - { - int bit = isHorizontal ? array[i][j] : array[j][i]; - if (bit == prevBit) - { - numSameBitCells += 1; - // Found five repetitive cells with the same color (bit). - // We'll give penalty of 3. - if (numSameBitCells == 5) - { - penalty += 3; - } - else if (numSameBitCells > 5) - { - // After five repetitive cells, we'll add the penalty one - // by one. - penalty += 1; - } - } - else - { - numSameBitCells = 1; // Include the cell itself. - prevBit = bit; - } - } - numSameBitCells = 0; // Clear at each row/column. - } - return penalty; - } - } -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/encoder/MatrixUtil.cs b/qrcode-scanner-live2/qrcode/encoder/MatrixUtil.cs deleted file mode 100644 index eb763d1..0000000 --- a/qrcode-scanner-live2/qrcode/encoder/MatrixUtil.cs +++ /dev/null @@ -1,531 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.qrcode.decoder; -using com.google.zxing.qrcode; - -namespace com.google.zxing.qrcode.encoder -{ - public sealed class MatrixUtil - { - private MatrixUtil() { - // do nothing - } - - private static int[][] POSITION_DETECTION_PATTERN = new int[][]{ - new int[]{1, 1, 1, 1, 1, 1, 1}, - new int[]{1, 0, 0, 0, 0, 0, 1}, - new int[]{1, 0, 1, 1, 1, 0, 1}, - new int[]{1, 0, 1, 1, 1, 0, 1}, - new int[]{1, 0, 1, 1, 1, 0, 1}, - new int[]{1, 0, 0, 0, 0, 0, 1}, - new int[]{1, 1, 1, 1, 1, 1, 1}, - }; - - private static int[][] HORIZONTAL_SEPARATION_PATTERN = new int[][]{ - new int[]{0, 0, 0, 0, 0, 0, 0, 0}, - }; - - private static int[][] VERTICAL_SEPARATION_PATTERN = new int[][]{ - new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, - }; - - private static int[][] POSITION_ADJUSTMENT_PATTERN = new int[][]{ - new int[]{1, 1, 1, 1, 1}, - new int[]{1, 0, 0, 0, 1}, - new int[]{1, 0, 1, 0, 1}, - new int[]{1, 0, 0, 0, 1}, - new int[]{1, 1, 1, 1, 1}, - }; - - // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu. - private static int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = new int[][]{ - new int[]{-1, -1, -1, -1, -1, -1, -1}, // Version 1 - new int[]{ 6, 18, -1, -1, -1, -1, -1}, // Version 2 - new int[]{ 6, 22, -1, -1, -1, -1, -1}, // Version 3 - new int[]{ 6, 26, -1, -1, -1, -1, -1}, // Version 4 - new int[]{ 6, 30, -1, -1, -1, -1, -1}, // Version 5 - new int[]{ 6, 34, -1, -1, -1, -1, -1}, // Version 6 - new int[]{ 6, 22, 38, -1, -1, -1, -1}, // Version 7 - new int[]{ 6, 24, 42, -1, -1, -1, -1}, // Version 8 - new int[]{ 6, 26, 46, -1, -1, -1, -1}, // Version 9 - new int[]{ 6, 28, 50, -1, -1, -1, -1}, // Version 10 - new int[]{ 6, 30, 54, -1, -1, -1, -1}, // Version 11 - new int[]{ 6, 32, 58, -1, -1, -1, -1}, // Version 12 - new int[]{ 6, 34, 62, -1, -1, -1, -1}, // Version 13 - new int[]{ 6, 26, 46, 66, -1, -1, -1}, // Version 14 - new int[]{ 6, 26, 48, 70, -1, -1, -1}, // Version 15 - new int[]{ 6, 26, 50, 74, -1, -1, -1}, // Version 16 - new int[]{ 6, 30, 54, 78, -1, -1, -1}, // Version 17 - new int[]{ 6, 30, 56, 82, -1, -1, -1}, // Version 18 - new int[]{ 6, 30, 58, 86, -1, -1, -1}, // Version 19 - new int[]{ 6, 34, 62, 90, -1, -1, -1}, // Version 20 - new int[]{ 6, 28, 50, 72, 94, -1, -1}, // Version 21 - new int[]{ 6, 26, 50, 74, 98, -1, -1}, // Version 22 - new int[]{ 6, 30, 54, 78, 102, -1, -1}, // Version 23 - new int[]{ 6, 28, 54, 80, 106, -1, -1}, // Version 24 - new int[]{ 6, 32, 58, 84, 110, -1, -1}, // Version 25 - new int[]{ 6, 30, 58, 86, 114, -1, -1}, // Version 26 - new int[]{ 6, 34, 62, 90, 118, -1, -1}, // Version 27 - new int[]{ 6, 26, 50, 74, 98, 122, -1}, // Version 28 - new int[]{ 6, 30, 54, 78, 102, 126, -1}, // Version 29 - new int[]{ 6, 26, 52, 78, 104, 130, -1}, // Version 30 - new int[]{ 6, 30, 56, 82, 108, 134, -1}, // Version 31 - new int[]{ 6, 34, 60, 86, 112, 138, -1}, // Version 32 - new int[]{ 6, 30, 58, 86, 114, 142, -1}, // Version 33 - new int[]{ 6, 34, 62, 90, 118, 146, -1}, // Version 34 - new int[]{ 6, 30, 54, 78, 102, 126, 150}, // Version 35 - new int[]{ 6, 24, 50, 76, 102, 128, 154}, // Version 36 - new int[]{ 6, 28, 54, 80, 106, 132, 158}, // Version 37 - new int[]{ 6, 32, 58, 84, 110, 136, 162}, // Version 38 - new int[]{ 6, 26, 54, 82, 110, 138, 166}, // Version 39 - new int[]{ 6, 30, 58, 86, 114, 142, 170}, // Version 40 - }; - - // Type info cells at the left top corner. - private static int[][] TYPE_INFO_COORDINATES = new int[][]{ - new int[]{8, 0}, - new int[]{8, 1}, - new int[]{8, 2}, - new int[]{8, 3}, - new int[]{8, 4}, - new int[]{8, 5}, - new int[]{8, 7}, - new int[]{8, 8}, - new int[]{7, 8}, - new int[]{5, 8}, - new int[]{4, 8}, - new int[]{3, 8}, - new int[]{2, 8}, - new int[]{1, 8}, - new int[]{0, 8}, - }; - - // From Appendix D in JISX0510:2004 (p. 67) - private static int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101 - - // From Appendix C in JISX0510:2004 (p.65). - private static int TYPE_INFO_POLY = 0x537; - private static int TYPE_INFO_MASK_PATTERN = 0x5412; - - // Set all cells to -1. -1 means that the cell is empty (not set yet). - // - // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding - // with the ByteMatrix initialized all to zero. - public static void clearMatrix(ByteMatrix matrix) { - matrix.clear((sbyte)(-1)); - } - - // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On - // success, store the result in "matrix" and return true. - public static void buildMatrix(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version,int maskPattern, ByteMatrix matrix) { - try{ - clearMatrix(matrix); - embedBasicPatterns(version, matrix); - // Type information appear with any version. - embedTypeInfo(ecLevel, maskPattern, matrix); - // Version info appear if version >= 7. - maybeEmbedVersionInfo(version, matrix); - // Data should be embedded at end. - embedDataBits(dataBits, maskPattern, matrix); - }catch(Exception e){ - throw new WriterException(e.Message); - } - - } - - // Embed basic patterns. On success, modify the matrix and return true. - // The basic patterns are: - // - Position detection patterns - // - Timing patterns - // - Dark dot at the left bottom corner - // - Position adjustment patterns, if need be - public static void embedBasicPatterns(int version, ByteMatrix matrix){ - try - { - // Let's get started with embedding big squares at corners. - embedPositionDetectionPatternsAndSeparators(matrix); - // Then, embed the dark dot at the left bottom corner. - embedDarkDotAtLeftBottomCorner(matrix); - - // Position adjustment patterns appear if version >= 2. - maybeEmbedPositionAdjustmentPatterns(version, matrix); - // Timing patterns should be embedded after position adj. patterns. - embedTimingPatterns(matrix); - }catch(Exception e){ - throw new WriterException (e.Message); - } - } - - // Embed type information. On success, modify the matrix. - public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) - { - BitVector typeInfoBits = new BitVector(); - makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); - - for (int i = 0; i < typeInfoBits.size(); ++i) { - // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in - // "typeInfoBits". - int bit = typeInfoBits.at(typeInfoBits.size() - 1 - i); - - // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). - int x1 = TYPE_INFO_COORDINATES[i][0]; - int y1 = TYPE_INFO_COORDINATES[i][1]; - matrix.set(y1, x1, bit); - - if (i < 8) { - // Right top corner. - int x2 = matrix.width() - i - 1; - int y2 = 8; - matrix.set(y2, x2, bit); - } else { - // Left bottom corner. - int x2 = 8; - int y2 = matrix.height() - 7 + (i - 8); - matrix.set(y2, x2, bit); - } - } - } - - // Embed version information if need be. On success, modify the matrix and return true. - // See 8.10 of JISX0510:2004 (p.47) for how to embed version information. - public static void maybeEmbedVersionInfo(int version, ByteMatrix matrix){ - if (version < 7) { // Version info is necessary if version >= 7. - return; // Don't need version info. - } - BitVector versionInfoBits = new BitVector(); - makeVersionInfoBits(version, versionInfoBits); - - int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. - for (int i = 0; i < 6; ++i) { - for (int j = 0; j < 3; ++j) { - // Place bits in LSB (least significant bit) to MSB order. - int bit = versionInfoBits.at(bitIndex); - bitIndex--; - // Left bottom corner. - matrix.set(matrix.height() - 11 + j, i, bit); - // Right bottom corner. - matrix.set(i, matrix.height() - 11 + j, bit); - } - } - } - - // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. - // For debugging purposes, it skips masking process if "getMaskPattern" is -1. - // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. - public static void embedDataBits(BitVector dataBits, int maskPattern, ByteMatrix matrix) - { - int bitIndex = 0; - int direction = -1; - // Start from the right bottom cell. - int x = matrix.width() - 1; - int y = matrix.height() - 1; - while (x > 0) { - // Skip the vertical timing pattern. - if (x == 6) { - x -= 1; - } - while (y >= 0 && y < matrix.height()) { - for (int i = 0; i < 2; ++i) { - int xx = x - i; - // Skip the cell if it's not empty. - if (!isEmpty(matrix.get(y, xx))) { - continue; - } - int bit; - if (bitIndex < dataBits.size()) { - bit = dataBits.at(bitIndex); - ++bitIndex; - } else { - // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described - // in 8.4.9 of JISX0510:2004 (p. 24). - bit = 0; - } - - // Skip masking if mask_pattern is -1. - if (maskPattern != -1) { - int mask = MaskUtil.getDataMaskBit(maskPattern, xx, y); - bit ^= mask; - } - matrix.set(y, xx, bit); - } - y += direction; - } - direction = -direction; // Reverse the direction. - y += direction; - x -= 2; // Move to the left. - } - // All bits should be consumed. - if (bitIndex != dataBits.size()) { - throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size()); - } - } - - // Return the position of the most significant bit set (to one) in the "value". The most - // significant bit is position 32. If there is no bit set, return 0. Examples: - // - findMSBSet(0) => 0 - // - findMSBSet(1) => 1 - // - findMSBSet(255) => 8 - public static int findMSBSet(int value) { - int numDigits = 0; - while (value != 0) { - value >>= 1; - ++numDigits; - } - return numDigits; - } - - // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH - // code is used for encoding type information and version information. - // Example: Calculation of version information of 7. - // f(x) is created from 7. - // - 7 = 000111 in 6 bits - // - f(x) = x^2 + x^2 + x^1 - // g(x) is given by the standard (p. 67) - // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 - // Multiply f(x) by x^(18 - 6) - // - f'(x) = f(x) * x^(18 - 6) - // - f'(x) = x^14 + x^13 + x^12 - // Calculate the remainder of f'(x) / g(x) - // x^2 - // __________________________________________________ - // g(x) )x^14 + x^13 + x^12 - // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2 - // -------------------------------------------------- - // x^11 + x^10 + x^7 + x^4 + x^2 - // - // The remainder is x^11 + x^10 + x^7 + x^4 + x^2 - // Encode it in binary: 110010010100 - // The return value is 0xc94 (1100 1001 0100) - // - // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit - // operations. We don't care if cofficients are positive or negative. - public static int calculateBCHCode(int value, int poly) { - // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 - // from 13 to make it 12. - int msbSetInPoly = findMSBSet(poly); - value <<= msbSetInPoly - 1; - // Do the division business using exclusive-or operations. - while (findMSBSet(value) >= msbSetInPoly) { - value ^= poly << (findMSBSet(value) - msbSetInPoly); - } - // Now the "value" is the remainder (i.e. the BCH code) - return value; - } - - // Make bit vector of type information. On success, store the result in "bits" and return true. - // Encode error correction level and mask pattern. See 8.9 of - // JISX0510:2004 (p.45) for details. - public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits) - { - if (!QRCode.isValidMaskPattern(maskPattern)) { - throw new WriterException("Invalid mask pattern"); - } - int typeInfo = (ecLevel.getBits() << 3) | maskPattern; - bits.appendBits(typeInfo, 5); - - int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); - bits.appendBits(bchCode, 10); - - BitVector maskBits = new BitVector(); - maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); - bits.xor(maskBits); - - if (bits.size() != 15) { // Just in case. - throw new WriterException("should not happen but we got: " + bits.size()); - } - } - - // Make bit vector of version information. On success, store the result in "bits" and return true. - // See 8.10 of JISX0510:2004 (p.45) for details. - public static void makeVersionInfoBits(int version, BitVector bits){ - bits.appendBits(version, 6); - int bchCode = calculateBCHCode(version, VERSION_INFO_POLY); - bits.appendBits(bchCode, 12); - - if (bits.size() != 18) { // Just in case. - throw new WriterException("should not happen but we got: " + bits.size()); - } - } - - // Check if "value" is empty. - private static bool isEmpty(int value) { - return value == -1; - } - - // Check if "value" is valid. - private static bool isValidValue(int value) { - return (value == -1 || // Empty. - value == 0 || // Light (white). - value == 1); // Dark (black). - } - - private static void embedTimingPatterns(ByteMatrix matrix) { - // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical - // separation patterns (size 1). Thus, 8 = 7 + 1. - for (int i = 8; i < matrix.width() - 8; ++i) { - int bit = (i + 1) % 2; - // Horizontal line. - if (!isValidValue(matrix.get(6, i))) { - throw new WriterException(); - } - if (isEmpty(matrix.get(6, i))) { - matrix.set(6, i, bit); - } - // Vertical line. - if (!isValidValue(matrix.get(i, 6))) { - throw new WriterException(); - } - if (isEmpty(matrix.get(i, 6))) { - matrix.set(i, 6, bit); - } - } - } - - // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) - private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix){ - if (matrix.get(matrix.height() - 8, 8) == 0) { - throw new WriterException(); - } - matrix.set(matrix.height() - 8, 8, 1); - } - - private static void embedHorizontalSeparationPattern(int xStart, int yStart,ByteMatrix matrix) { - // We know the width and height. - if (HORIZONTAL_SEPARATION_PATTERN[0].Length != 8 || HORIZONTAL_SEPARATION_PATTERN.Length != 1) { - throw new WriterException("Bad horizontal separation pattern"); - } - for (int x = 0; x < 8; ++x) { - if (!isEmpty(matrix.get(yStart, xStart + x))) { - throw new WriterException(); - } - matrix.set(yStart, xStart + x, HORIZONTAL_SEPARATION_PATTERN[0][x]); - } - } - - private static void embedVerticalSeparationPattern(int xStart, int yStart,ByteMatrix matrix){ - // We know the width and height. - if (VERTICAL_SEPARATION_PATTERN[0].Length != 1 || VERTICAL_SEPARATION_PATTERN.Length != 7) { - throw new WriterException("Bad vertical separation pattern"); - } - for (int y = 0; y < 7; ++y) { - if (!isEmpty(matrix.get(yStart + y, xStart))) { - throw new WriterException(); - } - matrix.set(yStart + y, xStart, VERTICAL_SEPARATION_PATTERN[y][0]); - } - } - - // Note that we cannot unify the function with embedPositionDetectionPattern() despite they are - // almost identical, since we cannot write a function that takes 2D arrays in different sizes in - // C/C++. We should live with the fact. - private static void embedPositionAdjustmentPattern(int xStart, int yStart,ByteMatrix matrix){ - // We know the width and height. - if (POSITION_ADJUSTMENT_PATTERN[0].Length != 5 || POSITION_ADJUSTMENT_PATTERN.Length != 5) { - throw new WriterException("Bad position adjustment"); - } - for (int y = 0; y < 5; ++y) { - for (int x = 0; x < 5; ++x) { - if (!isEmpty(matrix.get(yStart + y, xStart + x))) { - throw new WriterException(); - } - matrix.set(yStart + y, xStart + x, POSITION_ADJUSTMENT_PATTERN[y][x]); - } - } - } - - private static void embedPositionDetectionPattern(int xStart, int yStart,ByteMatrix matrix){ - // We know the width and height. - if (POSITION_DETECTION_PATTERN[0].Length != 7 || POSITION_DETECTION_PATTERN.Length != 7) { - throw new WriterException("Bad position detection pattern"); - } - for (int y = 0; y < 7; ++y) { - for (int x = 0; x < 7; ++x) { - if (!isEmpty(matrix.get(yStart + y, xStart + x))) { - throw new WriterException(); - } - matrix.set(yStart + y, xStart + x, POSITION_DETECTION_PATTERN[y][x]); - } - } - } - - // Embed position detection patterns and surrounding vertical/horizontal separators. - private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) { - // Embed three big squares at corners. - int pdpWidth = POSITION_DETECTION_PATTERN[0].Length; - // Left top corner. - embedPositionDetectionPattern(0, 0, matrix); - // Right top corner. - embedPositionDetectionPattern(matrix.width() - pdpWidth, 0, matrix); - // Left bottom corner. - embedPositionDetectionPattern(0, matrix.width() - pdpWidth, matrix); - - // Embed horizontal separation patterns around the squares. - int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].Length; - // Left top corner. - embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); - // Right top corner. - embedHorizontalSeparationPattern(matrix.width() - hspWidth, - hspWidth - 1, matrix); - // Left bottom corner. - embedHorizontalSeparationPattern(0, matrix.width() - hspWidth, matrix); - - // Embed vertical separation patterns around the squares. - int vspSize = VERTICAL_SEPARATION_PATTERN.Length; - // Left top corner. - embedVerticalSeparationPattern(vspSize, 0, matrix); - // Right top corner. - embedVerticalSeparationPattern(matrix.height() - vspSize - 1, 0, matrix); - // Left bottom corner. - embedVerticalSeparationPattern(vspSize, matrix.height() - vspSize, - matrix); - } - - // Embed position adjustment patterns if need be. - private static void maybeEmbedPositionAdjustmentPatterns(int version, ByteMatrix matrix) - { - if (version < 2) { // The patterns appear if version >= 2 - return; - } - int index = version - 1; - int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; - int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].Length; - for (int i = 0; i < numCoordinates; ++i) { - for (int j = 0; j < numCoordinates; ++j) { - int y = coordinates[i]; - int x = coordinates[j]; - if (x == -1 || y == -1) { - continue; - } - // If the cell is unset, we embed the position adjustment pattern here. - if (isEmpty(matrix.get(y, x))) { - // -2 is necessary since the x/y coordinates point to the center of the pattern, not the - // left top corner. - embedPositionAdjustmentPattern(x - 2, y - 2, matrix); - } - } - } - } - - - - } - - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/qrcode/encoder/QRCode.cs b/qrcode-scanner-live2/qrcode/encoder/QRCode.cs deleted file mode 100644 index b4292c9..0000000 --- a/qrcode-scanner-live2/qrcode/encoder/QRCode.cs +++ /dev/null @@ -1,242 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using System.Text; -using com.google.zxing; -using com.google.zxing.common; -using com.google.zxing.qrcode.decoder; -using com.google.zxing.qrcode; - -namespace com.google.zxing.qrcode.encoder -{ - - public sealed class QRCode - { - - public static int NUM_MASK_PATTERNS = 8; - - private Mode mode; - private ErrorCorrectionLevel ecLevel; - private int version; - private int matrixWidth; - private int maskPattern; - private int numTotalBytes; - private int numDataBytes; - private int numECBytes; - private int numRSBlocks; - private ByteMatrix matrix; - - public QRCode() { - mode = null; - ecLevel = null; - version = -1; - matrixWidth = -1; - maskPattern = -1; - numTotalBytes = -1; - numDataBytes = -1; - numECBytes = -1; - numRSBlocks = -1; - matrix = null; - } - - // Mode of the QR Code. - public Mode getMode() { - return mode; - } - - // Error correction level of the QR Code. - public ErrorCorrectionLevel getECLevel() { - return ecLevel; - } - - // Version of the QR Code. The bigger size, the bigger version. - public int getVersion() { - return version; - } - - // ByteMatrix width of the QR Code. - public int getMatrixWidth() { - return matrixWidth; - } - - // Mask pattern of the QR Code. - public int getMaskPattern() { - return maskPattern; - } - - // Number of total bytes in the QR Code. - public int getNumTotalBytes() { - return numTotalBytes; - } - - // Number of data bytes in the QR Code. - public int getNumDataBytes() { - return numDataBytes; - } - - // Number of error correction bytes in the QR Code. - public int getNumECBytes() { - return numECBytes; - } - - // Number of Reedsolomon blocks in the QR Code. - public int getNumRSBlocks() { - return numRSBlocks; - } - - // ByteMatrix data of the QR Code. - public ByteMatrix getMatrix() { - return matrix; - } - - - // Return the value of the module (cell) pointed by "x" and "y" in the matrix of the QR Code. They - // call cells in the matrix "modules". 1 represents a black cell, and 0 represents a white cell. - public int at(int x, int y) { - // The value must be zero or one. - int value = matrix.get(y, x); - if (!(value == 0 || value == 1)) { - // this is really like an assert... not sure what better exception to use? - throw new Exception("Bad value"); - } - return value; - } - - // Checks all the member variables are set properly. Returns true on success. Otherwise, returns - // false. - public bool isValid() { - return - // First check if all version are not uninitialized. - mode != null && - ecLevel != null && - version != -1 && - matrixWidth != -1 && - maskPattern != -1 && - numTotalBytes != -1 && - numDataBytes != -1 && - numECBytes != -1 && - numRSBlocks != -1 && - // Then check them in other ways.. - isValidMaskPattern(maskPattern) && - numTotalBytes == numDataBytes + numECBytes && - // ByteMatrix stuff. - matrix != null && - matrixWidth == matrix.width() && - // See 7.3.1 of JISX0510:2004 (p.5). - matrix.width() == matrix.height(); // Must be square. - } - - // Return debug String. - public String toString() { - StringBuilder result = new StringBuilder(200); - result.Append("<<\n"); - result.Append(" mode: "); - result.Append(mode); - result.Append("\n ecLevel: "); - result.Append(ecLevel); - result.Append("\n version: "); - result.Append(version); - result.Append("\n matrixWidth: "); - result.Append(matrixWidth); - result.Append("\n maskPattern: "); - result.Append(maskPattern); - result.Append("\n numTotalBytes: "); - result.Append(numTotalBytes); - result.Append("\n numDataBytes: "); - result.Append(numDataBytes); - result.Append("\n numECBytes: "); - result.Append(numECBytes); - result.Append("\n numRSBlocks: "); - result.Append(numRSBlocks); - if (matrix == null) { - result.Append("\n matrix: null\n"); - } else { - result.Append("\n matrix:\n"); - result.Append(matrix.toString()); - } - result.Append(">>\n"); - return result.ToString(); - } - - public void setMode(Mode value) { - mode = value; - } - - public void setECLevel(ErrorCorrectionLevel value) { - ecLevel = value; - } - - public void setVersion(int value) { - version = value; - } - - public void setMatrixWidth(int value) { - matrixWidth = value; - } - - public void setMaskPattern(int value) { - maskPattern = value; - } - - public void setNumTotalBytes(int value) { - numTotalBytes = value; - } - - public void setNumDataBytes(int value) { - numDataBytes = value; - } - - public void setNumECBytes(int value) { - numECBytes = value; - } - - public void setNumRSBlocks(int value) { - numRSBlocks = value; - } - - // This takes ownership of the 2D array. - public void setMatrix(ByteMatrix value) { - matrix = value; - } - - // Check if "mask_pattern" is valid. - public static bool isValidMaskPattern(int maskPattern) { - return maskPattern >= 0 && maskPattern < NUM_MASK_PATTERNS; - } - - // Return true if the all values in the matrix are binary numbers. - // - // JAVAPORT: This is going to be super expensive and unnecessary, we should not call this in - // production. I'm leaving it because it may be useful for testing. It should be removed entirely - // if ByteMatrix is changed never to contain a -1. - /* - private static boolean EverythingIsBinary(final ByteMatrix matrix) { - for (int y = 0; y < matrix.height(); ++y) { - for (int x = 0; x < matrix.width(); ++x) { - int value = matrix.get(y, x); - if (!(value == 0 || value == 1)) { - // Found non zero/one value. - return false; - } - } - } - return true; - } - */ - - } - -} \ No newline at end of file diff --git a/qrcode-scanner-live2/zxing.csproj b/qrcode-scanner-live2/zxing.csproj deleted file mode 100644 index 179dfcc..0000000 --- a/qrcode-scanner-live2/zxing.csproj +++ /dev/null @@ -1,139 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {22174889-87F2-4843-A5CE-99A4847D24EE} - Library - Properties - com.google.zxing - com.google.zxing - v3.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - 3.5 - - - - 3.5 - - - 3.5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/qrcode-scanner-live2/zxing.pidb b/qrcode-scanner-live2/zxing.pidb deleted file mode 100644 index d503487..0000000 Binary files a/qrcode-scanner-live2/zxing.pidb and /dev/null differ diff --git a/qrcode-scanner-live2/zxing.sln b/qrcode-scanner-live2/zxing.sln deleted file mode 100644 index 350ef5f..0000000 --- a/qrcode-scanner-live2/zxing.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual C# Express 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "zxing", "zxing.csproj", "{22174889-87F2-4843-A5CE-99A4847D24EE}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {22174889-87F2-4843-A5CE-99A4847D24EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {22174889-87F2-4843-A5CE-99A4847D24EE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {22174889-87F2-4843-A5CE-99A4847D24EE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {22174889-87F2-4843-A5CE-99A4847D24EE}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/qrcode-scanner-live2/zxing.suo b/qrcode-scanner-live2/zxing.suo deleted file mode 100644 index c662b2b..0000000 Binary files a/qrcode-scanner-live2/zxing.suo and /dev/null differ diff --git a/qrcode-scanner-live2/zxing.userprefs b/qrcode-scanner-live2/zxing.userprefs deleted file mode 100644 index e8f7acc..0000000 --- a/qrcode-scanner-live2/zxing.userprefs +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/uWavecs/uWave.c b/uWavecs/uWave.c deleted file mode 100644 index 6b8dc7b..0000000 --- a/uWavecs/uWave.c +++ /dev/null @@ -1,245 +0,0 @@ -/* - * uWave.c - * DarwiinRemote - * - * Created by Guest on 6/23/08. - * Copyright 2008 __MyCompanyName__. All rights reserved. - * - */ -// DTWLib.cpp : Defines the entry point for the console application. -// -#include "uWave.h" -#include -#include -#include - -FILE* flog; -int recordFlag = 0; // record gesture to file or recognize it -int tempIndex = 0; //index of template when recording gesture - -//////////////////////////////////////////////////////////////////////////////////////////////////// -int** allocAccBuf(int len){ - int** ret = (int**)malloc(sizeof(int*)*len); - int i; - for( i = 0; i < len; i++) - ret[i] = (int*)malloc(sizeof(int)*DIMENSION); - return ret; -} - -void releaseAccBuf(int** p, int len) { - int i; - for( i = 0; i < len; i++) - free(p[i]); - free(p); -} - -//routine at beginning -void beginGesture() { - accBuffer = allocAccBuf(MAX_ACC_LEN); - accIndex = 0; - - //output results to a file - flog = fopen("log.txt", "a"); - if( flog != NULL ) - fprintf(flog, "**********begin gesture\n"); - -} - -//routine at end: record gesture or detect gesture -int endGesture() { - int ret = 0, i; - if( recordFlag == 1) { - //write to file - writeFile(accBuffer, accIndex,tempIndex); - tempIndex++; - } else { - if( flog != NULL) - fscanf(flog, "reach end of Gesture\n"); - //recognize gesture - // 1) quantize acc - accIndex = quantizeAcc(accBuffer, accIndex); - if( flog != NULL) - fprintf(flog, "finish quantizing AccBuffer\n"); - - // 2) reads in templates, assume fixed number of templates now - Gesture templates[NUM_TEMPLATES]; - for( i = 0; i < NUM_TEMPLATES; i++) { - templates[i] = readFile(i); - if( flog != NULL) - fprintf(flog, "finish reading template %d\n", i); - templates[i].length = quantizeAcc(templates[i].data, templates[i].length); - } - ret = DetectGesture(accBuffer, accIndex, templates, NUM_TEMPLATES); - if( flog != NULL) - fprintf(flog, "gesture is # %d\n", ret); - for(i = 0; i < NUM_TEMPLATES; i++) - releaseAccBuf(templates[i].data, templates[i].length); - } - - if( flog != NULL) - fclose(flog); - releaseAccBuf(accBuffer, MAX_ACC_LEN); - return ret; -} -//quantize - -int quantizeAcc(int** acc_data, int length) { - int i=0, j, k = 0, l, window = QUAN_WIN_SIZE, sum; - int **temp = (int**)malloc(sizeof(int*)*(length/QUAN_MOV_STEP + 1)); - for(i = 0; i < length/QUAN_MOV_STEP + 1; i++) - temp[i] = (int*)malloc(sizeof(int)*DIMENSION); - //take moving window average - i = 0; - while(i < length) { - if( i + window > length) - window = length - i; - for( l = 0; l < DIMENSION; l++) { - sum = 0; - for( j = i; j < window+i; j++) - sum += acc_data[j][l]; - temp[k][l] = sum*1.0/window; - } - k++; - i += QUAN_MOV_STEP; - }//while - //nonlinear quantization and copy quantized value to original buffer - for( i = 0; i < k; i++) - for( l = 0; l < DIMENSION; l++) { - if( temp[i][l] > 10 ) { - if( temp[i][l] > 20) - temp[i][l] = 16; - else - temp[i][l] = 10 + (temp[i][l]-10)/10*5; - } else if( temp[i][l] < -10) { - if( temp[i][l] < -20) - temp[i][l] == -16; - else - temp[i][l] = -10 + (temp[i][l] + 10)/10*5; - } - acc_data[i][l] = temp[i][l]; - } - return k; -}//quantize - -//DTW algorithm, return distance -int DTWdistance(int** sample1, int length1, int** sample2, int length2, int i, int j, int* table) { - - if( i < 0 || j < 0) - return 100000000; - int tableWidth = length2; - int localDistance = 0; - int k; - for( k = 0; k < DIMENSION; k++) - localDistance += ((sample1[i][k]-sample2[j][k])*(sample1[i][k]-sample2[j][k])); - - int sdistance, s1, s2, s3; - - if( i == 0 && j == 0) { - if( table[i*tableWidth+j] < 0) - table[i*tableWidth+j] = localDistance; - return localDistance; - } else if( i==0) { - if( table[i*tableWidth+(j-1)] < 0) - sdistance = DTWdistance(sample1, length1, sample2, length2, i, j-1, table); - else - sdistance = table[i*tableWidth+j-1]; - } else if( j==0) { - if( table[(i-1)*tableWidth+ j] < 0) - sdistance = DTWdistance(sample1, length1, sample2, length2, i-1, j, table); - else - sdistance = table[(i-1)*tableWidth+j]; - } else { - if( table[i*tableWidth+(j-1)] < 0) - s1 = DTWdistance(sample1, length1, sample2, length2, i, j-1, table); - else - s1 = table[i*tableWidth+(j-1)]; - if( table[(i-1)*tableWidth+ j] < 0) - s2 = DTWdistance(sample1, length1, sample2, length2, i-1, j, table); - else - s2 = table[(i-1)*tableWidth+ j]; - if( table[(i-1)*tableWidth+ j-1] < 0) - s3 = DTWdistance(sample1, length1, sample2, length2, i-1, j-1, table); - else - s3 = table[(i-1)*tableWidth+ j-1]; - sdistance = s1 < s2 ? s1:s2; - sdistance = sdistance < s3 ? sdistance:s3; - } - table[i*tableWidth+j] = localDistance + sdistance; - return table[i*tableWidth+j]; -} - -//write/read gesture file -Gesture readFile(int index) { - FILE *fp; - char fname[10]; - int data[DIMENSION*MAX_ACC_LEN], i=0,j, n; - Gesture ret; - - sprintf(fname, "%d", index); - - fp = fopen(strcat(fname, ".uwv"), "r"); - if( fp == NULL) - return ret; - while(!feof(fp)) { - fscanf(fp, "%d %d %d \n", &data[i], &data[i+1], &data[i+2]); - i += 3; - } - n = (i-3)/DIMENSION; - ret.length = n; - ret.data = allocAccBuf(n); - for(i = 0; i < n; i++) - for(j = 0; j < DIMENSION; j++) - ret.data[i][j] = data[(i*DIMENSION)+j]; - - fclose(fp); - return ret; -} - -int writeFile(int** data, int len, int index){ - FILE *fp; - int i,j; - char fname[10]; - sprintf(fname, "%d", index); - fp = fopen(strcat(fname, ".uwv"), "w"); - if( fp == NULL) - return -1; - for(i = 0; i < len; i++) { - for( j = 0; j < DIMENSION; j++) { - fprintf(fp, "%d ", data[i][j]); - } - fprintf(fp, "\n"); - } - - fclose(fp); - return 0; -} - -//detect gesture, return detected template index -int DetectGesture(int** input, int length, Gesture* templates, int templateNum) -{ - if( length <= 0) - return -1; - int i, ret = 0,j; - - int distances[NUM_TEMPLATES]; - //int table[MAX_ACC_LEN/QUAN_MOV_STEP*MAX_ACC_LEN/QUAN_MOV_STEP]; - int* table; - for( i = 0; i < templateNum; i++) { - table = (int*) malloc(length * templates[i].length*sizeof(int)); - for( j = 0; j < length*templates[i].length; j++) - table[j] = -1; - - distances[i] = DTWdistance(input, length, templates[i].data, templates[i].length, length-1, templates[i].length-1, table); - distances[i] /= (length + templates[i].length); - free(table); - } - - for( i = 1; i < templateNum; i++) { - if( distances[i] < distances[ret]) { - ret = i; - } - } - - return ret; -} - diff --git a/uWavecs/uWave.h b/uWavecs/uWave.h deleted file mode 100644 index 0d99244..0000000 --- a/uWavecs/uWave.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * uWave.h - * DarwiinRemote - * - * Created by Guest on 6/23/08. - * Copyright 2008 __MyCompanyName__. All rights reserved. - * - */ - -#ifndef UWAVE_H -#define UWAVE_H - -// -//how to use this library: -//1. Set "recordFlag" to 1 to record gestures in a file as template. In this mode, input gestures will be written to files named "$index.umv" -//and become templates for recognition. The number of templates is fixed and defined as "NUM_TEMPLATES". -//Set "recordFlag" to 0 in uWave.c to enable recognization. Recognization result will be returned by endGesture() as the index of the template. -//The result is also writen into a file "log.txt". -// -//2. When a gesture begins, call beginGesture(); when the gesture finishes, call endGesture(); -//put the acc samples during a gesure into accBuffer like the following(x, y, z are the acceleration in g): -// accBuffer[accIndex][0] = x*10; -// accBuffer[accIndex][1] = y*10; -// accBuffer[accIndex][2] = (z-1)*10; -// accIndex++; -//Make sure (accIndex < MAX_ACC_LEN)!!!!!!!!!!!!!!!!!!!! -//beginGesure() allocates memory and initializes variables; endGesture() record/recognize the input gesture and output results -// - - -//macros for quantization -//(8,4) applies to 100Hz; if 50Hz, change to (4,2)... -#define QUAN_WIN_SIZE 8 -#define QUAN_MOV_STEP 4 - - -//max number of gesture templates -#define NUM_TEMPLATES 20 - -///////////////////////////////////////////////////////////////////////////// -#define DIMENSION 3 - -#define MAX_ACC_LEN 500 - -extern int recordFlag; - -extern int tempIndex; - -struct GestureStruct { - int** data; - int length; -}; -typedef struct GestureStruct Gesture; - -// 2D array to hold ACC data, each row contains (x, y, z) of an ACC sample -int** accBuffer; -int accIndex; - -int** allocAccBuf(int len); -void releaseAccBuf(int** p, int len); -void beginGesture(); - -int endGesture(); //return the gesture index if in recognizing mode (recordFlag = 0) - -int quantizeAcc(int** acc_data, int length); -int DTWdistance(int** sample1, int length1, int** sample2, int length2, int i, int j, int* table); -int DetectGesture(int** input, int length, Gesture* templates, int templateNum); -Gesture readFile(int index); -int writeFile(int** data, int len, int index); - - -#endif - diff --git a/zxing-csharp/AssemblyInfo.cs b/zxing-csharp/AssemblyInfo.cs deleted file mode 100644 index aaf882e..0000000 --- a/zxing-csharp/AssemblyInfo.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. - -// TODO: Review the values of the assembly attributes - -[assembly: AssemblyTitle("")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Revision -// Build Number -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly: AssemblyVersion("1.0.*")] - -// -// In order to sign your assembly you must specify a key to use. Refer to the -// Microsoft .NET Framework documentation for more information on assembly signing. -// -// Use the attributes below to control which key is used for signing. -// -// Notes: -// (*) If no key is specified, the assembly is not signed. -// (*) KeyName refers to a key that has been installed in the Crypto Service -// Provider (CSP) on your machine. KeyFile refers to a file which contains -// a key. -// (*) If the KeyFile and the KeyName values are both specified, the -// following processing occurs: -// (1) If the KeyName can be found in the CSP, that key is used. -// (2) If the KeyName does not exist and the KeyFile does exist, the key -// in the KeyFile is installed into the CSP and used. -// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. -// When specifying the KeyFile, the location of the KeyFile should be -// relative to the project output directory which is -// %Project Directory%\obj\. For example, if your KeyFile is -// located in the project directory, you would specify the AssemblyKeyFile -// attribute as [assembly: AssemblyKeyFile("..\..\mykey.snk")] -// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework -// documentation for more information on this. -// - -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyDelaySign(false)] -[assembly: AssemblyKeyFile("")] -[assembly: AssemblyKeyName("")] - - diff --git a/zxing-csharp/BarcodeFormat.cs b/zxing-csharp/BarcodeFormat.cs deleted file mode 100644 index 811419d..0000000 --- a/zxing-csharp/BarcodeFormat.cs +++ /dev/null @@ -1,108 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - /// Enumerates barcode formats known to this package. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class BarcodeFormat - { - public System.String Name - { - get - { - return name; - } - - } - - // No, we can't use an enum here. J2ME doesn't support it. - - //UPGRADE_NOTE: Final was removed from the declaration of 'VALUES '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.Collections.Hashtable VALUES = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - - /// QR Code 2D barcode format. - //UPGRADE_NOTE: Final was removed from the declaration of 'QR_CODE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat QR_CODE = new BarcodeFormat("QR_CODE"); - - /// DataMatrix 2D barcode format. - //UPGRADE_NOTE: Final was removed from the declaration of 'DATAMATRIX '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat DATAMATRIX = new BarcodeFormat("DATAMATRIX"); - - /// UPC-E 1D format. - //UPGRADE_NOTE: Final was removed from the declaration of 'UPC_E '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat UPC_E = new BarcodeFormat("UPC_E"); - - /// UPC-A 1D format. - //UPGRADE_NOTE: Final was removed from the declaration of 'UPC_A '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat UPC_A = new BarcodeFormat("UPC_A"); - - /// EAN-8 1D format. - //UPGRADE_NOTE: Final was removed from the declaration of 'EAN_8 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat EAN_8 = new BarcodeFormat("EAN_8"); - - /// EAN-13 1D format. - //UPGRADE_NOTE: Final was removed from the declaration of 'EAN_13 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat EAN_13 = new BarcodeFormat("EAN_13"); - - /// Code 128 1D format. - //UPGRADE_NOTE: Final was removed from the declaration of 'CODE_128 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat CODE_128 = new BarcodeFormat("CODE_128"); - - /// Code 39 1D format. - //UPGRADE_NOTE: Final was removed from the declaration of 'CODE_39 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat CODE_39 = new BarcodeFormat("CODE_39"); - - /// ITF (Interleaved Two of Five) 1D format. - //UPGRADE_NOTE: Final was removed from the declaration of 'ITF '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat ITF = new BarcodeFormat("ITF"); - - /// PDF417 format. - //UPGRADE_NOTE: Final was removed from the declaration of 'PDF417 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly BarcodeFormat PDF417 = new BarcodeFormat("PDF417"); - - //UPGRADE_NOTE: Final was removed from the declaration of 'name '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String name; - - private BarcodeFormat(System.String name) - { - this.name = name; - VALUES[name] = this; - } - - public override System.String ToString() - { - return name; - } - - public static BarcodeFormat valueOf(System.String name) - { - BarcodeFormat format = (BarcodeFormat) VALUES[name]; - if (format == null) - { - throw new System.ArgumentException(); - } - return format; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/Binarizer.cs b/zxing-csharp/Binarizer.cs deleted file mode 100644 index 5e5b928..0000000 --- a/zxing-csharp/Binarizer.cs +++ /dev/null @@ -1,93 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BitArray = com.google.zxing.common.BitArray; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing -{ - - /// This class hierarchy provides a set of methods to convert luminance data to 1 bit data. - /// It allows the algorithm to vary polymorphically, for example allowing a very expensive - /// thresholding technique for servers and a fast one for mobile. It also permits the implementation - /// to vary, e.g. a JNI version for Android and a Java fallback version for other platforms. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public abstract class Binarizer - { - virtual public LuminanceSource LuminanceSource - { - get - { - return source; - } - - } - /// Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive - /// and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or - /// may not apply sharpening. Therefore, a row from this matrix may not be identical to one - /// fetched using getBlackRow(), so don't mix and match between them. - /// - /// - /// The 2D array of bits for the image (true means black). - /// - public abstract BitMatrix BlackMatrix{get;} - - //UPGRADE_NOTE: Final was removed from the declaration of 'source '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private LuminanceSource source; - - protected internal Binarizer(LuminanceSource source) - { - if (source == null) - { - throw new System.ArgumentException("Source must be non-null."); - } - this.source = source; - } - - /// Converts one row of luminance data to 1 bit data. May actually do the conversion, or return - /// cached data. Callers should assume this method is expensive and call it as seldom as possible. - /// This method is intended for decoding 1D barcodes and may choose to apply sharpening. - /// For callers which only examine one row of pixels at a time, the same BitArray should be reused - /// and passed in with each call for performance. However it is legal to keep more than one row - /// at a time if needed. - /// - /// - /// The row to fetch, 0 <= y < bitmap height. - /// - /// An optional preallocated array. If null or too small, it will be ignored. - /// If used, the Binarizer will call BitArray.clear(). Always use the returned object. - /// - /// The array of bits for this row (true means black). - /// - public abstract BitArray getBlackRow(int y, BitArray row); - - /// Creates a new object with the same type as this Binarizer implementation, but with pristine - /// state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache - /// of 1 bit data. See Effective Java for why we can't use Java's clone() method. - /// - /// - /// The LuminanceSource this Binarizer will operate on. - /// - /// A new concrete Binarizer implementation object. - /// - public abstract Binarizer createBinarizer(LuminanceSource source); - } -} \ No newline at end of file diff --git a/zxing-csharp/BinaryBitmap.cs b/zxing-csharp/BinaryBitmap.cs deleted file mode 100644 index aee771b..0000000 --- a/zxing-csharp/BinaryBitmap.cs +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BitArray = com.google.zxing.common.BitArray; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing -{ - - /// This class is the core bitmap class used by ZXing to represent 1 bit data. Reader objects - /// accept a BinaryBitmap and attempt to decode it. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class BinaryBitmap - { - /// The width of the bitmap. - /// - public int Width - { - get - { - return binarizer.LuminanceSource.Width; - } - - } - /// The height of the bitmap. - /// - public int Height - { - get - { - return binarizer.LuminanceSource.Height; - } - - } - /// Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive - /// and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or - /// may not apply sharpening. Therefore, a row from this matrix may not be identical to one - /// fetched using getBlackRow(), so don't mix and match between them. - /// - /// - /// The 2D array of bits for the image (true means black). - /// - public BitMatrix BlackMatrix - { - get - { - // The matrix is created on demand the first time it is requested, then cached. There are two - // reasons for this: - // 1. This work will never be done if the caller only installs 1D Reader objects, or if a - // 1D Reader finds a barcode before the 2D Readers run. - // 2. This work will only be done once even if the caller installs multiple 2D Readers. - if (matrix == null) - { - matrix = binarizer.BlackMatrix; - } - return matrix; - } - - } - /// Whether this bitmap can be cropped. - /// - public bool CropSupported - { - get - { - return binarizer.LuminanceSource.CropSupported; - } - - } - /// Whether this bitmap supports counter-clockwise rotation. - /// - public bool RotateSupported - { - get - { - return binarizer.LuminanceSource.RotateSupported; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'binarizer '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private Binarizer binarizer; - private BitMatrix matrix; - - public BinaryBitmap(Binarizer binarizer) - { - if (binarizer == null) - { - throw new System.ArgumentException("Binarizer must be non-null."); - } - this.binarizer = binarizer; - matrix = null; - } - - /// Converts one row of luminance data to 1 bit data. May actually do the conversion, or return - /// cached data. Callers should assume this method is expensive and call it as seldom as possible. - /// This method is intended for decoding 1D barcodes and may choose to apply sharpening. - /// - /// - /// The row to fetch, 0 <= y < bitmap height. - /// - /// An optional preallocated array. If null or too small, it will be ignored. - /// If used, the Binarizer will call BitArray.clear(). Always use the returned object. - /// - /// The array of bits for this row (true means black). - /// - public BitArray getBlackRow(int y, BitArray row) - { - return binarizer.getBlackRow(y, row); - } - - /// Returns a new object with cropped image data. Implementations may keep a reference to the - /// original data rather than a copy. Only callable if isCropSupported() is true. - /// - /// - /// The left coordinate, 0 <= left < getWidth(). - /// - /// The top coordinate, 0 <= top <= getHeight(). - /// - /// The width of the rectangle to crop. - /// - /// The height of the rectangle to crop. - /// - /// A cropped version of this object. - /// - public BinaryBitmap crop(int left, int top, int width, int height) - { - LuminanceSource newSource = binarizer.LuminanceSource.crop(left, top, width, height); - return new BinaryBitmap(binarizer.createBinarizer(newSource)); - } - - /// Returns a new object with rotated image data. Only callable if isRotateSupported() is true. - /// - /// - /// A rotated version of this object. - /// - public BinaryBitmap rotateCounterClockwise() - { - LuminanceSource newSource = binarizer.LuminanceSource.rotateCounterClockwise(); - return new BinaryBitmap(binarizer.createBinarizer(newSource)); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/DecodeHintType.cs b/zxing-csharp/DecodeHintType.cs deleted file mode 100644 index ec55fac..0000000 --- a/zxing-csharp/DecodeHintType.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - /// Encapsulates a type of hint that a caller may pass to a barcode reader to help it - /// more quickly or accurately decode it. It is up to implementations to decide what, - /// if anything, to do with the information that is supplied. - /// - /// - /// Sean Owen - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - /// - /// - public sealed class DecodeHintType - { - - // No, we can't use an enum here. J2ME doesn't support it. - - /// Unspecified, application-specific hint. Maps to an unspecified {@link Object}. - //UPGRADE_NOTE: Final was removed from the declaration of 'OTHER '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly DecodeHintType OTHER = new DecodeHintType(); - - /// Image is a pure monochrome image of a barcode. Doesn't matter what it maps to; - /// use {@link Boolean#TRUE}. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'PURE_BARCODE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly DecodeHintType PURE_BARCODE = new DecodeHintType(); - - /// Image is known to be of one of a few possible formats. - /// Maps to a {@link java.util.Vector} of {@link BarcodeFormat}s. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'POSSIBLE_FORMATS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly DecodeHintType POSSIBLE_FORMATS = new DecodeHintType(); - - /// Spend more time to try to find a barcode; optimize for accuracy, not speed. - /// Doesn't matter what it maps to; use {@link Boolean#TRUE}. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'TRY_HARDER '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly DecodeHintType TRY_HARDER = new DecodeHintType(); - - /// Allowed lengths of encoded data -- reject anything else. Maps to an int[]. - //UPGRADE_NOTE: Final was removed from the declaration of 'ALLOWED_LENGTHS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly DecodeHintType ALLOWED_LENGTHS = new DecodeHintType(); - - /// Assume Code 39 codes employ a check digit. Maps to {@link Boolean}. - //UPGRADE_NOTE: Final was removed from the declaration of 'ASSUME_CODE_39_CHECK_DIGIT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly DecodeHintType ASSUME_CODE_39_CHECK_DIGIT = new DecodeHintType(); - - /// The caller needs to be notified via callback when a possible {@link ResultPoint} - /// is found. Maps to a {@link ResultPointCallback}. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'NEED_RESULT_POINT_CALLBACK '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly DecodeHintType NEED_RESULT_POINT_CALLBACK = new DecodeHintType(); - - private DecodeHintType() - { - } - } -} \ No newline at end of file diff --git a/zxing-csharp/EncodeHintType.cs b/zxing-csharp/EncodeHintType.cs deleted file mode 100644 index 9060bdc..0000000 --- a/zxing-csharp/EncodeHintType.cs +++ /dev/null @@ -1,43 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - /// These are a set of hints that you may pass to Writers to specify their behavior. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class EncodeHintType - { - - /// Specifies what degree of error correction to use, for example in QR Codes (type Integer). - //UPGRADE_NOTE: Final was removed from the declaration of 'ERROR_CORRECTION '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly EncodeHintType ERROR_CORRECTION = new EncodeHintType(); - - /// Specifies what character encoding to use where applicable (type String) - //UPGRADE_NOTE: Final was removed from the declaration of 'CHARACTER_SET '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly EncodeHintType CHARACTER_SET = new EncodeHintType(); - - private EncodeHintType() - { - } - } -} \ No newline at end of file diff --git a/zxing-csharp/LuminanceSource.cs b/zxing-csharp/LuminanceSource.cs deleted file mode 100644 index e87b428..0000000 --- a/zxing-csharp/LuminanceSource.cs +++ /dev/null @@ -1,140 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - /// The purpose of this class hierarchy is to abstract different bitmap implementations across - /// platforms into a standard interface for requesting greyscale luminance values. The interface - /// only provides immutable methods; therefore crop and rotation create copies. This is to ensure - /// that one Reader does not modify the original luminance source and leave it in an unknown state - /// for other Readers in the chain. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public abstract class LuminanceSource - { - /// Fetches luminance data for the underlying bitmap. Values should be fetched using: - /// int luminance = array[y * width + x] & 0xff; - /// - /// - /// A row-major 2D array of luminance values. Do not use result.length as it may be - /// larger than width * height bytes on some platforms. Do not modify the contents - /// of the result. - /// - public abstract sbyte[] Matrix{get;} - /// The width of the bitmap. - /// - virtual public int Width - { - get - { - return width; - } - - } - /// The height of the bitmap. - /// - virtual public int Height - { - get - { - return height; - } - - } - /// Whether this subclass supports cropping. - /// - virtual public bool CropSupported - { - get - { - return false; - } - - } - /// Whether this subclass supports counter-clockwise rotation. - /// - virtual public bool RotateSupported - { - get - { - return false; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'width '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int width; - //UPGRADE_NOTE: Final was removed from the declaration of 'height '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int height; - - protected internal LuminanceSource(int width, int height) - { - this.width = width; - this.height = height; - } - - /// Fetches one row of luminance data from the underlying platform's bitmap. Values range from - /// 0 (black) to 255 (white). Because Java does not have an unsigned byte type, callers will have - /// to bitwise and with 0xff for each value. It is preferable for implementations of this method - /// to only fetch this row rather than the whole image, since no 2D Readers may be installed and - /// getMatrix() may never be called. - /// - /// - /// The row to fetch, 0 <= y < getHeight(). - /// - /// An optional preallocated array. If null or too small, it will be ignored. - /// Always use the returned object, and ignore the .length of the array. - /// - /// An array containing the luminance data. - /// - public abstract sbyte[] getRow(int y, sbyte[] row); - - /// Returns a new object with cropped image data. Implementations may keep a reference to the - /// original data rather than a copy. Only callable if isCropSupported() is true. - /// - /// - /// The left coordinate, 0 <= left < getWidth(). - /// - /// The top coordinate, 0 <= top <= getHeight(). - /// - /// The width of the rectangle to crop. - /// - /// The height of the rectangle to crop. - /// - /// A cropped version of this object. - /// - public virtual LuminanceSource crop(int left, int top, int width, int height) - { - throw new System.SystemException("This luminance source does not support cropping."); - } - - /// Returns a new object with rotated image data. Only callable if isRotateSupported() is true. - /// - /// - /// A rotated version of this object. - /// - public virtual LuminanceSource rotateCounterClockwise() - { - throw new System.SystemException("This luminance source does not support rotation."); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/MultiFormatReader.cs b/zxing-csharp/MultiFormatReader.cs deleted file mode 100644 index 0c58f9f..0000000 --- a/zxing-csharp/MultiFormatReader.cs +++ /dev/null @@ -1,175 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using MultiFormatOneDReader = com.google.zxing.oned.MultiFormatOneDReader; -using PDF417Reader = com.google.zxing.pdf417.PDF417Reader; -using QRCodeReader = com.google.zxing.qrcode.QRCodeReader; -using DataMatrixReader = com.google.zxing.datamatrix.DataMatrixReader; -namespace com.google.zxing -{ - - /// MultiFormatReader is a convenience class and the main entry point into the library for most uses. - /// By default it attempts to decode all barcode formats that the library supports. Optionally, you - /// can provide a hints object to request different behavior, for example only decoding QR codes. - /// - /// - /// Sean Owen - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class MultiFormatReader : Reader - { - /// This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls - /// to decodeWithState(image) can reuse the same set of readers without reallocating memory. This - /// is important for performance in continuous scan clients. - /// - /// - /// The set of hints to use for subsequent calls to decode(image) - /// - public System.Collections.Hashtable Hints - { - set - { - this.hints = value; - - bool tryHarder = value != null && value.ContainsKey(DecodeHintType.TRY_HARDER); - System.Collections.ArrayList formats = value == null?null:(System.Collections.ArrayList) value[DecodeHintType.POSSIBLE_FORMATS]; - readers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - if (formats != null) - { - bool addOneDReader = formats.Contains(BarcodeFormat.UPC_A) || formats.Contains(BarcodeFormat.UPC_E) || formats.Contains(BarcodeFormat.EAN_13) || formats.Contains(BarcodeFormat.EAN_8) || formats.Contains(BarcodeFormat.CODE_39) || formats.Contains(BarcodeFormat.CODE_128) || formats.Contains(BarcodeFormat.ITF); - // Put 1D readers upfront in "normal" mode - if (addOneDReader && !tryHarder) - { - readers.Add(new MultiFormatOneDReader(value)); - } - if (formats.Contains(BarcodeFormat.QR_CODE)) - { - readers.Add(new QRCodeReader()); - } - if (formats.Contains(BarcodeFormat.DATAMATRIX)) - { - readers.Add(new DataMatrixReader()); - } - if (formats.Contains(BarcodeFormat.PDF417)) - { - readers.Add(new PDF417Reader()); - } - // At end in "try harder" mode - if (addOneDReader && tryHarder) - { - readers.Add(new MultiFormatOneDReader(value)); - } - } - if ((readers.Count == 0)) - { - if (!tryHarder) - { - readers.Add(new MultiFormatOneDReader(value)); - } - readers.Add(new QRCodeReader()); - - // TODO re-enable once Data Matrix is ready - // readers.addElement(new DataMatrixReader()); - - // TODO: Enable once PDF417 has passed QA - //readers.addElement(new PDF417Reader()); - - if (tryHarder) - { - readers.Add(new MultiFormatOneDReader(value)); - } - } - } - - } - - private System.Collections.Hashtable hints; - private System.Collections.ArrayList readers; - - /// This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it - /// passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly. - /// Use setHints() followed by decodeWithState() for continuous scan applications. - /// - /// - /// The pixel data to decode - /// - /// The contents of the image - /// - /// ReaderException Any errors which occurred - public Result decode(BinaryBitmap image) - { - Hints = null; - return decodeInternal(image); - } - - /// Decode an image using the hints provided. Does not honor existing state. - /// - /// - /// The pixel data to decode - /// - /// The hints to use, clearing the previous state. - /// - /// The contents of the image - /// - /// ReaderException Any errors which occurred - public Result decode(BinaryBitmap image, System.Collections.Hashtable hints) - { - Hints = hints; - return decodeInternal(image); - } - - /// Decode an image using the state set up by calling setHints() previously. Continuous scan - /// clients will get a large speed increase by using this instead of decode(). - /// - /// - /// The pixel data to decode - /// - /// The contents of the image - /// - /// ReaderException Any errors which occurred - public Result decodeWithState(BinaryBitmap image) - { - // Make sure to set up the default state so we don't crash - if (readers == null) - { - Hints = null; - } - return decodeInternal(image); - } - - private Result decodeInternal(BinaryBitmap image) - { - int size = readers.Count; - for (int i = 0; i < size; i++) - { - Reader reader = (Reader) readers[i]; - try - { - return reader.decode(image, hints); - } - catch (ReaderException re) - { - // continue - } - } - - throw ReaderException.Instance; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/MultiFormatWriter.cs b/zxing-csharp/MultiFormatWriter.cs deleted file mode 100644 index 160c453..0000000 --- a/zxing-csharp/MultiFormatWriter.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -using EAN13Writer = com.google.zxing.oned.EAN13Writer; -using EAN8Writer = com.google.zxing.oned.EAN8Writer; -using QRCodeWriter = com.google.zxing.qrcode.QRCodeWriter; -namespace com.google.zxing -{ - - /// This is a factory class which finds the appropriate Writer subclass for the BarcodeFormat - /// requested and encodes the barcode with the supplied contents. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class MultiFormatWriter : Writer - { - - public ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height) - { - - return encode(contents, format, width, height, null); - } - - public ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height, System.Collections.Hashtable hints) - { - - if (format == BarcodeFormat.EAN_8) - { - return new EAN8Writer().encode(contents, format, width, height, hints); - } - else if (format == BarcodeFormat.EAN_13) - { - return new EAN13Writer().encode(contents, format, width, height, hints); - } - else if (format == BarcodeFormat.QR_CODE) - { - return new QRCodeWriter().encode(contents, format, width, height, hints); - } - else - { - throw new System.ArgumentException("No encoder available for format " + format); - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/RGBLuminanceSource.cs b/zxing-csharp/RGBLuminanceSource.cs deleted file mode 100644 index 5e65a4b..0000000 --- a/zxing-csharp/RGBLuminanceSource.cs +++ /dev/null @@ -1,163 +0,0 @@ -using com.google.zxing; -using com.google.zxing.common; -using System.Drawing.Imaging; -using System.Drawing; -using System; - -public class RGBLuminanceSource : LuminanceSource -{ - - private sbyte[] luminances; - private bool isRotated = false; - private bool __isRegionSelect = false; - private Rectangle __Region; - - override public int Height - { - get - { - if (!isRotated) - return __height; - else - return __width; - } - - } - override public int Width - { - get - { - if (!isRotated) - return __width; - else - return __height; - } - - } - private int __height; - private int __width; - - public RGBLuminanceSource(byte[] d, int W, int H) - : base(W, H) - { - __width = W; - __height = H; - int width = W; - int height = H; - // In order to measure pure decoding speed, we convert the entire image to a greyscale array - // up front, which is the same as the Y channel of the YUVLuminanceSource in the real app. - luminances = new sbyte[width * height]; - for (int y = 0; y < height; y++) - { - int offset = y * width; - for (int x = 0; x < width; x++) - { - int r = d[offset * 3 + x * 3]; - int g = d[offset * 3 + x * 3 + 1]; - int b = d[offset * 3 + x * 3 + 2]; - if (r == g && g == b) - { - // Image is already greyscale, so pick any channel. - luminances[offset + x] = (sbyte)r; - } - else - { - // Calculate luminance cheaply, favoring green. - luminances[offset + x] = (sbyte)((r + g + g + b) >> 2); - } - } - } - } - public RGBLuminanceSource(byte[] d, int W, int H,bool Is8Bit) - : base(W, H) - { - __width = W; - __height = H; - luminances = new sbyte[W * H]; - Buffer.BlockCopy(d,0, luminances,0, W * H); - } - - public RGBLuminanceSource(byte[] d, int W, int H, bool Is8Bit,Rectangle Region) - : base(W, H) - { - __width = Region.Width; - __height = Region.Height; - __Region = Region; - __isRegionSelect = true; - //luminances = Red.Imaging.Filters.CropArea(d, W, H, Region); - } - - - public RGBLuminanceSource(Bitmap d, int W, int H) - : base(W, H) - { - int width = __width = W; - int height = __height = H; - // In order to measure pure decoding speed, we convert the entire image to a greyscale array - // up front, which is the same as the Y channel of the YUVLuminanceSource in the real app. - luminances = new sbyte[width * height]; - //if (format == PixelFormat.Format8bppIndexed) - { - Color c; - for (int y = 0; y < height; y++) - { - int offset = y * width; - for (int x = 0; x < width; x++) - { - c = d.GetPixel(x, y); - luminances[offset + x] = (sbyte)(((int)c.R) << 16 | ((int)c.G) << 8 | ((int)c.B)); - } - } - } - } - override public sbyte[] getRow(int y, sbyte[] row) - { - if (isRotated == false) - { - int width = Width; - if (row == null || row.Length < width) - { - row = new sbyte[width]; - } - for (int i = 0; i < width; i++) - row[i] = luminances[y * width + i]; - //System.arraycopy(luminances, y * width, row, 0, width); - return row; - } - else - { - int width = __width; - int height = __height; - if (row == null || row.Length < height) - { - row = new sbyte[height]; - } - for (int i = 0; i < height; i++) - row[i] = luminances[i * width + y]; - //System.arraycopy(luminances, y * width, row, 0, width); - return row; - } - } - public override sbyte[] Matrix - { - get { return luminances; } - } - - public override LuminanceSource crop(int left, int top, int width, int height) - { - return base.crop(left, top, width, height); - } - public override LuminanceSource rotateCounterClockwise() - { - isRotated = true; - return this; - } - public override bool RotateSupported - { - get - { - return true; - } - - } -} diff --git a/zxing-csharp/Reader.cs b/zxing-csharp/Reader.cs deleted file mode 100644 index c72e70a..0000000 --- a/zxing-csharp/Reader.cs +++ /dev/null @@ -1,65 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - /// Implementations of this interface can decode an image of a barcode in some format into - /// the String it encodes. For example, {@link com.google.zxing.qrcode.QRCodeReader} can - /// decode a QR code. The decoder may optionally receive hints from the caller which may help - /// it decode more quickly or accurately. - /// - /// See {@link com.google.zxing.MultiFormatReader}, which attempts to determine what barcode - /// format is present within the image as well, and then decodes it accordingly. - /// - /// - /// Sean Owen - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public interface Reader - { - - /// Locates and decodes a barcode in some format within an image. - /// - /// - /// image of barcode to decode - /// - /// String which the barcode encodes - /// - /// ReaderException if the barcode cannot be located or decoded for any reason - Result decode(BinaryBitmap image); - - /// Locates and decodes a barcode in some format within an image. This method also accepts - /// hints, each possibly associated to some data, which may help the implementation decode. - /// - /// - /// image of barcode to decode - /// - /// passed as a {@link java.util.Hashtable} from {@link com.google.zxing.DecodeHintType} - /// to arbitrary data. The - /// meaning of the data depends upon the hint type. The implementation may or may not do - /// anything with these hints. - /// - /// String which the barcode encodes - /// - /// ReaderException if the barcode cannot be located or decoded for any reason - Result decode(BinaryBitmap image, System.Collections.Hashtable hints); - } -} \ No newline at end of file diff --git a/zxing-csharp/ReaderException.cs b/zxing-csharp/ReaderException.cs deleted file mode 100644 index 1db0436..0000000 --- a/zxing-csharp/ReaderException.cs +++ /dev/null @@ -1,113 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - /// The general exception class throw when something goes wrong during decoding of a barcode. - /// This includes, but is not limited to, failing checksums / error correction algorithms, being - /// unable to locate finder timing patterns, and so on. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - [Serializable] - public sealed class ReaderException:System.Exception - { - public static ReaderException Instance - { - get - { - // Exception e = new Exception(); - // // Take the stack frame before this one. - // StackTraceElement stack = e.getStackTrace()[1]; - // String key = stack.getClassName() + "." + stack.getMethodName() + "(), line " + - // stack.getLineNumber(); - // if (throwers.containsKey(key)) { - // Integer value = throwers.get(key); - // value++; - // throwers.put(key, value); - // } else { - // throwers.put(key, 1); - // } - // exceptionCount++; - - return instance; - } - - } - - // TODO: Currently we throw up to 400 ReaderExceptions while scanning a single 240x240 image before - // rejecting it. This involves a lot of overhead and memory allocation, and affects both performance - // and latency on continuous scan clients. In the future, we should change all the decoders not to - // throw exceptions for routine events, like not finding a barcode on a given row. Instead, we - // should return error codes back to the callers, and simply delete this class. In the mean time, I - // have altered this class to be as lightweight as possible, by ignoring the exception string, and - // by disabling the generation of stack traces, which is especially time consuming. These are just - // temporary measures, pending the big cleanup. - - //UPGRADE_NOTE: Final was removed from the declaration of 'instance '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly ReaderException instance = new ReaderException(); - - // EXCEPTION TRACKING SUPPORT - // Identifies who is throwing exceptions and how often. To use: - // - // 1. Uncomment these lines and the code below which uses them. - // 2. Uncomment the two corresponding lines in j2se/CommandLineRunner.decode() - // 3. Change core to build as Java 1.5 temporarily - // private static int exceptionCount = 0; - // private static Map throwers = new HashMap(32); - - private ReaderException() - { - // do nothing - } - - // public static int getExceptionCountAndReset() { - // int temp = exceptionCount; - // exceptionCount = 0; - // return temp; - // } - // - // public static String getThrowersAndReset() { - // StringBuilder builder = new StringBuilder(1024); - // Object[] keys = throwers.keySet().toArray(); - // for (int x = 0; x < keys.length; x++) { - // String key = (String) keys[x]; - // Integer value = throwers.get(key); - // builder.append(key); - // builder.append(": "); - // builder.append(value); - // builder.append("\n"); - // } - // throwers.clear(); - // return builder.toString(); - // } - - // Prevent stack traces from being taken - // srowen says: huh, my IDE is saying this is not an override. native methods can't be overridden? - // This, at least, does not hurt. Because we use a singleton pattern here, it doesn't matter anyhow. - //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" - //UPGRADE_NOTE: The equivalent of method 'java.lang.Throwable.fillInStackTrace' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" - public System.Exception fillInStackTrace() - { - return null; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/Result.cs b/zxing-csharp/Result.cs deleted file mode 100644 index b09d9ac..0000000 --- a/zxing-csharp/Result.cs +++ /dev/null @@ -1,129 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - ///

Encapsulates the result of decoding a barcode within an image.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class Result - { - /// raw text encoded by the barcode, if applicable, otherwise null - /// - public System.String Text - { - get - { - return text; - } - - } - /// raw bytes encoded by the barcode, if applicable, otherwise null - /// - public sbyte[] RawBytes - { - get - { - return rawBytes; - } - - } - /// points related to the barcode in the image. These are typically points - /// identifying finder patterns or the corners of the barcode. The exact meaning is - /// specific to the type of barcode that was decoded. - /// - public ResultPoint[] ResultPoints - { - get - { - return resultPoints; - } - - } - /// {@link BarcodeFormat} representing the format of the barcode that was decoded - /// - public BarcodeFormat BarcodeFormat - { - get - { - return format; - } - - } - /// {@link Hashtable} mapping {@link ResultMetadataType} keys to values. May be - /// null. This contains optional metadata about what was detected about the barcode, - /// like orientation. - /// - public System.Collections.Hashtable ResultMetadata - { - get - { - return resultMetadata; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'text '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String text; - //UPGRADE_NOTE: Final was removed from the declaration of 'rawBytes '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte[] rawBytes; - //UPGRADE_NOTE: Final was removed from the declaration of 'resultPoints '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ResultPoint[] resultPoints; - //UPGRADE_NOTE: Final was removed from the declaration of 'format '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BarcodeFormat format; - private System.Collections.Hashtable resultMetadata; - - public Result(System.String text, sbyte[] rawBytes, ResultPoint[] resultPoints, BarcodeFormat format) - { - if (text == null && rawBytes == null) - { - throw new System.ArgumentException("Text and bytes are null"); - } - this.text = text; - this.rawBytes = rawBytes; - this.resultPoints = resultPoints; - this.format = format; - this.resultMetadata = null; - } - - public void putMetadata(ResultMetadataType type, System.Object value_Renamed) - { - if (resultMetadata == null) - { - resultMetadata = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable(3)); - } - resultMetadata[type] = value_Renamed; - } - - public override System.String ToString() - { - if (text == null) - { - return "[" + rawBytes.Length + " bytes]"; - } - else - { - return text; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/ResultMetadataType.cs b/zxing-csharp/ResultMetadataType.cs deleted file mode 100644 index d57ae27..0000000 --- a/zxing-csharp/ResultMetadataType.cs +++ /dev/null @@ -1,68 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - /// Represents some type of metadata about the result of the decoding that the decoder - /// wishes to communicate back to the caller. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class ResultMetadataType - { - - // No, we can't use an enum here. J2ME doesn't support it. - - /// Unspecified, application-specific metadata. Maps to an unspecified {@link Object}. - //UPGRADE_NOTE: Final was removed from the declaration of 'OTHER '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ResultMetadataType OTHER = new ResultMetadataType(); - - /// Denotes the likely approximate orientation of the barcode in the image. This value - /// is given as degrees rotated clockwise from the normal, upright orientation. - /// For example a 1D barcode which was found by reading top-to-bottom would be - /// said to have orientation "90". This key maps to an {@link Integer} whose - /// value is in the range [0,360). - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'ORIENTATION '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ResultMetadataType ORIENTATION = new ResultMetadataType(); - - ///

2D barcode formats typically encode text, but allow for a sort of 'byte mode' - /// which is sometimes used to encode binary data. While {@link Result} makes available - /// the complete raw bytes in the barcode for these formats, it does not offer the bytes - /// from the byte segments alone.

- /// - ///

This maps to a {@link java.util.Vector} of byte arrays corresponding to the - /// raw bytes in the byte segments in the barcode, in order.

- ///
- //UPGRADE_NOTE: Final was removed from the declaration of 'BYTE_SEGMENTS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ResultMetadataType BYTE_SEGMENTS = new ResultMetadataType(); - - /// Error correction level used, if applicable. The value type depends on the - /// format, but is typically a String. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'ERROR_CORRECTION_LEVEL '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ResultMetadataType ERROR_CORRECTION_LEVEL = new ResultMetadataType(); - - private ResultMetadataType() - { - } - } -} \ No newline at end of file diff --git a/zxing-csharp/ResultPoint.cs b/zxing-csharp/ResultPoint.cs deleted file mode 100644 index def8e2f..0000000 --- a/zxing-csharp/ResultPoint.cs +++ /dev/null @@ -1,157 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - ///

Encapsulates a point of interest in an image containing a barcode. Typically, this - /// would be the location of a finder pattern or the corner of the barcode, for example.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public class ResultPoint - { - virtual public float X - { - get - { - return x; - } - - } - virtual public float Y - { - get - { - return y; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'x '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private float x; - //UPGRADE_NOTE: Final was removed from the declaration of 'y '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private float y; - - public ResultPoint(float x, float y) - { - this.x = x; - this.y = y; - } - - public override bool Equals(System.Object other) - { - if (other is ResultPoint) - { - ResultPoint otherPoint = (ResultPoint) other; - return x == otherPoint.x && y == otherPoint.y; - } - return false; - } - - public override int GetHashCode() - { - // Redivivus.in Java to c# Porting update - // 30/01/2010 - // Commented function body - - //return 31 * Float.floatToIntBits(x) + Float.floatToIntBits(y); - return 0; - } - - public override System.String ToString() - { - System.Text.StringBuilder result = new System.Text.StringBuilder(25); - result.Append('('); - result.Append(x); - result.Append(','); - result.Append(y); - result.Append(')'); - return result.ToString(); - } - - ///

Orders an array of three ResultPoints in an order [A,B,C] such that AB < AC and - /// BC < AC and the angle between BC and BA is less than 180 degrees. - ///

- public static void orderBestPatterns(ResultPoint[] patterns) - { - - // Find distances between pattern centers - float zeroOneDistance = distance(patterns[0], patterns[1]); - float oneTwoDistance = distance(patterns[1], patterns[2]); - float zeroTwoDistance = distance(patterns[0], patterns[2]); - - ResultPoint pointA, pointB, pointC; - // Assume one closest to other two is B; A and C will just be guesses at first - if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) - { - pointB = patterns[0]; - pointA = patterns[1]; - pointC = patterns[2]; - } - else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) - { - pointB = patterns[1]; - pointA = patterns[0]; - pointC = patterns[2]; - } - else - { - pointB = patterns[2]; - pointA = patterns[0]; - pointC = patterns[1]; - } - - // Use cross product to figure out whether A and C are correct or flipped. - // This asks whether BC x BA has a positive z component, which is the arrangement - // we want for A, B, C. If it's negative, then we've got it flipped around and - // should swap A and C. - if (crossProductZ(pointA, pointB, pointC) < 0.0f) - { - ResultPoint temp = pointA; - pointA = pointC; - pointC = temp; - } - - patterns[0] = pointA; - patterns[1] = pointB; - patterns[2] = pointC; - } - - - /// distance between two points - /// - public static float distance(ResultPoint pattern1, ResultPoint pattern2) - { - float xDiff = pattern1.X - pattern2.X; - float yDiff = pattern1.Y - pattern2.Y; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (float) System.Math.Sqrt((double) (xDiff * xDiff + yDiff * yDiff)); - } - - /// Returns the z component of the cross product between vectors BC and BA. - private static float crossProductZ(ResultPoint pointA, ResultPoint pointB, ResultPoint pointC) - { - float bX = pointB.x; - float bY = pointB.y; - return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX)); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/ResultPointCallback.cs b/zxing-csharp/ResultPointCallback.cs deleted file mode 100644 index e736c0a..0000000 --- a/zxing-csharp/ResultPointCallback.cs +++ /dev/null @@ -1,31 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - /// Callback which is invoked when a possible result point (significant - /// point in the barcode image such as a corner) is found. - /// - /// - /// - /// - public interface ResultPointCallback - { - - void foundPossibleResultPoint(ResultPoint point); - } -} \ No newline at end of file diff --git a/zxing-csharp/SupportClass.cs b/zxing-csharp/SupportClass.cs deleted file mode 100644 index 7e2d298..0000000 --- a/zxing-csharp/SupportClass.cs +++ /dev/null @@ -1,215 +0,0 @@ -// -// In order to convert some functionality to Visual C#, the Java Language Conversion Assistant -// creates "support classes" that duplicate the original functionality. -// -// Support classes replicate the functionality of the original code, but in some cases they are -// substantially different architecturally. Although every effort is made to preserve the -// original architecture of the application in the converted project, the user should be aware that -// the primary goal of these support classes is to replicate functionality, and that at times -// the architecture of the resulting solution may differ somewhat. -// - -using System; - -/// -/// Contains conversion support elements such as classes, interfaces and static methods. -/// -public class SupportClass -{ - /// - /// Converts an array of sbytes to an array of bytes - /// - /// The array of sbytes to be converted - /// The new array of bytes - public static byte[] ToByteArray(sbyte[] sbyteArray) - { - byte[] byteArray = null; - - if (sbyteArray != null) - { - byteArray = new byte[sbyteArray.Length]; - for(int index=0; index < sbyteArray.Length; index++) - byteArray[index] = (byte) sbyteArray[index]; - } - return byteArray; - } - - /// - /// Converts a string to an array of bytes - /// - /// The string to be converted - /// The new array of bytes - public static byte[] ToByteArray(System.String sourceString) - { - return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); - } - - /// - /// Converts a array of object-type instances to a byte-type array. - /// - /// Array to convert. - /// An array of byte type elements. - public static byte[] ToByteArray(System.Object[] tempObjectArray) - { - byte[] byteArray = null; - if (tempObjectArray != null) - { - byteArray = new byte[tempObjectArray.Length]; - for (int index = 0; index < tempObjectArray.Length; index++) - byteArray[index] = (byte)tempObjectArray[index]; - } - return byteArray; - } - - /*******************************/ - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static int URShift(int number, int bits) - { - if ( number >= 0) - return number >> bits; - else - return (number >> bits) + (2 << ~bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static int URShift(int number, long bits) - { - return URShift(number, (int)bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static long URShift(long number, int bits) - { - if ( number >= 0) - return number >> bits; - else - return (number >> bits) + (2L << ~bits); - } - - /// - /// Performs an unsigned bitwise right shift with the specified number - /// - /// Number to operate on - /// Ammount of bits to shift - /// The resulting number from the shift operation - public static long URShift(long number, long bits) - { - return URShift(number, (int)bits); - } - - /*******************************/ - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static long Identity(long literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static ulong Identity(ulong literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static float Identity(float literal) - { - return literal; - } - - /// - /// This method returns the literal value received - /// - /// The literal to return - /// The received value - public static double Identity(double literal) - { - return literal; - } - - /*******************************/ - /// - /// Copies an array of chars obtained from a String into a specified array of chars - /// - /// The String to get the chars from - /// Position of the String to start getting the chars - /// Position of the String to end getting the chars - /// Array to return the chars - /// Position of the destination array of chars to start storing the chars - /// An array of chars - public static void GetCharsFromString(System.String sourceString, int sourceStart, int sourceEnd, char[] destinationArray, int destinationStart) - { - int sourceCounter; - int destinationCounter; - sourceCounter = sourceStart; - destinationCounter = destinationStart; - while (sourceCounter < sourceEnd) - { - destinationArray[destinationCounter] = (char) sourceString[sourceCounter]; - sourceCounter++; - destinationCounter++; - } - } - - /*******************************/ - /// - /// Sets the capacity for the specified ArrayList - /// - /// The ArrayList which capacity will be set - /// The new capacity value - public static void SetCapacity(System.Collections.ArrayList vector, int newCapacity) - { - if (newCapacity > vector.Count) - vector.AddRange(new Array[newCapacity-vector.Count]); - else if (newCapacity < vector.Count) - vector.RemoveRange(newCapacity, vector.Count - newCapacity); - vector.Capacity = newCapacity; - } - - - - /*******************************/ - /// - /// Receives a byte array and returns it transformed in an sbyte array - /// - /// Byte array to process - /// The transformed array - public static sbyte[] ToSByteArray(byte[] byteArray) - { - sbyte[] sbyteArray = null; - if (byteArray != null) - { - sbyteArray = new sbyte[byteArray.Length]; - for(int index=0; index < byteArray.Length; index++) - sbyteArray[index] = (sbyte) byteArray[index]; - } - return sbyteArray; - } - -} diff --git a/zxing-csharp/Writer.cs b/zxing-csharp/Writer.cs deleted file mode 100644 index 540b917..0000000 --- a/zxing-csharp/Writer.cs +++ /dev/null @@ -1,62 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -namespace com.google.zxing -{ - - /// The base class for all objects which encode/generate a barcode image. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public interface Writer - { - - /// Encode a barcode using the default settings. - /// - /// - /// The contents to encode in the barcode - /// - /// The barcode format to generate - /// - /// The preferred width in pixels - /// - /// The preferred height in pixels - /// - /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) - /// - ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height); - - /// - /// The contents to encode in the barcode - /// - /// The barcode format to generate - /// - /// The preferred width in pixels - /// - /// The preferred height in pixels - /// - /// Additional parameters to supply to the encoder - /// - /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) - /// - ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height, System.Collections.Hashtable hints); - } -} \ No newline at end of file diff --git a/zxing-csharp/WriterException.cs b/zxing-csharp/WriterException.cs deleted file mode 100644 index e36569e..0000000 --- a/zxing-csharp/WriterException.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing -{ - - /// A base class which covers the range of exceptions which may occur when encoding a barcode using - /// the Writer framework. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - [Serializable] - public sealed class WriterException:System.Exception - { - - public WriterException():base() - { - } - - public WriterException(System.String message):base(message) - { - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/AbstractDoCoMoResultParser.cs b/zxing-csharp/client/result/AbstractDoCoMoResultParser.cs deleted file mode 100644 index c364098..0000000 --- a/zxing-csharp/client/result/AbstractDoCoMoResultParser.cs +++ /dev/null @@ -1,45 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - ///

See - /// - /// DoCoMo's documentation about the result types represented by subclasses of this class.

- /// - ///

Thanks to Jeff Griffin for proposing rewrite of these classes that relies less - /// on exception-based mechanisms during parsing.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - abstract class AbstractDoCoMoResultParser:ResultParser - { - - internal static System.String[] matchDoCoMoPrefixedField(System.String prefix, System.String rawText, bool trim) - { - return matchPrefixedField(prefix, rawText, ';', trim); - } - - internal static System.String matchSingleDoCoMoPrefixedField(System.String prefix, System.String rawText, bool trim) - { - return matchSinglePrefixedField(prefix, rawText, ';', trim); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/AddressBookAUResultParser.cs b/zxing-csharp/client/result/AddressBookAUResultParser.cs deleted file mode 100644 index f3ba7c6..0000000 --- a/zxing-csharp/client/result/AddressBookAUResultParser.cs +++ /dev/null @@ -1,79 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Implements KDDI AU's address book format. See - /// - /// http://www.au.kddi.com/ezfactory/tec/two_dimensions/index.html. - /// (Thanks to Yuzo for translating!) - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class AddressBookAUResultParser:ResultParser - { - - public static AddressBookParsedResult parse(Result result) - { - System.String rawText = result.Text; - // MEMORY is mandatory; seems like a decent indicator, as does end-of-record separator CR/LF - if (rawText == null || rawText.IndexOf("MEMORY") < 0 || rawText.IndexOf("\r\n") < 0) - { - return null; - } - - // NAME1 and NAME2 have specific uses, namely written name and pronunciation, respectively. - // Therefore we treat them specially instead of as an array of names. - System.String name = matchSinglePrefixedField("NAME1:", rawText, '\r', true); - System.String pronunciation = matchSinglePrefixedField("NAME2:", rawText, '\r', true); - - System.String[] phoneNumbers = matchMultipleValuePrefix("TEL", 3, rawText, true); - System.String[] emails = matchMultipleValuePrefix("MAIL", 3, rawText, true); - System.String note = matchSinglePrefixedField("MEMORY:", rawText, '\r', false); - System.String address = matchSinglePrefixedField("ADD:", rawText, '\r', true); - System.String[] addresses = address == null?null:new System.String[]{address}; - return new AddressBookParsedResult(maybeWrap(name), pronunciation, phoneNumbers, emails, note, addresses, null, null, null, null); - } - - private static System.String[] matchMultipleValuePrefix(System.String prefix, int max, System.String rawText, bool trim) - { - System.Collections.ArrayList values = null; - for (int i = 1; i <= max; i++) - { - System.String value_Renamed = matchSinglePrefixedField(prefix + i + ':', rawText, '\r', trim); - if (value_Renamed == null) - { - break; - } - if (values == null) - { - values = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(max)); // lazy init - } - values.Add(value_Renamed); - } - if (values == null) - { - return null; - } - return toStringArray(values); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/AddressBookDoCoMoResultParser.cs b/zxing-csharp/client/result/AddressBookDoCoMoResultParser.cs deleted file mode 100644 index 68b5f23..0000000 --- a/zxing-csharp/client/result/AddressBookDoCoMoResultParser.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Implements the "MECARD" address book entry format. - /// - /// Supported keys: N, SOUND, TEL, EMAIL, NOTE, ADR, BDAY, URL, plus ORG - /// Unsupported keys: TEL-AV, NICKNAME - /// - /// Except for TEL, multiple values for keys are also not supported; - /// the first one found takes precedence. - /// - /// Our understanding of the MECARD format is based on this document: - /// - /// http://www.mobicode.org.tw/files/OMIA%20Mobile%20Bar%20Code%20Standard%20v3.2.1.doc - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class AddressBookDoCoMoResultParser:AbstractDoCoMoResultParser - { - - public static AddressBookParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null || !rawText.StartsWith("MECARD:")) - { - return null; - } - System.String[] rawName = matchDoCoMoPrefixedField("N:", rawText, true); - if (rawName == null) - { - return null; - } - System.String name = parseName(rawName[0]); - System.String pronunciation = matchSingleDoCoMoPrefixedField("SOUND:", rawText, true); - System.String[] phoneNumbers = matchDoCoMoPrefixedField("TEL:", rawText, true); - System.String[] emails = matchDoCoMoPrefixedField("EMAIL:", rawText, true); - System.String note = matchSingleDoCoMoPrefixedField("NOTE:", rawText, false); - System.String[] addresses = matchDoCoMoPrefixedField("ADR:", rawText, true); - System.String birthday = matchSingleDoCoMoPrefixedField("BDAY:", rawText, true); - if (birthday != null && !isStringOfDigits(birthday, 8)) - { - // No reason to throw out the whole card because the birthday is formatted wrong. - birthday = null; - } - System.String url = matchSingleDoCoMoPrefixedField("URL:", rawText, true); - - // Although ORG may not be strictly legal in MECARD, it does exist in VCARD and we might as well - // honor it when found in the wild. - System.String org = matchSingleDoCoMoPrefixedField("ORG:", rawText, true); - - return new AddressBookParsedResult(maybeWrap(name), pronunciation, phoneNumbers, emails, note, addresses, org, birthday, null, url); - } - - private static System.String parseName(System.String name) - { - int comma = name.IndexOf(','); - if (comma >= 0) - { - // Format may be last,first; switch it around - return name.Substring(comma + 1) + ' ' + name.Substring(0, (comma) - (0)); - } - return name; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/AddressBookParsedResult.cs b/zxing-csharp/client/result/AddressBookParsedResult.cs deleted file mode 100644 index d262327..0000000 --- a/zxing-csharp/client/result/AddressBookParsedResult.cs +++ /dev/null @@ -1,169 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class AddressBookParsedResult:ParsedResult - { - public System.String[] Names - { - get - { - return names; - } - - } - /// In Japanese, the name is written in kanji, which can have multiple readings. Therefore a hint - /// is often provided, called furigana, which spells the name phonetically. - /// - /// - /// The pronunciation of the getNames() field, often in hiragana or katakana. - /// - public System.String Pronunciation - { - get - { - return pronunciation; - } - - } - public System.String[] PhoneNumbers - { - get - { - return phoneNumbers; - } - - } - public System.String[] Emails - { - get - { - return emails; - } - - } - public System.String Note - { - get - { - return note; - } - - } - public System.String[] Addresses - { - get - { - return addresses; - } - - } - public System.String Title - { - get - { - return title; - } - - } - public System.String Org - { - get - { - return org; - } - - } - public System.String URL - { - get - { - return url; - } - - } - /// birthday formatted as yyyyMMdd (e.g. 19780917) - /// - public System.String Birthday - { - get - { - return birthday; - } - - } - override public System.String DisplayResult - { - get - { - System.Text.StringBuilder result = new System.Text.StringBuilder(100); - maybeAppend(names, result); - maybeAppend(pronunciation, result); - maybeAppend(title, result); - maybeAppend(org, result); - maybeAppend(addresses, result); - maybeAppend(phoneNumbers, result); - maybeAppend(emails, result); - maybeAppend(url, result); - maybeAppend(birthday, result); - maybeAppend(note, result); - return result.ToString(); - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'names '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String[] names; - //UPGRADE_NOTE: Final was removed from the declaration of 'pronunciation '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String pronunciation; - //UPGRADE_NOTE: Final was removed from the declaration of 'phoneNumbers '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String[] phoneNumbers; - //UPGRADE_NOTE: Final was removed from the declaration of 'emails '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String[] emails; - //UPGRADE_NOTE: Final was removed from the declaration of 'note '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String note; - //UPGRADE_NOTE: Final was removed from the declaration of 'addresses '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String[] addresses; - //UPGRADE_NOTE: Final was removed from the declaration of 'org '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String org; - //UPGRADE_NOTE: Final was removed from the declaration of 'birthday '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String birthday; - //UPGRADE_NOTE: Final was removed from the declaration of 'title '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String title; - //UPGRADE_NOTE: Final was removed from the declaration of 'url '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String url; - - public AddressBookParsedResult(System.String[] names, System.String pronunciation, System.String[] phoneNumbers, System.String[] emails, System.String note, System.String[] addresses, System.String org, System.String birthday, System.String title, System.String url):base(ParsedResultType.ADDRESSBOOK) - { - this.names = names; - this.pronunciation = pronunciation; - this.phoneNumbers = phoneNumbers; - this.emails = emails; - this.note = note; - this.addresses = addresses; - this.org = org; - this.birthday = birthday; - this.title = title; - this.url = url; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/BizcardResultParser.cs b/zxing-csharp/client/result/BizcardResultParser.cs deleted file mode 100644 index 2e4f48b..0000000 --- a/zxing-csharp/client/result/BizcardResultParser.cs +++ /dev/null @@ -1,98 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Implements the "BIZCARD" address book entry format, though this has been - /// largely reverse-engineered from examples observed in the wild -- still - /// looking for a definitive reference. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class BizcardResultParser:AbstractDoCoMoResultParser - { - - // Yes, we extend AbstractDoCoMoResultParser since the format is very much - // like the DoCoMo MECARD format, but this is not technically one of - // DoCoMo's proposed formats - - public static AddressBookParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null || !rawText.StartsWith("BIZCARD:")) - { - return null; - } - System.String firstName = matchSingleDoCoMoPrefixedField("N:", rawText, true); - System.String lastName = matchSingleDoCoMoPrefixedField("X:", rawText, true); - System.String fullName = buildName(firstName, lastName); - System.String title = matchSingleDoCoMoPrefixedField("T:", rawText, true); - System.String org = matchSingleDoCoMoPrefixedField("C:", rawText, true); - System.String[] addresses = matchDoCoMoPrefixedField("A:", rawText, true); - System.String phoneNumber1 = matchSingleDoCoMoPrefixedField("B:", rawText, true); - System.String phoneNumber2 = matchSingleDoCoMoPrefixedField("M:", rawText, true); - System.String phoneNumber3 = matchSingleDoCoMoPrefixedField("F:", rawText, true); - System.String email = matchSingleDoCoMoPrefixedField("E:", rawText, true); - - return new AddressBookParsedResult(maybeWrap(fullName), null, buildPhoneNumbers(phoneNumber1, phoneNumber2, phoneNumber3), maybeWrap(email), null, addresses, org, null, title, null); - } - - private static System.String[] buildPhoneNumbers(System.String number1, System.String number2, System.String number3) - { - System.Collections.ArrayList numbers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(3)); - if (number1 != null) - { - numbers.Add(number1); - } - if (number2 != null) - { - numbers.Add(number2); - } - if (number3 != null) - { - numbers.Add(number3); - } - int size = numbers.Count; - if (size == 0) - { - return null; - } - System.String[] result = new System.String[size]; - for (int i = 0; i < size; i++) - { - result[i] = ((System.String) numbers[i]); - } - return result; - } - - private static System.String buildName(System.String firstName, System.String lastName) - { - if (firstName == null) - { - return lastName; - } - else - { - return lastName == null?firstName:firstName + ' ' + lastName; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/BookmarkDoCoMoResultParser.cs b/zxing-csharp/client/result/BookmarkDoCoMoResultParser.cs deleted file mode 100644 index da70093..0000000 --- a/zxing-csharp/client/result/BookmarkDoCoMoResultParser.cs +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class BookmarkDoCoMoResultParser:AbstractDoCoMoResultParser - { - - private BookmarkDoCoMoResultParser() - { - } - - public static URIParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null || !rawText.StartsWith("MEBKM:")) - { - return null; - } - System.String title = matchSingleDoCoMoPrefixedField("TITLE:", rawText, true); - System.String[] rawUri = matchDoCoMoPrefixedField("URL:", rawText, true); - if (rawUri == null) - { - return null; - } - System.String uri = rawUri[0]; - if (!URIResultParser.isBasicallyValidURI(uri)) - { - return null; - } - return new URIParsedResult(uri, title); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/CalendarParsedResult.cs b/zxing-csharp/client/result/CalendarParsedResult.cs deleted file mode 100644 index e0786cd..0000000 --- a/zxing-csharp/client/result/CalendarParsedResult.cs +++ /dev/null @@ -1,172 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class CalendarParsedResult:ParsedResult - { - public System.String Summary - { - get - { - return summary; - } - - } - ///

We would return the start and end date as a {@link java.util.Date} except that this code - /// needs to work under JavaME / MIDP and there is no date parsing library available there, such - /// as java.text.SimpleDateFormat.

See validateDate() for the return format. - /// - ///
- /// start time formatted as a RFC 2445 DATE or DATE-TIME.

- ///
- public System.String Start - { - get - { - return start; - } - - } - /// - /// - public System.String End - { - get - { - return end; - } - - } - public System.String Location - { - get - { - return location; - } - - } - public System.String Attendee - { - get - { - return attendee; - } - - } - public System.String Title - { - get - { - return title; - } - - } - override public System.String DisplayResult - { - get - { - System.Text.StringBuilder result = new System.Text.StringBuilder(100); - maybeAppend(summary, result); - maybeAppend(start, result); - maybeAppend(end, result); - maybeAppend(location, result); - maybeAppend(attendee, result); - maybeAppend(title, result); - return result.ToString(); - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'summary '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String summary; - //UPGRADE_NOTE: Final was removed from the declaration of 'start '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String start; - //UPGRADE_NOTE: Final was removed from the declaration of 'end '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String end; - //UPGRADE_NOTE: Final was removed from the declaration of 'location '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String location; - //UPGRADE_NOTE: Final was removed from the declaration of 'attendee '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String attendee; - //UPGRADE_NOTE: Final was removed from the declaration of 'title '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String title; - - public CalendarParsedResult(System.String summary, System.String start, System.String end, System.String location, System.String attendee, System.String title):base(ParsedResultType.CALENDAR) - { - // Start is required, end is not - if (start == null) - { - throw new System.ArgumentException(); - } - validateDate(start); - validateDate(end); - this.summary = summary; - this.start = start; - this.end = end; - this.location = location; - this.attendee = attendee; - this.title = title; - } - - /// RFC 2445 allows the start and end fields to be of type DATE (e.g. 20081021) or DATE-TIME - /// (e.g. 20081021T123000 for local time, or 20081021T123000Z for UTC). - /// - /// - /// The string to validate - /// - private static void validateDate(System.String date) - { - if (date != null) - { - int length = date.Length; - if (length != 8 && length != 15 && length != 16) - { - throw new System.ArgumentException(); - } - for (int i = 0; i < 8; i++) - { - if (!System.Char.IsDigit(date[i])) - { - throw new System.ArgumentException(); - } - } - if (length > 8) - { - if (date[8] != 'T') - { - throw new System.ArgumentException(); - } - for (int i = 9; i < 15; i++) - { - if (!System.Char.IsDigit(date[i])) - { - throw new System.ArgumentException(); - } - } - if (length == 16 && date[15] != 'Z') - { - throw new System.ArgumentException(); - } - } - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/EmailAddressParsedResult.cs b/zxing-csharp/client/result/EmailAddressParsedResult.cs deleted file mode 100644 index 3322012..0000000 --- a/zxing-csharp/client/result/EmailAddressParsedResult.cs +++ /dev/null @@ -1,88 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class EmailAddressParsedResult:ParsedResult - { - public System.String EmailAddress - { - get - { - return emailAddress; - } - - } - public System.String Subject - { - get - { - return subject; - } - - } - public System.String Body - { - get - { - return body; - } - - } - public System.String MailtoURI - { - get - { - return mailtoURI; - } - - } - override public System.String DisplayResult - { - get - { - System.Text.StringBuilder result = new System.Text.StringBuilder(30); - maybeAppend(emailAddress, result); - maybeAppend(subject, result); - maybeAppend(body, result); - return result.ToString(); - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'emailAddress '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String emailAddress; - //UPGRADE_NOTE: Final was removed from the declaration of 'subject '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String subject; - //UPGRADE_NOTE: Final was removed from the declaration of 'body '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String body; - //UPGRADE_NOTE: Final was removed from the declaration of 'mailtoURI '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String mailtoURI; - - internal EmailAddressParsedResult(System.String emailAddress, System.String subject, System.String body, System.String mailtoURI):base(ParsedResultType.EMAIL_ADDRESS) - { - this.emailAddress = emailAddress; - this.subject = subject; - this.body = body; - this.mailtoURI = mailtoURI; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/EmailAddressResultParser.cs b/zxing-csharp/client/result/EmailAddressResultParser.cs deleted file mode 100644 index dff4546..0000000 --- a/zxing-csharp/client/result/EmailAddressResultParser.cs +++ /dev/null @@ -1,74 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Represents a result that encodes an e-mail address, either as a plain address - /// like "joe@example.org" or a mailto: URL like "mailto:joe@example.org". - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class EmailAddressResultParser:ResultParser - { - - public static EmailAddressParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null) - { - return null; - } - System.String emailAddress; - if (rawText.StartsWith("mailto:") || rawText.StartsWith("MAILTO:")) - { - // If it starts with mailto:, assume it is definitely trying to be an email address - emailAddress = rawText.Substring(7); - int queryStart = emailAddress.IndexOf('?'); - if (queryStart >= 0) - { - emailAddress = emailAddress.Substring(0, (queryStart) - (0)); - } - System.Collections.Hashtable nameValues = parseNameValuePairs(rawText); - System.String subject = null; - System.String body = null; - if (nameValues != null) - { - if (emailAddress.Length == 0) - { - emailAddress = ((System.String) nameValues["to"]); - } - subject = ((System.String) nameValues["subject"]); - body = ((System.String) nameValues["body"]); - } - return new EmailAddressParsedResult(emailAddress, subject, body, rawText); - } - else - { - if (!EmailDoCoMoResultParser.isBasicallyValidEmailAddress(rawText)) - { - return null; - } - emailAddress = rawText; - return new EmailAddressParsedResult(emailAddress, null, null, "mailto:" + emailAddress); - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/EmailDoCoMoResultParser.cs b/zxing-csharp/client/result/EmailDoCoMoResultParser.cs deleted file mode 100644 index adb065f..0000000 --- a/zxing-csharp/client/result/EmailDoCoMoResultParser.cs +++ /dev/null @@ -1,101 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Implements the "MATMSG" email message entry format. - /// - /// Supported keys: TO, SUB, BODY - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class EmailDoCoMoResultParser:AbstractDoCoMoResultParser - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'ATEXT_SYMBOLS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] ATEXT_SYMBOLS = new char[]{'@', '.', '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~'}; - - public static EmailAddressParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null || !rawText.StartsWith("MATMSG:")) - { - return null; - } - System.String[] rawTo = matchDoCoMoPrefixedField("TO:", rawText, true); - if (rawTo == null) - { - return null; - } - System.String to = rawTo[0]; - if (!isBasicallyValidEmailAddress(to)) - { - return null; - } - System.String subject = matchSingleDoCoMoPrefixedField("SUB:", rawText, false); - System.String body = matchSingleDoCoMoPrefixedField("BODY:", rawText, false); - return new EmailAddressParsedResult(to, subject, body, "mailto:" + to); - } - - /// This implements only the most basic checking for an email address's validity -- that it contains - /// an '@' contains no characters disallowed by RFC 2822. This is an overly lenient definition of - /// validity. We want to generally be lenient here since this class is only intended to encapsulate what's - /// in a barcode, not "judge" it. - /// - internal static bool isBasicallyValidEmailAddress(System.String email) - { - if (email == null) - { - return false; - } - bool atFound = false; - for (int i = 0; i < email.Length; i++) - { - char c = email[i]; - if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && !isAtextSymbol(c)) - { - return false; - } - if (c == '@') - { - if (atFound) - { - return false; - } - atFound = true; - } - } - return atFound; - } - - private static bool isAtextSymbol(char c) - { - for (int i = 0; i < ATEXT_SYMBOLS.Length; i++) - { - if (c == ATEXT_SYMBOLS[i]) - { - return true; - } - } - return false; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/GeoParsedResult.cs b/zxing-csharp/client/result/GeoParsedResult.cs deleted file mode 100644 index da4f217..0000000 --- a/zxing-csharp/client/result/GeoParsedResult.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class GeoParsedResult:ParsedResult - { - public System.String GeoURI - { - get - { - return geoURI; - } - - } - /// latitude in degrees - /// - public double Latitude - { - get - { - return latitude; - } - - } - /// longitude in degrees - /// - public double Longitude - { - get - { - return longitude; - } - - } - /// altitude in meters. If not specified, in the geo URI, returns 0.0 - /// - public double Altitude - { - get - { - return altitude; - } - - } - override public System.String DisplayResult - { - get - { - System.Text.StringBuilder result = new System.Text.StringBuilder(50); - result.Append(latitude); - result.Append(", "); - result.Append(longitude); - if (altitude > 0.0f) - { - result.Append(", "); - result.Append(altitude); - result.Append('m'); - } - return result.ToString(); - } - - /// a URI link to Google Maps which display the point on the Earth described - /// by this instance, and sets the zoom level in a way that roughly reflects the - /// altitude, if specified - /// - /* - public String getGoogleMapsURI() { - StringBuffer result = new StringBuffer(50); - result.append("http://maps.google.com/?ll="); - result.append(latitude); - result.append(','); - result.append(longitude); - if (altitude > 0.0f) { - // Map altitude to zoom level, cleverly. Roughly, zoom level 19 is like a - // view from 1000ft, 18 is like 2000ft, 17 like 4000ft, and so on. - double altitudeInFeet = altitude * 3.28; - int altitudeInKFeet = (int) (altitudeInFeet / 1000.0); - // No Math.log() available here, so compute log base 2 the old fashioned way - // Here logBaseTwo will take on a value between 0 and 18 actually - int logBaseTwo = 0; - while (altitudeInKFeet > 1 && logBaseTwo < 18) { - altitudeInKFeet >>= 1; - logBaseTwo++; - } - int zoom = 19 - logBaseTwo; - result.append("&z="); - result.append(zoom); - } - return result.toString(); - } - */ - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'geoURI '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String geoURI; - //UPGRADE_NOTE: Final was removed from the declaration of 'latitude '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private double latitude; - //UPGRADE_NOTE: Final was removed from the declaration of 'longitude '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private double longitude; - //UPGRADE_NOTE: Final was removed from the declaration of 'altitude '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private double altitude; - - internal GeoParsedResult(System.String geoURI, double latitude, double longitude, double altitude):base(ParsedResultType.GEO) - { - this.geoURI = geoURI; - this.latitude = latitude; - this.longitude = longitude; - this.altitude = altitude; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/GeoResultParser.cs b/zxing-csharp/client/result/GeoResultParser.cs deleted file mode 100644 index ebfbc5b..0000000 --- a/zxing-csharp/client/result/GeoResultParser.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Parses a "geo:" URI result, which specifies a location on the surface of - /// the Earth as well as an optional altitude above the surface. See - /// - /// http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class GeoResultParser:ResultParser - { - - private GeoResultParser() - { - } - - public static GeoParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null || (!rawText.StartsWith("geo:") && !rawText.StartsWith("GEO:"))) - { - return null; - } - // Drop geo, query portion - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - int queryStart = rawText.IndexOf('?', 4); - System.String geoURIWithoutQuery = queryStart < 0?rawText.Substring(4):rawText.Substring(4, (queryStart) - (4)); - int latitudeEnd = geoURIWithoutQuery.IndexOf(','); - if (latitudeEnd < 0) - { - return null; - } - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - int longitudeEnd = geoURIWithoutQuery.IndexOf(',', latitudeEnd + 1); - double latitude, longitude, altitude; - try - { - latitude = System.Double.Parse(geoURIWithoutQuery.Substring(0, (latitudeEnd) - (0))); - if (longitudeEnd < 0) - { - longitude = System.Double.Parse(geoURIWithoutQuery.Substring(latitudeEnd + 1)); - altitude = 0.0; - } - else - { - longitude = System.Double.Parse(geoURIWithoutQuery.Substring(latitudeEnd + 1, (longitudeEnd) - (latitudeEnd + 1))); - altitude = System.Double.Parse(geoURIWithoutQuery.Substring(longitudeEnd + 1)); - } - } - catch (System.FormatException nfe) - { - return null; - } - return new GeoParsedResult(rawText.StartsWith("GEO:")?"geo:" + rawText.Substring(4):rawText, latitude, longitude, altitude); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/ISBNParsedResult.cs b/zxing-csharp/client/result/ISBNParsedResult.cs deleted file mode 100644 index 75b5f8b..0000000 --- a/zxing-csharp/client/result/ISBNParsedResult.cs +++ /dev/null @@ -1,51 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// jbreiden@google.com (Jeff Breidenbach) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class ISBNParsedResult:ParsedResult - { - public System.String ISBN - { - get - { - return isbn; - } - - } - override public System.String DisplayResult - { - get - { - return isbn; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'isbn '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String isbn; - - internal ISBNParsedResult(System.String isbn):base(ParsedResultType.ISBN) - { - this.isbn = isbn; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/ISBNResultParser.cs b/zxing-csharp/client/result/ISBNResultParser.cs deleted file mode 100644 index 54f26d6..0000000 --- a/zxing-csharp/client/result/ISBNResultParser.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Parses strings of digits that represent a ISBN. - /// - /// - /// jbreiden@google.com (Jeff Breidenbach) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public class ISBNResultParser:ResultParser - { - - private ISBNResultParser() - { - } - - // ISBN-13 For Dummies - // http://www.bisg.org/isbn-13/for.dummies.html - public static ISBNParsedResult parse(Result result) - { - BarcodeFormat format = result.BarcodeFormat; - if (!BarcodeFormat.EAN_13.Equals(format)) - { - return null; - } - System.String rawText = result.Text; - if (rawText == null) - { - return null; - } - int length = rawText.Length; - if (length != 13) - { - return null; - } - if (!rawText.StartsWith("978") && !rawText.StartsWith("979")) - { - return null; - } - - return new ISBNParsedResult(rawText); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/ParsedResult.cs b/zxing-csharp/client/result/ParsedResult.cs deleted file mode 100644 index 5c522d6..0000000 --- a/zxing-csharp/client/result/ParsedResult.cs +++ /dev/null @@ -1,90 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - ///

Abstract class representing the result of decoding a barcode, as more than - /// a String -- as some type of structured data. This might be a subclass which represents - /// a URL, or an e-mail address. {@link ResultParser#parseResult(Result)} will turn a raw - /// decoded string into the most appropriate type of structured representation.

- /// - ///

Thanks to Jeff Griffin for proposing rewrite of these classes that relies less - /// on exception-based mechanisms during parsing.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public abstract class ParsedResult - { - virtual public ParsedResultType Type - { - get - { - return type; - } - - } - public abstract System.String DisplayResult{get;} - - //UPGRADE_NOTE: Final was removed from the declaration of 'type '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ParsedResultType type; - - protected internal ParsedResult(ParsedResultType type) - { - this.type = type; - } - - public override System.String ToString() - { - return DisplayResult; - } - - public static void maybeAppend(System.String value_Renamed, System.Text.StringBuilder result) - { - if (value_Renamed != null && value_Renamed.Length > 0) - { - // Don't add a newline before the first value - if (result.Length > 0) - { - result.Append('\n'); - } - result.Append(value_Renamed); - } - } - - public static void maybeAppend(System.String[] value_Renamed, System.Text.StringBuilder result) - { - if (value_Renamed != null) - { - for (int i = 0; i < value_Renamed.Length; i++) - { - if (value_Renamed[i] != null && value_Renamed[i].Length > 0) - { - if (result.Length > 0) - { - result.Append('\n'); - } - result.Append(value_Renamed[i]); - } - } - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/ParsedResultType.cs b/zxing-csharp/client/result/ParsedResultType.cs deleted file mode 100644 index fd962b5..0000000 --- a/zxing-csharp/client/result/ParsedResultType.cs +++ /dev/null @@ -1,72 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// Represents the type of data encoded by a barcode -- from plain text, to a - /// URI, to an e-mail address, etc. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class ParsedResultType - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'ADDRESSBOOK '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType ADDRESSBOOK = new ParsedResultType("ADDRESSBOOK"); - //UPGRADE_NOTE: Final was removed from the declaration of 'EMAIL_ADDRESS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType EMAIL_ADDRESS = new ParsedResultType("EMAIL_ADDRESS"); - //UPGRADE_NOTE: Final was removed from the declaration of 'PRODUCT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType PRODUCT = new ParsedResultType("PRODUCT"); - //UPGRADE_NOTE: Final was removed from the declaration of 'URI '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType URI = new ParsedResultType("URI"); - //UPGRADE_NOTE: Final was removed from the declaration of 'TEXT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType TEXT = new ParsedResultType("TEXT"); - //UPGRADE_NOTE: Final was removed from the declaration of 'ANDROID_INTENT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType ANDROID_INTENT = new ParsedResultType("ANDROID_INTENT"); - //UPGRADE_NOTE: Final was removed from the declaration of 'GEO '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType GEO = new ParsedResultType("GEO"); - //UPGRADE_NOTE: Final was removed from the declaration of 'TEL '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType TEL = new ParsedResultType("TEL"); - //UPGRADE_NOTE: Final was removed from the declaration of 'SMS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType SMS = new ParsedResultType("SMS"); - //UPGRADE_NOTE: Final was removed from the declaration of 'CALENDAR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType CALENDAR = new ParsedResultType("CALENDAR"); - // "optional" types - //UPGRADE_NOTE: Final was removed from the declaration of 'NDEF_SMART_POSTER '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType NDEF_SMART_POSTER = new ParsedResultType("NDEF_SMART_POSTER"); - //UPGRADE_NOTE: Final was removed from the declaration of 'MOBILETAG_RICH_WEB '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType MOBILETAG_RICH_WEB = new ParsedResultType("MOBILETAG_RICH_WEB"); - //UPGRADE_NOTE: Final was removed from the declaration of 'ISBN '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ParsedResultType ISBN = new ParsedResultType("ISBN"); - - //UPGRADE_NOTE: Final was removed from the declaration of 'name '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String name; - - private ParsedResultType(System.String name) - { - this.name = name; - } - - public override System.String ToString() - { - return name; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/ProductParsedResult.cs b/zxing-csharp/client/result/ProductParsedResult.cs deleted file mode 100644 index 3781f93..0000000 --- a/zxing-csharp/client/result/ProductParsedResult.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class ProductParsedResult:ParsedResult - { - public System.String ProductID - { - get - { - return productID; - } - - } - public System.String NormalizedProductID - { - get - { - return normalizedProductID; - } - - } - override public System.String DisplayResult - { - get - { - return productID; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'productID '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String productID; - //UPGRADE_NOTE: Final was removed from the declaration of 'normalizedProductID '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String normalizedProductID; - - internal ProductParsedResult(System.String productID):this(productID, productID) - { - } - - internal ProductParsedResult(System.String productID, System.String normalizedProductID):base(ParsedResultType.PRODUCT) - { - this.productID = productID; - this.normalizedProductID = normalizedProductID; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/ProductResultParser.cs b/zxing-csharp/client/result/ProductResultParser.cs deleted file mode 100644 index 8a80928..0000000 --- a/zxing-csharp/client/result/ProductResultParser.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using Result = com.google.zxing.Result; -using UPCEReader = com.google.zxing.oned.UPCEReader; -namespace com.google.zxing.client.result -{ - - /// Parses strings of digits that represent a UPC code. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class ProductResultParser:ResultParser - { - - private ProductResultParser() - { - } - - // Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes. - public static ProductParsedResult parse(Result result) - { - BarcodeFormat format = result.BarcodeFormat; - if (!(BarcodeFormat.UPC_A.Equals(format) || BarcodeFormat.UPC_E.Equals(format) || BarcodeFormat.EAN_8.Equals(format) || BarcodeFormat.EAN_13.Equals(format))) - { - return null; - } - // Really neither of these should happen: - System.String rawText = result.Text; - if (rawText == null) - { - return null; - } - - int length = rawText.Length; - for (int x = 0; x < length; x++) - { - char c = rawText[x]; - if (c < '0' || c > '9') - { - return null; - } - } - // Not actually checking the checksum again here - - System.String normalizedProductID; - // Expand UPC-E for purposes of searching - if (BarcodeFormat.UPC_E.Equals(format)) - { - normalizedProductID = UPCEReader.convertUPCEtoUPCA(rawText); - } - else - { - normalizedProductID = rawText; - } - - return new ProductParsedResult(rawText, normalizedProductID); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/ResultParser.cs b/zxing-csharp/client/result/ResultParser.cs deleted file mode 100644 index 0cd4de1..0000000 --- a/zxing-csharp/client/result/ResultParser.cs +++ /dev/null @@ -1,415 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - ///

Abstract class representing the result of decoding a barcode, as more than - /// a String -- as some type of structured data. This might be a subclass which represents - /// a URL, or an e-mail address. {@link #parseResult(com.google.zxing.Result)} will turn a raw - /// decoded string into the most appropriate type of structured representation.

- /// - ///

Thanks to Jeff Griffin for proposing rewrite of these classes that relies less - /// on exception-based mechanisms during parsing.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public abstract class ResultParser - { - - public static ParsedResult parseResult(Result theResult) - { - // This is a bit messy, but given limited options in MIDP / CLDC, this may well be the simplest - // way to go about this. For example, we have no reflection available, really. - // Order is important here. - ParsedResult result; - if ((result = BookmarkDoCoMoResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = AddressBookDoCoMoResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = EmailDoCoMoResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = AddressBookAUResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = VCardResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = BizcardResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = VEventResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = EmailAddressResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = TelResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = SMSMMSResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = GeoResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = URLTOResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = URIResultParser.parse(theResult)) != null) - { - return result; - } - else if ((result = ISBNResultParser.parse(theResult)) != null) - { - // We depend on ISBN parsing coming before UPC, as it is a subset. - return result; - } - else if ((result = ProductResultParser.parse(theResult)) != null) - { - return result; - } - return new TextParsedResult(theResult.Text, null); - } - - protected internal static void maybeAppend(System.String value_Renamed, System.Text.StringBuilder result) - { - if (value_Renamed != null) - { - result.Append('\n'); - result.Append(value_Renamed); - } - } - - protected internal static void maybeAppend(System.String[] value_Renamed, System.Text.StringBuilder result) - { - if (value_Renamed != null) - { - for (int i = 0; i < value_Renamed.Length; i++) - { - result.Append('\n'); - result.Append(value_Renamed[i]); - } - } - } - - protected internal static System.String[] maybeWrap(System.String value_Renamed) - { - return value_Renamed == null?null:new System.String[]{value_Renamed}; - } - - protected internal static System.String unescapeBackslash(System.String escaped) - { - if (escaped != null) - { - int backslash = escaped.IndexOf('\\'); - if (backslash >= 0) - { - int max = escaped.Length; - System.Text.StringBuilder unescaped = new System.Text.StringBuilder(max - 1); - unescaped.Append(escaped.ToCharArray(), 0, backslash); - bool nextIsEscaped = false; - for (int i = backslash; i < max; i++) - { - char c = escaped[i]; - if (nextIsEscaped || c != '\\') - { - unescaped.Append(c); - nextIsEscaped = false; - } - else - { - nextIsEscaped = true; - } - } - return unescaped.ToString(); - } - } - return escaped; - } - - private static System.String urlDecode(System.String escaped) - { - - // No we can't use java.net.URLDecoder here. JavaME doesn't have it. - if (escaped == null) - { - return null; - } - char[] escapedArray = escaped.ToCharArray(); - - int first = findFirstEscape(escapedArray); - if (first < 0) - { - return escaped; - } - - int max = escapedArray.Length; - // final length is at most 2 less than original due to at least 1 unescaping - System.Text.StringBuilder unescaped = new System.Text.StringBuilder(max - 2); - // Can append everything up to first escape character - unescaped.Append(escapedArray, 0, first); - - for (int i = first; i < max; i++) - { - char c = escapedArray[i]; - if (c == '+') - { - // + is translated directly into a space - unescaped.Append(' '); - } - else if (c == '%') - { - // Are there even two more chars? if not we will just copy the escaped sequence and be done - if (i >= max - 2) - { - unescaped.Append('%'); // append that % and move on - } - else - { - int firstDigitValue = parseHexDigit(escapedArray[++i]); - int secondDigitValue = parseHexDigit(escapedArray[++i]); - if (firstDigitValue < 0 || secondDigitValue < 0) - { - // bad digit, just move on - unescaped.Append('%'); - unescaped.Append(escapedArray[i - 1]); - unescaped.Append(escapedArray[i]); - } - unescaped.Append((char) ((firstDigitValue << 4) + secondDigitValue)); - } - } - else - { - unescaped.Append(c); - } - } - return unescaped.ToString(); - } - - private static int findFirstEscape(char[] escapedArray) - { - int max = escapedArray.Length; - for (int i = 0; i < max; i++) - { - char c = escapedArray[i]; - if (c == '+' || c == '%') - { - return i; - } - } - return - 1; - } - - private static int parseHexDigit(char c) - { - if (c >= 'a') - { - if (c <= 'f') - { - return 10 + (c - 'a'); - } - } - else if (c >= 'A') - { - if (c <= 'F') - { - return 10 + (c - 'A'); - } - } - else if (c >= '0') - { - if (c <= '9') - { - return c - '0'; - } - } - return - 1; - } - - protected internal static bool isStringOfDigits(System.String value_Renamed, int length) - { - if (value_Renamed == null) - { - return false; - } - int stringLength = value_Renamed.Length; - if (length != stringLength) - { - return false; - } - for (int i = 0; i < length; i++) - { - char c = value_Renamed[i]; - if (c < '0' || c > '9') - { - return false; - } - } - return true; - } - - protected internal static bool isSubstringOfDigits(System.String value_Renamed, int offset, int length) - { - if (value_Renamed == null) - { - return false; - } - int stringLength = value_Renamed.Length; - int max = offset + length; - if (stringLength < max) - { - return false; - } - for (int i = offset; i < max; i++) - { - char c = value_Renamed[i]; - if (c < '0' || c > '9') - { - return false; - } - } - return true; - } - - internal static System.Collections.Hashtable parseNameValuePairs(System.String uri) - { - int paramStart = uri.IndexOf('?'); - if (paramStart < 0) - { - return null; - } - System.Collections.Hashtable result = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable(3)); - paramStart++; - int paramEnd; - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - while ((paramEnd = uri.IndexOf('&', paramStart)) >= 0) - { - appendKeyValue(uri, paramStart, paramEnd, result); - paramStart = paramEnd + 1; - } - appendKeyValue(uri, paramStart, uri.Length, result); - return result; - } - - private static void appendKeyValue(System.String uri, int paramStart, int paramEnd, System.Collections.Hashtable result) - { - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - int separator = uri.IndexOf('=', paramStart); - if (separator >= 0) - { - // key = value - System.String key = uri.Substring(paramStart, (separator) - (paramStart)); - System.String value_Renamed = uri.Substring(separator + 1, (paramEnd) - (separator + 1)); - value_Renamed = urlDecode(value_Renamed); - result[key] = value_Renamed; - } - // Can't put key, null into a hashtable - } - - internal static System.String[] matchPrefixedField(System.String prefix, System.String rawText, char endChar, bool trim) - { - System.Collections.ArrayList matches = null; - int i = 0; - int max = rawText.Length; - while (i < max) - { - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - i = rawText.IndexOf(prefix, i); - if (i < 0) - { - break; - } - i += prefix.Length; // Skip past this prefix we found to start - int start = i; // Found the start of a match here - bool done = false; - while (!done) - { - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - i = rawText.IndexOf((System.Char) endChar, i); - if (i < 0) - { - // No terminating end character? uh, done. Set i such that loop terminates and break - i = rawText.Length; - done = true; - } - else if (rawText[i - 1] == '\\') - { - // semicolon was escaped so continue - i++; - } - else - { - // found a match - if (matches == null) - { - matches = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(3)); // lazy init - } - System.String element = unescapeBackslash(rawText.Substring(start, (i) - (start))); - if (trim) - { - element = element.Trim(); - } - matches.Add(element); - i++; - done = true; - } - } - } - if (matches == null || (matches.Count == 0)) - { - return null; - } - return toStringArray(matches); - } - - internal static System.String matchSinglePrefixedField(System.String prefix, System.String rawText, char endChar, bool trim) - { - System.String[] matches = matchPrefixedField(prefix, rawText, endChar, trim); - return matches == null?null:matches[0]; - } - - internal static System.String[] toStringArray(System.Collections.ArrayList strings) - { - int size = strings.Count; - System.String[] result = new System.String[size]; - for (int j = 0; j < size; j++) - { - result[j] = ((System.String) strings[j]); - } - return result; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/SMSMMSResultParser.cs b/zxing-csharp/client/result/SMSMMSResultParser.cs deleted file mode 100644 index 3719e11..0000000 --- a/zxing-csharp/client/result/SMSMMSResultParser.cs +++ /dev/null @@ -1,123 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - ///

Parses an "sms:" URI result, which specifies a number to SMS and optional - /// "via" number. See - /// the IETF draft on this.

- /// - ///

This actually also parses URIs starting with "mms:", "smsto:", "mmsto:", "SMSTO:", and - /// "MMSTO:", and treats them all the same way, and effectively converts them to an "sms:" URI - /// for purposes of forwarding to the platform.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class SMSMMSResultParser:ResultParser - { - - private SMSMMSResultParser() - { - } - - public static SMSParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null) - { - return null; - } - int prefixLength; - if (rawText.StartsWith("sms:") || rawText.StartsWith("SMS:") || rawText.StartsWith("mms:") || rawText.StartsWith("MMS:")) - { - prefixLength = 4; - } - else if (rawText.StartsWith("smsto:") || rawText.StartsWith("SMSTO:") || rawText.StartsWith("mmsto:") || rawText.StartsWith("MMSTO:")) - { - prefixLength = 6; - } - else - { - return null; - } - - // Check up front if this is a URI syntax string with query arguments - System.Collections.Hashtable nameValuePairs = parseNameValuePairs(rawText); - System.String subject = null; - System.String body = null; - bool querySyntax = false; - if (nameValuePairs != null && !(nameValuePairs.Count == 0)) - { - subject = ((System.String) nameValuePairs["subject"]); - body = ((System.String) nameValuePairs["body"]); - querySyntax = true; - } - - // Drop sms, query portion - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - int queryStart = rawText.IndexOf('?', prefixLength); - System.String smsURIWithoutQuery; - // If it's not query syntax, the question mark is part of the subject or message - if (queryStart < 0 || !querySyntax) - { - smsURIWithoutQuery = rawText.Substring(prefixLength); - } - else - { - smsURIWithoutQuery = rawText.Substring(prefixLength, (queryStart) - (prefixLength)); - } - int numberEnd = smsURIWithoutQuery.IndexOf(';'); - System.String number; - System.String via; - if (numberEnd < 0) - { - number = smsURIWithoutQuery; - via = null; - } - else - { - number = smsURIWithoutQuery.Substring(0, (numberEnd) - (0)); - System.String maybeVia = smsURIWithoutQuery.Substring(numberEnd + 1); - if (maybeVia.StartsWith("via=")) - { - via = maybeVia.Substring(4); - } - else - { - via = null; - } - } - - // Thanks to dominik.wild for suggesting this enhancement to support - // smsto:number:body URIs - if (body == null) - { - int bodyStart = number.IndexOf(':'); - if (bodyStart >= 0) - { - body = number.Substring(bodyStart + 1); - number = number.Substring(0, (bodyStart) - (0)); - } - } - return new SMSParsedResult("sms:" + number, number, via, subject, body, null); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/SMSParsedResult.cs b/zxing-csharp/client/result/SMSParsedResult.cs deleted file mode 100644 index c42eb28..0000000 --- a/zxing-csharp/client/result/SMSParsedResult.cs +++ /dev/null @@ -1,112 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class SMSParsedResult:ParsedResult - { - public System.String SMSURI - { - get - { - return smsURI; - } - - } - public System.String Number - { - get - { - return number; - } - - } - public System.String Via - { - get - { - return via; - } - - } - public System.String Subject - { - get - { - return subject; - } - - } - public System.String Body - { - get - { - return body; - } - - } - public System.String Title - { - get - { - return title; - } - - } - override public System.String DisplayResult - { - get - { - System.Text.StringBuilder result = new System.Text.StringBuilder(100); - maybeAppend(number, result); - maybeAppend(via, result); - maybeAppend(subject, result); - maybeAppend(body, result); - maybeAppend(title, result); - return result.ToString(); - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'smsURI '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String smsURI; - //UPGRADE_NOTE: Final was removed from the declaration of 'number '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String number; - //UPGRADE_NOTE: Final was removed from the declaration of 'via '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String via; - //UPGRADE_NOTE: Final was removed from the declaration of 'subject '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String subject; - //UPGRADE_NOTE: Final was removed from the declaration of 'body '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String body; - //UPGRADE_NOTE: Final was removed from the declaration of 'title '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String title; - - public SMSParsedResult(System.String smsURI, System.String number, System.String via, System.String subject, System.String body, System.String title):base(ParsedResultType.SMS) - { - this.smsURI = smsURI; - this.number = number; - this.via = via; - this.subject = subject; - this.body = body; - this.title = title; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/TelParsedResult.cs b/zxing-csharp/client/result/TelParsedResult.cs deleted file mode 100644 index 6c00ed4..0000000 --- a/zxing-csharp/client/result/TelParsedResult.cs +++ /dev/null @@ -1,76 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class TelParsedResult:ParsedResult - { - public System.String Number - { - get - { - return number; - } - - } - public System.String TelURI - { - get - { - return telURI; - } - - } - public System.String Title - { - get - { - return title; - } - - } - override public System.String DisplayResult - { - get - { - System.Text.StringBuilder result = new System.Text.StringBuilder(20); - maybeAppend(number, result); - maybeAppend(title, result); - return result.ToString(); - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'number '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String number; - //UPGRADE_NOTE: Final was removed from the declaration of 'telURI '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String telURI; - //UPGRADE_NOTE: Final was removed from the declaration of 'title '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String title; - - public TelParsedResult(System.String number, System.String telURI, System.String title):base(ParsedResultType.TEL) - { - this.number = number; - this.telURI = telURI; - this.title = title; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/TelResultParser.cs b/zxing-csharp/client/result/TelResultParser.cs deleted file mode 100644 index 0a472db..0000000 --- a/zxing-csharp/client/result/TelResultParser.cs +++ /dev/null @@ -1,51 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Parses a "tel:" URI result, which specifies a phone number. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class TelResultParser:ResultParser - { - - private TelResultParser() - { - } - - public static TelParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null || (!rawText.StartsWith("tel:") && !rawText.StartsWith("TEL:"))) - { - return null; - } - // Normalize "TEL:" to "tel:" - System.String telURI = rawText.StartsWith("TEL:")?"tel:" + rawText.Substring(4):rawText; - // Drop tel, query portion - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - int queryStart = rawText.IndexOf('?', 4); - System.String number = queryStart < 0?rawText.Substring(4):rawText.Substring(4, (queryStart) - (4)); - return new TelParsedResult(number, telURI, null); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/TextParsedResult.cs b/zxing-csharp/client/result/TextParsedResult.cs deleted file mode 100644 index 806eb2c..0000000 --- a/zxing-csharp/client/result/TextParsedResult.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// A simple result type encapsulating a string that has no further - /// interpretation. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class TextParsedResult:ParsedResult - { - public System.String Text - { - get - { - return text; - } - - } - public System.String Language - { - get - { - return language; - } - - } - override public System.String DisplayResult - { - get - { - return text; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'text '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String text; - //UPGRADE_NOTE: Final was removed from the declaration of 'language '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String language; - - public TextParsedResult(System.String text, System.String language):base(ParsedResultType.TEXT) - { - this.text = text; - this.language = language; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/URIParsedResult.cs b/zxing-csharp/client/result/URIParsedResult.cs deleted file mode 100644 index ea8cdff..0000000 --- a/zxing-csharp/client/result/URIParsedResult.cs +++ /dev/null @@ -1,148 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class URIParsedResult:ParsedResult - { - public System.String URI - { - get - { - return uri; - } - - } - public System.String Title - { - get - { - return title; - } - - } - /// true if the URI contains suspicious patterns that may suggest it intends to - /// mislead the user about its true nature. At the moment this looks for the presence - /// of user/password syntax in the host/authority portion of a URI which may be used - /// in attempts to make the URI's host appear to be other than it is. Example: - /// http://yourbank.com@phisher.com This URI connects to phisher.com but may appear - /// to connect to yourbank.com at first glance. - /// - public bool PossiblyMaliciousURI - { - get - { - return containsUser(); - } - - } - override public System.String DisplayResult - { - get - { - System.Text.StringBuilder result = new System.Text.StringBuilder(30); - maybeAppend(title, result); - maybeAppend(uri, result); - return result.ToString(); - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'uri '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String uri; - //UPGRADE_NOTE: Final was removed from the declaration of 'title '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String title; - - public URIParsedResult(System.String uri, System.String title):base(ParsedResultType.URI) - { - this.uri = massageURI(uri); - this.title = title; - } - - private bool containsUser() - { - // This method is likely not 100% RFC compliant yet - int hostStart = uri.IndexOf(':'); // we should always have scheme at this point - hostStart++; - // Skip slashes preceding host - int uriLength = uri.Length; - while (hostStart < uriLength && uri[hostStart] == '/') - { - hostStart++; - } - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - int hostEnd = uri.IndexOf('/', hostStart); - if (hostEnd < 0) - { - hostEnd = uriLength; - } - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - int at = uri.IndexOf('@', hostStart); - return at >= hostStart && at < hostEnd; - } - - /// Transforms a string that represents a URI into something more proper, by adding or canonicalizing - /// the protocol. - /// - private static System.String massageURI(System.String uri) - { - int protocolEnd = uri.IndexOf(':'); - if (protocolEnd < 0) - { - // No protocol, assume http - uri = "http://" + uri; - } - else if (isColonFollowedByPortNumber(uri, protocolEnd)) - { - // Found a colon, but it looks like it is after the host, so the protocol is still missing - uri = "http://" + uri; - } - else - { - // Lowercase protocol to avoid problems - uri = uri.Substring(0, (protocolEnd) - (0)).ToLower() + uri.Substring(protocolEnd); - } - return uri; - } - - private static bool isColonFollowedByPortNumber(System.String uri, int protocolEnd) - { - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - int nextSlash = uri.IndexOf('/', protocolEnd + 1); - if (nextSlash < 0) - { - nextSlash = uri.Length; - } - if (nextSlash <= protocolEnd + 1) - { - return false; - } - for (int x = protocolEnd + 1; x < nextSlash; x++) - { - if (uri[x] < '0' || uri[x] > '9') - { - return false; - } - } - return true; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/URIResultParser.cs b/zxing-csharp/client/result/URIResultParser.cs deleted file mode 100644 index 498513c..0000000 --- a/zxing-csharp/client/result/URIResultParser.cs +++ /dev/null @@ -1,106 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Tries to parse results that are a URI of some kind. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class URIResultParser:ResultParser - { - - private URIResultParser() - { - } - - public static URIParsedResult parse(Result result) - { - System.String rawText = result.Text; - // We specifically handle the odd "URL" scheme here for simplicity - if (rawText != null && rawText.StartsWith("URL:")) - { - rawText = rawText.Substring(4); - } - if (!isBasicallyValidURI(rawText)) - { - return null; - } - return new URIParsedResult(rawText, null); - } - - /// Determines whether a string is not obviously not a URI. This implements crude checks; this class does not - /// intend to strictly check URIs as its only function is to represent what is in a barcode, but, it does - /// need to know when a string is obviously not a URI. - /// - internal static bool isBasicallyValidURI(System.String uri) - { - if (uri == null || uri.IndexOf(' ') >= 0 || uri.IndexOf('\n') >= 0) - { - return false; - } - // Look for period in a domain but followed by at least a two-char TLD - // Forget strings that don't have a valid-looking protocol - int period = uri.IndexOf('.'); - if (period >= uri.Length - 2) - { - return false; - } - int colon = uri.IndexOf(':'); - if (period < 0 && colon < 0) - { - return false; - } - if (colon >= 0) - { - if (period < 0 || period > colon) - { - // colon ends the protocol - for (int i = 0; i < colon; i++) - { - char c = uri[i]; - if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z')) - { - return false; - } - } - } - else - { - // colon starts the port; crudely look for at least two numbers - if (colon >= uri.Length - 2) - { - return false; - } - for (int i = colon + 1; i < colon + 3; i++) - { - char c = uri[i]; - if (c < '0' || c > '9') - { - return false; - } - } - } - } - return true; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/URLTOResultParser.cs b/zxing-csharp/client/result/URLTOResultParser.cs deleted file mode 100644 index 9f3eea6..0000000 --- a/zxing-csharp/client/result/URLTOResultParser.cs +++ /dev/null @@ -1,55 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Parses the "URLTO" result format, which is of the form "URLTO:[title]:[url]". - /// This seems to be used sometimes, but I am not able to find documentation - /// on its origin or official format? - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class URLTOResultParser - { - - private URLTOResultParser() - { - } - - public static URIParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null || (!rawText.StartsWith("urlto:") && !rawText.StartsWith("URLTO:"))) - { - return null; - } - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - int titleEnd = rawText.IndexOf(':', 6); - if (titleEnd < 0) - { - return null; - } - System.String title = titleEnd <= 6?null:rawText.Substring(6, (titleEnd) - (6)); - System.String uri = rawText.Substring(titleEnd + 1); - return new URIParsedResult(uri, title); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/VCardResultParser.cs b/zxing-csharp/client/result/VCardResultParser.cs deleted file mode 100644 index 66480e4..0000000 --- a/zxing-csharp/client/result/VCardResultParser.cs +++ /dev/null @@ -1,230 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Parses contact information formatted according to the VCard (2.1) format. This is not a complete - /// implementation but should parse information as commonly encoded in 2D barcodes. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class VCardResultParser:ResultParser - { - - private VCardResultParser() - { - } - - public static AddressBookParsedResult parse(Result result) - { - // Although we should insist on the raw text ending with "END:VCARD", there's no reason - // to throw out everything else we parsed just because this was omitted. In fact, Eclair - // is doing just that, and we can't parse its contacts without this leniency. - System.String rawText = result.Text; - if (rawText == null || !rawText.StartsWith("BEGIN:VCARD")) - { - return null; - } - System.String[] names = matchVCardPrefixedField("FN", rawText, true); - if (names == null) - { - // If no display names found, look for regular name fields and format them - names = matchVCardPrefixedField("N", rawText, true); - formatNames(names); - } - System.String[] phoneNumbers = matchVCardPrefixedField("TEL", rawText, true); - System.String[] emails = matchVCardPrefixedField("EMAIL", rawText, true); - System.String note = matchSingleVCardPrefixedField("NOTE", rawText, false); - System.String[] addresses = matchVCardPrefixedField("ADR", rawText, true); - if (addresses != null) - { - for (int i = 0; i < addresses.Length; i++) - { - addresses[i] = formatAddress(addresses[i]); - } - } - System.String org = matchSingleVCardPrefixedField("ORG", rawText, true); - System.String birthday = matchSingleVCardPrefixedField("BDAY", rawText, true); - if (!isLikeVCardDate(birthday)) - { - birthday = null; - } - System.String title = matchSingleVCardPrefixedField("TITLE", rawText, true); - System.String url = matchSingleVCardPrefixedField("URL", rawText, true); - return new AddressBookParsedResult(names, null, phoneNumbers, emails, note, addresses, org, birthday, title, url); - } - - private static System.String[] matchVCardPrefixedField(System.String prefix, System.String rawText, bool trim) - { - System.Collections.ArrayList matches = null; - int i = 0; - int max = rawText.Length; - while (i < max) - { - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - i = rawText.IndexOf(prefix, i); - if (i < 0) - { - break; - } - if (i > 0 && rawText[i - 1] != '\n') - { - // then this didn't start a new token, we matched in the middle of something - i++; - continue; - } - i += prefix.Length; // Skip past this prefix we found to start - if (rawText[i] != ':' && rawText[i] != ';') - { - continue; - } - while (rawText[i] != ':') - { - // Skip until a colon - i++; - } - i++; // skip colon - int start = i; // Found the start of a match here - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - i = rawText.IndexOf('\n', i); // Really, ends in \r\n - if (i < 0) - { - // No terminating end character? uh, done. Set i such that loop terminates and break - i = max; - } - else if (i > start) - { - // found a match - if (matches == null) - { - matches = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(3)); // lazy init - } - System.String element = rawText.Substring(start, (i) - (start)); - if (trim) - { - element = element.Trim(); - } - matches.Add(element); - i++; - } - else - { - i++; - } - } - if (matches == null || (matches.Count == 0)) - { - return null; - } - return toStringArray(matches); - } - - internal static System.String matchSingleVCardPrefixedField(System.String prefix, System.String rawText, bool trim) - { - System.String[] values = matchVCardPrefixedField(prefix, rawText, trim); - return values == null?null:values[0]; - } - - private static bool isLikeVCardDate(System.String value_Renamed) - { - if (value_Renamed == null) - { - return true; - } - // Not really sure this is true but matches practice - // Mach YYYYMMDD - if (isStringOfDigits(value_Renamed, 8)) - { - return true; - } - // or YYYY-MM-DD - return value_Renamed.Length == 10 && value_Renamed[4] == '-' && value_Renamed[7] == '-' && isSubstringOfDigits(value_Renamed, 0, 4) && isSubstringOfDigits(value_Renamed, 5, 2) && isSubstringOfDigits(value_Renamed, 8, 2); - } - - private static System.String formatAddress(System.String address) - { - if (address == null) - { - return null; - } - int length = address.Length; - System.Text.StringBuilder newAddress = new System.Text.StringBuilder(length); - for (int j = 0; j < length; j++) - { - char c = address[j]; - if (c == ';') - { - newAddress.Append(' '); - } - else - { - newAddress.Append(c); - } - } - return newAddress.ToString().Trim(); - } - - /// Formats name fields of the form "Public;John;Q.;Reverend;III" into a form like - /// "Reverend John Q. Public III". - /// - /// - /// name values to format, in place - /// - private static void formatNames(System.String[] names) - { - if (names != null) - { - for (int i = 0; i < names.Length; i++) - { - System.String name = names[i]; - System.String[] components = new System.String[5]; - int start = 0; - int end; - int componentIndex = 0; - //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" - while ((end = name.IndexOf(';', start)) > 0) - { - components[componentIndex] = name.Substring(start, (end) - (start)); - componentIndex++; - start = end + 1; - } - components[componentIndex] = name.Substring(start); - System.Text.StringBuilder newName = new System.Text.StringBuilder(100); - maybeAppendComponent(components, 3, newName); - maybeAppendComponent(components, 1, newName); - maybeAppendComponent(components, 2, newName); - maybeAppendComponent(components, 0, newName); - maybeAppendComponent(components, 4, newName); - names[i] = newName.ToString().Trim(); - } - } - } - - private static void maybeAppendComponent(System.String[] components, int i, System.Text.StringBuilder newName) - { - if (components[i] != null) - { - newName.Append(' '); - newName.Append(components[i]); - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/VEventResultParser.cs b/zxing-csharp/client/result/VEventResultParser.cs deleted file mode 100644 index 83cfa63..0000000 --- a/zxing-csharp/client/result/VEventResultParser.cs +++ /dev/null @@ -1,67 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result -{ - - /// Partially implements the iCalendar format's "VEVENT" format for specifying a - /// calendar event. See RFC 2445. This supports SUMMARY, DTSTART and DTEND fields. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class VEventResultParser:ResultParser - { - - private VEventResultParser() - { - } - - public static CalendarParsedResult parse(Result result) - { - System.String rawText = result.Text; - if (rawText == null) - { - return null; - } - int vEventStart = rawText.IndexOf("BEGIN:VEVENT"); - if (vEventStart < 0) - { - return null; - } - int vEventEnd = rawText.IndexOf("END:VEVENT"); - if (vEventEnd < 0) - { - return null; - } - - System.String summary = VCardResultParser.matchSingleVCardPrefixedField("SUMMARY", rawText, true); - System.String start = VCardResultParser.matchSingleVCardPrefixedField("DTSTART", rawText, true); - System.String end = VCardResultParser.matchSingleVCardPrefixedField("DTEND", rawText, true); - try - { - return new CalendarParsedResult(summary, start, end, null, null, null); - } - catch (System.ArgumentException iae) - { - return null; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/optional/AbstractNDEFResultParser.cs b/zxing-csharp/client/result/optional/AbstractNDEFResultParser.cs deleted file mode 100644 index 8be8fa9..0000000 --- a/zxing-csharp/client/result/optional/AbstractNDEFResultParser.cs +++ /dev/null @@ -1,54 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ResultParser = com.google.zxing.client.result.ResultParser; -namespace com.google.zxing.client.result.optional -{ - - ///

Superclass for classes encapsulating results in the NDEF format. - /// See http://www.nfc-forum.org/specs/.

- /// - ///

This code supports a limited subset of NDEF messages, ones that are plausibly - /// useful in 2D barcode formats. This generally includes 1-record messages, no chunking, - /// "short record" syntax, no ID field.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - abstract class AbstractNDEFResultParser:ResultParser - { - - internal static System.String bytesToString(sbyte[] bytes, int offset, int length, System.String encoding) - { - try - { - System.String tempStr; - //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" - tempStr = System.Text.Encoding.GetEncoding(encoding).GetString(SupportClass.ToByteArray(bytes)); - return new System.String(tempStr.ToCharArray(), offset, length); - } - catch (System.IO.IOException uee) - { - // This should only be used when 'encoding' is an encoding that must necessarily - // be supported by the JVM, like UTF-8 - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.SystemException("Platform does not support required encoding: " + uee); - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/optional/NDEFRecord.cs b/zxing-csharp/client/result/optional/NDEFRecord.cs deleted file mode 100644 index 18ecf47..0000000 --- a/zxing-csharp/client/result/optional/NDEFRecord.cs +++ /dev/null @@ -1,118 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.client.result.optional -{ - - ///

Represents a record in an NDEF message. This class only supports certain types - /// of records -- namely, non-chunked records, where ID length is omitted, and only - /// "short records".

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class NDEFRecord - { - internal bool MessageBegin - { - get - { - return (header & 0x80) != 0; - } - - } - internal bool MessageEnd - { - get - { - return (header & 0x40) != 0; - } - - } - internal System.String Type - { - get - { - return type; - } - - } - internal sbyte[] Payload - { - get - { - return payload; - } - - } - internal int TotalRecordLength - { - get - { - return totalRecordLength; - } - - } - - private const int SUPPORTED_HEADER_MASK = 0x3F; // 0 0 1 1 1 111 (the bottom 6 bits matter) - private const int SUPPORTED_HEADER = 0x11; // 0 0 0 1 0 001 - - public const System.String TEXT_WELL_KNOWN_TYPE = "T"; - public const System.String URI_WELL_KNOWN_TYPE = "U"; - public const System.String SMART_POSTER_WELL_KNOWN_TYPE = "Sp"; - public const System.String ACTION_WELL_KNOWN_TYPE = "act"; - - //UPGRADE_NOTE: Final was removed from the declaration of 'header '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int header; - //UPGRADE_NOTE: Final was removed from the declaration of 'type '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String type; - //UPGRADE_NOTE: Final was removed from the declaration of 'payload '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte[] payload; - //UPGRADE_NOTE: Final was removed from the declaration of 'totalRecordLength '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int totalRecordLength; - - private NDEFRecord(int header, System.String type, sbyte[] payload, int totalRecordLength) - { - this.header = header; - this.type = type; - this.payload = payload; - this.totalRecordLength = totalRecordLength; - } - - internal static NDEFRecord readRecord(sbyte[] bytes, int offset) - { - int header = bytes[offset] & 0xFF; - // Does header match what we support in the bits we care about? - // XOR figures out where we differ, and if any of those are in the mask, fail - if (((header ^ SUPPORTED_HEADER) & SUPPORTED_HEADER_MASK) != 0) - { - return null; - } - int typeLength = bytes[offset + 1] & 0xFF; - - int payloadLength = bytes[offset + 2] & 0xFF; - - System.String type = AbstractNDEFResultParser.bytesToString(bytes, offset + 3, typeLength, "US-ASCII"); - - sbyte[] payload = new sbyte[payloadLength]; - Array.Copy(bytes, offset + 3 + typeLength, payload, 0, payloadLength); - - return new NDEFRecord(header, type, payload, 3 + typeLength + payloadLength); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/optional/NDEFSmartPosterParsedResult.cs b/zxing-csharp/client/result/optional/NDEFSmartPosterParsedResult.cs deleted file mode 100644 index 512e898..0000000 --- a/zxing-csharp/client/result/optional/NDEFSmartPosterParsedResult.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ParsedResult = com.google.zxing.client.result.ParsedResult; -using ParsedResultType = com.google.zxing.client.result.ParsedResultType; -namespace com.google.zxing.client.result.optional -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class NDEFSmartPosterParsedResult:ParsedResult - { - public System.String Title - { - get - { - return title; - } - - } - public System.String URI - { - get - { - return uri; - } - - } - public int Action - { - get - { - return action; - } - - } - override public System.String DisplayResult - { - get - { - if (title == null) - { - return uri; - } - else - { - return title + '\n' + uri; - } - } - - } - - public const int ACTION_UNSPECIFIED = - 1; - public const int ACTION_DO = 0; - public const int ACTION_SAVE = 1; - public const int ACTION_OPEN = 2; - - //UPGRADE_NOTE: Final was removed from the declaration of 'title '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String title; - //UPGRADE_NOTE: Final was removed from the declaration of 'uri '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String uri; - //UPGRADE_NOTE: Final was removed from the declaration of 'action '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int action; - - internal NDEFSmartPosterParsedResult(int action, System.String uri, System.String title):base(ParsedResultType.NDEF_SMART_POSTER) - { - this.action = action; - this.uri = uri; - this.title = title; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/optional/NDEFSmartPosterResultParser.cs b/zxing-csharp/client/result/optional/NDEFSmartPosterResultParser.cs deleted file mode 100644 index 19ff446..0000000 --- a/zxing-csharp/client/result/optional/NDEFSmartPosterResultParser.cs +++ /dev/null @@ -1,96 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -namespace com.google.zxing.client.result.optional -{ - - ///

Recognizes an NDEF message that encodes information according to the - /// "Smart Poster Record Type Definition" specification.

- /// - ///

This actually only supports some parts of the Smart Poster format: title, - /// URI, and action records. Icon records are not supported because the size - /// of these records are infeasibly large for barcodes. Size and type records - /// are not supported. Multiple titles are not supported.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class NDEFSmartPosterResultParser:AbstractNDEFResultParser - { - - public static NDEFSmartPosterParsedResult parse(Result result) - { - sbyte[] bytes = result.RawBytes; - if (bytes == null) - { - return null; - } - NDEFRecord headerRecord = NDEFRecord.readRecord(bytes, 0); - // Yes, header record starts and ends a message - if (headerRecord == null || !headerRecord.MessageBegin || !headerRecord.MessageEnd) - { - return null; - } - if (!headerRecord.Type.Equals(NDEFRecord.SMART_POSTER_WELL_KNOWN_TYPE)) - { - return null; - } - - int offset = 0; - int recordNumber = 0; - NDEFRecord ndefRecord = null; - sbyte[] payload = headerRecord.Payload; - int action = NDEFSmartPosterParsedResult.ACTION_UNSPECIFIED; - System.String title = null; - System.String uri = null; - - while (offset < payload.Length && (ndefRecord = NDEFRecord.readRecord(payload, offset)) != null) - { - if (recordNumber == 0 && !ndefRecord.MessageBegin) - { - return null; - } - - System.String type = ndefRecord.Type; - if (NDEFRecord.TEXT_WELL_KNOWN_TYPE.Equals(type)) - { - System.String[] languageText = NDEFTextResultParser.decodeTextPayload(ndefRecord.Payload); - title = languageText[1]; - } - else if (NDEFRecord.URI_WELL_KNOWN_TYPE.Equals(type)) - { - uri = NDEFURIResultParser.decodeURIPayload(ndefRecord.Payload); - } - else if (NDEFRecord.ACTION_WELL_KNOWN_TYPE.Equals(type)) - { - action = ndefRecord.Payload[0]; - } - recordNumber++; - offset += ndefRecord.TotalRecordLength; - } - - if (recordNumber == 0 || (ndefRecord != null && !ndefRecord.MessageEnd)) - { - return null; - } - - return new NDEFSmartPosterParsedResult(action, uri, title); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/optional/NDEFTextResultParser.cs b/zxing-csharp/client/result/optional/NDEFTextResultParser.cs deleted file mode 100644 index e38363b..0000000 --- a/zxing-csharp/client/result/optional/NDEFTextResultParser.cs +++ /dev/null @@ -1,65 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -using TextParsedResult = com.google.zxing.client.result.TextParsedResult; -namespace com.google.zxing.client.result.optional -{ - - /// Recognizes an NDEF message that encodes text according to the - /// "Text Record Type Definition" specification. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class NDEFTextResultParser:AbstractNDEFResultParser - { - - public static TextParsedResult parse(Result result) - { - sbyte[] bytes = result.RawBytes; - if (bytes == null) - { - return null; - } - NDEFRecord ndefRecord = NDEFRecord.readRecord(bytes, 0); - if (ndefRecord == null || !ndefRecord.MessageBegin || !ndefRecord.MessageEnd) - { - return null; - } - if (!ndefRecord.Type.Equals(NDEFRecord.TEXT_WELL_KNOWN_TYPE)) - { - return null; - } - System.String[] languageText = decodeTextPayload(ndefRecord.Payload); - return new TextParsedResult(languageText[0], languageText[1]); - } - - internal static System.String[] decodeTextPayload(sbyte[] payload) - { - sbyte statusByte = payload[0]; - bool isUTF16 = (statusByte & 0x80) != 0; - int languageLength = statusByte & 0x1F; - // language is always ASCII-encoded: - System.String language = bytesToString(payload, 1, languageLength, "US-ASCII"); - System.String encoding = isUTF16?"UTF-16":"UTF8"; - System.String text = bytesToString(payload, 1 + languageLength, payload.Length - languageLength - 1, encoding); - return new System.String[]{language, text}; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/client/result/optional/NDEFURIResultParser.cs b/zxing-csharp/client/result/optional/NDEFURIResultParser.cs deleted file mode 100644 index fabab7d..0000000 --- a/zxing-csharp/client/result/optional/NDEFURIResultParser.cs +++ /dev/null @@ -1,68 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -using URIParsedResult = com.google.zxing.client.result.URIParsedResult; -namespace com.google.zxing.client.result.optional -{ - - /// Recognizes an NDEF message that encodes a URI according to the - /// "URI Record Type Definition" specification. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class NDEFURIResultParser:AbstractNDEFResultParser - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'URI_PREFIXES'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[] URI_PREFIXES = new System.String[]{null, "http://www.", "https://www.", "http://", "https://", "tel:", "mailto:", "ftp://anonymous:anonymous@", "ftp://ftp.", "ftps://", "sftp://", "smb://", "nfs://", "ftp://", "dav://", "news:", "telnet://", "imap:", "rtsp://", "urn:", "pop:", "sip:", "sips:", "tftp:", "btspp://", "btl2cap://", "btgoep://", "tcpobex://", "irdaobex://", "file://", "urn:epc:id:", "urn:epc:tag:", "urn:epc:pat:", "urn:epc:raw:", "urn:epc:", "urn:nfc:"}; - - public static URIParsedResult parse(Result result) - { - sbyte[] bytes = result.RawBytes; - if (bytes == null) - { - return null; - } - NDEFRecord ndefRecord = NDEFRecord.readRecord(bytes, 0); - if (ndefRecord == null || !ndefRecord.MessageBegin || !ndefRecord.MessageEnd) - { - return null; - } - if (!ndefRecord.Type.Equals(NDEFRecord.URI_WELL_KNOWN_TYPE)) - { - return null; - } - System.String fullURI = decodeURIPayload(ndefRecord.Payload); - return new URIParsedResult(fullURI, null); - } - - internal static System.String decodeURIPayload(sbyte[] payload) - { - int identifierCode = payload[0] & 0xFF; - System.String prefix = null; - if (identifierCode < URI_PREFIXES.Length) - { - prefix = URI_PREFIXES[identifierCode]; - } - System.String restOfURI = bytesToString(payload, 1, payload.Length - 1, "UTF8"); - return prefix == null?restOfURI:prefix + restOfURI; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/BitArray.cs b/zxing-csharp/common/BitArray.cs deleted file mode 100644 index 51f2776..0000000 --- a/zxing-csharp/common/BitArray.cs +++ /dev/null @@ -1,208 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - ///

A simple, fast array of bits, represented compactly by an array of ints internally.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class BitArray - { - public int Size - { - get - { - return size; - } - - } - - // TODO: I have changed these members to be public so ProGuard can inline get() and set(). Ideally - // they'd be private and we'd use the -allowaccessmodification flag, but Dalvik rejects the - // resulting binary at runtime on Android. If we find a solution to this, these should be changed - // back to private. - public int[] bits; - //UPGRADE_NOTE: Final was removed from the declaration of 'size '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int size; - - public BitArray(int size) - { - if (size < 1) - { - throw new System.ArgumentException("size must be at least 1"); - } - this.size = size; - this.bits = makeArray(size); - } - - /// bit to get - /// - /// true iff bit i is set - /// - public bool get_Renamed(int i) - { - return (bits[i >> 5] & (1 << (i & 0x1F))) != 0; - } - - /// Sets bit i. - /// - /// - /// bit to set - /// - public void set_Renamed(int i) - { - bits[i >> 5] |= 1 << (i & 0x1F); - } - - /// Flips bit i. - /// - /// - /// bit to set - /// - public void flip(int i) - { - bits[i >> 5] ^= 1 << (i & 0x1F); - } - - /// Sets a block of 32 bits, starting at bit i. - /// - /// - /// first bit to set - /// - /// the new value of the next 32 bits. Note again that the least-significant bit - /// corresponds to bit i, the next-least-significant to i+1, and so on. - /// - public void setBulk(int i, int newBits) - { - bits[i >> 5] = newBits; - } - - /// Clears all bits (sets to false). - public void clear() - { - int max = bits.Length; - for (int i = 0; i < max; i++) - { - bits[i] = 0; - } - } - - /// Efficient method to check if a range of bits is set, or not set. - /// - /// - /// start of range, inclusive. - /// - /// end of range, exclusive - /// - /// if true, checks that bits in range are set, otherwise checks that they are not set - /// - /// true iff all bits are set or not set in range, according to value argument - /// - /// IllegalArgumentException if end is less than or equal to start - public bool isRange(int start, int end, bool value_Renamed) - { - if (end < start) - { - throw new System.ArgumentException(); - } - if (end == start) - { - return true; // empty range matches - } - end--; // will be easier to treat this as the last actually set bit -- inclusive - int firstInt = start >> 5; - int lastInt = end >> 5; - for (int i = firstInt; i <= lastInt; i++) - { - int firstBit = i > firstInt?0:start & 0x1F; - int lastBit = i < lastInt?31:end & 0x1F; - int mask; - if (firstBit == 0 && lastBit == 31) - { - mask = - 1; - } - else - { - mask = 0; - for (int j = firstBit; j <= lastBit; j++) - { - mask |= 1 << j; - } - } - - // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, - // equals the mask, or we're looking for 0s and the masked portion is not all 0s - if ((bits[i] & mask) != (value_Renamed?mask:0)) - { - return false; - } - } - return true; - } - - /// underlying array of ints. The first element holds the first 32 bits, and the least - /// significant bit is bit 0. - /// - public int[] getBitArray() - { - return bits; - } - - /// Reverses all bits in the array. - public void reverse() - { - int[] newBits = new int[bits.Length]; - int size = this.size; - for (int i = 0; i < size; i++) - { - if (get_Renamed(size - i - 1)) - { - newBits[i >> 5] |= 1 << (i & 0x1F); - } - } - bits = newBits; - } - - private static int[] makeArray(int size) - { - int arraySize = size >> 5; - if ((size & 0x1F) != 0) - { - arraySize++; - } - return new int[arraySize]; - } - - public override System.String ToString() - { - System.Text.StringBuilder result = new System.Text.StringBuilder(size); - for (int i = 0; i < size; i++) - { - if ((i & 0x07) == 0) - { - result.Append(' '); - } - result.Append(get_Renamed(i)?'X':'.'); - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/BitMatrix.cs b/zxing-csharp/common/BitMatrix.cs deleted file mode 100644 index 6612ff4..0000000 --- a/zxing-csharp/common/BitMatrix.cs +++ /dev/null @@ -1,237 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - ///

Represents a 2D matrix of bits. In function arguments below, and throughout the common - /// module, x is the column position, and y is the row position. The ordering is always x, y. - /// The origin is at the top-left.

- /// - ///

Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins - /// with a new int. This is done intentionally so that we can copy out a row into a BitArray very - /// efficiently.

- /// - ///

The ordering of bits is row-major. Within each int, the least significant bits are used first, - /// meaning they represent lower x values. This is compatible with BitArray's implementation.

- /// - ///
- /// Sean Owen - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class BitMatrix - { - /// The width of the matrix - /// - public int Width - { - get - { - return width; - } - - } - /// The height of the matrix - /// - public int Height - { - get - { - return height; - } - - } - /// This method is for compatibility with older code. It's only logical to call if the matrix - /// is square, so I'm throwing if that's not the case. - /// - /// - /// row/column dimension of this matrix - /// - public int Dimension - { - get - { - if (width != height) - { - throw new System.SystemException("Can't call getDimension() on a non-square matrix"); - } - return width; - } - - } - - // TODO: Just like BitArray, these need to be public so ProGuard can inline them. - //UPGRADE_NOTE: Final was removed from the declaration of 'width '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int width; - //UPGRADE_NOTE: Final was removed from the declaration of 'height '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int height; - //UPGRADE_NOTE: Final was removed from the declaration of 'rowSize '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int rowSize; - //UPGRADE_NOTE: Final was removed from the declaration of 'bits '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public int[] bits; - - // A helper to construct a square matrix. - public BitMatrix(int dimension):this(dimension, dimension) - { - } - - public BitMatrix(int width, int height) - { - if (width < 1 || height < 1) - { - throw new System.ArgumentException("Both dimensions must be greater than 0"); - } - this.width = width; - this.height = height; - int rowSize = width >> 5; - if ((width & 0x1f) != 0) - { - rowSize++; - } - this.rowSize = rowSize; - bits = new int[rowSize * height]; - } - - ///

Gets the requested bit, where true means black.

- /// - ///
- /// The horizontal component (i.e. which column) - /// - /// The vertical component (i.e. which row) - /// - /// value of given bit in matrix - /// - public bool get_Renamed(int x, int y) - { - int offset = y * rowSize + (x >> 5); - return ((SupportClass.URShift(bits[offset], (x & 0x1f))) & 1) != 0; - } - - ///

Sets the given bit to true.

- /// - ///
- /// The horizontal component (i.e. which column) - /// - /// The vertical component (i.e. which row) - /// - public void set_Renamed(int x, int y) - { - int offset = y * rowSize + (x >> 5); - bits[offset] |= 1 << (x & 0x1f); - } - - ///

Flips the given bit.

- /// - ///
- /// The horizontal component (i.e. which column) - /// - /// The vertical component (i.e. which row) - /// - public void flip(int x, int y) - { - int offset = y * rowSize + (x >> 5); - bits[offset] ^= 1 << (x & 0x1f); - } - - /// Clears all bits (sets to false). - public void clear() - { - int max = bits.Length; - for (int i = 0; i < max; i++) - { - bits[i] = 0; - } - } - - ///

Sets a square region of the bit matrix to true.

- /// - ///
- /// The horizontal position to begin at (inclusive) - /// - /// The vertical position to begin at (inclusive) - /// - /// The width of the region - /// - /// The height of the region - /// - public void setRegion(int left, int top, int width, int height) - { - if (top < 0 || left < 0) - { - throw new System.ArgumentException("Left and top must be nonnegative"); - } - if (height < 1 || width < 1) - { - throw new System.ArgumentException("Height and width must be at least 1"); - } - int right = left + width; - int bottom = top + height; - if (bottom > this.height || right > this.width) - { - throw new System.ArgumentException("The region must fit inside the matrix"); - } - for (int y = top; y < bottom; y++) - { - int offset = y * rowSize; - for (int x = left; x < right; x++) - { - bits[offset + (x >> 5)] |= 1 << (x & 0x1f); - } - } - } - - /// A fast method to retrieve one row of data from the matrix as a BitArray. - /// - /// - /// The row to retrieve - /// - /// An optional caller-allocated BitArray, will be allocated if null or too small - /// - /// The resulting BitArray - this reference should always be used even when passing - /// your own row - /// - public BitArray getRow(int y, BitArray row) - { - if (row == null || row.Size < width) - { - row = new BitArray(width); - } - int offset = y * rowSize; - for (int x = 0; x < rowSize; x++) - { - row.setBulk(x << 5, bits[offset + x]); - } - return row; - } - - public override System.String ToString() - { - System.Text.StringBuilder result = new System.Text.StringBuilder(height * (width + 1)); - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - result.Append(get_Renamed(x, y)?"X ":" "); - } - result.Append('\n'); - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/BitSource.cs b/zxing-csharp/common/BitSource.cs deleted file mode 100644 index 983caa7..0000000 --- a/zxing-csharp/common/BitSource.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - ///

This provides an easy abstraction to read bits at a time from a sequence of bytes, where the - /// number of bits read is not often a multiple of 8.

- /// - ///

This class is thread-safe but not reentrant. Unless the caller modifies the bytes array - /// it passed in, in which case all bets are off.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class BitSource - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'bytes '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte[] bytes; - private int byteOffset; - private int bitOffset; - - /// bytes from which this will read bits. Bits will be read from the first byte first. - /// Bits are read within a byte from most-significant to least-significant bit. - /// - public BitSource(sbyte[] bytes) - { - this.bytes = bytes; - } - - /// number of bits to read - /// - /// int representing the bits read. The bits will appear as the least-significant - /// bits of the int - /// - /// IllegalArgumentException if numBits isn't in [1,32] - public int readBits(int numBits) - { - if (numBits < 1 || numBits > 32) - { - throw new System.ArgumentException(); - } - - int result = 0; - - // First, read remainder from current byte - if (bitOffset > 0) - { - int bitsLeft = 8 - bitOffset; - int toRead = numBits < bitsLeft?numBits:bitsLeft; - int bitsToNotRead = bitsLeft - toRead; - int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; - result = (bytes[byteOffset] & mask) >> bitsToNotRead; - numBits -= toRead; - bitOffset += toRead; - if (bitOffset == 8) - { - bitOffset = 0; - byteOffset++; - } - } - - // Next read whole bytes - if (numBits > 0) - { - while (numBits >= 8) - { - result = (result << 8) | (bytes[byteOffset] & 0xFF); - byteOffset++; - numBits -= 8; - } - - // Finally read a partial byte - if (numBits > 0) - { - int bitsToNotRead = 8 - numBits; - int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; - result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead); - bitOffset += numBits; - } - } - - return result; - } - - /// number of bits that can be read successfully - /// - public int available() - { - return 8 * (bytes.Length - byteOffset) - bitOffset; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/ByteArray.cs b/zxing-csharp/common/ByteArray.cs deleted file mode 100644 index ada385d..0000000 --- a/zxing-csharp/common/ByteArray.cs +++ /dev/null @@ -1,116 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - /// This class implements an array of unsigned bytes. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class ByteArray - { - public bool Empty - { - get - { - return size_Renamed_Field == 0; - } - - } - - private const int INITIAL_SIZE = 32; - - private sbyte[] bytes; - private int size_Renamed_Field; - - public ByteArray() - { - bytes = null; - size_Renamed_Field = 0; - } - - public ByteArray(int size) - { - bytes = new sbyte[size]; - this.size_Renamed_Field = size; - } - - public ByteArray(sbyte[] byteArray) - { - bytes = byteArray; - size_Renamed_Field = bytes.Length; - } - - /// Access an unsigned byte at location index. - /// The index in the array to access. - /// - /// The unsigned value of the byte as an int. - /// - public int at(int index) - { - return bytes[index] & 0xff; - } - - public void set_Renamed(int index, int value_Renamed) - { - bytes[index] = (sbyte) value_Renamed; - } - - public int size() - { - return size_Renamed_Field; - } - - public void appendByte(int value_Renamed) - { - if (size_Renamed_Field == 0 || size_Renamed_Field >= bytes.Length) - { - int newSize = System.Math.Max(INITIAL_SIZE, size_Renamed_Field << 1); - reserve(newSize); - } - bytes[size_Renamed_Field] = (sbyte) value_Renamed; - size_Renamed_Field++; - } - - public void reserve(int capacity) - { - if (bytes == null || bytes.Length < capacity) - { - sbyte[] newArray = new sbyte[capacity]; - if (bytes != null) - { - Array.Copy(bytes, 0, newArray, 0, bytes.Length); - } - bytes = newArray; - } - } - - // Copy count bytes from array source starting at offset. - public void set_Renamed(sbyte[] source, int offset, int count) - { - bytes = new sbyte[count]; - size_Renamed_Field = count; - for (int x = 0; x < count; x++) - { - bytes[x] = source[offset + x]; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/ByteMatrix.cs b/zxing-csharp/common/ByteMatrix.cs deleted file mode 100644 index c656d40..0000000 --- a/zxing-csharp/common/ByteMatrix.cs +++ /dev/null @@ -1,131 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - /// A class which wraps a 2D array of bytes. The default usage is signed. If you want to use it as a - /// unsigned container, it's up to you to do byteValue & 0xff at each location. - /// - /// JAVAPORT: The original code was a 2D array of ints, but since it only ever gets assigned - /// -1, 0, and 1, I'm going to use less memory and go with bytes. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class ByteMatrix - { - public int Height - { - get - { - return height; - } - - } - public int Width - { - get - { - return width; - } - - } - public sbyte[][] Array - { - get - { - return bytes; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'bytes '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte[][] bytes; - //UPGRADE_NOTE: Final was removed from the declaration of 'width '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int width; - //UPGRADE_NOTE: Final was removed from the declaration of 'height '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int height; - - public ByteMatrix(int width, int height) - { - bytes = new sbyte[height][]; - for (int i = 0; i < height; i++) - { - bytes[i] = new sbyte[width]; - } - this.width = width; - this.height = height; - } - - public sbyte get_Renamed(int x, int y) - { - return bytes[y][x]; - } - - public void set_Renamed(int x, int y, sbyte value_Renamed) - { - bytes[y][x] = value_Renamed; - } - - public void set_Renamed(int x, int y, int value_Renamed) - { - bytes[y][x] = (sbyte) value_Renamed; - } - - public void clear(sbyte value_Renamed) - { - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - bytes[y][x] = value_Renamed; - } - } - } - - public override System.String ToString() - { - System.Text.StringBuilder result = new System.Text.StringBuilder(2 * width * height + 2); - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - switch (bytes[y][x]) - { - - case 0: - result.Append(" 0"); - break; - - case 1: - result.Append(" 1"); - break; - - default: - result.Append(" "); - break; - - } - } - result.Append('\n'); - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/CharacterSetECI.cs b/zxing-csharp/common/CharacterSetECI.cs deleted file mode 100644 index 54b8b98..0000000 --- a/zxing-csharp/common/CharacterSetECI.cs +++ /dev/null @@ -1,126 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - /// Encapsulates a Character Set ECI, according to "Extended Channel Interpretations" 5.3.1.1 - /// of ISO 18004. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class CharacterSetECI:ECI - { - public System.String EncodingName - { - get - { - return encodingName; - } - - } - - private static System.Collections.Hashtable VALUE_TO_ECI; - private static System.Collections.Hashtable NAME_TO_ECI; - - private static void initialize() - { - VALUE_TO_ECI = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable(29)); - NAME_TO_ECI = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable(29)); - // TODO figure out if these values are even right! - addCharacterSet(0, "Cp437"); - addCharacterSet(1, new System.String[]{"ISO8859_1", "ISO-8859-1"}); - addCharacterSet(2, "Cp437"); - addCharacterSet(3, new System.String[]{"ISO8859_1", "ISO-8859-1"}); - addCharacterSet(4, "ISO8859_2"); - addCharacterSet(5, "ISO8859_3"); - addCharacterSet(6, "ISO8859_4"); - addCharacterSet(7, "ISO8859_5"); - addCharacterSet(8, "ISO8859_6"); - addCharacterSet(9, "ISO8859_7"); - addCharacterSet(10, "ISO8859_8"); - addCharacterSet(11, "ISO8859_9"); - addCharacterSet(12, "ISO8859_10"); - addCharacterSet(13, "ISO8859_11"); - addCharacterSet(15, "ISO8859_13"); - addCharacterSet(16, "ISO8859_14"); - addCharacterSet(17, "ISO8859_15"); - addCharacterSet(18, "ISO8859_16"); - addCharacterSet(20, new System.String[]{"SJIS", "Shift_JIS"}); - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'encodingName '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String encodingName; - - private CharacterSetECI(int value_Renamed, System.String encodingName):base(value_Renamed) - { - this.encodingName = encodingName; - } - - private static void addCharacterSet(int value_Renamed, System.String encodingName) - { - CharacterSetECI eci = new CharacterSetECI(value_Renamed, encodingName); - VALUE_TO_ECI[(System.Int32) value_Renamed] = eci; // can't use valueOf - NAME_TO_ECI[encodingName] = eci; - } - - private static void addCharacterSet(int value_Renamed, System.String[] encodingNames) - { - CharacterSetECI eci = new CharacterSetECI(value_Renamed, encodingNames[0]); - VALUE_TO_ECI[(System.Int32) value_Renamed] = eci; // can't use valueOf - for (int i = 0; i < encodingNames.Length; i++) - { - NAME_TO_ECI[encodingNames[i]] = eci; - } - } - - /// character set ECI value - /// - /// {@link CharacterSetECI} representing ECI of given value, or null if it is legal but - /// unsupported - /// - /// IllegalArgumentException if ECI value is invalid - public static CharacterSetECI getCharacterSetECIByValue(int value_Renamed) - { - if (VALUE_TO_ECI == null) - { - initialize(); - } - if (value_Renamed < 0 || value_Renamed >= 900) - { - throw new System.ArgumentException("Bad ECI value: " + value_Renamed); - } - return (CharacterSetECI) VALUE_TO_ECI[(System.Int32) value_Renamed]; - } - - /// character set ECI encoding name - /// - /// {@link CharacterSetECI} representing ECI for character encoding, or null if it is legal - /// but unsupported - /// - public static CharacterSetECI getCharacterSetECIByName(System.String name) - { - if (NAME_TO_ECI == null) - { - initialize(); - } - return (CharacterSetECI) NAME_TO_ECI[name]; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/Collections.cs b/zxing-csharp/common/Collections.cs deleted file mode 100644 index d9b8c29..0000000 --- a/zxing-csharp/common/Collections.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - ///

This is basically a substitute for java.util.Collections, which is not - /// present in MIDP 2.0 / CLDC 1.1.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Collections - { - - private Collections() - { - } - - /// Sorts its argument (destructively) using insert sort; in the context of this package - /// insertion sort is simple and efficient given its relatively small inputs. - /// - /// - /// vector to sort - /// - /// comparator to define sort ordering - /// - public static void insertionSort(System.Collections.ArrayList vector, Comparator comparator) - { - int max = vector.Count; - for (int i = 1; i < max; i++) - { - System.Object value_Renamed = vector[i]; - int j = i - 1; - System.Object valueB; - while (j >= 0 && comparator.compare((valueB = vector[j]), value_Renamed) > 0) - { - vector[j + 1] = valueB; - j--; - } - vector[j + 1] = value_Renamed; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/Comparator.cs b/zxing-csharp/common/Comparator.cs deleted file mode 100644 index 450be93..0000000 --- a/zxing-csharp/common/Comparator.cs +++ /dev/null @@ -1,28 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - /// This is merely a clone of Comparator since it is not available in - /// CLDC 1.1 / MIDP 2.0. - /// - public interface Comparator - { - - int compare(System.Object o1, System.Object o2); - } -} \ No newline at end of file diff --git a/zxing-csharp/common/DecoderResult.cs b/zxing-csharp/common/DecoderResult.cs deleted file mode 100644 index 8cbf31a..0000000 --- a/zxing-csharp/common/DecoderResult.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ErrorCorrectionLevel = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; -namespace com.google.zxing.common -{ - - ///

Encapsulates the result of decoding a matrix of bits. This typically - /// applies to 2D barcode formats. For now it contains the raw bytes obtained, - /// as well as a String interpretation of those bytes, if applicable.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class DecoderResult - { - public sbyte[] RawBytes - { - get - { - return rawBytes; - } - - } - public System.String Text - { - get - { - return text; - } - - } - public System.Collections.ArrayList ByteSegments - { - get - { - return byteSegments; - } - - } - public ErrorCorrectionLevel ECLevel - { - get - { - return ecLevel; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'rawBytes '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte[] rawBytes; - //UPGRADE_NOTE: Final was removed from the declaration of 'text '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String text; - //UPGRADE_NOTE: Final was removed from the declaration of 'byteSegments '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Collections.ArrayList byteSegments; - //UPGRADE_NOTE: Final was removed from the declaration of 'ecLevel '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ErrorCorrectionLevel ecLevel; - - public DecoderResult(sbyte[] rawBytes, System.String text, System.Collections.ArrayList byteSegments, ErrorCorrectionLevel ecLevel) - { - if (rawBytes == null && text == null) - { - throw new System.ArgumentException(); - } - this.rawBytes = rawBytes; - this.text = text; - this.byteSegments = byteSegments; - this.ecLevel = ecLevel; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/DefaultGridSampler.cs b/zxing-csharp/common/DefaultGridSampler.cs deleted file mode 100644 index f884dbf..0000000 --- a/zxing-csharp/common/DefaultGridSampler.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -namespace com.google.zxing.common -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class DefaultGridSampler:GridSampler - { - - public override BitMatrix sampleGrid(BitMatrix image, int dimension, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) - { - - PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); - - return sampleGrid(image, dimension, transform); - } - - public override BitMatrix sampleGrid(BitMatrix image, int dimension, PerspectiveTransform transform) - { - BitMatrix bits = new BitMatrix(dimension); - float[] points = new float[dimension << 1]; - for (int y = 0; y < dimension; y++) - { - int max = points.Length; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float iValue = (float) y + 0.5f; - for (int x = 0; x < max; x += 2) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - points[x] = (float) (x >> 1) + 0.5f; - points[x + 1] = iValue; - } - transform.transformPoints(points); - // Quick check to see if points transformed to something inside the image; - // sufficient to check the endpoints - checkAndNudgePoints(image, points); - try - { - for (int x = 0; x < max; x += 2) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - if (image.get_Renamed((int) points[x], (int) points[x + 1])) - { - // Black(-ish) pixel - bits.set_Renamed(x >> 1, y); - } - } - } - catch (System.IndexOutOfRangeException aioobe) - { - // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting - // transform gets "twisted" such that it maps a straight line of points to a set of points - // whose endpoints are in bounds, but others are not. There is probably some mathematical - // way to detect this about the transformation that I don't know yet. - // This results in an ugly runtime exception despite our clever checks above -- can't have - // that. We could check each point's coordinates but that feels duplicative. We settle for - // catching and wrapping ArrayIndexOutOfBoundsException. - throw ReaderException.Instance; - } - } - return bits; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/DetectorResult.cs b/zxing-csharp/common/DetectorResult.cs deleted file mode 100644 index 9a327a4..0000000 --- a/zxing-csharp/common/DetectorResult.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ResultPoint = com.google.zxing.ResultPoint; -namespace com.google.zxing.common -{ - - ///

Encapsulates the result of detecting a barcode in an image. This includes the raw - /// matrix of black/white pixels corresponding to the barcode, and possibly points of interest - /// in the image, like the location of finder patterns or corners of the barcode in the image.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class DetectorResult - { - public BitMatrix Bits - { - get - { - return bits; - } - - } - public ResultPoint[] Points - { - get - { - return points; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'bits '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix bits; - //UPGRADE_NOTE: Final was removed from the declaration of 'points '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ResultPoint[] points; - - public DetectorResult(BitMatrix bits, ResultPoint[] points) - { - this.bits = bits; - this.points = points; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/ECI.cs b/zxing-csharp/common/ECI.cs deleted file mode 100644 index 27ff679..0000000 --- a/zxing-csharp/common/ECI.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - /// Superclass of classes encapsulating types ECIs, according to "Extended Channel Interpretations" - /// 5.3 of ISO 18004. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public abstract class ECI - { - virtual public int Value - { - get - { - return value_Renamed; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'value '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int value_Renamed; - - internal ECI(int value_Renamed) - { - this.value_Renamed = value_Renamed; - } - - /// ECI value - /// - /// {@link ECI} representing ECI of given value, or null if it is legal but unsupported - /// - /// IllegalArgumentException if ECI value is invalid - public static ECI getECIByValue(int value_Renamed) - { - if (value_Renamed < 0 || value_Renamed > 999999) - { - throw new System.ArgumentException("Bad ECI value: " + value_Renamed); - } - if (value_Renamed < 900) - { - // Character set ECIs use 000000 - 000899 - return CharacterSetECI.getCharacterSetECIByValue(value_Renamed); - } - return null; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/GlobalHistogramBinarizer.cs b/zxing-csharp/common/GlobalHistogramBinarizer.cs deleted file mode 100644 index f6d0ae2..0000000 --- a/zxing-csharp/common/GlobalHistogramBinarizer.cs +++ /dev/null @@ -1,250 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Binarizer = com.google.zxing.Binarizer; -using LuminanceSource = com.google.zxing.LuminanceSource; -using ReaderException = com.google.zxing.ReaderException; -namespace com.google.zxing.common -{ - - /// This Binarizer implementation uses the old ZXing global histogram approach. It is suitable - /// for low-end mobile devices which don't have enough CPU or memory to use a local thresholding - /// algorithm. However, because it picks a global black point, it cannot handle difficult shadows - /// and gradients. - /// - /// Faster mobile devices and all desktop applications should probably use HybridBinarizer instead. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public class GlobalHistogramBinarizer:Binarizer - { - override public BitMatrix BlackMatrix - { - // Does not sharpen the data, as this call is intended to only be used by 2D Readers. - - get - { - LuminanceSource source = LuminanceSource; - // Redivivus.in Java to c# Porting update - // 30/01/2010 - // Added - // START - sbyte[] localLuminances; - //END - - int width = source.Width; - int height = source.Height; - BitMatrix matrix = new BitMatrix(width, height); - - // Quickly calculates the histogram by sampling four rows from the image. This proved to be - // more robust on the blackbox tests than sampling a diagonal as we used to do. - initArrays(width); - int[] localBuckets = buckets; - for (int y = 1; y < 5; y++) - { - int row = height * y / 5; - // Redivivus.in Java to c# Porting update - // 30/01/2010 - // Commented & Added - // START - //sbyte[] localLuminances = source.getRow(row, luminances); - localLuminances = source.getRow(row, luminances); - // END - int right = (width << 2) / 5; - for (int x = width / 5; x < right; x++) - { - int pixel = localLuminances[x] & 0xff; - localBuckets[pixel >> LUMINANCE_SHIFT]++; - } - } - int blackPoint = estimateBlackPoint(localBuckets); - - // We delay reading the entire image luminance until the black point estimation succeeds. - // Although we end up reading four rows twice, it is consistent with our motto of - // "fail quickly" which is necessary for continuous scanning. - - localLuminances = source.Matrix; // Govinda : Removed sbyte [] - for (int y = 0; y < height; y++) - { - int offset = y * width; - for (int x = 0; x < width; x++) - { - int pixel = localLuminances[offset + x] & 0xff; - if (pixel < blackPoint) - { - matrix.set_Renamed(x, y); - } - } - } - - return matrix; - } - - } - - private const int LUMINANCE_BITS = 5; - //UPGRADE_NOTE: Final was removed from the declaration of 'LUMINANCE_SHIFT '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; - //UPGRADE_NOTE: Final was removed from the declaration of 'LUMINANCE_BUCKETS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; - - private sbyte[] luminances = null; - private int[] buckets = null; - - public GlobalHistogramBinarizer(LuminanceSource source):base(source) - { - } - - // Applies simple sharpening to the row data to improve performance of the 1D Readers. - public override BitArray getBlackRow(int y, BitArray row) - { - LuminanceSource source = LuminanceSource; - int width = source.Width; - if (row == null || row.Size < width) - { - row = new BitArray(width); - } - else - { - row.clear(); - } - - initArrays(width); - sbyte[] localLuminances = source.getRow(y, luminances); - int[] localBuckets = buckets; - for (int x = 0; x < width; x++) - { - int pixel = localLuminances[x] & 0xff; - localBuckets[pixel >> LUMINANCE_SHIFT]++; - } - int blackPoint = estimateBlackPoint(localBuckets); - - int left = localLuminances[0] & 0xff; - int center = localLuminances[1] & 0xff; - for (int x = 1; x < width - 1; x++) - { - int right = localLuminances[x + 1] & 0xff; - // A simple -1 4 -1 box filter with a weight of 2. - int luminance = ((center << 2) - left - right) >> 1; - if (luminance < blackPoint) - { - row.set_Renamed(x); - } - left = center; - center = right; - } - return row; - } - - public override Binarizer createBinarizer(LuminanceSource source) - { - return new GlobalHistogramBinarizer(source); - } - - private void initArrays(int luminanceSize) - { - if (luminances == null || luminances.Length < luminanceSize) - { - luminances = new sbyte[luminanceSize]; - } - if (buckets == null) - { - buckets = new int[LUMINANCE_BUCKETS]; - } - else - { - for (int x = 0; x < LUMINANCE_BUCKETS; x++) - { - buckets[x] = 0; - } - } - } - - private static int estimateBlackPoint(int[] buckets) - { - // Find the tallest peak in the histogram. - int numBuckets = buckets.Length; - int maxBucketCount = 0; - int firstPeak = 0; - int firstPeakSize = 0; - for (int x = 0; x < numBuckets; x++) - { - if (buckets[x] > firstPeakSize) - { - firstPeak = x; - firstPeakSize = buckets[x]; - } - if (buckets[x] > maxBucketCount) - { - maxBucketCount = buckets[x]; - } - } - - // Find the second-tallest peak which is somewhat far from the tallest peak. - int secondPeak = 0; - int secondPeakScore = 0; - for (int x = 0; x < numBuckets; x++) - { - int distanceToBiggest = x - firstPeak; - // Encourage more distant second peaks by multiplying by square of distance. - int score = buckets[x] * distanceToBiggest * distanceToBiggest; - if (score > secondPeakScore) - { - secondPeak = x; - secondPeakScore = score; - } - } - - // Make sure firstPeak corresponds to the black peak. - if (firstPeak > secondPeak) - { - int temp = firstPeak; - firstPeak = secondPeak; - secondPeak = temp; - } - - // If there is too little contrast in the image to pick a meaningful black point, throw rather - // than waste time trying to decode the image, and risk false positives. - // TODO: It might be worth comparing the brightest and darkest pixels seen, rather than the - // two peaks, to determine the contrast. - if (secondPeak - firstPeak <= numBuckets >> 4) - { - throw ReaderException.Instance; - } - - // Find a valley between them that is low and closer to the white peak. - int bestValley = secondPeak - 1; - int bestValleyScore = - 1; - for (int x = secondPeak - 1; x > firstPeak; x--) - { - int fromFirst = x - firstPeak; - int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]); - if (score > bestValleyScore) - { - bestValley = x; - bestValleyScore = score; - } - } - - return bestValley << LUMINANCE_SHIFT; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/GridSampler.cs b/zxing-csharp/common/GridSampler.cs deleted file mode 100644 index bec46b7..0000000 --- a/zxing-csharp/common/GridSampler.cs +++ /dev/null @@ -1,193 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -namespace com.google.zxing.common -{ - - /// Implementations of this class can, given locations of finder patterns for a QR code in an - /// image, sample the right points in the image to reconstruct the QR code, accounting for - /// perspective distortion. It is abstracted since it is relatively expensive and should be allowed - /// to take advantage of platform-specific optimized implementations, like Sun's Java Advanced - /// Imaging library, but which may not be available in other environments such as J2ME, and vice - /// versa. - /// - /// The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)} - /// with an instance of a class which implements this interface. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public abstract class GridSampler - { - /// the current implementation of {@link GridSampler} - /// - public static GridSampler Instance - { - get - { - return gridSampler; - } - - } - - private static GridSampler gridSampler = new DefaultGridSampler(); - - /// Sets the implementation of {@link GridSampler} used by the library. One global - /// instance is stored, which may sound problematic. But, the implementation provided - /// ought to be appropriate for the entire platform, and all uses of this library - /// in the whole lifetime of the JVM. For instance, an Android activity can swap in - /// an implementation that takes advantage of native platform libraries. - /// - /// - /// The platform-specific object to install. - /// - public static void setGridSampler(GridSampler newGridSampler) - { - if (newGridSampler == null) - { - throw new System.ArgumentException(); - } - gridSampler = newGridSampler; - } - - ///

Samples an image for a square matrix of bits of the given dimension. This is used to extract - /// the black/white modules of a 2D barcode like a QR Code found in an image. Because this barcode - /// may be rotated or perspective-distorted, the caller supplies four points in the source image - /// that define known points in the barcode, so that the image may be sampled appropriately.

- /// - ///

The last eight "from" parameters are four X/Y coordinate pairs of locations of points in - /// the image that define some significant points in the image to be sample. For example, - /// these may be the location of finder pattern in a QR Code.

- /// - ///

The first eight "to" parameters are four X/Y coordinate pairs measured in the destination - /// {@link BitMatrix}, from the top left, where the known points in the image given by the "from" - /// parameters map to.

- /// - ///

These 16 parameters define the transformation needed to sample the image.

- /// - ///
- /// image to sample - /// - /// width/height of {@link BitMatrix} to sample from image - /// - /// {@link BitMatrix} representing a grid of points sampled from the image within a region - /// defined by the "from" parameters - /// - /// ReaderException if image can't be sampled, for example, if the transformation defined - /// by the given points is invalid or results in sampling outside the image boundaries - /// - public abstract BitMatrix sampleGrid(BitMatrix image, int dimension, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY); - - public virtual BitMatrix sampleGrid(BitMatrix image, int dimension, PerspectiveTransform transform) - { - throw new System.NotSupportedException(); - } - - - ///

Checks a set of points that have been transformed to sample points on an image against - /// the image's dimensions to see if the point are even within the image.

- /// - ///

This method will actually "nudge" the endpoints back onto the image if they are found to be - /// barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder - /// patterns in an image where the QR Code runs all the way to the image border.

- /// - ///

For efficiency, the method will check points from either end of the line until one is found - /// to be within the image. Because the set of points are assumed to be linear, this is valid.

- /// - ///
- /// image into which the points should map - /// - /// actual points in x1,y1,...,xn,yn form - /// - /// ReaderException if an endpoint is lies outside the image boundaries - protected internal static void checkAndNudgePoints(BitMatrix image, float[] points) - { - int width = image.Width; - int height = image.Height; - // Check and nudge points from start until we see some that are OK: - bool nudged = true; - for (int offset = 0; offset < points.Length && nudged; offset += 2) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int x = (int) points[offset]; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int y = (int) points[offset + 1]; - if (x < - 1 || x > width || y < - 1 || y > height) - { - throw ReaderException.Instance; - } - nudged = false; - if (x == - 1) - { - points[offset] = 0.0f; - nudged = true; - } - else if (x == width) - { - points[offset] = width - 1; - nudged = true; - } - if (y == - 1) - { - points[offset + 1] = 0.0f; - nudged = true; - } - else if (y == height) - { - points[offset + 1] = height - 1; - nudged = true; - } - } - // Check and nudge points from end: - nudged = true; - for (int offset = points.Length - 2; offset >= 0 && nudged; offset -= 2) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int x = (int) points[offset]; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int y = (int) points[offset + 1]; - if (x < - 1 || x > width || y < - 1 || y > height) - { - throw ReaderException.Instance; - } - nudged = false; - if (x == - 1) - { - points[offset] = 0.0f; - nudged = true; - } - else if (x == width) - { - points[offset] = width - 1; - nudged = true; - } - if (y == - 1) - { - points[offset + 1] = 0.0f; - nudged = true; - } - else if (y == height) - { - points[offset + 1] = height - 1; - nudged = true; - } - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/HybridBinarizer.cs b/zxing-csharp/common/HybridBinarizer.cs deleted file mode 100644 index 19d8fa3..0000000 --- a/zxing-csharp/common/HybridBinarizer.cs +++ /dev/null @@ -1,187 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Binarizer = com.google.zxing.Binarizer; -using LuminanceSource = com.google.zxing.LuminanceSource; -using ReaderException = com.google.zxing.ReaderException; -namespace com.google.zxing.common -{ - - /// This class implements a local thresholding algorithm, which while slower than the - /// GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for - /// high frequency images of barcodes with black data on white backgrounds. For this application, - /// it does a much better job than a global blackpoint with severe shadows and gradients. - /// However it tends to produce artifacts on lower frequency images and is therefore not - /// a good general purpose binarizer for uses outside ZXing. - /// - /// This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers, - /// and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already - /// inherently local, and only fails for horizontal gradients. We can revisit that problem later, - /// but for now it was not a win to use local blocks for 1D. - /// - /// This Binarizer is the default for the unit tests and the recommended class for library users. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class HybridBinarizer:GlobalHistogramBinarizer - { - override public BitMatrix BlackMatrix - { - get - { - binarizeEntireImage(); - return matrix; - } - - } - - // This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels. - // So this is the smallest dimension in each axis we can accept. - private const int MINIMUM_DIMENSION = 40; - - private BitMatrix matrix = null; - - public HybridBinarizer(LuminanceSource source):base(source) - { - } - - public override Binarizer createBinarizer(LuminanceSource source) - { - return new HybridBinarizer(source); - } - - // Calculates the final BitMatrix once for all requests. This could be called once from the - // constructor instead, but there are some advantages to doing it lazily, such as making - // profiling easier, and not doing heavy lifting when callers don't expect it. - private void binarizeEntireImage() - { - if (matrix == null) - { - LuminanceSource source = LuminanceSource; - if (source.Width >= MINIMUM_DIMENSION && source.Height >= MINIMUM_DIMENSION) - { - sbyte[] luminances = source.Matrix; - int width = source.Width; - int height = source.Height; - int subWidth = width >> 3; - int subHeight = height >> 3; - int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width); - - matrix = new BitMatrix(width, height); - calculateThresholdForBlock(luminances, subWidth, subHeight, width, blackPoints, matrix); - } - else - { - // If the image is too small, fall back to the global histogram approach. - matrix = base.BlackMatrix; - } - } - } - - // For each 8x8 block in the image, calculate the average black point using a 5x5 grid - // of the blocks around it. Also handles the corner cases, but will ignore up to 7 pixels - // on the right edge and 7 pixels at the bottom of the image if the overall dimensions are not - // multiples of eight. In practice, leaving those pixels white does not seem to be a problem. - private static void calculateThresholdForBlock(sbyte[] luminances, int subWidth, int subHeight, int stride, int[][] blackPoints, BitMatrix matrix) - { - for (int y = 0; y < subHeight; y++) - { - for (int x = 0; x < subWidth; x++) - { - int left = (x > 1)?x:2; - left = (left < subWidth - 2)?left:subWidth - 3; - int top = (y > 1)?y:2; - top = (top < subHeight - 2)?top:subHeight - 3; - int sum = 0; - for (int z = - 2; z <= 2; z++) - { - int[] blackRow = blackPoints[top + z]; - sum += blackRow[left - 2]; - sum += blackRow[left - 1]; - sum += blackRow[left]; - sum += blackRow[left + 1]; - sum += blackRow[left + 2]; - } - int average = sum / 25; - threshold8x8Block(luminances, x << 3, y << 3, average, stride, matrix); - } - } - } - - // Applies a single threshold to an 8x8 block of pixels. - private static void threshold8x8Block(sbyte[] luminances, int xoffset, int yoffset, int threshold, int stride, BitMatrix matrix) - { - for (int y = 0; y < 8; y++) - { - int offset = (yoffset + y) * stride + xoffset; - for (int x = 0; x < 8; x++) - { - int pixel = luminances[offset + x] & 0xff; - if (pixel < threshold) - { - matrix.set_Renamed(xoffset + x, yoffset + y); - } - } - } - } - - // Calculates a single black point for each 8x8 block of pixels and saves it away. - private static int[][] calculateBlackPoints(sbyte[] luminances, int subWidth, int subHeight, int stride) - { - int[][] blackPoints = new int[subHeight][]; - for (int i = 0; i < subHeight; i++) - { - blackPoints[i] = new int[subWidth]; - } - for (int y = 0; y < subHeight; y++) - { - for (int x = 0; x < subWidth; x++) - { - int sum = 0; - int min = 255; - int max = 0; - for (int yy = 0; yy < 8; yy++) - { - int offset = ((y << 3) + yy) * stride + (x << 3); - for (int xx = 0; xx < 8; xx++) - { - int pixel = luminances[offset + xx] & 0xff; - sum += pixel; - if (pixel < min) - { - min = pixel; - } - if (pixel > max) - { - max = pixel; - } - } - } - - // If the contrast is inadequate, use half the minimum, so that this block will be - // treated as part of the white background, but won't drag down neighboring blocks - // too much. - int average = (max - min > 24)?(sum >> 6):(min >> 1); - blackPoints[y][x] = average; - } - } - return blackPoints; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/PerspectiveTransform.cs b/zxing-csharp/common/PerspectiveTransform.cs deleted file mode 100644 index b516ef7..0000000 --- a/zxing-csharp/common/PerspectiveTransform.cs +++ /dev/null @@ -1,146 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common -{ - - ///

This class implements a perspective transform in two dimensions. Given four source and four - /// destination points, it will compute the transformation implied between them. The code is based - /// directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class PerspectiveTransform - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'a11 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: Final was removed from the declaration of 'a12 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: Final was removed from the declaration of 'a13 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: Final was removed from the declaration of 'a21 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: Final was removed from the declaration of 'a22 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: Final was removed from the declaration of 'a23 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: Final was removed from the declaration of 'a31 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: Final was removed from the declaration of 'a32 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_NOTE: Final was removed from the declaration of 'a33 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private float a11; - private float a12; - private float a13; - private float a21; - private float a22; - private float a23; - private float a31; - private float a32; - private float a33; - - private PerspectiveTransform(float a11, float a21, float a31, float a12, float a22, float a32, float a13, float a23, float a33) - { - this.a11 = a11; - this.a12 = a12; - this.a13 = a13; - this.a21 = a21; - this.a22 = a22; - this.a23 = a23; - this.a31 = a31; - this.a32 = a32; - this.a33 = a33; - } - - public static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x3p, float y3p) - { - - PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); - PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); - return sToQ.times(qToS); - } - - public void transformPoints(float[] points) - { - int max = points.Length; - float a11 = this.a11; - float a12 = this.a12; - float a13 = this.a13; - float a21 = this.a21; - float a22 = this.a22; - float a23 = this.a23; - float a31 = this.a31; - float a32 = this.a32; - float a33 = this.a33; - for (int i = 0; i < max; i += 2) - { - float x = points[i]; - float y = points[i + 1]; - float denominator = a13 * x + a23 * y + a33; - points[i] = (a11 * x + a21 * y + a31) / denominator; - points[i + 1] = (a12 * x + a22 * y + a32) / denominator; - } - } - - /// Convenience method, not optimized for performance. - public void transformPoints(float[] xValues, float[] yValues) - { - int n = xValues.Length; - for (int i = 0; i < n; i++) - { - float x = xValues[i]; - float y = yValues[i]; - float denominator = a13 * x + a23 * y + a33; - xValues[i] = (a11 * x + a21 * y + a31) / denominator; - yValues[i] = (a12 * x + a22 * y + a32) / denominator; - } - } - - public static PerspectiveTransform squareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) - { - float dy2 = y3 - y2; - float dy3 = y0 - y1 + y2 - y3; - if (dy2 == 0.0f && dy3 == 0.0f) - { - return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0f, 0.0f, 1.0f); - } - else - { - float dx1 = x1 - x2; - float dx2 = x3 - x2; - float dx3 = x0 - x1 + x2 - x3; - float dy1 = y1 - y2; - float denominator = dx1 * dy2 - dx2 * dy1; - float a13 = (dx3 * dy2 - dx2 * dy3) / denominator; - float a23 = (dx1 * dy3 - dx3 * dy1) / denominator; - return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0f); - } - } - - public static PerspectiveTransform quadrilateralToSquare(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) - { - // Here, the adjoint serves as the inverse: - return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); - } - - internal PerspectiveTransform buildAdjoint() - { - // Adjoint is the transpose of the cofactor matrix: - return new PerspectiveTransform(a22 * a33 - a23 * a32, a23 * a31 - a21 * a33, a21 * a32 - a22 * a31, a13 * a32 - a12 * a33, a11 * a33 - a13 * a31, a12 * a31 - a11 * a32, a12 * a23 - a13 * a22, a13 * a21 - a11 * a23, a11 * a22 - a12 * a21); - } - - internal PerspectiveTransform times(PerspectiveTransform other) - { - return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13, a11 * other.a21 + a21 * other.a22 + a31 * other.a23, a11 * other.a31 + a21 * other.a32 + a31 * other.a33, a12 * other.a11 + a22 * other.a12 + a32 * other.a13, a12 * other.a21 + a22 * other.a22 + a32 * other.a23, a12 * other.a31 + a22 * other.a32 + a32 * other.a33, a13 * other.a11 + a23 * other.a12 + a33 * other.a13, a13 * other.a21 + a23 * other.a22 + a33 * other.a23, a13 * other.a31 + a23 * other.a32 + a33 * other.a33); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/detector/MonochromeRectangleDetector.cs b/zxing-csharp/common/detector/MonochromeRectangleDetector.cs deleted file mode 100644 index eea5cb1..0000000 --- a/zxing-csharp/common/detector/MonochromeRectangleDetector.cs +++ /dev/null @@ -1,255 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using ResultPoint = com.google.zxing.ResultPoint; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing.common.detector -{ - - ///

A somewhat generic detector that looks for a barcode-like rectangular region within an image. - /// It looks within a mostly white region of an image for a region of black and white, but mostly - /// black. It returns the four corners of the region, as best it can determine.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class MonochromeRectangleDetector - { - - private const int MAX_MODULES = 32; - - //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix image; - - public MonochromeRectangleDetector(BitMatrix image) - { - this.image = image; - } - - ///

Detects a rectangular region of black and white -- mostly black -- with a region of mostly - /// white, in an image.

- /// - ///
- /// {@link ResultPoint}[] describing the corners of the rectangular region. The first and - /// last points are opposed on the diagonal, as are the second and third. The first point will be - /// the topmost point and the last, the bottommost. The second point will be leftmost and the - /// third, the rightmost - /// - /// ReaderException if no Data Matrix Code can be found - public ResultPoint[] detect() - { - int height = image.Height; - int width = image.Width; - int halfHeight = height >> 1; - int halfWidth = width >> 1; - int deltaY = System.Math.Max(1, height / (MAX_MODULES << 3)); - int deltaX = System.Math.Max(1, width / (MAX_MODULES << 3)); - - int top = 0; - int bottom = height; - int left = 0; - int right = width; - ResultPoint pointA = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, - deltaY, top, bottom, halfWidth >> 1); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - top = (int) pointA.Y - 1; - ResultPoint pointB = findCornerFromCenter(halfWidth, - deltaX, left, right, halfHeight, 0, top, bottom, halfHeight >> 1); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - left = (int) pointB.X - 1; - ResultPoint pointC = findCornerFromCenter(halfWidth, deltaX, left, right, halfHeight, 0, top, bottom, halfHeight >> 1); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - right = (int) pointC.X + 1; - ResultPoint pointD = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, deltaY, top, bottom, halfWidth >> 1); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - bottom = (int) pointD.Y + 1; - - // Go try to find point A again with better information -- might have been off at first. - pointA = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, - deltaY, top, bottom, halfWidth >> 2); - - return new ResultPoint[]{pointA, pointB, pointC, pointD}; - } - - /// Attempts to locate a corner of the barcode by scanning up, down, left or right from a center - /// point which should be within the barcode. - /// - /// - /// center's x component (horizontal) - /// - /// same as deltaY but change in x per step instead - /// - /// minimum value of x - /// - /// maximum value of x - /// - /// center's y component (vertical) - /// - /// change in y per step. If scanning up this is negative; down, positive; - /// left or right, 0 - /// - /// minimum value of y to search through (meaningless when di == 0) - /// - /// maximum value of y - /// - /// maximum run of white pixels that can still be considered to be within - /// the barcode - /// - /// a {@link com.google.zxing.ResultPoint} encapsulating the corner that was found - /// - /// com.google.zxing.ReaderException if such a point cannot be found - private ResultPoint findCornerFromCenter(int centerX, int deltaX, int left, int right, int centerY, int deltaY, int top, int bottom, int maxWhiteRun) - { - int[] lastRange = null; - for (int y = centerY, x = centerX; y < bottom && y >= top && x < right && x >= left; y += deltaY, x += deltaX) - { - int[] range; - if (deltaX == 0) - { - // horizontal slices, up and down - range = blackWhiteRange(y, maxWhiteRun, left, right, true); - } - else - { - // vertical slices, left and right - range = blackWhiteRange(x, maxWhiteRun, top, bottom, false); - } - if (range == null) - { - if (lastRange == null) - { - throw ReaderException.Instance; - } - // lastRange was found - if (deltaX == 0) - { - int lastY = y - deltaY; - if (lastRange[0] < centerX) - { - if (lastRange[1] > centerX) - { - // straddle, choose one or the other based on direction - return new ResultPoint(deltaY > 0?lastRange[0]:lastRange[1], lastY); - } - return new ResultPoint(lastRange[0], lastY); - } - else - { - return new ResultPoint(lastRange[1], lastY); - } - } - else - { - int lastX = x - deltaX; - if (lastRange[0] < centerY) - { - if (lastRange[1] > centerY) - { - return new ResultPoint(lastX, deltaX < 0?lastRange[0]:lastRange[1]); - } - return new ResultPoint(lastX, lastRange[0]); - } - else - { - return new ResultPoint(lastX, lastRange[1]); - } - } - } - lastRange = range; - } - throw ReaderException.Instance; - } - - /// Computes the start and end of a region of pixels, either horizontally or vertically, that could - /// be part of a Data Matrix barcode. - /// - /// - /// if scanning horizontally, this is the row (the fixed vertical location) - /// where we are scanning. If scanning vertically it's the column, the fixed horizontal location - /// - /// largest run of white pixels that can still be considered part of the - /// barcode region - /// - /// minimum pixel location, horizontally or vertically, to consider - /// - /// maximum pixel location, horizontally or vertically, to consider - /// - /// if true, we're scanning left-right, instead of up-down - /// - /// int[] with start and end of found range, or null if no such range is found - /// (e.g. only white was found) - /// - private int[] blackWhiteRange(int fixedDimension, int maxWhiteRun, int minDim, int maxDim, bool horizontal) - { - - int center = (minDim + maxDim) >> 1; - - // Scan left/up first - int start = center; - while (start >= minDim) - { - if (horizontal?image.get_Renamed(start, fixedDimension):image.get_Renamed(fixedDimension, start)) - { - start--; - } - else - { - int whiteRunStart = start; - do - { - start--; - } - while (start >= minDim && !(horizontal?image.get_Renamed(start, fixedDimension):image.get_Renamed(fixedDimension, start))); - int whiteRunSize = whiteRunStart - start; - if (start < minDim || whiteRunSize > maxWhiteRun) - { - start = whiteRunStart; - break; - } - } - } - start++; - - // Then try right/down - int end = center; - while (end < maxDim) - { - if (horizontal?image.get_Renamed(end, fixedDimension):image.get_Renamed(fixedDimension, end)) - { - end++; - } - else - { - int whiteRunStart = end; - do - { - end++; - } - while (end < maxDim && !(horizontal?image.get_Renamed(end, fixedDimension):image.get_Renamed(fixedDimension, end))); - int whiteRunSize = end - whiteRunStart; - if (end >= maxDim || whiteRunSize > maxWhiteRun) - { - end = whiteRunStart; - break; - } - } - } - end--; - - return end > start?new int[]{start, end}:null; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/reedsolomon/GF256.cs b/zxing-csharp/common/reedsolomon/GF256.cs deleted file mode 100644 index d006633..0000000 --- a/zxing-csharp/common/reedsolomon/GF256.cs +++ /dev/null @@ -1,174 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

This class contains utility methods for performing mathematical operations over - /// the Galois Field GF(256). Operations use a given primitive polynomial in calculations.

- /// - ///

Throughout this package, elements of GF(256) are represented as an int - /// for convenience and speed (but at the cost of memory). - /// Only the bottom 8 bits are really used.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class GF256 - { - internal GF256Poly Zero - { - get - { - return zero; - } - - } - internal GF256Poly One - { - get - { - return one; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'QR_CODE_FIELD '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly GF256 QR_CODE_FIELD = new GF256(0x011D); // x^8 + x^4 + x^3 + x^2 + 1 - //UPGRADE_NOTE: Final was removed from the declaration of 'DATA_MATRIX_FIELD '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly GF256 DATA_MATRIX_FIELD = new GF256(0x012D); // x^8 + x^5 + x^3 + x^2 + 1 - - //UPGRADE_NOTE: Final was removed from the declaration of 'expTable '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] expTable; - //UPGRADE_NOTE: Final was removed from the declaration of 'logTable '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] logTable; - //UPGRADE_NOTE: Final was removed from the declaration of 'zero '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private GF256Poly zero; - //UPGRADE_NOTE: Final was removed from the declaration of 'one '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private GF256Poly one; - - /// Create a representation of GF(256) using the given primitive polynomial. - /// - /// - /// irreducible polynomial whose coefficients are represented by - /// the bits of an int, where the least-significant bit represents the constant - /// coefficient - /// - private GF256(int primitive) - { - expTable = new int[256]; - logTable = new int[256]; - int x = 1; - for (int i = 0; i < 256; i++) - { - expTable[i] = x; - x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 - if (x >= 0x100) - { - x ^= primitive; - } - } - for (int i = 0; i < 255; i++) - { - logTable[expTable[i]] = i; - } - // logTable[0] == 0 but this should never be used - zero = new GF256Poly(this, new int[]{0}); - one = new GF256Poly(this, new int[]{1}); - } - - /// the monomial representing coefficient * x^degree - /// - internal GF256Poly buildMonomial(int degree, int coefficient) - { - if (degree < 0) - { - throw new System.ArgumentException(); - } - if (coefficient == 0) - { - return zero; - } - int[] coefficients = new int[degree + 1]; - coefficients[0] = coefficient; - return new GF256Poly(this, coefficients); - } - - /// Implements both addition and subtraction -- they are the same in GF(256). - /// - /// - /// sum/difference of a and b - /// - internal static int addOrSubtract(int a, int b) - { - return a ^ b; - } - - /// 2 to the power of a in GF(256) - /// - internal int exp(int a) - { - return expTable[a]; - } - - /// base 2 log of a in GF(256) - /// - internal int log(int a) - { - if (a == 0) - { - throw new System.ArgumentException(); - } - return logTable[a]; - } - - /// multiplicative inverse of a - /// - internal int inverse(int a) - { - if (a == 0) - { - throw new System.ArithmeticException(); - } - return expTable[255 - logTable[a]]; - } - - /// - /// - /// - /// - /// product of a and b in GF(256) - /// - internal int multiply(int a, int b) - { - if (a == 0 || b == 0) - { - return 0; - } - if (a == 1) - { - return b; - } - if (b == 1) - { - return a; - } - return expTable[(logTable[a] + logTable[b]) % 255]; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/reedsolomon/GF256Poly.cs b/zxing-csharp/common/reedsolomon/GF256Poly.cs deleted file mode 100644 index df5abb3..0000000 --- a/zxing-csharp/common/reedsolomon/GF256Poly.cs +++ /dev/null @@ -1,328 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Represents a polynomial whose coefficients are elements of GF(256). - /// Instances of this class are immutable.

- /// - ///

Much credit is due to William Rucklidge since portions of this code are an indirect - /// port of his C++ Reed-Solomon implementation.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class GF256Poly - { - internal int[] Coefficients - { - get - { - return coefficients; - } - - } - /// degree of this polynomial - /// - internal int Degree - { - get - { - return coefficients.Length - 1; - } - - } - /// true iff this polynomial is the monomial "0" - /// - internal bool Zero - { - get - { - return coefficients[0] == 0; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'field '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private GF256 field; - //UPGRADE_NOTE: Final was removed from the declaration of 'coefficients '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] coefficients; - - /// the {@link GF256} instance representing the field to use - /// to perform computations - /// - /// coefficients as ints representing elements of GF(256), arranged - /// from most significant (highest-power term) coefficient to least significant - /// - /// IllegalArgumentException if argument is null or empty, - /// or if leading coefficient is 0 and this is not a - /// constant polynomial (that is, it is not the monomial "0") - /// - internal GF256Poly(GF256 field, int[] coefficients) - { - if (coefficients == null || coefficients.Length == 0) - { - throw new System.ArgumentException(); - } - this.field = field; - int coefficientsLength = coefficients.Length; - if (coefficientsLength > 1 && coefficients[0] == 0) - { - // Leading term must be non-zero for anything except the constant polynomial "0" - int firstNonZero = 1; - while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) - { - firstNonZero++; - } - if (firstNonZero == coefficientsLength) - { - this.coefficients = field.Zero.coefficients; - } - else - { - this.coefficients = new int[coefficientsLength - firstNonZero]; - Array.Copy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.Length); - } - } - else - { - this.coefficients = coefficients; - } - } - - /// coefficient of x^degree term in this polynomial - /// - internal int getCoefficient(int degree) - { - return coefficients[coefficients.Length - 1 - degree]; - } - - /// evaluation of this polynomial at a given point - /// - internal int evaluateAt(int a) - { - if (a == 0) - { - // Just return the x^0 coefficient - return getCoefficient(0); - } - int size = coefficients.Length; - if (a == 1) - { - // Just the sum of the coefficients - int result = 0; - for (int i = 0; i < size; i++) - { - result = GF256.addOrSubtract(result, coefficients[i]); - } - return result; - } - int result2 = coefficients[0]; - for (int i = 1; i < size; i++) - { - result2 = GF256.addOrSubtract(field.multiply(a, result2), coefficients[i]); - } - return result2; - } - - internal GF256Poly addOrSubtract(GF256Poly other) - { - if (!field.Equals(other.field)) - { - throw new System.ArgumentException("GF256Polys do not have same GF256 field"); - } - if (Zero) - { - return other; - } - if (other.Zero) - { - return this; - } - - int[] smallerCoefficients = this.coefficients; - int[] largerCoefficients = other.coefficients; - if (smallerCoefficients.Length > largerCoefficients.Length) - { - int[] temp = smallerCoefficients; - smallerCoefficients = largerCoefficients; - largerCoefficients = temp; - } - int[] sumDiff = new int[largerCoefficients.Length]; - int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length; - // Copy high-order terms only found in higher-degree polynomial's coefficients - Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); - - for (int i = lengthDiff; i < largerCoefficients.Length; i++) - { - sumDiff[i] = GF256.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); - } - - return new GF256Poly(field, sumDiff); - } - - internal GF256Poly multiply(GF256Poly other) - { - if (!field.Equals(other.field)) - { - throw new System.ArgumentException("GF256Polys do not have same GF256 field"); - } - if (Zero || other.Zero) - { - return field.Zero; - } - int[] aCoefficients = this.coefficients; - int aLength = aCoefficients.Length; - int[] bCoefficients = other.coefficients; - int bLength = bCoefficients.Length; - int[] product = new int[aLength + bLength - 1]; - for (int i = 0; i < aLength; i++) - { - int aCoeff = aCoefficients[i]; - for (int j = 0; j < bLength; j++) - { - product[i + j] = GF256.addOrSubtract(product[i + j], field.multiply(aCoeff, bCoefficients[j])); - } - } - return new GF256Poly(field, product); - } - - internal GF256Poly multiply(int scalar) - { - if (scalar == 0) - { - return field.Zero; - } - if (scalar == 1) - { - return this; - } - int size = coefficients.Length; - int[] product = new int[size]; - for (int i = 0; i < size; i++) - { - product[i] = field.multiply(coefficients[i], scalar); - } - return new GF256Poly(field, product); - } - - internal GF256Poly multiplyByMonomial(int degree, int coefficient) - { - if (degree < 0) - { - throw new System.ArgumentException(); - } - if (coefficient == 0) - { - return field.Zero; - } - int size = coefficients.Length; - int[] product = new int[size + degree]; - for (int i = 0; i < size; i++) - { - product[i] = field.multiply(coefficients[i], coefficient); - } - return new GF256Poly(field, product); - } - - internal GF256Poly[] divide(GF256Poly other) - { - if (!field.Equals(other.field)) - { - throw new System.ArgumentException("GF256Polys do not have same GF256 field"); - } - if (other.Zero) - { - throw new System.ArgumentException("Divide by 0"); - } - - GF256Poly quotient = field.Zero; - GF256Poly remainder = this; - - int denominatorLeadingTerm = other.getCoefficient(other.Degree); - int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm); - - while (remainder.Degree >= other.Degree && !remainder.Zero) - { - int degreeDifference = remainder.Degree - other.Degree; - int scale = field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm); - GF256Poly term = other.multiplyByMonomial(degreeDifference, scale); - GF256Poly iterationQuotient = field.buildMonomial(degreeDifference, scale); - quotient = quotient.addOrSubtract(iterationQuotient); - remainder = remainder.addOrSubtract(term); - } - - return new GF256Poly[]{quotient, remainder}; - } - - public override System.String ToString() - { - System.Text.StringBuilder result = new System.Text.StringBuilder(8 * Degree); - for (int degree = Degree; degree >= 0; degree--) - { - int coefficient = getCoefficient(degree); - if (coefficient != 0) - { - if (coefficient < 0) - { - result.Append(" - "); - coefficient = - coefficient; - } - else - { - if (result.Length > 0) - { - result.Append(" + "); - } - } - if (degree == 0 || coefficient != 1) - { - int alphaPower = field.log(coefficient); - if (alphaPower == 0) - { - result.Append('1'); - } - else if (alphaPower == 1) - { - result.Append('a'); - } - else - { - result.Append("a^"); - result.Append(alphaPower); - } - } - if (degree != 0) - { - if (degree == 1) - { - result.Append('x'); - } - else - { - result.Append("x^"); - result.Append(degree); - } - } - } - } - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/reedsolomon/ReedSolomonDecoder.cs b/zxing-csharp/common/reedsolomon/ReedSolomonDecoder.cs deleted file mode 100644 index 1812311..0000000 --- a/zxing-csharp/common/reedsolomon/ReedSolomonDecoder.cs +++ /dev/null @@ -1,217 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Implements Reed-Solomon decoding, as the name implies.

- /// - ///

The algorithm will not be explained here, but the following references were helpful - /// in creating this implementation:

- /// - /// - /// - ///

Much credit is due to William Rucklidge since portions of this code are an indirect - /// port of his C++ Reed-Solomon implementation.

- /// - ///
- /// Sean Owen - /// - /// William Rucklidge - /// - /// sanfordsquires - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class ReedSolomonDecoder - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'field '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private GF256 field; - - public ReedSolomonDecoder(GF256 field) - { - this.field = field; - } - - ///

Decodes given set of received codewords, which include both data and error-correction - /// codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place, - /// in the input.

- /// - ///
- /// data and error-correction codewords - /// - /// number of error-correction codewords available - /// - /// ReedSolomonException if decoding fails for any reason - public void decode(int[] received, int twoS) - { - GF256Poly poly = new GF256Poly(field, received); - int[] syndromeCoefficients = new int[twoS]; - bool dataMatrix = field.Equals(GF256.DATA_MATRIX_FIELD); - bool noError = true; - for (int i = 0; i < twoS; i++) - { - // Thanks to sanfordsquires for this fix: - int eval = poly.evaluateAt(field.exp(dataMatrix?i + 1:i)); - syndromeCoefficients[syndromeCoefficients.Length - 1 - i] = eval; - if (eval != 0) - { - noError = false; - } - } - if (noError) - { - return ; - } - GF256Poly syndrome = new GF256Poly(field, syndromeCoefficients); - GF256Poly[] sigmaOmega = runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS); - GF256Poly sigma = sigmaOmega[0]; - GF256Poly omega = sigmaOmega[1]; - int[] errorLocations = findErrorLocations(sigma); - int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations, dataMatrix); - for (int i = 0; i < errorLocations.Length; i++) - { - int position = received.Length - 1 - field.log(errorLocations[i]); - if (position < 0) - { - throw new ReedSolomonException("Bad error location"); - } - received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]); - } - } - - private GF256Poly[] runEuclideanAlgorithm(GF256Poly a, GF256Poly b, int R) - { - // Assume a's degree is >= b's - if (a.Degree < b.Degree) - { - GF256Poly temp = a; - a = b; - b = temp; - } - - GF256Poly rLast = a; - GF256Poly r = b; - GF256Poly sLast = field.One; - GF256Poly s = field.Zero; - GF256Poly tLast = field.Zero; - GF256Poly t = field.One; - - // Run Euclidean algorithm until r's degree is less than R/2 - while (r.Degree >= R / 2) - { - GF256Poly rLastLast = rLast; - GF256Poly sLastLast = sLast; - GF256Poly tLastLast = tLast; - rLast = r; - sLast = s; - tLast = t; - - // Divide rLastLast by rLast, with quotient in q and remainder in r - if (rLast.Zero) - { - // Oops, Euclidean algorithm already terminated? - throw new ReedSolomonException("r_{i-1} was zero"); - } - r = rLastLast; - GF256Poly q = field.Zero; - int denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree); - int dltInverse = field.inverse(denominatorLeadingTerm); - while (r.Degree >= rLast.Degree && !r.Zero) - { - int degreeDiff = r.Degree - rLast.Degree; - int scale = field.multiply(r.getCoefficient(r.Degree), dltInverse); - q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale)); - r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); - } - - s = q.multiply(sLast).addOrSubtract(sLastLast); - t = q.multiply(tLast).addOrSubtract(tLastLast); - } - - int sigmaTildeAtZero = t.getCoefficient(0); - if (sigmaTildeAtZero == 0) - { - throw new ReedSolomonException("sigmaTilde(0) was zero"); - } - - int inverse = field.inverse(sigmaTildeAtZero); - GF256Poly sigma = t.multiply(inverse); - GF256Poly omega = r.multiply(inverse); - return new GF256Poly[]{sigma, omega}; - } - - private int[] findErrorLocations(GF256Poly errorLocator) - { - // This is a direct application of Chien's search - int numErrors = errorLocator.Degree; - if (numErrors == 1) - { - // shortcut - return new int[]{errorLocator.getCoefficient(1)}; - } - int[] result = new int[numErrors]; - int e = 0; - for (int i = 1; i < 256 && e < numErrors; i++) - { - if (errorLocator.evaluateAt(i) == 0) - { - result[e] = field.inverse(i); - e++; - } - } - if (e != numErrors) - { - throw new ReedSolomonException("Error locator degree does not match number of roots"); - } - return result; - } - - private int[] findErrorMagnitudes(GF256Poly errorEvaluator, int[] errorLocations, bool dataMatrix) - { - // This is directly applying Forney's Formula - int s = errorLocations.Length; - int[] result = new int[s]; - for (int i = 0; i < s; i++) - { - int xiInverse = field.inverse(errorLocations[i]); - int denominator = 1; - for (int j = 0; j < s; j++) - { - if (i != j) - { - denominator = field.multiply(denominator, GF256.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse))); - } - } - result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denominator)); - // Thanks to sanfordsquires for this fix: - if (dataMatrix) - { - result[i] = field.multiply(result[i], xiInverse); - } - } - return result; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/reedsolomon/ReedSolomonEncoder.cs b/zxing-csharp/common/reedsolomon/ReedSolomonEncoder.cs deleted file mode 100644 index 162f80e..0000000 --- a/zxing-csharp/common/reedsolomon/ReedSolomonEncoder.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Implements Reed-Solomon enbcoding, as the name implies.

- /// - ///
- /// Sean Owen - /// - /// William Rucklidge - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class ReedSolomonEncoder - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'field '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private GF256 field; - //UPGRADE_NOTE: Final was removed from the declaration of 'cachedGenerators '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Collections.ArrayList cachedGenerators; - - public ReedSolomonEncoder(GF256 field) - { - if (!GF256.QR_CODE_FIELD.Equals(field)) - { - throw new System.ArgumentException("Only QR Code is supported at this time"); - } - this.field = field; - this.cachedGenerators = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - cachedGenerators.Add(new GF256Poly(field, new int[]{1})); - } - - private GF256Poly buildGenerator(int degree) - { - if (degree >= cachedGenerators.Count) - { - GF256Poly lastGenerator = (GF256Poly) cachedGenerators[cachedGenerators.Count - 1]; - for (int d = cachedGenerators.Count; d <= degree; d++) - { - GF256Poly nextGenerator = lastGenerator.multiply(new GF256Poly(field, new int[]{1, field.exp(d - 1)})); - cachedGenerators.Add(nextGenerator); - lastGenerator = nextGenerator; - } - } - return (GF256Poly) cachedGenerators[degree]; - } - - public void encode(int[] toEncode, int ecBytes) - { - if (ecBytes == 0) - { - throw new System.ArgumentException("No error correction bytes"); - } - int dataBytes = toEncode.Length - ecBytes; - if (dataBytes <= 0) - { - throw new System.ArgumentException("No data bytes provided"); - } - GF256Poly generator = buildGenerator(ecBytes); - int[] infoCoefficients = new int[dataBytes]; - Array.Copy(toEncode, 0, infoCoefficients, 0, dataBytes); - GF256Poly info = new GF256Poly(field, infoCoefficients); - info = info.multiplyByMonomial(ecBytes, 1); - GF256Poly remainder = info.divide(generator)[1]; - int[] coefficients = remainder.Coefficients; - int numZeroCoefficients = ecBytes - coefficients.Length; - for (int i = 0; i < numZeroCoefficients; i++) - { - toEncode[dataBytes + i] = 0; - } - Array.Copy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.Length); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/common/reedsolomon/ReedSolomonException.cs b/zxing-csharp/common/reedsolomon/ReedSolomonException.cs deleted file mode 100644 index 964d0e6..0000000 --- a/zxing-csharp/common/reedsolomon/ReedSolomonException.cs +++ /dev/null @@ -1,36 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.common.reedsolomon -{ - - ///

Thrown when an exception occurs during Reed-Solomon decoding, such as when - /// there are too many errors to correct.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - [Serializable] - public sealed class ReedSolomonException:System.Exception - { - - public ReedSolomonException(System.String message):base(message) - { - } - } -} \ No newline at end of file diff --git a/zxing-csharp/datamatrix/DataMatrixReader.cs b/zxing-csharp/datamatrix/DataMatrixReader.cs deleted file mode 100644 index 25f2dbb..0000000 --- a/zxing-csharp/datamatrix/DataMatrixReader.cs +++ /dev/null @@ -1,171 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using DecodeHintType = com.google.zxing.DecodeHintType; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using Reader = com.google.zxing.Reader; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultPoint = com.google.zxing.ResultPoint; -using ResultMetadataType = com.google.zxing.ResultMetadataType; -using BitMatrix = com.google.zxing.common.BitMatrix; -using DecoderResult = com.google.zxing.common.DecoderResult; -using DetectorResult = com.google.zxing.common.DetectorResult; -using Decoder = com.google.zxing.datamatrix.decoder.Decoder; -using Detector = com.google.zxing.datamatrix.detector.Detector; -namespace com.google.zxing.datamatrix -{ - - /// This implementation can detect and decode Data Matrix codes in an image. - /// - /// - /// bbrown@google.com (Brian Brown) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class DataMatrixReader : Reader - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'NO_POINTS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0]; - - //UPGRADE_NOTE: Final was removed from the declaration of 'decoder '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private Decoder decoder = new Decoder(); - - /// Locates and decodes a Data Matrix code in an image. - /// - /// - /// a String representing the content encoded by the Data Matrix code - /// - /// ReaderException if a Data Matrix code cannot be found, or cannot be decoded - public Result decode(BinaryBitmap image) - { - return decode(image, null); - } - - public Result decode(BinaryBitmap image, System.Collections.Hashtable hints) - { - DecoderResult decoderResult; - ResultPoint[] points; - if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) - { - BitMatrix bits = extractPureBits(image.BlackMatrix); - decoderResult = decoder.decode(bits); - points = NO_POINTS; - } - else - { - DetectorResult detectorResult = new Detector(image.BlackMatrix).detect(); - decoderResult = decoder.decode(detectorResult.Bits); - points = detectorResult.Points; - } - Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.DATAMATRIX); - if (decoderResult.ByteSegments != null) - { - result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.ByteSegments); - } - if (decoderResult.ECLevel != null) - { - result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.ECLevel.ToString()); - } - return result; - } - - /// This method detects a Data Matrix code in a "pure" image -- that is, pure monochrome image - /// which contains only an unrotated, unskewed, image of a Data Matrix code, with some white border - /// around it. This is a specialized method that works exceptionally fast in this special - /// case. - /// - private static BitMatrix extractPureBits(BitMatrix image) - { - // Now need to determine module size in pixels - - int height = image.Height; - int width = image.Width; - int minDimension = System.Math.Min(height, width); - - // First, skip white border by tracking diagonally from the top left down and to the right: - int borderWidth = 0; - while (borderWidth < minDimension && !image.get_Renamed(borderWidth, borderWidth)) - { - borderWidth++; - } - if (borderWidth == minDimension) - { - throw ReaderException.Instance; - } - - // And then keep tracking across the top-left black module to determine module size - int moduleEnd = borderWidth + 1; - while (moduleEnd < width && image.get_Renamed(moduleEnd, borderWidth)) - { - moduleEnd++; - } - if (moduleEnd == width) - { - throw ReaderException.Instance; - } - - int moduleSize = moduleEnd - borderWidth; - - // And now find where the bottommost black module on the first column ends - int columnEndOfSymbol = height - 1; - while (columnEndOfSymbol >= 0 && !image.get_Renamed(borderWidth, columnEndOfSymbol)) - { - columnEndOfSymbol--; - } - if (columnEndOfSymbol < 0) - { - throw ReaderException.Instance; - } - columnEndOfSymbol++; - - // Make sure width of barcode is a multiple of module size - if ((columnEndOfSymbol - borderWidth) % moduleSize != 0) - { - throw ReaderException.Instance; - } - int dimension = (columnEndOfSymbol - borderWidth) / moduleSize; - - // Push in the "border" by half the module width so that we start - // sampling in the middle of the module. Just in case the image is a - // little off, this will help recover. - borderWidth += (moduleSize >> 1); - - int sampleDimension = borderWidth + (dimension - 1) * moduleSize; - if (sampleDimension >= width || sampleDimension >= height) - { - throw ReaderException.Instance; - } - - // Now just read off the bits - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) - { - int iOffset = borderWidth + i * moduleSize; - for (int j = 0; j < dimension; j++) - { - if (image.get_Renamed(borderWidth + j * moduleSize, iOffset)) - { - bits.set_Renamed(j, i); - } - } - } - return bits; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/datamatrix/decoder/BitMatrixParser.cs b/zxing-csharp/datamatrix/decoder/BitMatrixParser.cs deleted file mode 100644 index b94a682..0000000 --- a/zxing-csharp/datamatrix/decoder/BitMatrixParser.cs +++ /dev/null @@ -1,547 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing.datamatrix.decoder -{ - - /// bbrown@google.com (Brian Brown) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class BitMatrixParser - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'mappingBitMatrix '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix mappingBitMatrix; - //UPGRADE_NOTE: Final was removed from the declaration of 'readMappingMatrix '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix readMappingMatrix; - //UPGRADE_NOTE: Final was removed from the declaration of 'version '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private Version version; - - /// {@link BitMatrix} to parse - /// - /// ReaderException if dimension is < 10 or > 144 or not 0 mod 2 - internal BitMatrixParser(BitMatrix bitMatrix) - { - int dimension = bitMatrix.Dimension; - if (dimension < 10 || dimension > 144 || (dimension & 0x01) != 0) - { - throw ReaderException.Instance; - } - - version = readVersion(bitMatrix); - this.mappingBitMatrix = extractDataRegion(bitMatrix); - // TODO(bbrown): Make this work for rectangular symbols - this.readMappingMatrix = new BitMatrix(this.mappingBitMatrix.Dimension); - } - - ///

Creates the version object based on the dimension of the original bit matrix from - /// the datamatrix code.

- /// - ///

See ISO 16022:2006 Table 7 - ECC 200 symbol attributes

- /// - ///
- /// Original {@link BitMatrix} including alignment patterns - /// - /// {@link Version} encapsulating the Data Matrix Code's "version" - /// - /// ReaderException if the dimensions of the mapping matrix are not valid - /// Data Matrix dimensions. - /// - internal Version readVersion(BitMatrix bitMatrix) - { - - if (version != null) - { - return version; - } - - // TODO(bbrown): make this work for rectangular dimensions as well. - int numRows = bitMatrix.Dimension; - int numColumns = numRows; - - return Version.getVersionForDimensions(numRows, numColumns); - } - - ///

Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns) - /// in the correct order in order to reconstitute the codewords bytes contained within the - /// Data Matrix Code.

- /// - ///
- /// bytes encoded within the Data Matrix Code - /// - /// ReaderException if the exact number of bytes expected is not read - internal sbyte[] readCodewords() - { - - sbyte[] result = new sbyte[version.TotalCodewords]; - int resultOffset = 0; - - int row = 4; - int column = 0; - // TODO(bbrown): Data Matrix can be rectangular, assuming square for now - int numRows = mappingBitMatrix.Dimension; - int numColumns = numRows; - - bool corner1Read = false; - bool corner2Read = false; - bool corner3Read = false; - bool corner4Read = false; - - // Read all of the codewords - do - { - // Check the four corner cases - if ((row == numRows) && (column == 0) && !corner1Read) - { - result[resultOffset++] = (sbyte) readCorner1(numRows, numColumns); - row -= 2; - column += 2; - corner1Read = true; - } - else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x03) != 0) && !corner2Read) - { - result[resultOffset++] = (sbyte) readCorner2(numRows, numColumns); - row -= 2; - column += 2; - corner2Read = true; - } - else if ((row == numRows + 4) && (column == 2) && ((numColumns & 0x07) == 0) && !corner3Read) - { - result[resultOffset++] = (sbyte) readCorner3(numRows, numColumns); - row -= 2; - column += 2; - corner3Read = true; - } - else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x07) == 4) && !corner4Read) - { - result[resultOffset++] = (sbyte) readCorner4(numRows, numColumns); - row -= 2; - column += 2; - corner4Read = true; - } - else - { - // Sweep upward diagonally to the right - do - { - if ((row < numRows) && (column >= 0) && !readMappingMatrix.get_Renamed(column, row)) - { - result[resultOffset++] = (sbyte) readUtah(row, column, numRows, numColumns); - } - row -= 2; - column += 2; - } - while ((row >= 0) && (column < numColumns)); - row += 1; - column += 3; - - // Sweep downward diagonally to the left - do - { - if ((row >= 0) && (column < numColumns) && !readMappingMatrix.get_Renamed(column, row)) - { - result[resultOffset++] = (sbyte) readUtah(row, column, numRows, numColumns); - } - row += 2; - column -= 2; - } - while ((row < numRows) && (column >= 0)); - row += 3; - column += 1; - } - } - while ((row < numRows) || (column < numColumns)); - - if (resultOffset != version.TotalCodewords) - { - throw ReaderException.Instance; - } - return result; - } - - ///

Reads a bit of the mapping matrix accounting for boundary wrapping.

- /// - ///
- /// Row to read in the mapping matrix - /// - /// Column to read in the mapping matrix - /// - /// Number of rows in the mapping matrix - /// - /// Number of columns in the mapping matrix - /// - /// value of the given bit in the mapping matrix - /// - internal bool readModule(int row, int column, int numRows, int numColumns) - { - // Adjust the row and column indices based on boundary wrapping - if (row < 0) - { - row += numRows; - column += 4 - ((numRows + 4) & 0x07); - } - if (column < 0) - { - column += numColumns; - row += 4 - ((numColumns + 4) & 0x07); - } - readMappingMatrix.set_Renamed(column, row); - return mappingBitMatrix.get_Renamed(column, row); - } - - ///

Reads the 8 bits of the standard Utah-shaped pattern.

- /// - ///

See ISO 16022:2006, 5.8.1 Figure 6

- /// - ///
- /// Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern - /// - /// Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern - /// - /// Number of rows in the mapping matrix - /// - /// Number of columns in the mapping matrix - /// - /// byte from the utah shape - /// - internal int readUtah(int row, int column, int numRows, int numColumns) - { - int currentByte = 0; - if (readModule(row - 2, column - 2, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 2, column - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 1, column - 2, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 1, column - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row - 1, column, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row, column - 2, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row, column - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(row, column, numRows, numColumns)) - { - currentByte |= 1; - } - return currentByte; - } - - ///

Reads the 8 bits of the special corner condition 1.

- /// - ///

See ISO 16022:2006, Figure F.3

- /// - ///
- /// Number of rows in the mapping matrix - /// - /// Number of columns in the mapping matrix - /// - /// byte from the Corner condition 1 - /// - internal int readCorner1(int numRows, int numColumns) - { - int currentByte = 0; - if (readModule(numRows - 1, 0, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 2, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(2, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(3, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - return currentByte; - } - - ///

Reads the 8 bits of the special corner condition 2.

- /// - ///

See ISO 16022:2006, Figure F.4

- /// - ///
- /// Number of rows in the mapping matrix - /// - /// Number of columns in the mapping matrix - /// - /// byte from the Corner condition 2 - /// - internal int readCorner2(int numRows, int numColumns) - { - int currentByte = 0; - if (readModule(numRows - 3, 0, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 2, 0, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 0, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 4, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 3, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - return currentByte; - } - - ///

Reads the 8 bits of the special corner condition 3.

- /// - ///

See ISO 16022:2006, Figure F.5

- /// - ///
- /// Number of rows in the mapping matrix - /// - /// Number of columns in the mapping matrix - /// - /// byte from the Corner condition 3 - /// - internal int readCorner3(int numRows, int numColumns) - { - int currentByte = 0; - if (readModule(numRows - 1, 0, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 3, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 3, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 2, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - return currentByte; - } - - ///

Reads the 8 bits of the special corner condition 4.

- /// - ///

See ISO 16022:2006, Figure F.6

- /// - ///
- /// Number of rows in the mapping matrix - /// - /// Number of columns in the mapping matrix - /// - /// byte from the Corner condition 4 - /// - internal int readCorner4(int numRows, int numColumns) - { - int currentByte = 0; - if (readModule(numRows - 3, 0, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 2, 0, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(numRows - 1, 0, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 2, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(0, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(1, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(2, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - currentByte <<= 1; - if (readModule(3, numColumns - 1, numRows, numColumns)) - { - currentByte |= 1; - } - return currentByte; - } - - ///

Extracts the data region from a {@link BitMatrix} that contains - /// alignment patterns.

- /// - ///
- /// Original {@link BitMatrix} with alignment patterns - /// - /// BitMatrix that has the alignment patterns removed - /// - internal BitMatrix extractDataRegion(BitMatrix bitMatrix) - { - int symbolSizeRows = version.SymbolSizeRows; - int symbolSizeColumns = version.SymbolSizeColumns; - - // TODO(bbrown): Make this work with rectangular codes - if (bitMatrix.Dimension != symbolSizeRows) - { - throw new System.ArgumentException("Dimension of bitMarix must match the version size"); - } - - int dataRegionSizeRows = version.DataRegionSizeRows; - int dataRegionSizeColumns = version.DataRegionSizeColumns; - - int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows; - int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns; - - int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows; - //int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns; - - // TODO(bbrown): Make this work with rectangular codes - BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionRow); - for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) - { - int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows; - for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) - { - int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns; - for (int i = 0; i < dataRegionSizeRows; ++i) - { - int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i; - int writeRowOffset = dataRegionRowOffset + i; - for (int j = 0; j < dataRegionSizeColumns; ++j) - { - int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j; - if (bitMatrix.get_Renamed(readColumnOffset, readRowOffset)) - { - int writeColumnOffset = dataRegionColumnOffset + j; - bitMatrixWithoutAlignment.set_Renamed(writeColumnOffset, writeRowOffset); - } - } - } - } - } - return bitMatrixWithoutAlignment; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/datamatrix/decoder/DataBlock.cs b/zxing-csharp/datamatrix/decoder/DataBlock.cs deleted file mode 100644 index 28d48a1..0000000 --- a/zxing-csharp/datamatrix/decoder/DataBlock.cs +++ /dev/null @@ -1,144 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.datamatrix.decoder -{ - - ///

Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into - /// multiple blocks, each of which is a unit of data and error-correction codewords. Each - /// is represented by an instance of this class.

- /// - ///
- /// bbrown@google.com (Brian Brown) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class DataBlock - { - internal int NumDataCodewords - { - get - { - return numDataCodewords; - } - - } - internal sbyte[] Codewords - { - get - { - return codewords; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'numDataCodewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int numDataCodewords; - //UPGRADE_NOTE: Final was removed from the declaration of 'codewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte[] codewords; - - private DataBlock(int numDataCodewords, sbyte[] codewords) - { - this.numDataCodewords = numDataCodewords; - this.codewords = codewords; - } - - ///

When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them. - /// That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This - /// method will separate the data into original blocks.

- /// - ///
- /// bytes as read directly from the Data Matrix Code - /// - /// version of the Data Matrix Code - /// - /// {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the - /// Data Matrix Code - /// - internal static DataBlock[] getDataBlocks(sbyte[] rawCodewords, Version version) - { - // Figure out the number and size of data blocks used by this version - Version.ECBlocks ecBlocks = version.getECBlocks(); - - // First count the total number of data blocks - int totalBlocks = 0; - Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); - for (int i = 0; i < ecBlockArray.Length; i++) - { - totalBlocks += ecBlockArray[i].Count; - } - - // Now establish DataBlocks of the appropriate size and number of data codewords - DataBlock[] result = new DataBlock[totalBlocks]; - int numResultBlocks = 0; - for (int j = 0; j < ecBlockArray.Length; j++) - { - Version.ECB ecBlock = ecBlockArray[j]; - for (int i = 0; i < ecBlock.Count; i++) - { - int numDataCodewords = ecBlock.DataCodewords; - int numBlockCodewords = ecBlocks.ECCodewords + numDataCodewords; - result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]); - } - } - - // All blocks have the same amount of data, except that the last n - // (where n may be 0) have 1 less byte. Figure out where these start. - // TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144 - int longerBlocksTotalCodewords = result[0].codewords.Length; - //int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1; - - int longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.ECCodewords; - int shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1; - // The last elements of result may be 1 element shorter for 144 matrix - // first fill out as many elements as all of them have minus 1 - int rawCodewordsOffset = 0; - for (int i = 0; i < shorterBlocksNumDataCodewords; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; - } - } - - // Fill out the last data block in the longer ones - bool specialVersion = version.VersionNumber == 24; - int numLongerBlocks = specialVersion?8:numResultBlocks; - for (int j = 0; j < numLongerBlocks; j++) - { - result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++]; - } - - // Now add in error correction blocks - int max = result[0].codewords.Length; - for (int i = longerBlocksNumDataCodewords; i < max; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - int iOffset = (specialVersion && j > 7)?i - 1:i; - result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; - } - } - - if (rawCodewordsOffset != rawCodewords.Length) - { - throw new System.ArgumentException(); - } - - return result; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/datamatrix/decoder/DecodedBitStreamParser.cs b/zxing-csharp/datamatrix/decoder/DecodedBitStreamParser.cs deleted file mode 100644 index 12e3faa..0000000 --- a/zxing-csharp/datamatrix/decoder/DecodedBitStreamParser.cs +++ /dev/null @@ -1,625 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using BitSource = com.google.zxing.common.BitSource; -using DecoderResult = com.google.zxing.common.DecoderResult; -namespace com.google.zxing.datamatrix.decoder -{ - - ///

Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes - /// in one Data Matrix Code. This class decodes the bits back into text.

- /// - ///

See ISO 16022:2006, 5.2.1 - 5.2.9.2

- /// - ///
- /// bbrown@google.com (Brian Brown) - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class DecodedBitStreamParser - { - - /// See ISO 16022:2006, Annex C Table C.1 - /// The C40 Basic Character Set (*'s used for placeholders for the shift values) - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'C40_BASIC_SET_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] C40_BASIC_SET_CHARS = new char[]{'*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'C40_SHIFT2_SET_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] C40_SHIFT2_SET_CHARS = new char[]{'!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_'}; - - /// See ISO 16022:2006, Annex C Table C.2 - /// The Text Basic Character Set (*'s used for placeholders for the shift values) - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'TEXT_BASIC_SET_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] TEXT_BASIC_SET_CHARS = new char[]{'*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; - - private static char[] TEXT_SHIFT3_SET_CHARS = new char[]{'\'', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char) 127}; - - private const int PAD_ENCODE = 0; // Not really an encoding - private const int ASCII_ENCODE = 1; - private const int C40_ENCODE = 2; - private const int TEXT_ENCODE = 3; - private const int ANSIX12_ENCODE = 4; - private const int EDIFACT_ENCODE = 5; - private const int BASE256_ENCODE = 6; - - private DecodedBitStreamParser() - { - } - - internal static DecoderResult decode(sbyte[] bytes) - { - BitSource bits = new BitSource(bytes); - System.Text.StringBuilder result = new System.Text.StringBuilder(100); - System.Text.StringBuilder resultTrailer = new System.Text.StringBuilder(0); - System.Collections.ArrayList byteSegments = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(1)); - int mode = ASCII_ENCODE; - do - { - if (mode == ASCII_ENCODE) - { - mode = decodeAsciiSegment(bits, result, resultTrailer); - } - else - { - switch (mode) - { - - case C40_ENCODE: - decodeC40Segment(bits, result); - break; - - case TEXT_ENCODE: - decodeTextSegment(bits, result); - break; - - case ANSIX12_ENCODE: - decodeAnsiX12Segment(bits, result); - break; - - case EDIFACT_ENCODE: - decodeEdifactSegment(bits, result); - break; - - case BASE256_ENCODE: - decodeBase256Segment(bits, result, byteSegments); - break; - - default: - throw ReaderException.Instance; - - } - mode = ASCII_ENCODE; - } - } - while (mode != PAD_ENCODE && bits.available() > 0); - if (resultTrailer.Length > 0) - { - result.Append(resultTrailer.ToString()); - } - return new DecoderResult(bytes, result.ToString(), (byteSegments.Count == 0)?null:byteSegments, null); - } - - /// See ISO 16022:2006, 5.2.3 and Annex C, Table C.2 - private static int decodeAsciiSegment(BitSource bits, System.Text.StringBuilder result, System.Text.StringBuilder resultTrailer) - { - bool upperShift = false; - do - { - int oneByte = bits.readBits(8); - if (oneByte == 0) - { - throw ReaderException.Instance; - } - else if (oneByte <= 128) - { - // ASCII data (ASCII value + 1) - oneByte = upperShift?(oneByte + 128):oneByte; - upperShift = false; - result.Append((char) (oneByte - 1)); - return ASCII_ENCODE; - } - else if (oneByte == 129) - { - // Pad - return PAD_ENCODE; - } - else if (oneByte <= 229) - { - // 2-digit data 00-99 (Numeric Value + 130) - int value_Renamed = oneByte - 130; - if (value_Renamed < 10) - { - // padd with '0' for single digit values - result.Append('0'); - } - result.Append(value_Renamed); - } - else if (oneByte == 230) - { - // Latch to C40 encodation - return C40_ENCODE; - } - else if (oneByte == 231) - { - // Latch to Base 256 encodation - return BASE256_ENCODE; - } - else if (oneByte == 232) - { - // FNC1 - //throw ReaderException.getInstance(); - // Ignore this symbol for now - } - else if (oneByte == 233) - { - // Structured Append - //throw ReaderException.getInstance(); - // Ignore this symbol for now - } - else if (oneByte == 234) - { - // Reader Programming - //throw ReaderException.getInstance(); - // Ignore this symbol for now - } - else if (oneByte == 235) - { - // Upper Shift (shift to Extended ASCII) - upperShift = true; - } - else if (oneByte == 236) - { - // 05 Macro - result.Append("[)>\u001E05\u001D"); - resultTrailer.Insert(0, "\u001E\u0004"); - } - else if (oneByte == 237) - { - // 06 Macro - result.Append("[)>\u001E06\u001D"); - resultTrailer.Insert(0, "\u001E\u0004"); - } - else if (oneByte == 238) - { - // Latch to ANSI X12 encodation - return ANSIX12_ENCODE; - } - else if (oneByte == 239) - { - // Latch to Text encodation - return TEXT_ENCODE; - } - else if (oneByte == 240) - { - // Latch to EDIFACT encodation - return EDIFACT_ENCODE; - } - else if (oneByte == 241) - { - // ECI Character - // TODO(bbrown): I think we need to support ECI - //throw ReaderException.getInstance(); - // Ignore this symbol for now - } - else if (oneByte >= 242) - { - // Not to be used in ASCII encodation - throw ReaderException.Instance; - } - } - while (bits.available() > 0); - return ASCII_ENCODE; - } - - /// See ISO 16022:2006, 5.2.5 and Annex C, Table C.1 - private static void decodeC40Segment(BitSource bits, System.Text.StringBuilder result) - { - // Three C40 values are encoded in a 16-bit value as - // (1600 * C1) + (40 * C2) + C3 + 1 - // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time - bool upperShift = false; - - int[] cValues = new int[3]; - do - { - // If there is only one byte left then it will be encoded as ASCII - if (bits.available() == 8) - { - return ; - } - int firstByte = bits.readBits(8); - if (firstByte == 254) - { - // Unlatch codeword - return ; - } - - parseTwoBytes(firstByte, bits.readBits(8), cValues); - - int shift = 0; - for (int i = 0; i < 3; i++) - { - int cValue = cValues[i]; - switch (shift) - { - - case 0: - if (cValue < 3) - { - shift = cValue + 1; - } - else - { - if (upperShift) - { - result.Append((char) (C40_BASIC_SET_CHARS[cValue] + 128)); - upperShift = false; - } - else - { - result.Append(C40_BASIC_SET_CHARS[cValue]); - } - } - break; - - case 1: - if (upperShift) - { - result.Append((char) (cValue + 128)); - upperShift = false; - } - else - { - result.Append(cValue); - } - shift = 0; - break; - - case 2: - if (cValue < 27) - { - if (upperShift) - { - result.Append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); - upperShift = false; - } - else - { - result.Append(C40_SHIFT2_SET_CHARS[cValue]); - } - } - else if (cValue == 27) - { - // FNC1 - throw ReaderException.Instance; - } - else if (cValue == 30) - { - // Upper Shift - upperShift = true; - } - else - { - throw ReaderException.Instance; - } - shift = 0; - break; - - case 3: - if (upperShift) - { - result.Append((char) (cValue + 224)); - upperShift = false; - } - else - { - result.Append((char) (cValue + 96)); - } - shift = 0; - break; - - default: - throw ReaderException.Instance; - - } - } - } - while (bits.available() > 0); - } - - /// See ISO 16022:2006, 5.2.6 and Annex C, Table C.2 - private static void decodeTextSegment(BitSource bits, System.Text.StringBuilder result) - { - // Three Text values are encoded in a 16-bit value as - // (1600 * C1) + (40 * C2) + C3 + 1 - // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time - bool upperShift = false; - - int[] cValues = new int[3]; - do - { - // If there is only one byte left then it will be encoded as ASCII - if (bits.available() == 8) - { - return ; - } - int firstByte = bits.readBits(8); - if (firstByte == 254) - { - // Unlatch codeword - return ; - } - - parseTwoBytes(firstByte, bits.readBits(8), cValues); - - int shift = 0; - for (int i = 0; i < 3; i++) - { - int cValue = cValues[i]; - switch (shift) - { - - case 0: - if (cValue < 3) - { - shift = cValue + 1; - } - else - { - if (upperShift) - { - result.Append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128)); - upperShift = false; - } - else - { - result.Append(TEXT_BASIC_SET_CHARS[cValue]); - } - } - break; - - case 1: - if (upperShift) - { - result.Append((char) (cValue + 128)); - upperShift = false; - } - else - { - result.Append(cValue); - } - shift = 0; - break; - - case 2: - // Shift 2 for Text is the same encoding as C40 - if (cValue < 27) - { - if (upperShift) - { - result.Append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); - upperShift = false; - } - else - { - result.Append(C40_SHIFT2_SET_CHARS[cValue]); - } - } - else if (cValue == 27) - { - // FNC1 - throw ReaderException.Instance; - } - else if (cValue == 30) - { - // Upper Shift - upperShift = true; - } - else - { - throw ReaderException.Instance; - } - shift = 0; - break; - - case 3: - if (upperShift) - { - result.Append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128)); - upperShift = false; - } - else - { - result.Append(TEXT_SHIFT3_SET_CHARS[cValue]); - } - shift = 0; - break; - - default: - throw ReaderException.Instance; - - } - } - } - while (bits.available() > 0); - } - - /// See ISO 16022:2006, 5.2.7 - private static void decodeAnsiX12Segment(BitSource bits, System.Text.StringBuilder result) - { - // Three ANSI X12 values are encoded in a 16-bit value as - // (1600 * C1) + (40 * C2) + C3 + 1 - - int[] cValues = new int[3]; - do - { - // If there is only one byte left then it will be encoded as ASCII - if (bits.available() == 8) - { - return ; - } - int firstByte = bits.readBits(8); - if (firstByte == 254) - { - // Unlatch codeword - return ; - } - - parseTwoBytes(firstByte, bits.readBits(8), cValues); - - for (int i = 0; i < 3; i++) - { - int cValue = cValues[i]; - if (cValue == 0) - { - // X12 segment terminator - result.Append('\r'); - } - else if (cValue == 1) - { - // X12 segment separator * - result.Append('*'); - } - else if (cValue == 2) - { - // X12 sub-element separator > - result.Append('>'); - } - else if (cValue == 3) - { - // space - result.Append(' '); - } - else if (cValue < 14) - { - // 0 - 9 - result.Append((char) (cValue + 44)); - } - else if (cValue < 40) - { - // A - Z - result.Append((char) (cValue + 51)); - } - else - { - throw ReaderException.Instance; - } - } - } - while (bits.available() > 0); - } - - private static void parseTwoBytes(int firstByte, int secondByte, int[] result) - { - int fullBitValue = (firstByte << 8) + secondByte - 1; - int temp = fullBitValue / 1600; - result[0] = temp; - fullBitValue -= temp * 1600; - temp = fullBitValue / 40; - result[1] = temp; - result[2] = fullBitValue - temp * 40; - } - - /// See ISO 16022:2006, 5.2.8 and Annex C Table C.3 - private static void decodeEdifactSegment(BitSource bits, System.Text.StringBuilder result) - { - bool unlatch = false; - do - { - // If there is only two or less bytes left then it will be encoded as ASCII - if (bits.available() <= 16) - { - return ; - } - - for (int i = 0; i < 4; i++) - { - int edifactValue = bits.readBits(6); - - // Check for the unlatch character - if (edifactValue == 0x2B67) - { - // 011111 - unlatch = true; - // If we encounter the unlatch code then continue reading because the Codeword triple - // is padded with 0's - } - - if (!unlatch) - { - if ((edifactValue & 32) == 0) - { - // no 1 in the leading (6th) bit - edifactValue |= 64; // Add a leading 01 to the 6 bit binary value - } - result.Append(edifactValue); - } - } - } - while (!unlatch && bits.available() > 0); - } - - /// See ISO 16022:2006, 5.2.9 and Annex B, B.2 - private static void decodeBase256Segment(BitSource bits, System.Text.StringBuilder result, System.Collections.ArrayList byteSegments) - { - // Figure out how long the Base 256 Segment is. - int d1 = bits.readBits(8); - int count; - if (d1 == 0) - { - // Read the remainder of the symbol - count = bits.available() / 8; - } - else if (d1 < 250) - { - count = d1; - } - else - { - count = 250 * (d1 - 249) + bits.readBits(8); - } - sbyte[] bytes = new sbyte[count]; - for (int i = 0; i < count; i++) - { - bytes[i] = unrandomize255State(bits.readBits(8), i); - } - byteSegments.Add(SupportClass.ToByteArray(bytes)); - try - { - //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" - result.Append(System.Text.Encoding.GetEncoding("ISO8859_1").GetString(SupportClass.ToByteArray(bytes))); - } - catch (System.IO.IOException uee) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new System.SystemException("Platform does not support required encoding: " + uee); - } - } - - /// See ISO 16022:2006, Annex B, B.2 - private static sbyte unrandomize255State(int randomizedBase256Codeword, int base256CodewordPosition) - { - int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1; - int tempVariable = randomizedBase256Codeword - pseudoRandomNumber; - return (sbyte) (tempVariable >= 0?tempVariable:(tempVariable + 256)); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/datamatrix/decoder/Decoder.cs b/zxing-csharp/datamatrix/decoder/Decoder.cs deleted file mode 100644 index 4901ceb..0000000 --- a/zxing-csharp/datamatrix/decoder/Decoder.cs +++ /dev/null @@ -1,153 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using BitMatrix = com.google.zxing.common.BitMatrix; -using DecoderResult = com.google.zxing.common.DecoderResult; -using GF256 = com.google.zxing.common.reedsolomon.GF256; -using ReedSolomonDecoder = com.google.zxing.common.reedsolomon.ReedSolomonDecoder; -using ReedSolomonException = com.google.zxing.common.reedsolomon.ReedSolomonException; -namespace com.google.zxing.datamatrix.decoder -{ - - ///

The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting - /// the Data Matrix Code from an image.

- /// - ///
- /// bbrown@google.com (Brian Brown) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Decoder - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'rsDecoder '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ReedSolomonDecoder rsDecoder; - - public Decoder() - { - rsDecoder = new ReedSolomonDecoder(GF256.DATA_MATRIX_FIELD); - } - - ///

Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans. - /// "true" is taken to mean a black module.

- /// - ///
- /// booleans representing white/black Data Matrix Code modules - /// - /// text and bytes encoded within the Data Matrix Code - /// - /// ReaderException if the Data Matrix Code cannot be decoded - public DecoderResult decode(bool[][] image) - { - int dimension = image.Length; - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) - { - for (int j = 0; j < dimension; j++) - { - if (image[i][j]) - { - bits.set_Renamed(j, i); - } - } - } - return decode(bits); - } - - ///

Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken - /// to mean a black module.

- /// - ///
- /// booleans representing white/black Data Matrix Code modules - /// - /// text and bytes encoded within the Data Matrix Code - /// - /// ReaderException if the Data Matrix Code cannot be decoded - public DecoderResult decode(BitMatrix bits) - { - - // Construct a parser and read version, error-correction level - BitMatrixParser parser = new BitMatrixParser(bits); - Version version = parser.readVersion(bits); - - // Read codewords - sbyte[] codewords = parser.readCodewords(); - // Separate into data blocks - DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version); - - // Count total number of data bytes - int totalBytes = 0; - for (int i = 0; i < dataBlocks.Length; i++) - { - totalBytes += dataBlocks[i].NumDataCodewords; - } - sbyte[] resultBytes = new sbyte[totalBytes]; - int resultOffset = 0; - - // Error-correct and copy data blocks together into a stream of bytes - for (int j = 0; j < dataBlocks.Length; j++) - { - DataBlock dataBlock = dataBlocks[j]; - sbyte[] codewordBytes = dataBlock.Codewords; - int numDataCodewords = dataBlock.NumDataCodewords; - correctErrors(codewordBytes, numDataCodewords); - for (int i = 0; i < numDataCodewords; i++) - { - resultBytes[resultOffset++] = codewordBytes[i]; - } - } - - // Decode the contents of that stream of bytes - return DecodedBitStreamParser.decode(resultBytes); - } - - ///

Given data and error-correction codewords received, possibly corrupted by errors, attempts to - /// correct the errors in-place using Reed-Solomon error correction.

- /// - ///
- /// data and error correction codewords - /// - /// number of codewords that are data bytes - /// - /// ReaderException if error correction fails - private void correctErrors(sbyte[] codewordBytes, int numDataCodewords) - { - int numCodewords = codewordBytes.Length; - // First read into an array of ints - int[] codewordsInts = new int[numCodewords]; - for (int i = 0; i < numCodewords; i++) - { - codewordsInts[i] = codewordBytes[i] & 0xFF; - } - int numECCodewords = codewordBytes.Length - numDataCodewords; - try - { - rsDecoder.decode(codewordsInts, numECCodewords); - } - catch (ReedSolomonException rse) - { - throw ReaderException.Instance; - } - // Copy back into array of bytes -- only need to worry about the bytes that were data - // We don't care about errors in the error-correction codewords - for (int i = 0; i < numDataCodewords; i++) - { - codewordBytes[i] = (sbyte) codewordsInts[i]; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/datamatrix/decoder/Version.cs b/zxing-csharp/datamatrix/decoder/Version.cs deleted file mode 100644 index e91ef7d..0000000 --- a/zxing-csharp/datamatrix/decoder/Version.cs +++ /dev/null @@ -1,241 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -namespace com.google.zxing.datamatrix.decoder -{ - - /// The Version object encapsulates attributes about a particular - /// size Data Matrix Code. - /// - /// - /// bbrown@google.com (Brian Brown) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Version - { - public int VersionNumber - { - get - { - return versionNumber; - } - - } - public int SymbolSizeRows - { - get - { - return symbolSizeRows; - } - - } - public int SymbolSizeColumns - { - get - { - return symbolSizeColumns; - } - - } - public int DataRegionSizeRows - { - get - { - return dataRegionSizeRows; - } - - } - public int DataRegionSizeColumns - { - get - { - return dataRegionSizeColumns; - } - - } - public int TotalCodewords - { - get - { - return totalCodewords; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'VERSIONS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly Version[] VERSIONS = buildVersions(); - - //UPGRADE_NOTE: Final was removed from the declaration of 'versionNumber '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int versionNumber; - //UPGRADE_NOTE: Final was removed from the declaration of 'symbolSizeRows '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int symbolSizeRows; - //UPGRADE_NOTE: Final was removed from the declaration of 'symbolSizeColumns '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int symbolSizeColumns; - //UPGRADE_NOTE: Final was removed from the declaration of 'dataRegionSizeRows '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int dataRegionSizeRows; - //UPGRADE_NOTE: Final was removed from the declaration of 'dataRegionSizeColumns '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int dataRegionSizeColumns; - //UPGRADE_NOTE: Final was removed from the declaration of 'ecBlocks '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ECBlocks ecBlocks; - //UPGRADE_NOTE: Final was removed from the declaration of 'totalCodewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int totalCodewords; - - private Version(int versionNumber, int symbolSizeRows, int symbolSizeColumns, int dataRegionSizeRows, int dataRegionSizeColumns, ECBlocks ecBlocks) - { - this.versionNumber = versionNumber; - this.symbolSizeRows = symbolSizeRows; - this.symbolSizeColumns = symbolSizeColumns; - this.dataRegionSizeRows = dataRegionSizeRows; - this.dataRegionSizeColumns = dataRegionSizeColumns; - this.ecBlocks = ecBlocks; - - // Calculate the total number of codewords - int total = 0; - int ecCodewords = ecBlocks.ECCodewords; - ECB[] ecbArray = ecBlocks.getECBlocks(); - for (int i = 0; i < ecbArray.Length; i++) - { - ECB ecBlock = ecbArray[i]; - total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); - } - this.totalCodewords = total; - } - - internal ECBlocks getECBlocks() - { - return ecBlocks; - } - - ///

Deduces version information from Data Matrix dimensions.

- /// - ///
- /// Number of rows in modules - /// - /// Number of columns in modules - /// - /// {@link Version} for a Data Matrix Code of those dimensions - /// - /// ReaderException if dimensions do correspond to a valid Data Matrix size - public static Version getVersionForDimensions(int numRows, int numColumns) - { - if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0) - { - throw ReaderException.Instance; - } - - // TODO(bbrown): This is doing a linear search through the array of versions. - // If we interleave the rectangular versions with the square versions we could - // do a binary search. - int numVersions = VERSIONS.Length; - for (int i = 0; i < numVersions; ++i) - { - Version version = VERSIONS[i]; - if (version.symbolSizeRows == numRows && version.symbolSizeColumns == numColumns) - { - return version; - } - } - - throw ReaderException.Instance; - } - - ///

Encapsulates a set of error-correction blocks in one symbol version. Most versions will - /// use blocks of differing sizes within one version, so, this encapsulates the parameters for - /// each set of blocks. It also holds the number of error-correction codewords per block since it - /// will be the same across all blocks within one version.

- ///
- internal sealed class ECBlocks - { - internal int ECCodewords - { - get - { - return ecCodewords; - } - - } - //UPGRADE_NOTE: Final was removed from the declaration of 'ecCodewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int ecCodewords; - //UPGRADE_NOTE: Final was removed from the declaration of 'ecBlocks '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ECB[] ecBlocks; - - internal ECBlocks(int ecCodewords, ECB ecBlocks) - { - this.ecCodewords = ecCodewords; - this.ecBlocks = new ECB[]{ecBlocks}; - } - - internal ECBlocks(int ecCodewords, ECB ecBlocks1, ECB ecBlocks2) - { - this.ecCodewords = ecCodewords; - this.ecBlocks = new ECB[]{ecBlocks1, ecBlocks2}; - } - - internal ECB[] getECBlocks() - { - return ecBlocks; - } - } - - ///

Encapsualtes the parameters for one error-correction block in one symbol version. - /// This includes the number of data codewords, and the number of times a block with these - /// parameters is used consecutively in the Data Matrix code version's format.

- ///
- internal sealed class ECB - { - internal int Count - { - get - { - return count; - } - - } - internal int DataCodewords - { - get - { - return dataCodewords; - } - - } - //UPGRADE_NOTE: Final was removed from the declaration of 'count '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int count; - //UPGRADE_NOTE: Final was removed from the declaration of 'dataCodewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int dataCodewords; - - internal ECB(int count, int dataCodewords) - { - this.count = count; - this.dataCodewords = dataCodewords; - } - } - - public override System.String ToString() - { - return System.Convert.ToString(versionNumber); - } - - /// See ISO 16022:2006 5.5.1 Table 7 - private static Version[] buildVersions() - { - return new Version[]{new Version(1, 10, 10, 8, 8, new ECBlocks(5, new ECB(1, 3))), new Version(2, 12, 12, 10, 10, new ECBlocks(7, new ECB(1, 5))), new Version(3, 14, 14, 12, 12, new ECBlocks(10, new ECB(1, 8))), new Version(4, 16, 16, 14, 14, new ECBlocks(12, new ECB(1, 12))), new Version(5, 18, 18, 16, 16, new ECBlocks(14, new ECB(1, 18))), new Version(6, 20, 20, 18, 18, new ECBlocks(18, new ECB(1, 22))), new Version(7, 22, 22, 20, 20, new ECBlocks(20, new ECB(1, 30))), new Version(8, 24, 24, 22, 22, new ECBlocks(24, new ECB(1, 36))), new Version(9, 26, 26, 24, 24, new ECBlocks(28, new ECB(1, 44))), new Version(10, 32, 32, 14, 14, new ECBlocks(36, new ECB(1, 62))), new Version(11, 36, 36, 16, 16, new ECBlocks(42, new ECB(1, 86))), new Version(12, 40, 40, 18, 18, new ECBlocks(48, new ECB(1, 114))), new Version(13, 44, 44, 20, 20, new ECBlocks(56, new ECB(1, 144))), new Version(14, 48, 48, 22, 22, new ECBlocks(68, new ECB(1, 174))), new Version(15, 52, 52, 24, 24, new ECBlocks(42, new ECB(2, 102))), new Version(16, 64, 64, 14, 14, new ECBlocks(56, new ECB(2, 140))), new Version(17, 72, 72, 16, 16, new ECBlocks(36, new ECB(4, 92))), new Version(18, 80, 80, 18, 18, new ECBlocks(48, new ECB(4, 114))), new Version(19, 88, 88, 20, 20, new ECBlocks(56, new ECB(4, 144))), new Version(20, 96, 96, 22, 22, new ECBlocks(68, new ECB(4, 174))), new Version(21, 104, 104, 24, 24, new ECBlocks(56, new ECB(6, 136))), new Version(22, 120, 120, 18, 18, new ECBlocks(68, new ECB(6, 175))), new Version(23, 132, 132, 20, 20, new ECBlocks(62, new ECB(8, 163))), new Version(24, 144, 144, 22, 22, new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))), new Version(25, 8, 18, 6, 16, new ECBlocks(7, new ECB(1, 5))), new Version(26, 8, 32, 6, 14, new ECBlocks(11, new ECB(1, 10))), new Version(27, 12, 26, 10, 24, new ECBlocks(14, new ECB(1, 16))), new Version(28, 12, 36, 10, 16, new ECBlocks(18, new ECB(1, 22))), new Version(29, 16, 36, 10, 16, new ECBlocks(24, new ECB(1, 32))), new Version(30, 16, 48, 14, 22, new ECBlocks(28, - new ECB(1, 49)))}; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/datamatrix/detector/Detector.cs b/zxing-csharp/datamatrix/detector/Detector.cs deleted file mode 100644 index 31278d0..0000000 --- a/zxing-csharp/datamatrix/detector/Detector.cs +++ /dev/null @@ -1,325 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using ResultPoint = com.google.zxing.ResultPoint; -using BitMatrix = com.google.zxing.common.BitMatrix; -using Collections = com.google.zxing.common.Collections; -using Comparator = com.google.zxing.common.Comparator; -using DetectorResult = com.google.zxing.common.DetectorResult; -using GridSampler = com.google.zxing.common.GridSampler; -using MonochromeRectangleDetector = com.google.zxing.common.detector.MonochromeRectangleDetector; -namespace com.google.zxing.datamatrix.detector -{ - - ///

Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code - /// is rotated or skewed, or partially obscured.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Detector - { - - //private static final int MAX_MODULES = 32; - - // Trick to avoid creating new Integer objects below -- a sort of crude copy of - // the Integer.valueOf(int) optimization added in Java 5, not in J2ME - //UPGRADE_NOTE: Final was removed from the declaration of 'INTEGERS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.Int32[] INTEGERS = new System.Int32[]{0, 1, 2, 3, 4}; - // No, can't use valueOf() - - //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix image; - //UPGRADE_NOTE: Final was removed from the declaration of 'rectangleDetector '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private MonochromeRectangleDetector rectangleDetector; - - public Detector(BitMatrix image) - { - this.image = image; - rectangleDetector = new MonochromeRectangleDetector(image); - } - - ///

Detects a Data Matrix Code in an image.

- /// - ///
- /// {@link DetectorResult} encapsulating results of detecting a QR Code - /// - /// ReaderException if no Data Matrix Code can be found - public DetectorResult detect() - { - - ResultPoint[] cornerPoints = rectangleDetector.detect(); - ResultPoint pointA = cornerPoints[0]; - ResultPoint pointB = cornerPoints[1]; - ResultPoint pointC = cornerPoints[2]; - ResultPoint pointD = cornerPoints[3]; - - // Point A and D are across the diagonal from one another, - // as are B and C. Figure out which are the solid black lines - // by counting transitions - System.Collections.ArrayList transitions = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(4)); - transitions.Add(transitionsBetween(pointA, pointB)); - transitions.Add(transitionsBetween(pointA, pointC)); - transitions.Add(transitionsBetween(pointB, pointD)); - transitions.Add(transitionsBetween(pointC, pointD)); - Collections.insertionSort(transitions, new ResultPointsAndTransitionsComparator()); - - // Sort by number of transitions. First two will be the two solid sides; last two - // will be the two alternating black/white sides - ResultPointsAndTransitions lSideOne = (ResultPointsAndTransitions) transitions[0]; - ResultPointsAndTransitions lSideTwo = (ResultPointsAndTransitions) transitions[1]; - - // Figure out which point is their intersection by tallying up the number of times we see the - // endpoints in the four endpoints. One will show up twice. - System.Collections.Hashtable pointCount = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); - increment(pointCount, lSideOne.From); - increment(pointCount, lSideOne.To); - increment(pointCount, lSideTwo.From); - increment(pointCount, lSideTwo.To); - - ResultPoint maybeTopLeft = null; - ResultPoint bottomLeft = null; - ResultPoint maybeBottomRight = null; - System.Collections.IEnumerator points = pointCount.Keys.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (points.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - ResultPoint point = (ResultPoint) points.Current; - System.Int32 value_Renamed = (System.Int32) pointCount[point]; - if (value_Renamed == 2) - { - bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides - } - else - { - // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now - if (maybeTopLeft == null) - { - maybeTopLeft = point; - } - else - { - maybeBottomRight = point; - } - } - } - - if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null) - { - throw ReaderException.Instance; - } - - // Bottom left is correct but top left and bottom right might be switched - ResultPoint[] corners = new ResultPoint[]{maybeTopLeft, bottomLeft, maybeBottomRight}; - // Use the dot product trick to sort them out - ResultPoint.orderBestPatterns(corners); - - // Now we know which is which: - ResultPoint bottomRight = corners[0]; - bottomLeft = corners[1]; - ResultPoint topLeft = corners[2]; - - // Which point didn't we find in relation to the "L" sides? that's the top right corner - ResultPoint topRight; - if (!pointCount.ContainsKey(pointA)) - { - topRight = pointA; - } - else if (!pointCount.ContainsKey(pointB)) - { - topRight = pointB; - } - else if (!pointCount.ContainsKey(pointC)) - { - topRight = pointC; - } - else - { - topRight = pointD; - } - - // Next determine the dimension by tracing along the top or right side and counting black/white - // transitions. Since we start inside a black module, we should see a number of transitions - // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to - // end on a black module: - - // The top right point is actually the corner of a module, which is one of the two black modules - // adjacent to the white module at the top right. Tracing to that corner from either the top left - // or bottom right should work here. The number of transitions could be higher than it should be - // due to noise. So we try both and take the min. - - int dimension = System.Math.Min(transitionsBetween(topLeft, topRight).Transitions, transitionsBetween(bottomRight, topRight).Transitions); - if ((dimension & 0x01) == 1) - { - // it can't be odd, so, round... up? - dimension++; - } - dimension += 2; - - BitMatrix bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, dimension); - return new DetectorResult(bits, new ResultPoint[]{pointA, pointB, pointC, pointD}); - } - - /// Increments the Integer associated with a key by one. - private static void increment(System.Collections.Hashtable table, ResultPoint key) - { - //System.Int32 value_Renamed = (System.Int32) table[key]; - ////UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'" - //table[key] = value_Renamed == null?INTEGERS[1]:INTEGERS[value_Renamed + 1]; - // Redivivus.in Java to c# Porting update - // 30/01/2010 - // Added - // START - System.Int32 value_Renamed = 0; - try - { - if (table.Count > 0) - value_Renamed = (System.Int32)table[key]; - } - catch - { - value_Renamed = 0; - } - table[key] = value_Renamed == 0 ? INTEGERS[1] : INTEGERS[value_Renamed + 1]; - //END - } - - private static BitMatrix sampleGrid(BitMatrix image, ResultPoint topLeft, ResultPoint bottomLeft, ResultPoint bottomRight, int dimension) - { - - // We make up the top right point for now, based on the others. - // TODO: we actually found a fourth corner above and figured out which of two modules - // it was the corner of. We could use that here and adjust for perspective distortion. - float topRightX = (bottomRight.X - bottomLeft.X) + topLeft.X; - float topRightY = (bottomRight.Y - bottomLeft.Y) + topLeft.Y; - - // Note that unlike in the QR Code sampler, we didn't find the center of modules, but the - // very corners. So there is no 0.5f here; 0.0f is right. - GridSampler sampler = GridSampler.Instance; - return sampler.sampleGrid(image, dimension, 0.0f, 0.0f, dimension, 0.0f, dimension, dimension, 0.0f, dimension, topLeft.X, topLeft.Y, topRightX, topRightY, bottomRight.X, bottomRight.Y, bottomLeft.X, bottomLeft.Y); - } - - /// Counts the number of black/white transitions between two points, using something like Bresenham's algorithm. - private ResultPointsAndTransitions transitionsBetween(ResultPoint from, ResultPoint to) - { - // See QR Code Detector, sizeOfBlackWhiteBlackRun() - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int fromX = (int) from.X; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int fromY = (int) from.Y; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int toX = (int) to.X; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int toY = (int) to.Y; - bool steep = System.Math.Abs(toY - fromY) > System.Math.Abs(toX - fromX); - if (steep) - { - int temp = fromX; - fromX = fromY; - fromY = temp; - temp = toX; - toX = toY; - toY = temp; - } - - int dx = System.Math.Abs(toX - fromX); - int dy = System.Math.Abs(toY - fromY); - int error = - dx >> 1; - int ystep = fromY < toY?1:- 1; - int xstep = fromX < toX?1:- 1; - int transitions = 0; - bool inBlack = image.get_Renamed(steep?fromY:fromX, steep?fromX:fromY); - for (int x = fromX, y = fromY; x != toX; x += xstep) - { - bool isBlack = image.get_Renamed(steep?y:x, steep?x:y); - if (isBlack != inBlack) - { - transitions++; - inBlack = isBlack; - } - error += dy; - if (error > 0) - { - if (y == toY) - { - break; - } - y += ystep; - error -= dx; - } - } - return new ResultPointsAndTransitions(from, to, transitions); - } - - /// Simply encapsulates two points and a number of transitions between them. - private class ResultPointsAndTransitions - { - public ResultPoint From - { - get - { - return from; - } - - } - public ResultPoint To - { - get - { - return to; - } - - } - public int Transitions - { - get - { - return transitions; - } - - } - //UPGRADE_NOTE: Final was removed from the declaration of 'from '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ResultPoint from; - //UPGRADE_NOTE: Final was removed from the declaration of 'to '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ResultPoint to; - //UPGRADE_NOTE: Final was removed from the declaration of 'transitions '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int transitions; - internal ResultPointsAndTransitions(ResultPoint from, ResultPoint to, int transitions) - { - this.from = from; - this.to = to; - this.transitions = transitions; - } - public override System.String ToString() - { - return from + "/" + to + '/' + transitions; - } - } - - /// Orders ResultPointsAndTransitions by number of transitions, ascending. - private class ResultPointsAndTransitionsComparator : Comparator - { - public int compare(System.Object o1, System.Object o2) - { - return ((ResultPointsAndTransitions) o1).Transitions - ((ResultPointsAndTransitions) o2).Transitions; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/multi/ByQuadrantReader.cs b/zxing-csharp/multi/ByQuadrantReader.cs deleted file mode 100644 index a885d98..0000000 --- a/zxing-csharp/multi/ByQuadrantReader.cs +++ /dev/null @@ -1,103 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using Reader = com.google.zxing.Reader; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -namespace com.google.zxing.multi -{ - - /// This class attempts to decode a barcode from an image, not by scanning the whole image, - /// but by scanning subsets of the image. This is important when there may be multiple barcodes in - /// an image, and detecting a barcode may find parts of multiple barcode and fail to decode - /// (e.g. QR Codes). Instead this scans the four quadrants of the image -- and also the center - /// 'quadrant' to cover the case where a barcode is found in the center. - /// - /// - /// - /// - public sealed class ByQuadrantReader : Reader - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'delegate '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private Reader delegate_Renamed; - - public ByQuadrantReader(Reader delegate_Renamed) - { - this.delegate_Renamed = delegate_Renamed; - } - - public Result decode(BinaryBitmap image) - { - return decode(image, null); - } - - public Result decode(BinaryBitmap image, System.Collections.Hashtable hints) - { - - int width = image.Width; - int height = image.Height; - int halfWidth = width / 2; - int halfHeight = height / 2; - - BinaryBitmap topLeft = image.crop(0, 0, halfWidth, halfHeight); - try - { - return delegate_Renamed.decode(topLeft, hints); - } - catch (ReaderException re) - { - // continue - } - - BinaryBitmap topRight = image.crop(halfWidth, 0, halfWidth, halfHeight); - try - { - return delegate_Renamed.decode(topRight, hints); - } - catch (ReaderException re) - { - // continue - } - - BinaryBitmap bottomLeft = image.crop(0, halfHeight, halfWidth, halfHeight); - try - { - return delegate_Renamed.decode(bottomLeft, hints); - } - catch (ReaderException re) - { - // continue - } - - BinaryBitmap bottomRight = image.crop(halfWidth, halfHeight, halfWidth, halfHeight); - try - { - return delegate_Renamed.decode(bottomRight, hints); - } - catch (ReaderException re) - { - // continue - } - - int quarterWidth = halfWidth / 2; - int quarterHeight = halfHeight / 2; - BinaryBitmap center = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight); - return delegate_Renamed.decode(center, hints); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/multi/GenericMultipleBarcodeReader.cs b/zxing-csharp/multi/GenericMultipleBarcodeReader.cs deleted file mode 100644 index ba37eb6..0000000 --- a/zxing-csharp/multi/GenericMultipleBarcodeReader.cs +++ /dev/null @@ -1,175 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Reader = com.google.zxing.Reader; -using Result = com.google.zxing.Result; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using ReaderException = com.google.zxing.ReaderException; -using ResultPoint = com.google.zxing.ResultPoint; -namespace com.google.zxing.multi -{ - - ///

Attempts to locate multiple barcodes in an image by repeatedly decoding portion of the image. - /// After one barcode is found, the areas left, above, right and below the barcode's - /// {@link com.google.zxing.ResultPoint}s are scanned, recursively.

- /// - ///

A caller may want to also employ {@link ByQuadrantReader} when attempting to find multiple - /// 2D barcodes, like QR Codes, in an image, where the presence of multiple barcodes might prevent - /// detecting any one of them.

- /// - ///

That is, instead of passing a {@link Reader} a caller might pass - /// new ByQuadrantReader(reader).

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class GenericMultipleBarcodeReader : MultipleBarcodeReader - { - - private const int MIN_DIMENSION_TO_RECUR = 30; - - //UPGRADE_NOTE: Final was removed from the declaration of 'delegate '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private Reader delegate_Renamed; - - public GenericMultipleBarcodeReader(Reader delegate_Renamed) - { - this.delegate_Renamed = delegate_Renamed; - } - - public Result[] decodeMultiple(BinaryBitmap image) - { - return decodeMultiple(image, null); - } - - public Result[] decodeMultiple(BinaryBitmap image, System.Collections.Hashtable hints) - { - System.Collections.ArrayList results = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - doDecodeMultiple(image, hints, results, 0, 0); - if ((results.Count == 0)) - { - throw ReaderException.Instance; - } - int numResults = results.Count; - Result[] resultArray = new Result[numResults]; - for (int i = 0; i < numResults; i++) - { - resultArray[i] = (Result) results[i]; - } - return resultArray; - } - - private void doDecodeMultiple(BinaryBitmap image, System.Collections.Hashtable hints, System.Collections.ArrayList results, int xOffset, int yOffset) - { - Result result; - try - { - result = delegate_Renamed.decode(image, hints); - } - catch (ReaderException re) - { - return ; - } - bool alreadyFound = false; - for (int i = 0; i < results.Count; i++) - { - Result existingResult = (Result) results[i]; - if (existingResult.Text.Equals(result.Text)) - { - alreadyFound = true; - break; - } - } - if (alreadyFound) - { - return ; - } - results.Add(translateResultPoints(result, xOffset, yOffset)); - ResultPoint[] resultPoints = result.ResultPoints; - if (resultPoints == null || resultPoints.Length == 0) - { - return ; - } - int width = image.Width; - int height = image.Height; - float minX = width; - float minY = height; - float maxX = 0.0f; - float maxY = 0.0f; - for (int i = 0; i < resultPoints.Length; i++) - { - ResultPoint point = resultPoints[i]; - float x = point.X; - float y = point.Y; - if (x < minX) - { - minX = x; - } - if (y < minY) - { - minY = y; - } - if (x > maxX) - { - maxX = x; - } - if (y > maxY) - { - maxY = y; - } - } - - // Decode left of barcode - if (minX > MIN_DIMENSION_TO_RECUR) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - doDecodeMultiple(image.crop(0, 0, (int) minX, height), hints, results, xOffset, yOffset); - } - // Decode above barcode - if (minY > MIN_DIMENSION_TO_RECUR) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - doDecodeMultiple(image.crop(0, 0, width, (int) minY), hints, results, xOffset, yOffset); - } - // Decode right of barcode - if (maxX < width - MIN_DIMENSION_TO_RECUR) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - doDecodeMultiple(image.crop((int) maxX, 0, width - (int) maxX, height), hints, results, xOffset + (int) maxX, yOffset); - } - // Decode below barcode - if (maxY < height - MIN_DIMENSION_TO_RECUR) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - doDecodeMultiple(image.crop(0, (int) maxY, width, height - (int) maxY), hints, results, xOffset, yOffset + (int) maxY); - } - } - - private static Result translateResultPoints(Result result, int xOffset, int yOffset) - { - ResultPoint[] oldResultPoints = result.ResultPoints; - ResultPoint[] newResultPoints = new ResultPoint[oldResultPoints.Length]; - for (int i = 0; i < oldResultPoints.Length; i++) - { - ResultPoint oldPoint = oldResultPoints[i]; - newResultPoints[i] = new ResultPoint(oldPoint.X + xOffset, oldPoint.Y + yOffset); - } - return new Result(result.Text, result.RawBytes, newResultPoints, result.BarcodeFormat); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/multi/MultipleBarcodeReader.cs b/zxing-csharp/multi/MultipleBarcodeReader.cs deleted file mode 100644 index 3a0dcba..0000000 --- a/zxing-csharp/multi/MultipleBarcodeReader.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using Result = com.google.zxing.Result; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using ReaderException = com.google.zxing.ReaderException; -namespace com.google.zxing.multi -{ - - /// Implementation of this interface attempt to read several barcodes from one image. - /// - /// - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public interface MultipleBarcodeReader - { - - Result[] decodeMultiple(BinaryBitmap image); - - Result[] decodeMultiple(BinaryBitmap image, System.Collections.Hashtable hints); - } -} \ No newline at end of file diff --git a/zxing-csharp/multi/qrcode/QRCodeMultiReader.cs b/zxing-csharp/multi/qrcode/QRCodeMultiReader.cs deleted file mode 100644 index 77def72..0000000 --- a/zxing-csharp/multi/qrcode/QRCodeMultiReader.cs +++ /dev/null @@ -1,93 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultMetadataType = com.google.zxing.ResultMetadataType; -using ResultPoint = com.google.zxing.ResultPoint; -using DecoderResult = com.google.zxing.common.DecoderResult; -using DetectorResult = com.google.zxing.common.DetectorResult; -using MultipleBarcodeReader = com.google.zxing.multi.MultipleBarcodeReader; -using MultiDetector = com.google.zxing.multi.qrcode.detector.MultiDetector; -using QRCodeReader = com.google.zxing.qrcode.QRCodeReader; -namespace com.google.zxing.multi.qrcode -{ - - /// This implementation can detect and decode multiple QR Codes in an image. - /// - /// - /// Sean Owen - /// - /// Hannes Erven - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class QRCodeMultiReader:QRCodeReader, MultipleBarcodeReader - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'EMPTY_RESULT_ARRAY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly Result[] EMPTY_RESULT_ARRAY = new Result[0]; - - public Result[] decodeMultiple(BinaryBitmap image) - { - return decodeMultiple(image, null); - } - - public Result[] decodeMultiple(BinaryBitmap image, System.Collections.Hashtable hints) - { - System.Collections.ArrayList results = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - DetectorResult[] detectorResult = new MultiDetector(image.BlackMatrix).detectMulti(hints); - for (int i = 0; i < detectorResult.Length; i++) - { - try - { - DecoderResult decoderResult = Decoder.decode(detectorResult[i].Bits); - ResultPoint[] points = detectorResult[i].Points; - Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE); - if (decoderResult.ByteSegments != null) - { - result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.ByteSegments); - } - if (decoderResult.ECLevel != null) - { - result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.ECLevel.ToString()); - } - results.Add(result); - } - catch (ReaderException re) - { - // ignore and continue - } - } - if ((results.Count == 0)) - { - return EMPTY_RESULT_ARRAY; - } - else - { - Result[] resultArray = new Result[results.Count]; - for (int i = 0; i < results.Count; i++) - { - resultArray[i] = (Result) results[i]; - } - return resultArray; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/multi/qrcode/detector/MultiDetector.cs b/zxing-csharp/multi/qrcode/detector/MultiDetector.cs deleted file mode 100644 index 2f82f04..0000000 --- a/zxing-csharp/multi/qrcode/detector/MultiDetector.cs +++ /dev/null @@ -1,84 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using DetectorResult = com.google.zxing.common.DetectorResult; -using BitMatrix = com.google.zxing.common.BitMatrix; -using Detector = com.google.zxing.qrcode.detector.Detector; -using FinderPatternInfo = com.google.zxing.qrcode.detector.FinderPatternInfo; -namespace com.google.zxing.multi.qrcode.detector -{ - - ///

Encapsulates logic that can detect one or more QR Codes in an image, even if the QR Code - /// is rotated or skewed, or partially obscured.

- /// - ///
- /// Sean Owen - /// - /// Hannes Erven - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - public sealed class MultiDetector:Detector - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'EMPTY_DETECTOR_RESULTS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly DetectorResult[] EMPTY_DETECTOR_RESULTS = new DetectorResult[0]; - - public MultiDetector(BitMatrix image):base(image) - { - } - - public DetectorResult[] detectMulti(System.Collections.Hashtable hints) - { - BitMatrix image = Image; - MultiFinderPatternFinder finder = new MultiFinderPatternFinder(image); - FinderPatternInfo[] info = finder.findMulti(hints); - - if (info == null || info.Length == 0) - { - throw ReaderException.Instance; - } - - System.Collections.ArrayList result = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - for (int i = 0; i < info.Length; i++) - { - try - { - result.Add(processFinderPatternInfo(info[i])); - } - catch (ReaderException e) - { - // ignore - } - } - if ((result.Count == 0)) - { - return EMPTY_DETECTOR_RESULTS; - } - else - { - DetectorResult[] resultArray = new DetectorResult[result.Count]; - for (int i = 0; i < result.Count; i++) - { - resultArray[i] = (DetectorResult) result[i]; - } - return resultArray; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/multi/qrcode/detector/MultiFinderPatternFinder.cs b/zxing-csharp/multi/qrcode/detector/MultiFinderPatternFinder.cs deleted file mode 100644 index 7766b19..0000000 --- a/zxing-csharp/multi/qrcode/detector/MultiFinderPatternFinder.cs +++ /dev/null @@ -1,367 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using DecodeHintType = com.google.zxing.DecodeHintType; -using ReaderException = com.google.zxing.ReaderException; -using ResultPoint = com.google.zxing.ResultPoint; -using ResultPointCallback = com.google.zxing.ResultPointCallback; -using Collections = com.google.zxing.common.Collections; -using Comparator = com.google.zxing.common.Comparator; -using BitMatrix = com.google.zxing.common.BitMatrix; -using FinderPattern = com.google.zxing.qrcode.detector.FinderPattern; -using FinderPatternFinder = com.google.zxing.qrcode.detector.FinderPatternFinder; -using FinderPatternInfo = com.google.zxing.qrcode.detector.FinderPatternInfo; -namespace com.google.zxing.multi.qrcode.detector -{ - - ///

This class attempts to find finder patterns in a QR Code. Finder patterns are the square - /// markers at three corners of a QR Code.

- /// - ///

This class is thread-safe but not reentrant. Each thread must allocate its own object. - /// - ///

In contrast to {@link FinderPatternFinder}, this class will return an array of all possible - /// QR code locations in the image.

- /// - ///

Use the TRY_HARDER hint to ask for a more thorough detection.

- /// - ///
- /// Sean Owen - /// - /// Hannes Erven - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - - - sealed class MultiFinderPatternFinder:FinderPatternFinder - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'EMPTY_RESULT_ARRAY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly FinderPatternInfo[] EMPTY_RESULT_ARRAY = new FinderPatternInfo[0]; - - // TODO MIN_MODULE_COUNT and MAX_MODULE_COUNT would be great hints to ask the user for - // since it limits the number of regions to decode - - // max. legal count of modules per QR code edge (177) - private const float MAX_MODULE_COUNT_PER_EDGE = 180; - // min. legal count per modules per QR code edge (11) - private const float MIN_MODULE_COUNT_PER_EDGE = 9; - - /// More or less arbitrary cutoff point for determining if two finder patterns might belong - /// to the same code if they differ less than DIFF_MODSIZE_CUTOFF_PERCENT percent in their - /// estimated modules sizes. - /// - private const float DIFF_MODSIZE_CUTOFF_PERCENT = 0.05f; - - /// More or less arbitrary cutoff point for determining if two finder patterns might belong - /// to the same code if they differ less than DIFF_MODSIZE_CUTOFF pixels/module in their - /// estimated modules sizes. - /// - private const float DIFF_MODSIZE_CUTOFF = 0.5f; - - - /// A comparator that orders FinderPatterns by their estimated module size. - private class ModuleSizeComparator : Comparator - { - public int compare(System.Object center1, System.Object center2) - { - float value_Renamed = ((FinderPattern) center2).EstimatedModuleSize - ((FinderPattern) center1).EstimatedModuleSize; - return value_Renamed < 0.0?- 1:(value_Renamed > 0.0?1:0); - } - } - - ///

Creates a finder that will search the image for three finder patterns.

- /// - ///
- /// image to search - /// - internal MultiFinderPatternFinder(BitMatrix image):base(image) - { - } - - internal MultiFinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback):base(image, resultPointCallback) - { - } - - /// the 3 best {@link FinderPattern}s from our list of candidates. The "best" are - /// those that have been detected at least {@link #CENTER_QUORUM} times, and whose module - /// size differs from the average among those patterns the least - /// - /// ReaderException if 3 such finder patterns do not exist - private FinderPattern[][] selectBestPatterns() - { - System.Collections.ArrayList possibleCenters = PossibleCenters; - int size = possibleCenters.Count; - - if (size < 3) - { - // Couldn't find enough finder patterns - throw ReaderException.Instance; - } - - /* - * Begin HE modifications to safely detect multiple codes of equal size - */ - if (size == 3) - { - return new FinderPattern[][]{new FinderPattern[]{(FinderPattern) possibleCenters[0], (FinderPattern) possibleCenters[1], (FinderPattern) possibleCenters[2]}}; - } - - // Sort by estimated module size to speed up the upcoming checks - Collections.insertionSort(possibleCenters, new ModuleSizeComparator()); - - /* - * Now lets start: build a list of tuples of three finder locations that - * - feature similar module sizes - * - are placed in a distance so the estimated module count is within the QR specification - * - have similar distance between upper left/right and left top/bottom finder patterns - * - form a triangle with 90° angle (checked by comparing top right/bottom left distance - * with pythagoras) - * - * Note: we allow each point to be used for more than one code region: this might seem - * counterintuitive at first, but the performance penalty is not that big. At this point, - * we cannot make a good quality decision whether the three finders actually represent - * a QR code, or are just by chance layouted so it looks like there might be a QR code there. - * So, if the layout seems right, lets have the decoder try to decode. - */ - - System.Collections.ArrayList results = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // holder for the results - - for (int i1 = 0; i1 < (size - 2); i1++) - { - FinderPattern p1 = (FinderPattern) possibleCenters[i1]; - if (p1 == null) - { - continue; - } - - for (int i2 = i1 + 1; i2 < (size - 1); i2++) - { - FinderPattern p2 = (FinderPattern) possibleCenters[i2]; - if (p2 == null) - { - continue; - } - - // Compare the expected module sizes; if they are really off, skip - float vModSize12 = (p1.EstimatedModuleSize - p2.EstimatedModuleSize) / (System.Math.Min(p1.EstimatedModuleSize, p2.EstimatedModuleSize)); - float vModSize12A = System.Math.Abs(p1.EstimatedModuleSize - p2.EstimatedModuleSize); - if (vModSize12A > DIFF_MODSIZE_CUTOFF && vModSize12 >= DIFF_MODSIZE_CUTOFF_PERCENT) - { - // break, since elements are ordered by the module size deviation there cannot be - // any more interesting elements for the given p1. - break; - } - - for (int i3 = i2 + 1; i3 < size; i3++) - { - FinderPattern p3 = (FinderPattern) possibleCenters[i3]; - if (p3 == null) - { - continue; - } - - // Compare the expected module sizes; if they are really off, skip - float vModSize23 = (p2.EstimatedModuleSize - p3.EstimatedModuleSize) / (System.Math.Min(p2.EstimatedModuleSize, p3.EstimatedModuleSize)); - float vModSize23A = System.Math.Abs(p2.EstimatedModuleSize - p3.EstimatedModuleSize); - if (vModSize23A > DIFF_MODSIZE_CUTOFF && vModSize23 >= DIFF_MODSIZE_CUTOFF_PERCENT) - { - // break, since elements are ordered by the module size deviation there cannot be - // any more interesting elements for the given p1. - break; - } - - FinderPattern[] test = new FinderPattern[]{p1, p2, p3}; - ResultPoint.orderBestPatterns(test); - - // Calculate the distances: a = topleft-bottomleft, b=topleft-topright, c = diagonal - FinderPatternInfo info = new FinderPatternInfo(test); - float dA = ResultPoint.distance(info.TopLeft, info.BottomLeft); - float dC = ResultPoint.distance(info.TopRight, info.BottomLeft); - float dB = ResultPoint.distance(info.TopLeft, info.TopRight); - - // Check the sizes - float estimatedModuleCount = ((dA + dB) / p1.EstimatedModuleSize) / 2; - if (estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE || estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE) - { - continue; - } - - // Calculate the difference of the edge lengths in percent - float vABBC = System.Math.Abs(((dA - dB) / System.Math.Min(dA, dB))); - if (vABBC >= 0.1f) - { - continue; - } - - // Calculate the diagonal length by assuming a 90° angle at topleft - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float dCpy = (float) System.Math.Sqrt(dA * dA + dB * dB); - // Compare to the real distance in % - float vPyC = System.Math.Abs(((dC - dCpy) / System.Math.Min(dC, dCpy))); - - if (vPyC >= 0.1f) - { - continue; - } - - // All tests passed! - results.Add(test); - } // end iterate p3 - } // end iterate p2 - } // end iterate p1 - - if (!(results.Count == 0)) - { - FinderPattern[][] resultArray = new FinderPattern[results.Count][]; - for (int i = 0; i < results.Count; i++) - { - resultArray[i] = (FinderPattern[]) results[i]; - } - return resultArray; - } - - // Nothing found! - throw ReaderException.Instance; - } - - public FinderPatternInfo[] findMulti(System.Collections.Hashtable hints) - { - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - BitMatrix image = Image; - int maxI = image.Height; - int maxJ = image.Width; - // We are looking for black/white/black/white/black modules in - // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far - - // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the - // image, and then account for the center being 3 modules in size. This gives the smallest - // number of pixels the center could be, so skip this often. When trying harder, look for all - // QR versions regardless of how dense they are. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int iSkip = (int) (maxI / (MAX_MODULES * 4.0f) * 3); - if (iSkip < MIN_SKIP || tryHarder) - { - iSkip = MIN_SKIP; - } - - int[] stateCount = new int[5]; - for (int i = iSkip - 1; i < maxI; i += iSkip) - { - // Get a row of black/white values - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - int currentState = 0; - for (int j = 0; j < maxJ; j++) - { - if (image.get_Renamed(j, i)) - { - // Black pixel - if ((currentState & 1) == 1) - { - // Counting white pixels - currentState++; - } - stateCount[currentState]++; - } - else - { - // White pixel - if ((currentState & 1) == 0) - { - // Counting black pixels - if (currentState == 4) - { - // A winner? - if (foundPatternCross(stateCount)) - { - // Yes - bool confirmed = handlePossibleCenter(stateCount, i, j); - if (!confirmed) - { - do - { - // Advance to next black pixel - j++; - } - while (j < maxJ && !image.get_Renamed(j, i)); - j--; // back up to that last white pixel - } - // Clear state to start looking again - currentState = 0; - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - } - else - { - // No, shift counts back by two - stateCount[0] = stateCount[2]; - stateCount[1] = stateCount[3]; - stateCount[2] = stateCount[4]; - stateCount[3] = 1; - stateCount[4] = 0; - currentState = 3; - } - } - else - { - stateCount[++currentState]++; - } - } - else - { - // Counting white pixels - stateCount[currentState]++; - } - } - } // for j=... - - if (foundPatternCross(stateCount)) - { - handlePossibleCenter(stateCount, i, maxJ); - } // end if foundPatternCross - } // for i=iSkip-1 ... - FinderPattern[][] patternInfo = selectBestPatterns(); - System.Collections.ArrayList result = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - for (int i = 0; i < patternInfo.Length; i++) - { - FinderPattern[] pattern = patternInfo[i]; - ResultPoint.orderBestPatterns(pattern); - result.Add(new FinderPatternInfo(pattern)); - } - - if ((result.Count == 0)) - { - return EMPTY_RESULT_ARRAY; - } - else - { - FinderPatternInfo[] resultArray = new FinderPatternInfo[result.Count]; - for (int i = 0; i < result.Count; i++) - { - resultArray[i] = (FinderPatternInfo) result[i]; - } - return resultArray; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/Code128Reader.cs b/zxing-csharp/oned/Code128Reader.cs deleted file mode 100644 index e7dc192..0000000 --- a/zxing-csharp/oned/Code128Reader.cs +++ /dev/null @@ -1,444 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultPoint = com.google.zxing.ResultPoint; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - ///

Decodes Code 128 barcodes.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Code128Reader:OneDReader - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'CODE_PATTERNS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] CODE_PATTERNS = new int[][]{new int[]{2, 1, 2, 2, 2, 2}, new int[]{2, 2, 2, 1, 2, 2}, new int[]{2, 2, 2, 2, 2, 1}, new int[]{1, 2, 1, 2, 2, 3}, new int[]{1, 2, 1, 3, 2, 2}, new int[]{1, 3, 1, 2, 2, 2}, new int[]{1, 2, 2, 2, 1, 3}, new int[]{1, 2, 2, 3, 1, 2}, new int[]{1, 3, 2, 2, 1, 2}, new int[]{2, 2, 1, 2, 1, 3}, new int[]{2, 2, 1, 3, 1, 2}, new int[]{2, 3, 1, 2, 1, 2}, new int[]{1, 1, 2, 2, 3, 2}, new int[]{1, 2, 2, 1, 3, 2}, new int[]{1, 2, 2, 2, 3, 1}, new int[]{1, 1, 3, 2, 2, 2}, new int[]{1, 2, 3, 1, 2, 2}, new int[]{1, 2, 3, 2, 2, 1}, new int[]{2, 2, 3, 2, 1, 1}, new int[]{2, 2, 1, 1, 3, 2}, new int[]{2, 2, 1, 2, 3, 1}, new int[]{2, 1, 3, 2, 1, 2}, new int[]{2, 2, 3, 1, 1, 2}, new int[]{3, 1, 2, 1, 3, 1}, new int[]{3, 1, 1, 2, 2, 2}, new int[]{3, 2, 1, 1, 2, 2}, new int[]{3, 2, 1, 2, 2, 1}, new int[]{3, 1, 2, 2, 1, 2}, new int[]{3, 2, 2, 1, 1, 2}, new int[]{3, 2, 2, 2, 1, 1}, new int[]{2, 1, 2, 1, 2, 3}, new int[]{2, 1, 2, 3, 2, 1}, new int[]{2, 3, 2, 1, 2, 1}, new int[]{1, 1, 1, 3, 2, 3}, new int[]{1, 3, 1, 1, 2, 3}, new int[]{1, 3, 1, 3, 2, 1}, new int[]{1, 1, 2, 3, 1, 3}, new int[]{1, 3, 2, 1, 1, 3}, new int[]{1, 3, 2, 3, 1, 1}, new int[]{2, 1, 1, 3, 1, 3}, new int[]{2, 3, 1, 1, 1, 3}, new int[]{2, 3, 1, 3, 1, 1}, new int[]{1, 1, 2, 1, 3, 3}, new int[]{1, 1, 2, 3, 3, 1}, new int[]{1, 3, 2, 1, 3, 1}, new int[]{1, 1, 3, 1, 2, 3}, new int[]{1, 1, 3, 3, 2, 1}, new int[]{1, 3, 3, 1, 2, 1}, new int[]{3, 1, 3, 1, 2, 1}, new int[]{2, 1, 1, 3, 3, 1}, new int[]{2, 3, 1, 1, 3, 1}, new int[]{2, 1, 3, 1, 1, 3}, new int[]{2, 1, 3, 3, 1, 1}, new int[]{2, 1, 3, 1, 3, 1}, new int[]{3, 1, 1, 1, 2, 3}, new int[]{3, 1, 1, 3, 2, 1}, new int[]{3, 3, 1, 1, 2, 1}, new int[]{3, 1, 2, 1, 1, 3}, new int[]{3, 1, 2, 3, 1, 1}, new int[]{3, 3, 2, 1, 1, 1}, new int[]{3, 1, 4, 1, 1, 1}, new int[]{2, 2, 1, 4, 1, 1}, new int[]{4, 3, 1, 1, 1, 1}, new int[]{1, 1, 1, 2, 2, 4}, new int[]{1, 1, 1, 4, 2, 2}, new int[]{1, 2, 1, 1, 2, 4}, new int[]{1, 2, 1, 4, 2, 1}, new int[]{1, 4, 1, 1, 2, 2}, new - int[]{1, 4, 1, 2, 2, 1}, new int[]{1, 1, 2, 2, 1, 4}, new int[]{1, 1, 2, 4, 1, 2}, new int[]{1, 2, 2, 1, 1, 4}, new int[]{1, 2, 2, 4, 1, 1}, new int[]{1, 4, 2, 1, 1, 2}, new int[]{1, 4, 2, 2, 1, 1}, new int[]{2, 4, 1, 2, 1, 1}, new int[]{2, 2, 1, 1, 1, 4}, new int[]{4, 1, 3, 1, 1, 1}, new int[]{2, 4, 1, 1, 1, 2}, new int[]{1, 3, 4, 1, 1, 1}, new int[]{1, 1, 1, 2, 4, 2}, new int[]{1, 2, 1, 1, 4, 2}, new int[]{1, 2, 1, 2, 4, 1}, new int[]{1, 1, 4, 2, 1, 2}, new int[]{1, 2, 4, 1, 1, 2}, new int[]{1, 2, 4, 2, 1, 1}, new int[]{4, 1, 1, 2, 1, 2}, new int[]{4, 2, 1, 1, 1, 2}, new int[]{4, 2, 1, 2, 1, 1}, new int[]{2, 1, 2, 1, 4, 1}, new int[]{2, 1, 4, 1, 2, 1}, new int[]{4, 1, 2, 1, 2, 1}, new int[]{1, 1, 1, 1, 4, 3}, new int[]{1, 1, 1, 3, 4, 1}, new int[]{1, 3, 1, 1, 4, 1}, new int[]{1, 1, 4, 1, 1, 3}, new int[]{1, 1, 4, 3, 1, 1}, new int[]{4, 1, 1, 1, 1, 3}, new int[]{4, 1, 1, 3, 1, 1}, new int[]{1, 1, 3, 1, 4, 1}, new int[]{1, 1, 4, 1, 3, 1}, new int[]{3, 1, 1, 1, 4, 1}, new int[]{4, 1, 1, 1, 3, 1}, new int[]{2, 1, 1, 4, 1, 2}, new int[]{2, 1, 1, 2, 1, 4}, new int[]{2, 1, 1, 2, 3, 2}, new int[]{2, 3, 3, 1, 1, 1, 2}}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'MAX_AVG_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - private static readonly int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.25f); - //UPGRADE_NOTE: Final was removed from the declaration of 'MAX_INDIVIDUAL_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - private static readonly int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); - - private const int CODE_SHIFT = 98; - - private const int CODE_CODE_C = 99; - private const int CODE_CODE_B = 100; - private const int CODE_CODE_A = 101; - - private const int CODE_FNC_1 = 102; - private const int CODE_FNC_2 = 97; - private const int CODE_FNC_3 = 96; - private const int CODE_FNC_4_A = 101; - private const int CODE_FNC_4_B = 100; - - private const int CODE_START_A = 103; - private const int CODE_START_B = 104; - private const int CODE_START_C = 105; - private const int CODE_STOP = 106; - - private static int[] findStartPattern(BitArray row) - { - int width = row.Size; - int rowOffset = 0; - while (rowOffset < width) - { - if (row.get_Renamed(rowOffset)) - { - break; - } - rowOffset++; - } - - int counterPosition = 0; - int[] counters = new int[6]; - int patternStart = rowOffset; - bool isWhite = false; - int patternLength = counters.Length; - - for (int i = rowOffset; i < width; i++) - { - bool pixel = row.get_Renamed(i); - if (pixel ^ isWhite) - { - counters[counterPosition]++; - } - else - { - if (counterPosition == patternLength - 1) - { - int bestVariance = MAX_AVG_VARIANCE; - int bestMatch = - 1; - for (int startCode = CODE_START_A; startCode <= CODE_START_C; startCode++) - { - int variance = patternMatchVariance(counters, CODE_PATTERNS[startCode], MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) - { - bestVariance = variance; - bestMatch = startCode; - } - } - if (bestMatch >= 0) - { - // Look for whitespace before start pattern, >= 50% of width of start pattern - if (row.isRange(System.Math.Max(0, patternStart - (i - patternStart) / 2), patternStart, false)) - { - return new int[]{patternStart, i, bestMatch}; - } - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) - { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } - else - { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw ReaderException.Instance; - } - - private static int decodeCode(BitArray row, int[] counters, int rowOffset) - { - recordPattern(row, rowOffset, counters); - int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept - int bestMatch = - 1; - for (int d = 0; d < CODE_PATTERNS.Length; d++) - { - int[] pattern = CODE_PATTERNS[d]; - int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) - { - bestVariance = variance; - bestMatch = d; - } - } - // TODO We're overlooking the fact that the STOP pattern has 7 values, not 6. - if (bestMatch >= 0) - { - return bestMatch; - } - else - { - throw ReaderException.Instance; - } - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) - { - - int[] startPatternInfo = findStartPattern(row); - int startCode = startPatternInfo[2]; - int codeSet; - switch (startCode) - { - - case CODE_START_A: - codeSet = CODE_CODE_A; - break; - - case CODE_START_B: - codeSet = CODE_CODE_B; - break; - - case CODE_START_C: - codeSet = CODE_CODE_C; - break; - - default: - throw ReaderException.Instance; - - } - - bool done = false; - bool isNextShifted = false; - - System.Text.StringBuilder result = new System.Text.StringBuilder(20); - int lastStart = startPatternInfo[0]; - int nextStart = startPatternInfo[1]; - int[] counters = new int[6]; - - int lastCode = 0; - int code = 0; - int checksumTotal = startCode; - int multiplier = 0; - bool lastCharacterWasPrintable = true; - - while (!done) - { - - bool unshift = isNextShifted; - isNextShifted = false; - - // Save off last code - lastCode = code; - - // Decode another code from image - code = decodeCode(row, counters, nextStart); - - // Remember whether the last code was printable or not (excluding CODE_STOP) - if (code != CODE_STOP) - { - lastCharacterWasPrintable = true; - } - - // Add to checksum computation (if not CODE_STOP of course) - if (code != CODE_STOP) - { - multiplier++; - checksumTotal += multiplier * code; - } - - // Advance to where the next code will to start - lastStart = nextStart; - for (int i = 0; i < counters.Length; i++) - { - nextStart += counters[i]; - } - - // Take care of illegal start codes - switch (code) - { - - case CODE_START_A: - case CODE_START_B: - case CODE_START_C: - throw ReaderException.Instance; - } - - switch (codeSet) - { - - - case CODE_CODE_A: - if (code < 64) - { - result.Append((char) (' ' + code)); - } - else if (code < 96) - { - result.Append((char) (code - 64)); - } - else - { - // Don't let CODE_STOP, which always appears, affect whether whether we think the last - // code was printable or not. - if (code != CODE_STOP) - { - lastCharacterWasPrintable = false; - } - switch (code) - { - - case CODE_FNC_1: - case CODE_FNC_2: - case CODE_FNC_3: - case CODE_FNC_4_A: - // do nothing? - break; - - case CODE_SHIFT: - isNextShifted = true; - codeSet = CODE_CODE_B; - break; - - case CODE_CODE_B: - codeSet = CODE_CODE_B; - break; - - case CODE_CODE_C: - codeSet = CODE_CODE_C; - break; - - case CODE_STOP: - done = true; - break; - } - } - break; - - case CODE_CODE_B: - if (code < 96) - { - result.Append((char) (' ' + code)); - } - else - { - if (code != CODE_STOP) - { - lastCharacterWasPrintable = false; - } - switch (code) - { - - case CODE_FNC_1: - case CODE_FNC_2: - case CODE_FNC_3: - case CODE_FNC_4_B: - // do nothing? - break; - - case CODE_SHIFT: - isNextShifted = true; - codeSet = CODE_CODE_C; - break; - - case CODE_CODE_A: - codeSet = CODE_CODE_A; - break; - - case CODE_CODE_C: - codeSet = CODE_CODE_C; - break; - - case CODE_STOP: - done = true; - break; - } - } - break; - - case CODE_CODE_C: - if (code < 100) - { - if (code < 10) - { - result.Append('0'); - } - result.Append(code); - } - else - { - if (code != CODE_STOP) - { - lastCharacterWasPrintable = false; - } - switch (code) - { - - case CODE_FNC_1: - // do nothing? - break; - - case CODE_CODE_A: - codeSet = CODE_CODE_A; - break; - - case CODE_CODE_B: - codeSet = CODE_CODE_B; - break; - - case CODE_STOP: - done = true; - break; - } - } - break; - } - - // Unshift back to another code set if we were shifted - if (unshift) - { - switch (codeSet) - { - - case CODE_CODE_A: - codeSet = CODE_CODE_C; - break; - - case CODE_CODE_B: - codeSet = CODE_CODE_A; - break; - - case CODE_CODE_C: - codeSet = CODE_CODE_B; - break; - } - } - } - - // Check for ample whitespace following pattern, but, to do this we first need to remember that - // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left - // to read off. Would be slightly better to properly read. Here we just skip it: - int width = row.Size; - while (nextStart < width && row.get_Renamed(nextStart)) - { - nextStart++; - } - if (!row.isRange(nextStart, System.Math.Min(width, nextStart + (nextStart - lastStart) / 2), false)) - { - throw ReaderException.Instance; - } - - // Pull out from sum the value of the penultimate check code - checksumTotal -= multiplier * lastCode; - // lastCode is the checksum then: - if (checksumTotal % 103 != lastCode) - { - throw ReaderException.Instance; - } - - // Need to pull out the check digits from string - int resultLength = result.Length; - // Only bother if the result had at least one character, and if the checksum digit happened to - // be a printable character. If it was just interpreted as a control code, nothing to remove. - if (resultLength > 0 && lastCharacterWasPrintable) - { - if (codeSet == CODE_CODE_C) - { - result.Remove(resultLength - 2, resultLength - (resultLength - 2)); - } - else - { - result.Remove(resultLength - 1, resultLength - (resultLength - 1)); - } - } - - System.String resultString = result.ToString(); - - if (resultString.Length == 0) - { - // Almost surely a false positive - throw ReaderException.Instance; - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float left = (float) (startPatternInfo[1] + startPatternInfo[0]) / 2.0f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float right = (float) (nextStart + lastStart) / 2.0f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return new Result(resultString, null, new ResultPoint[]{new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_128); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/Code39Reader.cs b/zxing-csharp/oned/Code39Reader.cs deleted file mode 100644 index 3e1fc99..0000000 --- a/zxing-csharp/oned/Code39Reader.cs +++ /dev/null @@ -1,392 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultPoint = com.google.zxing.ResultPoint; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - ///

Decodes Code 39 barcodes. This does not support "Full ASCII Code 39" yet.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Code39Reader:OneDReader - { - - internal const System.String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"; - //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHABET '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] ALPHABET = ALPHABET_STRING.ToCharArray(); - - /// These represent the encodings of characters, as patterns of wide and narrow bars. - /// The 9 least-significant bits of each int correspond to the pattern of wide and narrow, - /// with 1s representing "wide" and 0s representing narrow. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'CHARACTER_ENCODINGS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] CHARACTER_ENCODINGS = new int[]{0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, 0x0A8, 0x0A2, 0x08A, 0x02A}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'ASTERISK_ENCODING '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int ASTERISK_ENCODING = CHARACTER_ENCODINGS[39]; - - //UPGRADE_NOTE: Final was removed from the declaration of 'usingCheckDigit '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private bool usingCheckDigit; - //UPGRADE_NOTE: Final was removed from the declaration of 'extendedMode '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private bool extendedMode; - - /// Creates a reader that assumes all encoded data is data, and does not treat the final - /// character as a check digit. It will not decoded "extended Code 39" sequences. - /// - public Code39Reader() - { - usingCheckDigit = false; - extendedMode = false; - } - - /// Creates a reader that can be configured to check the last character as a check digit. - /// It will not decoded "extended Code 39" sequences. - /// - /// - /// if true, treat the last data character as a check digit, not - /// data, and verify that the checksum passes. - /// - public Code39Reader(bool usingCheckDigit) - { - this.usingCheckDigit = usingCheckDigit; - this.extendedMode = false; - } - - /// Creates a reader that can be configured to check the last character as a check digit, - /// or optionally attempt to decode "extended Code 39" sequences that are used to encode - /// the full ASCII character set. - /// - /// - /// if true, treat the last data character as a check digit, not - /// data, and verify that the checksum passes. - /// - /// if true, will attempt to decode extended Code 39 sequences in the - /// text. - /// - public Code39Reader(bool usingCheckDigit, bool extendedMode) - { - this.usingCheckDigit = usingCheckDigit; - this.extendedMode = extendedMode; - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) - { - - int[] start = findAsteriskPattern(row); - int nextStart = start[1]; - int end = row.Size; - - // Read off white space - while (nextStart < end && !row.get_Renamed(nextStart)) - { - nextStart++; - } - - System.Text.StringBuilder result = new System.Text.StringBuilder(20); - int[] counters = new int[9]; - char decodedChar; - int lastStart; - do - { - recordPattern(row, nextStart, counters); - int pattern = toNarrowWidePattern(counters); - if (pattern < 0) - { - throw ReaderException.Instance; - } - decodedChar = patternToChar(pattern); - result.Append(decodedChar); - lastStart = nextStart; - for (int i = 0; i < counters.Length; i++) - { - nextStart += counters[i]; - } - // Read off white space - while (nextStart < end && !row.get_Renamed(nextStart)) - { - nextStart++; - } - } - while (decodedChar != '*'); - result.Remove(result.Length - 1, 1); // remove asterisk - - // Look for whitespace after pattern: - int lastPatternSize = 0; - for (int i = 0; i < counters.Length; i++) - { - lastPatternSize += counters[i]; - } - int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize; - // If 50% of last pattern size, following last pattern, is not whitespace, fail - // (but if it's whitespace to the very end of the image, that's OK) - if (nextStart != end && whiteSpaceAfterEnd / 2 < lastPatternSize) - { - throw ReaderException.Instance; - } - - if (usingCheckDigit) - { - int max = result.Length - 1; - int total = 0; - for (int i = 0; i < max; i++) - { - total += ALPHABET_STRING.IndexOf((System.Char) result[i]); - } - if (total % 43 != ALPHABET_STRING.IndexOf((System.Char) result[max])) - { - throw ReaderException.Instance; - } - result.Remove(max, 1); - } - - System.String resultString = result.ToString(); - if (extendedMode) - { - resultString = decodeExtended(resultString); - } - - if (resultString.Length == 0) - { - // Almost surely a false positive - throw ReaderException.Instance; - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float left = (float) (start[1] + start[0]) / 2.0f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float right = (float) (nextStart + lastStart) / 2.0f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return new Result(resultString, null, new ResultPoint[]{new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat.CODE_39); - } - - private static int[] findAsteriskPattern(BitArray row) - { - int width = row.Size; - int rowOffset = 0; - while (rowOffset < width) - { - if (row.get_Renamed(rowOffset)) - { - break; - } - rowOffset++; - } - - int counterPosition = 0; - int[] counters = new int[9]; - int patternStart = rowOffset; - bool isWhite = false; - int patternLength = counters.Length; - - for (int i = rowOffset; i < width; i++) - { - bool pixel = row.get_Renamed(i); - if (pixel ^ isWhite) - { - counters[counterPosition]++; - } - else - { - if (counterPosition == patternLength - 1) - { - if (toNarrowWidePattern(counters) == ASTERISK_ENCODING) - { - // Look for whitespace before start pattern, >= 50% of width of start pattern - if (row.isRange(System.Math.Max(0, patternStart - (i - patternStart) / 2), patternStart, false)) - { - return new int[]{patternStart, i}; - } - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) - { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } - else - { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw ReaderException.Instance; - } - - // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions - // per image when using some of our blackbox images. - private static int toNarrowWidePattern(int[] counters) - { - int numCounters = counters.Length; - int maxNarrowCounter = 0; - int wideCounters; - do - { - int minCounter = System.Int32.MaxValue; - for (int i = 0; i < numCounters; i++) - { - int counter = counters[i]; - if (counter < minCounter && counter > maxNarrowCounter) - { - minCounter = counter; - } - } - maxNarrowCounter = minCounter; - wideCounters = 0; - int totalWideCountersWidth = 0; - int pattern = 0; - for (int i = 0; i < numCounters; i++) - { - int counter = counters[i]; - if (counters[i] > maxNarrowCounter) - { - pattern |= 1 << (numCounters - 1 - i); - wideCounters++; - totalWideCountersWidth += counter; - } - } - if (wideCounters == 3) - { - // Found 3 wide counters, but are they close enough in width? - // We can perform a cheap, conservative check to see if any individual - // counter is more than 1.5 times the average: - for (int i = 0; i < numCounters && wideCounters > 0; i++) - { - int counter = counters[i]; - if (counters[i] > maxNarrowCounter) - { - wideCounters--; - // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average - if ((counter << 1) >= totalWideCountersWidth) - { - return - 1; - } - } - } - return pattern; - } - } - while (wideCounters > 3); - return - 1; - } - - private static char patternToChar(int pattern) - { - for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++) - { - if (CHARACTER_ENCODINGS[i] == pattern) - { - return ALPHABET[i]; - } - } - throw ReaderException.Instance; - } - - private static System.String decodeExtended(System.String encoded) - { - int length = encoded.Length; - System.Text.StringBuilder decoded = new System.Text.StringBuilder(length); - for (int i = 0; i < length; i++) - { - char c = encoded[i]; - if (c == '+' || c == '$' || c == '%' || c == '/') - { - char next = encoded[i + 1]; - char decodedChar = '\x0000'; - switch (c) - { - - case '+': - // +A to +Z map to a to z - if (next >= 'A' && next <= 'Z') - { - decodedChar = (char) (next + 32); - } - else - { - throw ReaderException.Instance; - } - break; - - case '$': - // $A to $Z map to control codes SH to SB - if (next >= 'A' && next <= 'Z') - { - decodedChar = (char) (next - 64); - } - else - { - throw ReaderException.Instance; - } - break; - - case '%': - // %A to %E map to control codes ESC to US - if (next >= 'A' && next <= 'E') - { - decodedChar = (char) (next - 38); - } - else if (next >= 'F' && next <= 'W') - { - decodedChar = (char) (next - 11); - } - else - { - throw ReaderException.Instance; - } - break; - - case '/': - // /A to /O map to ! to , and /Z maps to : - if (next >= 'A' && next <= 'O') - { - decodedChar = (char) (next - 32); - } - else if (next == 'Z') - { - decodedChar = ':'; - } - else - { - throw ReaderException.Instance; - } - break; - } - decoded.Append(decodedChar); - // bump up i again since we read two characters - i++; - } - else - { - decoded.Append(c); - } - } - return decoded.ToString(); - } - } -} diff --git a/zxing-csharp/oned/Code39Writer.cs b/zxing-csharp/oned/Code39Writer.cs deleted file mode 100644 index 4780334..0000000 --- a/zxing-csharp/oned/Code39Writer.cs +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2011 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -using System; -using System.Collections; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultPoint = com.google.zxing.ResultPoint; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -namespace com.google.zxing.oned -{ - ///

Implements decoding of the EAN-13 format.

- /// - ///
- /// erik.barbara@gmail.com (Erik Barbara) - /// - /// em@nerd.ocracy.org (Emanuele Aina) - Ported from ZXING Java Source - /// - public sealed class Code39Writer:UPCEANWriter - { - public override ByteMatrix encode(string contents, BarcodeFormat format, int width, int height, Hashtable hints) { - if (format != BarcodeFormat.CODE_39) { - throw new ArgumentException("Can only encode CODE_39, but got " + format); - } - return base.encode(contents, format, width, height, hints); - } - - public override sbyte[] encode(string contents) { - int length = contents.Length; - if (length > 80) { - throw new ArgumentException("Requested contents should be less than 80 digits long, but got " + length); - } - - int[] widths = new int[9]; - int codeWidth = 24 + 1 + length; - for (int i = 0; i < length; i++) { - int indexInString = Code39Reader.ALPHABET_STRING.IndexOf(contents[i]); - toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); - for(int j = 0; j < widths.Length; j++) { - codeWidth += widths[j]; - } - } - sbyte[] result = new sbyte[codeWidth]; - toIntArray(Code39Reader.CHARACTER_ENCODINGS[39], widths); - int pos = appendPattern(result, 0, widths, 1); - int[] narrowWhite = {1}; - pos += appendPattern(result, pos, narrowWhite, 0); - //append next character to bytematrix - for(int i = length-1; i >= 0; i--) { - int indexInString = Code39Reader.ALPHABET_STRING.IndexOf(contents[i]); - toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); - pos += appendPattern(result, pos, widths, 1); - pos += appendPattern(result, pos, narrowWhite, 0); - } - toIntArray(Code39Reader.CHARACTER_ENCODINGS[39], widths); - pos += appendPattern(result, pos, widths, 1); - return result; - } - - private static void toIntArray(int a, int[] toReturn) { - for (int i = 0; i < 9; i++) { - int temp = a & (1 << i); - toReturn[i] = (temp == 0) ? 1 : 2; - } - } - } -} diff --git a/zxing-csharp/oned/EAN13Reader.cs b/zxing-csharp/oned/EAN13Reader.cs deleted file mode 100644 index b8c2df4..0000000 --- a/zxing-csharp/oned/EAN13Reader.cs +++ /dev/null @@ -1,153 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using ReaderException = com.google.zxing.ReaderException; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - ///

Implements decoding of the EAN-13 format.

- /// - ///
- /// dswitkin@google.com (Daniel Switkin) - /// - /// Sean Owen - /// - /// alasdair@google.com (Alasdair Mackintosh) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class EAN13Reader:UPCEANReader - { - override internal BarcodeFormat BarcodeFormat - { - get - { - return BarcodeFormat.EAN_13; - } - - } - - // For an EAN-13 barcode, the first digit is represented by the parities used - // to encode the next six digits, according to the table below. For example, - // if the barcode is 5 123456 789012 then the value of the first digit is - // signified by using odd for '1', even for '2', even for '3', odd for '4', - // odd for '5', and even for '6'. See http://en.wikipedia.org/wiki/EAN-13 - // - // Parity of next 6 digits - // Digit 0 1 2 3 4 5 - // 0 Odd Odd Odd Odd Odd Odd - // 1 Odd Odd Even Odd Even Even - // 2 Odd Odd Even Even Odd Even - // 3 Odd Odd Even Even Even Odd - // 4 Odd Even Odd Odd Even Even - // 5 Odd Even Even Odd Odd Even - // 6 Odd Even Even Even Odd Odd - // 7 Odd Even Odd Even Odd Even - // 8 Odd Even Odd Even Even Odd - // 9 Odd Even Even Odd Even Odd - // - // Note that the encoding for '0' uses the same parity as a UPC barcode. Hence - // a UPC barcode can be converted to an EAN-13 barcode by prepending a 0. - // - // The encoding is represented by the following array, which is a bit pattern - // using Odd = 0 and Even = 1. For example, 5 is represented by: - // - // Odd Even Even Odd Odd Even - // in binary: - // 0 1 1 0 0 1 == 0x19 - // - //UPGRADE_NOTE: Final was removed from the declaration of 'FIRST_DIGIT_ENCODINGS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] FIRST_DIGIT_ENCODINGS = new int[]{0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'decodeMiddleCounters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] decodeMiddleCounters; - - public EAN13Reader() - { - decodeMiddleCounters = new int[4]; - } - - protected internal override int decodeMiddle(BitArray row, int[] startRange, System.Text.StringBuilder resultString) - { - int[] counters = decodeMiddleCounters; - counters[0] = 0; - counters[1] = 0; - counters[2] = 0; - counters[3] = 0; - int end = row.Size; - int rowOffset = startRange[1]; - - int lgPatternFound = 0; - - for (int x = 0; x < 6 && rowOffset < end; x++) - { - int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); - resultString.Append((char) ('0' + bestMatch % 10)); - for (int i = 0; i < counters.Length; i++) - { - rowOffset += counters[i]; - } - if (bestMatch >= 10) - { - lgPatternFound |= 1 << (5 - x); - } - } - - determineFirstDigit(resultString, lgPatternFound); - - int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); - rowOffset = middleRange[1]; - - for (int x = 0; x < 6 && rowOffset < end; x++) - { - int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); - resultString.Append((char) ('0' + bestMatch)); - for (int i = 0; i < counters.Length; i++) - { - rowOffset += counters[i]; - } - } - - return rowOffset; - } - - /// Based on pattern of odd-even ('L' and 'G') patterns used to encoded the explicitly-encoded - /// digits in a barcode, determines the implicitly encoded first digit and adds it to the - /// result string. - /// - /// - /// string to insert decoded first digit into - /// - /// int whose bits indicates the pattern of odd/even L/G patterns used to - /// encode digits - /// - /// ReaderException if first digit cannot be determined - private static void determineFirstDigit(System.Text.StringBuilder resultString, int lgPatternFound) - { - for (int d = 0; d < 10; d++) - { - if (lgPatternFound == FIRST_DIGIT_ENCODINGS[d]) - { - resultString.Insert(0, (char) ('0' + d)); - return ; - } - } - throw ReaderException.Instance; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/EAN13Writer.cs b/zxing-csharp/oned/EAN13Writer.cs deleted file mode 100644 index cc2c406..0000000 --- a/zxing-csharp/oned/EAN13Writer.cs +++ /dev/null @@ -1,84 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using WriterException = com.google.zxing.WriterException; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -namespace com.google.zxing.oned -{ - - - /// This object renders an EAN13 code as a ByteMatrix 2D array of greyscale - /// values. - /// - /// - /// aripollak@gmail.com (Ari Pollak) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class EAN13Writer:UPCEANWriter - { - - private const int codeWidth = 3 + (7 * 6) + 5 + (7 * 6) + 3; // end guard - - public override ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height, System.Collections.Hashtable hints) - { - if (format != BarcodeFormat.EAN_13) - { - throw new System.ArgumentException("Can only encode EAN_13, but got " + format); - } - - return base.encode(contents, format, width, height, hints); - } - - public override sbyte[] encode(System.String contents) - { - if (contents.Length != 13) - { - throw new System.ArgumentException("Requested contents should be 13 digits long, but got " + contents.Length); - } - - int firstDigit = System.Int32.Parse(contents.Substring(0, (1) - (0))); - int parities = EAN13Reader.FIRST_DIGIT_ENCODINGS[firstDigit]; - sbyte[] result = new sbyte[codeWidth]; - int pos = 0; - - pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, 1); - - // See {@link #EAN13Reader} for a description of how the first digit & left bars are encoded - for (int i = 1; i <= 6; i++) - { - int digit = System.Int32.Parse(contents.Substring(i, (i + 1) - (i))); - if ((parities >> (6 - i) & 1) == 1) - { - digit += 10; - } - pos += appendPattern(result, pos, UPCEANReader.L_AND_G_PATTERNS[digit], 0); - } - - pos += appendPattern(result, pos, UPCEANReader.MIDDLE_PATTERN, 0); - - for (int i = 7; i <= 12; i++) - { - int digit = System.Int32.Parse(contents.Substring(i, (i + 1) - (i))); - pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], 1); - } - pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, 1); - - return result; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/EAN8Reader.cs b/zxing-csharp/oned/EAN8Reader.cs deleted file mode 100644 index 7fc8c0b..0000000 --- a/zxing-csharp/oned/EAN8Reader.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using ReaderException = com.google.zxing.ReaderException; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - ///

Implements decoding of the EAN-8 format.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class EAN8Reader:UPCEANReader - { - override internal BarcodeFormat BarcodeFormat - { - get - { - return BarcodeFormat.EAN_8; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'decodeMiddleCounters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] decodeMiddleCounters; - - public EAN8Reader() - { - decodeMiddleCounters = new int[4]; - } - - protected internal override int decodeMiddle(BitArray row, int[] startRange, System.Text.StringBuilder result) - { - int[] counters = decodeMiddleCounters; - counters[0] = 0; - counters[1] = 0; - counters[2] = 0; - counters[3] = 0; - int end = row.Size; - int rowOffset = startRange[1]; - - for (int x = 0; x < 4 && rowOffset < end; x++) - { - int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); - result.Append((char) ('0' + bestMatch)); - for (int i = 0; i < counters.Length; i++) - { - rowOffset += counters[i]; - } - } - - int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); - rowOffset = middleRange[1]; - - for (int x = 0; x < 4 && rowOffset < end; x++) - { - int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); - result.Append((char) ('0' + bestMatch)); - for (int i = 0; i < counters.Length; i++) - { - rowOffset += counters[i]; - } - } - - return rowOffset; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/EAN8Writer.cs b/zxing-csharp/oned/EAN8Writer.cs deleted file mode 100644 index 8f9b0a6..0000000 --- a/zxing-csharp/oned/EAN8Writer.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using WriterException = com.google.zxing.WriterException; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -namespace com.google.zxing.oned -{ - - /// This object renders an EAN8 code as a ByteMatrix 2D array of greyscale - /// values. - /// - /// - /// aripollak@gmail.com (Ari Pollak) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class EAN8Writer:UPCEANWriter - { - - private const int codeWidth = 3 + (7 * 4) + 5 + (7 * 4) + 3; // end guard - - public override ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height, System.Collections.Hashtable hints) - { - if (format != BarcodeFormat.EAN_8) - { - throw new System.ArgumentException("Can only encode EAN_8, but got " + format); - } - - return base.encode(contents, format, width, height, hints); - } - - /// a byte array of horizontal pixels (0 = white, 1 = black) - /// - public override sbyte[] encode(System.String contents) - { - if (contents.Length != 8) - { - throw new System.ArgumentException("Requested contents should be 8 digits long, but got " + contents.Length); - } - - sbyte[] result = new sbyte[codeWidth]; - int pos = 0; - - pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, 1); - - for (int i = 0; i <= 3; i++) - { - int digit = System.Int32.Parse(contents.Substring(i, (i + 1) - (i))); - pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], 0); - } - - pos += appendPattern(result, pos, UPCEANReader.MIDDLE_PATTERN, 0); - - for (int i = 4; i <= 7; i++) - { - int digit = System.Int32.Parse(contents.Substring(i, (i + 1) - (i))); - pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], 1); - } - pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, 1); - - return result; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/ITFReader.cs b/zxing-csharp/oned/ITFReader.cs deleted file mode 100644 index 2a57009..0000000 --- a/zxing-csharp/oned/ITFReader.cs +++ /dev/null @@ -1,382 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using DecodeHintType = com.google.zxing.DecodeHintType; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultPoint = com.google.zxing.ResultPoint; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - ///

Implements decoding of the ITF format.

- /// - ///

"ITF" stands for Interleaved Two of Five. This Reader will scan ITF barcode with 6, 10 or 14 - /// digits. The checksum is optional and is not applied by this Reader. The consumer of the decoded - /// value will have to apply a checksum if required.

- /// - ///

http://en.wikipedia.org/wiki/Interleaved_2_of_5 - /// is a great reference for Interleaved 2 of 5 information.

- /// - ///
- /// kevin.osullivan@sita.aero, SITA Lab. - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class ITFReader:OneDReader - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'MAX_AVG_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - private static readonly int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f); - //UPGRADE_NOTE: Final was removed from the declaration of 'MAX_INDIVIDUAL_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - private static readonly int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.8f); - - private const int W = 3; // Pixel width of a wide line - private const int N = 1; // Pixed width of a narrow line - - //UPGRADE_NOTE: Final was removed from the declaration of 'DEFAULT_ALLOWED_LENGTHS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] DEFAULT_ALLOWED_LENGTHS = new int[]{6, 10, 14, 44}; - - // Stores the actual narrow line width of the image being decoded. - private int narrowLineWidth = - 1; - - /// Start/end guard pattern. - /// - /// Note: The end pattern is reversed because the row is reversed before - /// searching for the END_PATTERN - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'START_PATTERN '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] START_PATTERN = new int[]{N, N, N, N}; - //UPGRADE_NOTE: Final was removed from the declaration of 'END_PATTERN_REVERSED '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] END_PATTERN_REVERSED = new int[]{N, N, W}; - - /// Patterns of Wide / Narrow lines to indicate each digit - //UPGRADE_NOTE: Final was removed from the declaration of 'PATTERNS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] PATTERNS = new int[][]{new int[]{N, N, W, W, N}, new int[]{W, N, N, N, W}, new int[]{N, W, N, N, W}, new int[]{W, W, N, N, N}, new int[]{N, N, W, N, W}, new int[]{W, N, W, N, N}, new int[]{N, W, W, N, N}, new int[]{N, N, N, W, W}, new int[]{W, N, N, W, N}, new int[]{N, W, N, W, N}}; - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) - { - - // Find out where the Middle section (payload) starts & ends - int[] startRange = decodeStart(row); - int[] endRange = decodeEnd(row); - - System.Text.StringBuilder result = new System.Text.StringBuilder(20); - decodeMiddle(row, startRange[1], endRange[0], result); - System.String resultString = result.ToString(); - - int[] allowedLengths = null; - if (hints != null) - { - allowedLengths = (int[]) hints[DecodeHintType.ALLOWED_LENGTHS]; - } - if (allowedLengths == null) - { - allowedLengths = DEFAULT_ALLOWED_LENGTHS; - } - - // To avoid false positives with 2D barcodes (and other patterns), make - // an assumption that the decoded string must be 6, 10 or 14 digits. - int length = resultString.Length; - bool lengthOK = false; - for (int i = 0; i < allowedLengths.Length; i++) - { - if (length == allowedLengths[i]) - { - lengthOK = true; - break; - } - } - if (!lengthOK) - { - throw ReaderException.Instance; - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return new Result(resultString, null, new ResultPoint[]{new ResultPoint(startRange[1], (float) rowNumber), new ResultPoint(endRange[0], (float) rowNumber)}, BarcodeFormat.ITF); - } - - /// row of black/white values to search - /// - /// offset of start pattern - /// - /// {@link StringBuffer} to append decoded chars to - /// - /// ReaderException if decoding could not complete successfully - private static void decodeMiddle(BitArray row, int payloadStart, int payloadEnd, System.Text.StringBuilder resultString) - { - - // Digits are interleaved in pairs - 5 black lines for one digit, and the - // 5 - // interleaved white lines for the second digit. - // Therefore, need to scan 10 lines and then - // split these into two arrays - int[] counterDigitPair = new int[10]; - int[] counterBlack = new int[5]; - int[] counterWhite = new int[5]; - - while (payloadStart < payloadEnd) - { - - // Get 10 runs of black/white. - recordPattern(row, payloadStart, counterDigitPair); - // Split them into each array - for (int k = 0; k < 5; k++) - { - int twoK = k << 1; - counterBlack[k] = counterDigitPair[twoK]; - counterWhite[k] = counterDigitPair[twoK + 1]; - } - - int bestMatch = decodeDigit(counterBlack); - resultString.Append((char) ('0' + bestMatch)); - bestMatch = decodeDigit(counterWhite); - resultString.Append((char) ('0' + bestMatch)); - - for (int i = 0; i < counterDigitPair.Length; i++) - { - payloadStart += counterDigitPair[i]; - } - } - } - - /// Identify where the start of the middle / payload section starts. - /// - /// - /// row of black/white values to search - /// - /// Array, containing index of start of 'start block' and end of - /// 'start block' - /// - /// ReaderException - internal int[] decodeStart(BitArray row) - { - int endStart = skipWhiteSpace(row); - int[] startPattern = findGuardPattern(row, endStart, START_PATTERN); - - // Determine the width of a narrow line in pixels. We can do this by - // getting the width of the start pattern and dividing by 4 because its - // made up of 4 narrow lines. - this.narrowLineWidth = (startPattern[1] - startPattern[0]) >> 2; - - validateQuietZone(row, startPattern[0]); - - return startPattern; - } - - /// The start & end patterns must be pre/post fixed by a quiet zone. This - /// zone must be at least 10 times the width of a narrow line. Scan back until - /// we either get to the start of the barcode or match the necessary number of - /// quiet zone pixels. - /// - /// Note: Its assumed the row is reversed when using this method to find - /// quiet zone after the end pattern. - /// - /// ref: http://www.barcode-1.net/i25code.html - /// - /// - /// bit array representing the scanned barcode. - /// - /// index into row of the start or end pattern. - /// - /// ReaderException if the quiet zone cannot be found, a ReaderException is thrown. - private void validateQuietZone(BitArray row, int startPattern) - { - - int quietCount = this.narrowLineWidth * 10; // expect to find this many pixels of quiet zone - - for (int i = startPattern - 1; quietCount > 0 && i >= 0; i--) - { - if (row.get_Renamed(i)) - { - break; - } - quietCount--; - } - if (quietCount != 0) - { - // Unable to find the necessary number of quiet zone pixels. - throw ReaderException.Instance; - } - } - - /// Skip all whitespace until we get to the first black line. - /// - /// - /// row of black/white values to search - /// - /// index of the first black line. - /// - /// ReaderException Throws exception if no black lines are found in the row - private static int skipWhiteSpace(BitArray row) - { - int width = row.Size; - int endStart = 0; - while (endStart < width) - { - if (row.get_Renamed(endStart)) - { - break; - } - endStart++; - } - if (endStart == width) - { - throw ReaderException.Instance; - } - - return endStart; - } - - /// Identify where the end of the middle / payload section ends. - /// - /// - /// row of black/white values to search - /// - /// Array, containing index of start of 'end block' and end of 'end - /// block' - /// - /// ReaderException - - internal int[] decodeEnd(BitArray row) - { - - // For convenience, reverse the row and then - // search from 'the start' for the end block - row.reverse(); - try - { - int endStart = skipWhiteSpace(row); - int[] endPattern = findGuardPattern(row, endStart, END_PATTERN_REVERSED); - - // The start & end patterns must be pre/post fixed by a quiet zone. This - // zone must be at least 10 times the width of a narrow line. - // ref: http://www.barcode-1.net/i25code.html - validateQuietZone(row, endPattern[0]); - - // Now recalculate the indices of where the 'endblock' starts & stops to - // accommodate - // the reversed nature of the search - int temp = endPattern[0]; - endPattern[0] = row.Size - endPattern[1]; - endPattern[1] = row.Size - temp; - - return endPattern; - } - finally - { - // Put the row back the right way. - row.reverse(); - } - } - - /// row of black/white values to search - /// - /// position to start search - /// - /// pattern of counts of number of black and white pixels that are - /// being searched for as a pattern - /// - /// start/end horizontal offset of guard pattern, as an array of two - /// ints - /// - /// ReaderException if pattern is not found - private static int[] findGuardPattern(BitArray row, int rowOffset, int[] pattern) - { - - // TODO: This is very similar to implementation in UPCEANReader. Consider if they can be - // merged to a single method. - int patternLength = pattern.Length; - int[] counters = new int[patternLength]; - int width = row.Size; - bool isWhite = false; - - int counterPosition = 0; - int patternStart = rowOffset; - for (int x = rowOffset; x < width; x++) - { - bool pixel = row.get_Renamed(x); - if (pixel ^ isWhite) - { - counters[counterPosition]++; - } - else - { - if (counterPosition == patternLength - 1) - { - if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) - { - return new int[]{patternStart, x}; - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) - { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } - else - { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw ReaderException.Instance; - } - - /// Attempts to decode a sequence of ITF black/white lines into single - /// digit. - /// - /// - /// the counts of runs of observed black/white/black/... values - /// - /// The decoded digit - /// - /// ReaderException if digit cannot be decoded - private static int decodeDigit(int[] counters) - { - - int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept - int bestMatch = - 1; - int max = PATTERNS.Length; - for (int i = 0; i < max; i++) - { - int[] pattern = PATTERNS[i]; - int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) - { - bestVariance = variance; - bestMatch = i; - } - } - if (bestMatch >= 0) - { - return bestMatch; - } - else - { - throw ReaderException.Instance; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/MultiFormatOneDReader.cs b/zxing-csharp/oned/MultiFormatOneDReader.cs deleted file mode 100644 index cd81dce..0000000 --- a/zxing-csharp/oned/MultiFormatOneDReader.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using DecodeHintType = com.google.zxing.DecodeHintType; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - /// dswitkin@google.com (Daniel Switkin) - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class MultiFormatOneDReader:OneDReader - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'readers '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Collections.ArrayList readers; - - public MultiFormatOneDReader(System.Collections.Hashtable hints) - { - System.Collections.ArrayList possibleFormats = hints == null?null:(System.Collections.ArrayList) hints[DecodeHintType.POSSIBLE_FORMATS]; - bool useCode39CheckDigit = hints != null && hints[DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT] != null; - readers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - if (possibleFormats != null) - { - if (possibleFormats.Contains(BarcodeFormat.EAN_13) || possibleFormats.Contains(BarcodeFormat.UPC_A) || possibleFormats.Contains(BarcodeFormat.EAN_8) || possibleFormats.Contains(BarcodeFormat.UPC_E)) - { - readers.Add(new MultiFormatUPCEANReader(hints)); - } - if (possibleFormats.Contains(BarcodeFormat.CODE_39)) - { - readers.Add(new Code39Reader(useCode39CheckDigit)); - } - if (possibleFormats.Contains(BarcodeFormat.CODE_128)) - { - readers.Add(new Code128Reader()); - } - if (possibleFormats.Contains(BarcodeFormat.ITF)) - { - readers.Add(new ITFReader()); - } - } - if ((readers.Count == 0)) - { - readers.Add(new MultiFormatUPCEANReader(hints)); - readers.Add(new Code39Reader()); - readers.Add(new Code128Reader()); - readers.Add(new ITFReader()); - } - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) - { - int size = readers.Count; - for (int i = 0; i < size; i++) - { - OneDReader reader = (OneDReader) readers[i]; - try - { - return reader.decodeRow(rowNumber, row, hints); - } - catch (ReaderException re) - { - // continue - } - } - - throw ReaderException.Instance; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/MultiFormatUPCEANReader.cs b/zxing-csharp/oned/MultiFormatUPCEANReader.cs deleted file mode 100644 index a801fa6..0000000 --- a/zxing-csharp/oned/MultiFormatUPCEANReader.cs +++ /dev/null @@ -1,109 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using DecodeHintType = com.google.zxing.DecodeHintType; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - ///

A reader that can read all available UPC/EAN formats. If a caller wants to try to - /// read all such formats, it is most efficient to use this implementation rather than invoke - /// individual readers.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class MultiFormatUPCEANReader:OneDReader - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'readers '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Collections.ArrayList readers; - - public MultiFormatUPCEANReader(System.Collections.Hashtable hints) - { - System.Collections.ArrayList possibleFormats = hints == null?null:(System.Collections.ArrayList) hints[DecodeHintType.POSSIBLE_FORMATS]; - readers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - if (possibleFormats != null) - { - if (possibleFormats.Contains(BarcodeFormat.EAN_13)) - { - readers.Add(new EAN13Reader()); - } - else if (possibleFormats.Contains(BarcodeFormat.UPC_A)) - { - readers.Add(new UPCAReader()); - } - if (possibleFormats.Contains(BarcodeFormat.EAN_8)) - { - readers.Add(new EAN8Reader()); - } - if (possibleFormats.Contains(BarcodeFormat.UPC_E)) - { - readers.Add(new UPCEReader()); - } - } - if ((readers.Count == 0)) - { - readers.Add(new EAN13Reader()); - // UPC-A is covered by EAN-13 - readers.Add(new EAN8Reader()); - readers.Add(new UPCEReader()); - } - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) - { - // Compute this location once and reuse it on multiple implementations - int[] startGuardPattern = UPCEANReader.findStartGuardPattern(row); - int size = readers.Count; - for (int i = 0; i < size; i++) - { - UPCEANReader reader = (UPCEANReader) readers[i]; - Result result; - try - { - result = reader.decodeRow(rowNumber, row, startGuardPattern, hints); - } - catch (ReaderException re) - { - continue; - } - // Special case: a 12-digit code encoded in UPC-A is identical to a "0" - // followed by those 12 digits encoded as EAN-13. Each will recognize such a code, - // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0". - // Individually these are correct and their readers will both read such a code - // and correctly call it EAN-13, or UPC-A, respectively. - // - // In this case, if we've been looking for both types, we'd like to call it - // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read - // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A - // result if appropriate. - if (result.BarcodeFormat.Equals(BarcodeFormat.EAN_13) && result.Text[0] == '0') - { - return new Result(result.Text.Substring(1), null, result.ResultPoints, BarcodeFormat.UPC_A); - } - return result; - } - - throw ReaderException.Instance; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/OneDReader.cs b/zxing-csharp/oned/OneDReader.cs deleted file mode 100644 index bdb768b..0000000 --- a/zxing-csharp/oned/OneDReader.cs +++ /dev/null @@ -1,332 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using DecodeHintType = com.google.zxing.DecodeHintType; -using Reader = com.google.zxing.Reader; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultMetadataType = com.google.zxing.ResultMetadataType; -using ResultPoint = com.google.zxing.ResultPoint; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - /// Encapsulates functionality and implementation that is common to all families - /// of one-dimensional barcodes. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public abstract class OneDReader : Reader - { - - private const int INTEGER_MATH_SHIFT = 8; - //UPGRADE_NOTE: Final was removed from the declaration of 'PATTERN_MATCH_RESULT_SCALE_FACTOR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT; - - public virtual Result decode(BinaryBitmap image) - { - return decode(image, null); - } - - // Note that we don't try rotation without the try harder flag, even if rotation was supported. - public virtual Result decode(BinaryBitmap image, System.Collections.Hashtable hints) - { - try - { - return doDecode(image, hints); - } - catch (ReaderException re) - { - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - if (tryHarder && image.RotateSupported) - { - BinaryBitmap rotatedImage = image.rotateCounterClockwise(); - Result result = doDecode(rotatedImage, hints); - // Record that we found it rotated 90 degrees CCW / 270 degrees CW - System.Collections.Hashtable metadata = result.ResultMetadata; - int orientation = 270; - if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION)) - { - // But if we found it reversed in doDecode(), add in that result here: - orientation = (orientation + ((System.Int32) metadata[ResultMetadataType.ORIENTATION])) % 360; - } - result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) orientation); - // Update result points - ResultPoint[] points = result.ResultPoints; - int height = rotatedImage.Height; - for (int i = 0; i < points.Length; i++) - { - points[i] = new ResultPoint(height - points[i].Y - 1, points[i].X); - } - return result; - } - else - { - throw re; - } - } - } - - /// We're going to examine rows from the middle outward, searching alternately above and below the - /// middle, and farther out each time. rowStep is the number of rows between each successive - /// attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then - /// middle + rowStep, then middle - (2 * rowStep), etc. - /// rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily - /// decided that moving up and down by about 1/16 of the image is pretty good; we try more of the - /// image if "trying harder". - /// - /// - /// The image to decode - /// - /// Any hints that were requested - /// - /// The contents of the decoded barcode - /// - /// ReaderException Any spontaneous errors which occur - private Result doDecode(BinaryBitmap image, System.Collections.Hashtable hints) - { - int width = image.Width; - int height = image.Height; - BitArray row = new BitArray(width); - - int middle = height >> 1; - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - int rowStep = System.Math.Max(1, height >> (tryHarder?7:4)); - int maxLines; - if (tryHarder) - { - maxLines = height; // Look at the whole image, not just the center - } - else - { - maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image - } - - for (int x = 0; x < maxLines; x++) - { - - // Scanning from the middle out. Determine which row we're looking at next: - int rowStepsAboveOrBelow = (x + 1) >> 1; - bool isAbove = (x & 0x01) == 0; // i.e. is x even? - int rowNumber = middle + rowStep * (isAbove?rowStepsAboveOrBelow:- rowStepsAboveOrBelow); - if (rowNumber < 0 || rowNumber >= height) - { - // Oops, if we run off the top or bottom, stop - break; - } - - // Estimate black point for this row and load it: - try - { - row = image.getBlackRow(rowNumber, row); - } - catch (ReaderException re) - { - continue; - } - - // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to - // handle decoding upside down barcodes. - for (int attempt = 0; attempt < 2; attempt++) - { - if (attempt == 1) - { - // trying again? - row.reverse(); // reverse the row and continue - // This means we will only ever draw result points *once* in the life of this method - // since we want to avoid drawing the wrong points after flipping the row, and, - // don't want to clutter with noise from every single row scan -- just the scans - // that start on the center line. - if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) - { - System.Collections.Hashtable newHints = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); // Can't use clone() in J2ME - System.Collections.IEnumerator hintEnum = hints.Keys.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" - while (hintEnum.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" - System.Object key = hintEnum.Current; - if (!key.Equals(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) - { - newHints[key] = hints[key]; - } - } - hints = newHints; - } - } - try - { - // Look for a barcode - Result result = decodeRow(rowNumber, row, hints); - // We found our barcode - if (attempt == 1) - { - // But it was upside down, so note that - result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) 180); - // And remember to flip the result points horizontally. - ResultPoint[] points = result.ResultPoints; - points[0] = new ResultPoint(width - points[0].X - 1, points[0].Y); - points[1] = new ResultPoint(width - points[1].X - 1, points[1].Y); - } - return result; - } - catch (ReaderException re) - { - // continue -- just couldn't decode this row - } - } - } - - throw ReaderException.Instance; - } - - /// Records the size of successive runs of white and black pixels in a row, starting at a given point. - /// The values are recorded in the given array, and the number of runs recorded is equal to the size - /// of the array. If the row starts on a white pixel at the given start point, then the first count - /// recorded is the run of white pixels starting from that point; likewise it is the count of a run - /// of black pixels if the row begin on a black pixels at that point. - /// - /// - /// row to count from - /// - /// offset into row to start at - /// - /// array into which to record counts - /// - /// ReaderException if counters cannot be filled entirely from row before running out - /// of pixels - /// - internal static void recordPattern(BitArray row, int start, int[] counters) - { - int numCounters = counters.Length; - for (int i = 0; i < numCounters; i++) - { - counters[i] = 0; - } - int end = row.Size; - if (start >= end) - { - throw ReaderException.Instance; - } - bool isWhite = !row.get_Renamed(start); - int counterPosition = 0; - int i2 = start; - while (i2 < end) - { - bool pixel = row.get_Renamed(i2); - if (pixel ^ isWhite) - { - // that is, exactly one is true - counters[counterPosition]++; - } - else - { - counterPosition++; - if (counterPosition == numCounters) - { - break; - } - else - { - counters[counterPosition] = 1; - isWhite ^= true; // isWhite = !isWhite; - } - } - i2++; - } - // If we read fully the last section of pixels and filled up our counters -- or filled - // the last counter but ran off the side of the image, OK. Otherwise, a problem. - if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i2 == end))) - { - throw ReaderException.Instance; - } - } - - /// Determines how closely a set of observed counts of runs of black/white values matches a given - /// target pattern. This is reported as the ratio of the total variance from the expected pattern - /// proportions across all pattern elements, to the length of the pattern. - /// - /// - /// observed counters - /// - /// expected pattern - /// - /// The most any counter can differ before we give up - /// - /// ratio of total variance between counters and pattern compared to total pattern size, - /// where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means - /// the total variance between counters and patterns equals the pattern length, higher values mean - /// even more variance - /// - internal static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) - { - int numCounters = counters.Length; - int total = 0; - int patternLength = 0; - for (int i = 0; i < numCounters; i++) - { - total += counters[i]; - patternLength += pattern[i]; - } - if (total < patternLength) - { - // If we don't even have one pixel per unit of bar width, assume this is too small - // to reliably match, so fail: - return System.Int32.MaxValue; - } - // We're going to fake floating-point math in integers. We just need to use more bits. - // Scale up patternLength so that intermediate values below like scaledCounter will have - // more "significant digits" - int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength; - maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT; - - int totalVariance = 0; - for (int x = 0; x < numCounters; x++) - { - int counter = counters[x] << INTEGER_MATH_SHIFT; - int scaledPattern = pattern[x] * unitBarWidth; - int variance = counter > scaledPattern?counter - scaledPattern:scaledPattern - counter; - if (variance > maxIndividualVariance) - { - return System.Int32.MaxValue; - } - totalVariance += variance; - } - return totalVariance / total; - } - - ///

Attempts to decode a one-dimensional barcode format given a single row of - /// an image.

- /// - ///
- /// row number from top of the row - /// - /// the black/white pixel data of the row - /// - /// decode hints - /// - /// {@link Result} containing encoded string and start/end of barcode - /// - /// ReaderException if an error occurs or barcode cannot be found - public abstract Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints); - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/UPCAReader.cs b/zxing-csharp/oned/UPCAReader.cs deleted file mode 100644 index 660e011..0000000 --- a/zxing-csharp/oned/UPCAReader.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - ///

Implements decoding of the UPC-A format.

- /// - ///
- /// dswitkin@google.com (Daniel Switkin) - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class UPCAReader:UPCEANReader - { - override internal BarcodeFormat BarcodeFormat - { - get - { - return BarcodeFormat.UPC_A; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'ean13Reader '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private UPCEANReader ean13Reader = new EAN13Reader(); - - public override Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, System.Collections.Hashtable hints) - { - return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange, hints)); - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) - { - return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, hints)); - } - - public override Result decode(BinaryBitmap image) - { - return maybeReturnResult(ean13Reader.decode(image)); - } - - public override Result decode(BinaryBitmap image, System.Collections.Hashtable hints) - { - return maybeReturnResult(ean13Reader.decode(image, hints)); - } - - protected internal override int decodeMiddle(BitArray row, int[] startRange, System.Text.StringBuilder resultString) - { - return ean13Reader.decodeMiddle(row, startRange, resultString); - } - - private static Result maybeReturnResult(Result result) - { - System.String text = result.Text; - if (text[0] == '0') - { - return new Result(text.Substring(1), null, result.ResultPoints, BarcodeFormat.UPC_A); - } - else - { - throw ReaderException.Instance; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/UPCEANReader.cs b/zxing-csharp/oned/UPCEANReader.cs deleted file mode 100644 index b0a031e..0000000 --- a/zxing-csharp/oned/UPCEANReader.cs +++ /dev/null @@ -1,359 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultPointCallback = com.google.zxing.ResultPointCallback; -using DecodeHintType = com.google.zxing.DecodeHintType; -using ResultPoint = com.google.zxing.ResultPoint; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - ///

Encapsulates functionality and implementation that is common to UPC and EAN families - /// of one-dimensional barcodes.

- /// - ///
- /// dswitkin@google.com (Daniel Switkin) - /// - /// Sean Owen - /// - /// alasdair@google.com (Alasdair Mackintosh) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public abstract class UPCEANReader:OneDReader - { - /// Get the format of this decoder. - /// - /// - /// The 1D format. - /// - internal abstract BarcodeFormat BarcodeFormat{get;} - - // These two values are critical for determining how permissive the decoding will be. - // We've arrived at these values through a lot of trial and error. Setting them any higher - // lets false positives creep in quickly. - //UPGRADE_NOTE: Final was removed from the declaration of 'MAX_AVG_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - private static readonly int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f); - //UPGRADE_NOTE: Final was removed from the declaration of 'MAX_INDIVIDUAL_VARIANCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - private static readonly int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.7f); - - /// Start/end guard pattern. - //UPGRADE_NOTE: Final was removed from the declaration of 'START_END_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] START_END_PATTERN = new int[]{1, 1, 1}; - - /// Pattern marking the middle of a UPC/EAN pattern, separating the two halves. - //UPGRADE_NOTE: Final was removed from the declaration of 'MIDDLE_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[] MIDDLE_PATTERN = new int[]{1, 1, 1, 1, 1}; - - /// "Odd", or "L" patterns used to encode UPC/EAN digits. - //UPGRADE_NOTE: Final was removed from the declaration of 'L_PATTERNS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - internal static readonly int[][] L_PATTERNS = new int[][]{new int[]{3, 2, 1, 1}, new int[]{2, 2, 2, 1}, new int[]{2, 1, 2, 2}, new int[]{1, 4, 1, 1}, new int[]{1, 1, 3, 2}, new int[]{1, 2, 3, 1}, new int[]{1, 1, 1, 4}, new int[]{1, 3, 1, 2}, new int[]{1, 2, 1, 3}, new int[]{3, 1, 1, 2}}; - - /// As above but also including the "even", or "G" patterns used to encode UPC/EAN digits. - internal static int[][] L_AND_G_PATTERNS; - - //UPGRADE_NOTE: Final was removed from the declaration of 'decodeRowStringBuffer '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Text.StringBuilder decodeRowStringBuffer; - - protected internal UPCEANReader() - { - decodeRowStringBuffer = new System.Text.StringBuilder(20); - } - - internal static int[] findStartGuardPattern(BitArray row) - { - bool foundStart = false; - int[] startRange = null; - int nextStart = 0; - while (!foundStart) - { - startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN); - int start = startRange[0]; - nextStart = startRange[1]; - // Make sure there is a quiet zone at least as big as the start pattern before the barcode. - // If this check would run off the left edge of the image, do not accept this barcode, - // as it is very likely to be a false positive. - int quietStart = start - (nextStart - start); - if (quietStart >= 0) - { - foundStart = row.isRange(quietStart, start, false); - } - } - return startRange; - } - - public override Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints) - { - return decodeRow(rowNumber, row, findStartGuardPattern(row), hints); - } - - ///

Like {@link #decodeRow(int, BitArray, java.util.Hashtable)}, but - /// allows caller to inform method about where the UPC/EAN start pattern is - /// found. This allows this to be computed once and reused across many implementations.

- ///
- public virtual Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, System.Collections.Hashtable hints) - { - - ResultPointCallback resultPointCallback = hints == null?null:(ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK]; - - if (resultPointCallback != null) - { - resultPointCallback.foundPossibleResultPoint(new ResultPoint((startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber)); - } - - System.Text.StringBuilder result = decodeRowStringBuffer; - result.Length = 0; - int endStart = decodeMiddle(row, startGuardRange, result); - - if (resultPointCallback != null) - { - resultPointCallback.foundPossibleResultPoint(new ResultPoint(endStart, rowNumber)); - } - - int[] endRange = decodeEnd(row, endStart); - - if (resultPointCallback != null) - { - resultPointCallback.foundPossibleResultPoint(new ResultPoint((endRange[0] + endRange[1]) / 2.0f, rowNumber)); - } - - - // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The - // spec might want more whitespace, but in practice this is the maximum we can count on. - int end = endRange[1]; - int quietEnd = end + (end - endRange[0]); - if (quietEnd >= row.Size || !row.isRange(end, quietEnd, false)) - { - throw ReaderException.Instance; - } - - System.String resultString = result.ToString(); - if (!checkChecksum(resultString)) - { - throw ReaderException.Instance; - } - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float left = (float) (startGuardRange[1] + startGuardRange[0]) / 2.0f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float right = (float) (endRange[1] + endRange[0]) / 2.0f; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return new Result(resultString, null, new ResultPoint[]{new ResultPoint(left, (float) rowNumber), new ResultPoint(right, (float) rowNumber)}, BarcodeFormat); - } - - /// {@link #checkStandardUPCEANChecksum(String)} - /// - //UPGRADE_NOTE: Access modifiers of method 'checkChecksum' were changed to 'protected'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1204'" - protected internal virtual bool checkChecksum(System.String s) - { - return checkStandardUPCEANChecksum(s); - } - - /// Computes the UPC/EAN checksum on a string of digits, and reports - /// whether the checksum is correct or not. - /// - /// - /// string of digits to check - /// - /// true iff string of digits passes the UPC/EAN checksum algorithm - /// - /// ReaderException if the string does not contain only digits - private static bool checkStandardUPCEANChecksum(System.String s) - { - int length = s.Length; - if (length == 0) - { - return false; - } - - int sum = 0; - for (int i = length - 2; i >= 0; i -= 2) - { - int digit = (int) s[i] - (int) '0'; - if (digit < 0 || digit > 9) - { - throw ReaderException.Instance; - } - sum += digit; - } - sum *= 3; - for (int i = length - 1; i >= 0; i -= 2) - { - int digit = (int) s[i] - (int) '0'; - if (digit < 0 || digit > 9) - { - throw ReaderException.Instance; - } - sum += digit; - } - return sum % 10 == 0; - } - - //UPGRADE_NOTE: Access modifiers of method 'decodeEnd' were changed to 'protected'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1204'" - protected internal virtual int[] decodeEnd(BitArray row, int endStart) - { - return findGuardPattern(row, endStart, false, START_END_PATTERN); - } - - /// row of black/white values to search - /// - /// position to start search - /// - /// if true, indicates that the pattern specifies white/black/white/... - /// pixel counts, otherwise, it is interpreted as black/white/black/... - /// - /// pattern of counts of number of black and white pixels that are being - /// searched for as a pattern - /// - /// start/end horizontal offset of guard pattern, as an array of two ints - /// - /// ReaderException if pattern is not found - internal static int[] findGuardPattern(BitArray row, int rowOffset, bool whiteFirst, int[] pattern) - { - int patternLength = pattern.Length; - int[] counters = new int[patternLength]; - int width = row.Size; - bool isWhite = false; - while (rowOffset < width) - { - isWhite = !row.get_Renamed(rowOffset); - if (whiteFirst == isWhite) - { - break; - } - rowOffset++; - } - - int counterPosition = 0; - int patternStart = rowOffset; - for (int x = rowOffset; x < width; x++) - { - bool pixel = row.get_Renamed(x); - if (pixel ^ isWhite) - { - counters[counterPosition]++; - } - else - { - if (counterPosition == patternLength - 1) - { - if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) - { - return new int[]{patternStart, x}; - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) - { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } - else - { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - throw ReaderException.Instance; - } - - /// Attempts to decode a single UPC/EAN-encoded digit. - /// - /// - /// row of black/white values to decode - /// - /// the counts of runs of observed black/white/black/... values - /// - /// horizontal offset to start decoding from - /// - /// the set of patterns to use to decode -- sometimes different encodings - /// for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should - /// be used - /// - /// horizontal offset of first pixel beyond the decoded digit - /// - /// ReaderException if digit cannot be decoded - internal static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns) - { - recordPattern(row, rowOffset, counters); - int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept - int bestMatch = - 1; - int max = patterns.Length; - for (int i = 0; i < max; i++) - { - int[] pattern = patterns[i]; - int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); - if (variance < bestVariance) - { - bestVariance = variance; - bestMatch = i; - } - } - if (bestMatch >= 0) - { - return bestMatch; - } - else - { - throw ReaderException.Instance; - } - } - - /// Subclasses override this to decode the portion of a barcode between the start - /// and end guard patterns. - /// - /// - /// row of black/white values to search - /// - /// start/end offset of start guard pattern - /// - /// {@link StringBuffer} to append decoded chars to - /// - /// horizontal offset of first pixel after the "middle" that was decoded - /// - /// ReaderException if decoding could not complete successfully - protected internal abstract int decodeMiddle(BitArray row, int[] startRange, System.Text.StringBuilder resultString); - static UPCEANReader() - { - { - L_AND_G_PATTERNS = new int[20][]; - for (int i = 0; i < 10; i++) - { - L_AND_G_PATTERNS[i] = L_PATTERNS[i]; - } - for (int i = 10; i < 20; i++) - { - int[] widths = L_PATTERNS[i - 10]; - int[] reversedWidths = new int[widths.Length]; - for (int j = 0; j < widths.Length; j++) - { - reversedWidths[j] = widths[widths.Length - j - 1]; - } - L_AND_G_PATTERNS[i] = reversedWidths; - } - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/UPCEANWriter.cs b/zxing-csharp/oned/UPCEANWriter.cs deleted file mode 100644 index 6368db1..0000000 --- a/zxing-csharp/oned/UPCEANWriter.cs +++ /dev/null @@ -1,145 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using Writer = com.google.zxing.Writer; -using WriterException = com.google.zxing.WriterException; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -namespace com.google.zxing.oned -{ - - ///

Encapsulates functionality and implementation that is common to UPC and EAN families - /// of one-dimensional barcodes.

- /// - ///
- /// aripollak@gmail.com (Ari Pollak) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public abstract class UPCEANWriter : Writer - { - - public virtual ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height) - { - return encode(contents, format, width, height, null); - } - - public virtual ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height, System.Collections.Hashtable hints) - { - if (contents == null || contents.Length == 0) - { - throw new System.ArgumentException("Found empty contents"); - } - - if (width < 0 || height < 0) - { - throw new System.ArgumentException("Requested dimensions are too small: " + width + 'x' + height); - } - - sbyte[] code = encode(contents); - return renderResult(code, width, height); - } - - /// a byte array of horizontal pixels (0 = white, 1 = black) - /// - private static ByteMatrix renderResult(sbyte[] code, int width, int height) - { - int inputWidth = code.Length; - // Add quiet zone on both sides - int fullWidth = inputWidth + (UPCEANReader.START_END_PATTERN.Length << 1); - int outputWidth = System.Math.Max(width, fullWidth); - int outputHeight = System.Math.Max(1, height); - - int multiple = outputWidth / fullWidth; - int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; - - ByteMatrix output = new ByteMatrix(outputWidth, outputHeight); - sbyte[][] outputArray = output.Array; - - sbyte[] row = new sbyte[outputWidth]; - - // a. Write the white pixels at the left of each row - for (int x = 0; x < leftPadding; x++) - { - row[x] = (sbyte) SupportClass.Identity(255); - } - - // b. Write the contents of this row of the barcode - int offset = leftPadding; - for (int x = 0; x < inputWidth; x++) - { - // Redivivus.in Java to c# Porting update - // 30/01/2010 - // type cased 0 with sbyte - sbyte value_Renamed = (code[x] == 1) ? (sbyte)0 : (sbyte)SupportClass.Identity(255); - for (int z = 0; z < multiple; z++) - { - row[offset + z] = value_Renamed; - } - offset += multiple; - } - - // c. Write the white pixels at the right of each row - offset = leftPadding + (inputWidth * multiple); - for (int x = offset; x < outputWidth; x++) - { - row[x] = (sbyte) SupportClass.Identity(255); - } - - // d. Write the completed row multiple times - for (int z = 0; z < outputHeight; z++) - { - Array.Copy(row, 0, outputArray[z], 0, outputWidth); - } - - return output; - } - - - /// Appends the given pattern to the target array starting at pos. - /// - /// - /// starting color - 0 for white, 1 for black - /// - /// the number of elements added to target. - /// - protected internal static int appendPattern(sbyte[] target, int pos, int[] pattern, int startColor) - { - if (startColor != 0 && startColor != 1) - { - throw new System.ArgumentException("startColor must be either 0 or 1, but got: " + startColor); - } - - sbyte color = (sbyte) startColor; - int numAdded = 0; - for (int i = 0; i < pattern.Length; i++) - { - for (int j = 0; j < pattern[i]; j++) - { - target[pos] = color; - pos += 1; - numAdded += 1; - } - color ^= 1; // flip color after each segment - } - return numAdded; - } - - /// a byte array of horizontal pixels (0 = white, 1 = black) - /// - public abstract sbyte[] encode(System.String contents); - } -} \ No newline at end of file diff --git a/zxing-csharp/oned/UPCEReader.cs b/zxing-csharp/oned/UPCEReader.cs deleted file mode 100644 index 5c0f853..0000000 --- a/zxing-csharp/oned/UPCEReader.cs +++ /dev/null @@ -1,173 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using ReaderException = com.google.zxing.ReaderException; -using BitArray = com.google.zxing.common.BitArray; -namespace com.google.zxing.oned -{ - - ///

Implements decoding of the UPC-E format.

- ///

- ///

This is a great reference for - /// UPC-E information.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class UPCEReader:UPCEANReader - { - override internal BarcodeFormat BarcodeFormat - { - get - { - return BarcodeFormat.UPC_E; - } - - } - - /// The pattern that marks the middle, and end, of a UPC-E pattern. - /// There is no "second half" to a UPC-E barcode. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'MIDDLE_END_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] MIDDLE_END_PATTERN = new int[]{1, 1, 1, 1, 1, 1}; - - /// See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of - /// even-odd parity encodings of digits that imply both the number system (0 or 1) - /// used, and the check digit. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'NUMSYS_AND_CHECK_DIGIT_PATTERNS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] NUMSYS_AND_CHECK_DIGIT_PATTERNS = new int[][]{new int[]{0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25}, new int[]{0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A}}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'decodeMiddleCounters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] decodeMiddleCounters; - - public UPCEReader() - { - decodeMiddleCounters = new int[4]; - } - - protected internal override int decodeMiddle(BitArray row, int[] startRange, System.Text.StringBuilder result) - { - int[] counters = decodeMiddleCounters; - counters[0] = 0; - counters[1] = 0; - counters[2] = 0; - counters[3] = 0; - int end = row.Size; - int rowOffset = startRange[1]; - - int lgPatternFound = 0; - - for (int x = 0; x < 6 && rowOffset < end; x++) - { - int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); - result.Append((char) ('0' + bestMatch % 10)); - for (int i = 0; i < counters.Length; i++) - { - rowOffset += counters[i]; - } - if (bestMatch >= 10) - { - lgPatternFound |= 1 << (5 - x); - } - } - - determineNumSysAndCheckDigit(result, lgPatternFound); - - return rowOffset; - } - - protected internal override int[] decodeEnd(BitArray row, int endStart) - { - return findGuardPattern(row, endStart, true, MIDDLE_END_PATTERN); - } - - protected internal override bool checkChecksum(System.String s) - { - return base.checkChecksum(convertUPCEtoUPCA(s)); - } - - private static void determineNumSysAndCheckDigit(System.Text.StringBuilder resultString, int lgPatternFound) - { - - for (int numSys = 0; numSys <= 1; numSys++) - { - for (int d = 0; d < 10; d++) - { - if (lgPatternFound == NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]) - { - resultString.Insert(0, (char) ('0' + numSys)); - resultString.Append((char) ('0' + d)); - return ; - } - } - } - throw ReaderException.Instance; - } - - /// Expands a UPC-E value back into its full, equivalent UPC-A code value. - /// - /// - /// UPC-E code as string of digits - /// - /// equivalent UPC-A code as string of digits - /// - public static System.String convertUPCEtoUPCA(System.String upce) - { - char[] upceChars = new char[6]; - SupportClass.GetCharsFromString(upce, 1, 7, upceChars, 0); - System.Text.StringBuilder result = new System.Text.StringBuilder(12); - result.Append(upce[0]); - char lastChar = upceChars[5]; - switch (lastChar) - { - - case '0': - case '1': - case '2': - result.Append(upceChars, 0, 2); - result.Append(lastChar); - result.Append("0000"); - result.Append(upceChars, 2, 3); - break; - - case '3': - result.Append(upceChars, 0, 3); - result.Append("00000"); - result.Append(upceChars, 3, 2); - break; - - case '4': - result.Append(upceChars, 0, 4); - result.Append("00000"); - result.Append(upceChars[4]); - break; - - default: - result.Append(upceChars, 0, 5); - result.Append("0000"); - result.Append(lastChar); - break; - - } - result.Append(upce[7]); - return result.ToString(); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/pdf417/PDF417Reader.cs b/zxing-csharp/pdf417/PDF417Reader.cs deleted file mode 100644 index 765d789..0000000 --- a/zxing-csharp/pdf417/PDF417Reader.cs +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using DecodeHintType = com.google.zxing.DecodeHintType; -using Reader = com.google.zxing.Reader; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultPoint = com.google.zxing.ResultPoint; -using BitMatrix = com.google.zxing.common.BitMatrix; -using DecoderResult = com.google.zxing.common.DecoderResult; -using DetectorResult = com.google.zxing.common.DetectorResult; -using Decoder = com.google.zxing.pdf417.decoder.Decoder; -using Detector = com.google.zxing.pdf417.detector.Detector; -namespace com.google.zxing.pdf417 -{ - - /// This implementation can detect and decode PDF417 codes in an image. - /// - /// - /// SITA Lab (kevin.osullivan@sita.aero) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class PDF417Reader : Reader - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'NO_POINTS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0]; - - //UPGRADE_NOTE: Final was removed from the declaration of 'decoder '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private Decoder decoder = new Decoder(); - - /// Locates and decodes a PDF417 code in an image. - /// - /// - /// a String representing the content encoded by the PDF417 code - /// - /// ReaderException if a PDF417 code cannot be found, or cannot be decoded - public Result decode(BinaryBitmap image) - { - return decode(image, null); - } - - public Result decode(BinaryBitmap image, System.Collections.Hashtable hints) - { - DecoderResult decoderResult; - ResultPoint[] points; - if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) - { - BitMatrix bits = extractPureBits(image); - decoderResult = decoder.decode(bits); - points = NO_POINTS; - } - else - { - DetectorResult detectorResult = new Detector(image).detect(); - decoderResult = decoder.decode(detectorResult.Bits); - points = detectorResult.Points; - } - return new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.PDF417); - } - - /// This method detects a barcode in a "pure" image -- that is, pure monochrome image - /// which contains only an unrotated, unskewed, image of a barcode, with some white border - /// around it. This is a specialized method that works exceptionally fast in this special - /// case. - /// - private static BitMatrix extractPureBits(BinaryBitmap image) - { - // Now need to determine module size in pixels - BitMatrix matrix = image.BlackMatrix; - int height = matrix.Height; - int width = matrix.Width; - int minDimension = System.Math.Min(height, width); - - // First, skip white border by tracking diagonally from the top left down and to the right: - int borderWidth = 0; - while (borderWidth < minDimension && !matrix.get_Renamed(borderWidth, borderWidth)) - { - borderWidth++; - } - if (borderWidth == minDimension) - { - throw ReaderException.Instance; - } - - // And then keep tracking across the top-left black module to determine module size - int moduleEnd = borderWidth; - while (moduleEnd < minDimension && matrix.get_Renamed(moduleEnd, moduleEnd)) - { - moduleEnd++; - } - if (moduleEnd == minDimension) - { - throw ReaderException.Instance; - } - - int moduleSize = moduleEnd - borderWidth; - - // And now find where the rightmost black module on the first row ends - int rowEndOfSymbol = width - 1; - while (rowEndOfSymbol >= 0 && !matrix.get_Renamed(rowEndOfSymbol, borderWidth)) - { - rowEndOfSymbol--; - } - if (rowEndOfSymbol < 0) - { - throw ReaderException.Instance; - } - rowEndOfSymbol++; - - // Make sure width of barcode is a multiple of module size - if ((rowEndOfSymbol - borderWidth) % moduleSize != 0) - { - throw ReaderException.Instance; - } - int dimension = (rowEndOfSymbol - borderWidth) / moduleSize; - - // Push in the "border" by half the module width so that we start - // sampling in the middle of the module. Just in case the image is a - // little off, this will help recover. - borderWidth += (moduleSize >> 1); - - int sampleDimension = borderWidth + (dimension - 1) * moduleSize; - if (sampleDimension >= width || sampleDimension >= height) - { - throw ReaderException.Instance; - } - - // Now just read off the bits - BitMatrix bits = new BitMatrix(dimension); - for (int y = 0; y < dimension; y++) - { - int iOffset = borderWidth + y * moduleSize; - for (int x = 0; x < dimension; x++) - { - if (matrix.get_Renamed(borderWidth + x * moduleSize, iOffset)) - { - bits.set_Renamed(x, y); - } - } - } - return bits; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/pdf417/decoder/BitMatrixParser.cs b/zxing-csharp/pdf417/decoder/BitMatrixParser.cs deleted file mode 100644 index 2b78f69..0000000 --- a/zxing-csharp/pdf417/decoder/BitMatrixParser.cs +++ /dev/null @@ -1,630 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing.pdf417.decoder -{ - - ///

- /// This class parses the BitMatrix image into codewords. - ///

- /// - ///
- /// SITA Lab (kevin.osullivan@sita.aero) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class BitMatrixParser - { - /// Returns an array of locations representing the erasures. - public int[] Erasures - { - get - { - return erasures; - } - - } - public int ECLevel - { - get - { - return ecLevel; - } - - } - - private const int MAX_ROW_DIFFERENCE = 6; - private const int MAX_ROWS = 90; - //private static final int MAX_COLUMNS = 30; - // Maximum Codewords (Data + Error) - private const int MAX_CW_CAPACITY = 929; - private const int MODULES_IN_SYMBOL = 17; - - //UPGRADE_NOTE: Final was removed from the declaration of 'bitMatrix '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix bitMatrix; - private int rows = 0; - //private int columns = 0; - - private int leftColumnECData = 0; - private int rightColumnECData = 0; - private int eraseCount = 0; - private int[] erasures = null; - private int ecLevel = - 1; - - internal BitMatrixParser(BitMatrix bitMatrix) - { - this.bitMatrix = bitMatrix; - } - - /// To ensure separability of rows, codewords of consecutive rows belong to - /// different subsets of all possible codewords. This routine scans the - /// symbols in the barcode. When it finds a number of consecutive rows which - /// are the same, it assumes that this is a row of codewords and processes - /// them into a codeword array. - /// - /// - /// an array of codewords. - /// - internal int[] readCodewords() - { - int width = bitMatrix.Dimension; - // TODO should be a rectangular matrix - int height = width; - - erasures = new int[MAX_CW_CAPACITY]; - - // Get the number of pixels in a module across the X dimension - //float moduleWidth = bitMatrix.getModuleWidth(); - float moduleWidth = 1.0f; // Image has been sampled and reduced - - int[] rowCounters = new int[width]; - int[] codewords = new int[MAX_CW_CAPACITY]; - int next = 0; - int matchingConsecutiveScans = 0; - bool rowInProgress = false; - int rowNumber = 0; - int rowHeight = 0; - for (int i = 1; i < height; i++) - { - if (rowNumber >= MAX_ROWS) - { - // Something is wrong, since we have exceeded - // the maximum rows in the specification. - // TODO Maybe return error code - return null; - } - int rowDifference = 0; - // Scan a line of modules and check the - // difference between this and the previous line - for (int j = 0; j < width; j++) - { - // Accumulate differences between this line and the - // previous line. - if (bitMatrix.get_Renamed(j, i) != bitMatrix.get_Renamed(j, i - 1)) - { - rowDifference++; - } - } - if (rowDifference <= moduleWidth * MAX_ROW_DIFFERENCE) - { - for (int j = 0; j < width; j++) - { - // Accumulate the black pixels on this line - if (bitMatrix.get_Renamed(j, i)) - { - rowCounters[j]++; - } - } - // Increment the number of consecutive rows of pixels - // that are more or less the same - matchingConsecutiveScans++; - // Height of a row is a multiple of the module size in pixels - // Usually at least 3 times the module size - if (matchingConsecutiveScans >= moduleWidth * 2) - { - // MGMG - // We have some previous matches as well as a match here - // Set processing a unique row. - rowInProgress = true; - } - } - else - { - if (rowInProgress) - { - // Process Row - next = processRow(rowCounters, rowNumber, rowHeight, codewords, next); - if (next == - 1) - { - // Something is wrong, since we have exceeded - // the maximum columns in the specification. - // TODO Maybe return error code - return null; - } - // Reinitialize the row counters. - for (int j = 0; j < rowCounters.Length; j++) - { - rowCounters[j] = 0; - } - rowNumber++; - rowHeight = 0; - } - matchingConsecutiveScans = 0; - rowInProgress = false; - } - rowHeight++; - } - // Check for a row that was in progress before we exited above. - if (rowInProgress) - { - // Process Row - if (rowNumber >= MAX_ROWS) - { - // Something is wrong, since we have exceeded - // the maximum rows in the specification. - // TODO Maybe return error code - return null; - } - next = processRow(rowCounters, rowNumber, rowHeight, codewords, next); - rowNumber++; - rows = rowNumber; - } - erasures = trimArray(erasures, eraseCount); - return trimArray(codewords, next); - } - - /// Trim the array to the required size. - /// - /// - /// the array - /// - /// the size to trim it to - /// - /// the new trimmed array - /// - private static int[] trimArray(int[] array, int size) - { - if (size > 0) - { - int[] a = new int[size]; - for (int i = 0; i < size; i++) - { - a[i] = array[i]; - } - return a; - } - else - { - return null; - } - } - - /// Convert the symbols in the row to codewords. - /// Each PDF417 symbol character consists of four bar elements and four space - /// elements, each of which can be one to six modules wide. The four bar and - /// four space elements shall measure 17 modules in total. - /// - /// - /// an array containing the counts of black pixels for each column - /// in the row. - /// - /// the current row number of codewords. - /// - /// the height of this row in pixels. - /// - /// the codeword array to save codewords into. - /// - /// the next available index into the codewords array. - /// - /// the next available index into the codeword array after processing - /// this row. - /// - internal int processRow(int[] rowCounters, int rowNumber, int rowHeight, int[] codewords, int next) - { - int width = bitMatrix.Dimension; - int columnNumber = 0; - long symbol = 0; - for (int i = 0; i < width; i += MODULES_IN_SYMBOL) - { - for (int mask = MODULES_IN_SYMBOL - 1; mask >= 0; mask--) - { - if (rowCounters[i + (MODULES_IN_SYMBOL - 1 - mask)] >= SupportClass.URShift(rowHeight, 1)) - { - symbol |= 1L << mask; - } - } - if (columnNumber > 0) - { - int cw = getCodeword(symbol); - // if (debug) System.out.println(" " + Long.toBinaryString(symbol) + - // " cw=" +cw + " ColumnNumber=" +columnNumber + "i=" +i); - if (cw < 0 && i < width - MODULES_IN_SYMBOL) - { - // Skip errors on the Right row indicator column - erasures[eraseCount] = next; - next++; - eraseCount++; - } - else - { - codewords[next++] = cw; - } - } - else - { - // Left row indicator column - int cw = getCodeword(symbol); - // if (debug) System.out.println(" " + Long.toBinaryString(symbol) + - // " cw=" +cw + " ColumnNumber=" +columnNumber + "i=" +i); - if (ecLevel < 0) - { - switch (rowNumber % 3) - { - - case 0: - break; - - case 1: - leftColumnECData = cw; - break; - - case 2: - break; - } - } - } - symbol = 0; - //columns = columnNumber; - columnNumber++; - } - if (columnNumber > 1) - { - // Right row indicator column is in codeword[next] - //columns--; - // Overwrite the last codeword i.e. Right Row Indicator - --next; - if (ecLevel < 0) - { - switch (rowNumber % 3) - { - - case 0: - break; - - case 1: - break; - - case 2: - rightColumnECData = codewords[next]; - if (rightColumnECData == leftColumnECData && leftColumnECData != 0) - { - ecLevel = ((rightColumnECData % 30) - rows % 3) / 3; - } - break; - } - } - codewords[next] = 0; - } - return next; - } - - /// Build a symbol from the pixels. - /// Each symbol character is defined by an 8-digit bar-space sequence which - /// represents the module widths of the eight elements of that symbol - /// character. - /// - /// - /// array of pixel counter corresponding to each Bar/Space pattern. - /// - /// the symbol - /// - /* - private static long getSymbol(int[] counters, float moduleWidth) { - int pixelsInSymbol = 0; - for (int j = 0; j < counters.length; j++) { - pixelsInSymbol += counters[j]; - } - float avgModuleWidth = (pixelsInSymbol / 17.0f); - boolean toggle = true; - int shift = 0; - int symbol = 0; - for (int j = 0; j < counters.length; j++) { - if (counters[j] < moduleWidth && counters[j] > 0) { - // Give a very narrow bar/space a chance - counters[j] = (int) moduleWidth; - } - // Calculate number of modules in the symbol. - // int modules = (int)(counters[j]/moduleWidth); - // int modules = round(counters[j]/moduleWidth); - int modules = round(counters[j] / avgModuleWidth); - if (modules > 6) { - // Maximum size is 6 modules - modules = 6; - } else if (modules < 1) { - modules = 1; - } - if (toggle) { - for (int k = 0; k < modules; k++) { - symbol |= 1 << (16 - k - shift); - } - toggle = false; - } else { - toggle = true; - } - shift += modules; - } - return symbol; - } - */ - - /// Translate the symbol into a codeword. - /// - /// - /// - /// - /// the codeword corresponding to the symbol. - /// - private static int getCodeword(long symbol) - { - long sym = symbol; - sym &= 0x3ffff; - int i = findCodewordIndex(sym); - if (i == - 1) - { - return - 1; - } - else - { - long cw = CODEWORD_TABLE[i] - 1; - cw %= 929; - return (int) cw; - } - } - - /// Use a binary search to find the index of the codeword corresponding to - /// this symbol. - /// - /// - /// the symbol from the barcode. - /// - /// the index into the codeword table. - /// - private static int findCodewordIndex(long symbol) - { - int first = 0; - int upto = SYMBOL_TABLE.Length; - while (first < upto) - { - int mid = SupportClass.URShift((first + upto), 1); // Compute mid point. - if (symbol < SYMBOL_TABLE[mid]) - { - upto = mid; // repeat search in bottom half. - } - else if (symbol > SYMBOL_TABLE[mid]) - { - first = mid + 1; // Repeat search in top half. - } - else - { - return mid; // Found it. return position - } - } - return - 1; - // if (debug) System.out.println("Failed to find codeword for Symbol=" + - // symbol); - } - - /// Ends up being a bit faster than Math.round(). This merely rounds its - /// argument to the nearest int, where x.5 rounds up. - /// - /* - private static int round(float d) { - return (int) (d + 0.5f); - } - */ - - /// Convert the symbols in the row to codewords. - /// Each PDF417 symbol character consists of four bar elements and four space - /// elements, each of which can be one to six modules wide. The four bar and - /// four space elements shall measure 17 modules in total. - /// - /// - /// an array containing the counts of black pixels for each column - /// in the row. - /// - /// the current row number of codewords. - /// - /// the height of this row in pixels. - /// - /// the size of a module in pixels. - /// - /// the codeword array to save codewords into. - /// - /// the next available index into the codewords array. - /// - /// the next available index into the codeword array after processing - /// this row. - /// - /// ReaderException - /* - int processRow1(int[] rowCounters, int rowNumber, int rowHeight, - float moduleWidth, int[] codewords, int next) { - int width = bitMatrix.getDimension(); - int firstBlack = 0; - - for (firstBlack = 0; firstBlack < width; firstBlack++) { - // Step forward until we find the first black pixels - if (rowCounters[firstBlack] >= rowHeight >>> 1) { - break; - } - } - - int[] counters = new int[8]; - int state = 0; // In black pixels, looking for white, first or second time - long symbol = 0; - int columnNumber = 0; - for (int i = firstBlack; i < width; i++) { - if (state == 1 || state == 3 || state == 5 || state == 7) { // In white - // pixels, - // looking - // for - // black - // If more than half the column is black - if (rowCounters[i] >= rowHeight >>> 1 || i == width - 1) { - if (i == width - 1) { - counters[state]++; - } - // In black pixels or the end of a row - state++; - if (state < 8) { - // Don't count the last one - counters[state]++; - } - } else { - counters[state]++; - } - } else { - if (rowCounters[i] < rowHeight >>> 1) { - // Found white pixels - state++; - if (state == 7 && i == width - 1) { - // Its found white pixels at the end of the row, - // give it a chance to exit gracefully - i--; - } else { - // Found white pixels - counters[state]++; - } - } else { - if (state < 8) { - // Still in black pixels - counters[state]++; - } - } - } - if (state == 8) { // Found black, white, black, white, black, white, - // black, white and stumbled back onto black; done - if (columnNumber >= MAX_COLUMNS) { - // Something is wrong, since we have exceeded - // the maximum columns in the specification. - // TODO Maybe return error code - return -1; - } - if (columnNumber > 0) { - symbol = getSymbol(counters, moduleWidth); - int cw = getCodeword(symbol); - // if (debug) System.out.println(" " + - // Long.toBinaryString(symbol) + " cw=" +cw + " ColumnNumber=" - // +columnNumber + "i=" +i); - if (cw < 0) { - erasures[eraseCount] = next; - next++; - eraseCount++; - } else { - codewords[next++] = cw; - } - } else { - // Left row indicator column - symbol = getSymbol(counters, moduleWidth); - int cw = getCodeword(symbol); - if (ecLevel < 0) { - switch (rowNumber % 3) { - case 0: - break; - case 1: - leftColumnECData = cw; - break; - case 2: - break; - } - } - } - // Step back so that this pixel can be examined during the next - // pass. - i--; - counters = new int[8]; - columns = columnNumber; - columnNumber++; - // Introduce some errors if (rowNumber == 0 && columnNumber == 4) - // { codewords[next-1] = 0; erasures[eraseCount] = next-1; - // eraseCount++; } if (rowNumber == 0 && columnNumber == 6) { - // codewords[next-1] = 10; erasures[eraseCount] = next-1; - // eraseCount++; } if (rowNumber == 0 && columnNumber == 8) { - // codewords[next-1] = 10; erasures[eraseCount] = next-1; - // eraseCount++; } - state = 0; - symbol = 0; - } - } - if (columnNumber > 1) { - // Right row indicator column is in codeword[next] - columns--; - // Overwrite the last codeword i.e. Right Row Indicator - --next; - if (ecLevel < 0) { - switch (rowNumber % 3) { - case 0: - break; - case 1: - break; - case 2: - rightColumnECData = codewords[next]; - if (rightColumnECData == leftColumnECData - && leftColumnECData != 0) { - ecLevel = ((rightColumnECData % 30) - rows % 3) / 3; - } - break; - } - } - codewords[next] = 0; - } - return next; - } - */ - - /// The sorted table of all possible symbols. Extracted from the PDF417 - /// specification. The index of a symbol in this table corresponds to the - /// index into the codeword table. - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'SYMBOL_TABLE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] SYMBOL_TABLE = new int[]{0x1025e, 0x1027a, 0x1029e, 0x102bc, 0x102f2, 0x102f4, 0x1032e, 0x1034e, 0x1035c, 0x10396, 0x103a6, 0x103ac, 0x10422, 0x10428, 0x10436, 0x10442, 0x10444, 0x10448, 0x10450, 0x1045e, 0x10466, 0x1046c, 0x1047a, 0x10482, 0x1049e, 0x104a0, 0x104bc, 0x104c6, 0x104d8, 0x104ee, 0x104f2, 0x104f4, 0x10504, 0x10508, 0x10510, 0x1051e, 0x10520, 0x1053c, 0x10540, 0x10578, 0x10586, 0x1058c, 0x10598, 0x105b0, 0x105be, 0x105ce, 0x105dc, 0x105e2, 0x105e4, 0x105e8, 0x105f6, 0x1062e, 0x1064e, 0x1065c, 0x1068e, 0x1069c, 0x106b8, 0x106de, 0x106fa, 0x10716, 0x10726, 0x1072c, 0x10746, 0x1074c, 0x10758, 0x1076e, 0x10792, 0x10794, 0x107a2, 0x107a4, 0x107a8, 0x107b6, 0x10822, 0x10828, 0x10842, 0x10848, 0x10850, 0x1085e, 0x10866, 0x1086c, 0x1087a, 0x10882, 0x10884, 0x10890, 0x1089e, 0x108a0, 0x108bc, 0x108c6, 0x108cc, 0x108d8, 0x108ee, 0x108f2, 0x108f4, 0x10902, 0x10908, 0x1091e, 0x10920, 0x1093c, 0x10940, 0x10978, 0x10986, 0x10998, 0x109b0, 0x109be, 0x109ce, 0x109dc, 0x109e2, 0x109e4, 0x109e8, 0x109f6, 0x10a08, 0x10a10, 0x10a1e, 0x10a20, 0x10a3c, 0x10a40, 0x10a78, 0x10af0, 0x10b06, 0x10b0c, 0x10b18, 0x10b30, 0x10b3e, 0x10b60, 0x10b7c, 0x10b8e, 0x10b9c, 0x10bb8, 0x10bc2, 0x10bc4, 0x10bc8, 0x10bd0, 0x10bde, 0x10be6, 0x10bec, 0x10c2e, 0x10c4e, 0x10c5c, 0x10c62, 0x10c64, 0x10c68, 0x10c76, 0x10c8e, 0x10c9c, 0x10cb8, 0x10cc2, 0x10cc4, 0x10cc8, 0x10cd0, 0x10cde, 0x10ce6, 0x10cec, 0x10cfa, 0x10d0e, 0x10d1c, 0x10d38, 0x10d70, 0x10d7e, 0x10d82, 0x10d84, 0x10d88, 0x10d90, 0x10d9e, 0x10da0, 0x10dbc, 0x10dc6, 0x10dcc, 0x10dd8, 0x10dee, 0x10df2, 0x10df4, 0x10e16, 0x10e26, 0x10e2c, 0x10e46, 0x10e58, 0x10e6e, 0x10e86, 0x10e8c, 0x10e98, 0x10eb0, 0x10ebe, 0x10ece, 0x10edc, 0x10f0a, 0x10f12, 0x10f14, 0x10f22, 0x10f28, 0x10f36, 0x10f42, 0x10f44, 0x10f48, 0x10f50, 0x10f5e, 0x10f66, 0x10f6c, 0x10fb2, 0x10fb4, 0x11022, 0x11028, 0x11042, 0x11048, 0x11050, 0x1105e, 0x1107a, 0x11082, 0x11084, 0x11090, 0x1109e, 0x110a0, 0x110bc, 0x110c6, 0x110cc, 0x110d8, 0x110ee, 0x110f2, 0x110f4, 0x11102, 0x1111e, - 0x11120, 0x1113c, 0x11140, 0x11178, 0x11186, 0x11198, 0x111b0, 0x111be, 0x111ce, 0x111dc, 0x111e2, 0x111e4, 0x111e8, 0x111f6, 0x11208, 0x1121e, 0x11220, 0x11278, 0x112f0, 0x1130c, 0x11330, 0x1133e, 0x11360, 0x1137c, 0x1138e, 0x1139c, 0x113b8, 0x113c2, 0x113c8, 0x113d0, 0x113de, 0x113e6, 0x113ec, 0x11408, 0x11410, 0x1141e, 0x11420, 0x1143c, 0x11440, 0x11478, 0x114f0, 0x115e0, 0x1160c, 0x11618, 0x11630, 0x1163e, 0x11660, 0x1167c, 0x116c0, 0x116f8, 0x1171c, 0x11738, 0x11770, 0x1177e, 0x11782, 0x11784, 0x11788, 0x11790, 0x1179e, 0x117a0, 0x117bc, 0x117c6, 0x117cc, 0x117d8, 0x117ee, 0x1182e, 0x11834, 0x1184e, 0x1185c, 0x11862, 0x11864, 0x11868, 0x11876, 0x1188e, 0x1189c, 0x118b8, 0x118c2, 0x118c8, 0x118d0, 0x118de, 0x118e6, 0x118ec, 0x118fa, 0x1190e, 0x1191c, 0x11938, 0x11970, 0x1197e, 0x11982, 0x11984, 0x11990, 0x1199e, 0x119a0, 0x119bc, 0x119c6, 0x119cc, 0x119d8, 0x119ee, 0x119f2, 0x119f4, 0x11a0e, 0x11a1c, 0x11a38, 0x11a70, 0x11a7e, 0x11ae0, 0x11afc, 0x11b08, 0x11b10, 0x11b1e, 0x11b20, 0x11b3c, 0x11b40, 0x11b78, 0x11b8c, 0x11b98, 0x11bb0, 0x11bbe, 0x11bce, 0x11bdc, 0x11be2, 0x11be4, 0x11be8, 0x11bf6, 0x11c16, 0x11c26, 0x11c2c, 0x11c46, 0x11c4c, 0x11c58, 0x11c6e, 0x11c86, 0x11c98, 0x11cb0, 0x11cbe, 0x11cce, 0x11cdc, 0x11ce2, 0x11ce4, 0x11ce8, 0x11cf6, 0x11d06, 0x11d0c, 0x11d18, 0x11d30, 0x11d3e, 0x11d60, 0x11d7c, 0x11d8e, 0x11d9c, 0x11db8, 0x11dc4, 0x11dc8, 0x11dd0, 0x11dde, 0x11de6, 0x11dec, 0x11dfa, 0x11e0a, 0x11e12, 0x11e14, 0x11e22, 0x11e24, 0x11e28, 0x11e36, 0x11e42, 0x11e44, 0x11e50, 0x11e5e, 0x11e66, 0x11e6c, 0x11e82, 0x11e84, 0x11e88, 0x11e90, 0x11e9e, 0x11ea0, 0x11ebc, 0x11ec6, 0x11ecc, 0x11ed8, 0x11eee, 0x11f1a, 0x11f2e, 0x11f32, 0x11f34, 0x11f4e, 0x11f5c, 0x11f62, 0x11f64, 0x11f68, 0x11f76, 0x12048, 0x1205e, 0x12082, 0x12084, 0x12090, 0x1209e, 0x120a0, 0x120bc, 0x120d8, 0x120f2, 0x120f4, 0x12108, 0x1211e, 0x12120, 0x1213c, 0x12140, 0x12178, 0x12186, 0x12198, 0x121b0, 0x121be, 0x121e2, 0x121e4, 0x121e8, 0x121f6, 0x12204, 0x12210, 0x1221e, 0x12220, 0x12278, 0x122f0, 0x12306, 0x1230c, - 0x12330, 0x1233e, 0x12360, 0x1237c, 0x1238e, 0x1239c, 0x123b8, 0x123c2, 0x123c8, 0x123d0, 0x123e6, 0x123ec, 0x1241e, 0x12420, 0x1243c, 0x124f0, 0x125e0, 0x12618, 0x1263e, 0x12660, 0x1267c, 0x126c0, 0x126f8, 0x12738, 0x12770, 0x1277e, 0x12782, 0x12784, 0x12790, 0x1279e, 0x127a0, 0x127bc, 0x127c6, 0x127cc, 0x127d8, 0x127ee, 0x12820, 0x1283c, 0x12840, 0x12878, 0x128f0, 0x129e0, 0x12bc0, 0x12c18, 0x12c30, 0x12c3e, 0x12c60, 0x12c7c, 0x12cc0, 0x12cf8, 0x12df0, 0x12e1c, 0x12e38, 0x12e70, 0x12e7e, 0x12ee0, 0x12efc, 0x12f04, 0x12f08, 0x12f10, 0x12f20, 0x12f3c, 0x12f40, 0x12f78, 0x12f86, 0x12f8c, 0x12f98, 0x12fb0, 0x12fbe, 0x12fce, 0x12fdc, 0x1302e, 0x1304e, 0x1305c, 0x13062, 0x13068, 0x1308e, 0x1309c, 0x130b8, 0x130c2, 0x130c8, 0x130d0, 0x130de, 0x130ec, 0x130fa, 0x1310e, 0x13138, 0x13170, 0x1317e, 0x13182, 0x13184, 0x13190, 0x1319e, 0x131a0, 0x131bc, 0x131c6, 0x131cc, 0x131d8, 0x131f2, 0x131f4, 0x1320e, 0x1321c, 0x13270, 0x1327e, 0x132e0, 0x132fc, 0x13308, 0x1331e, 0x13320, 0x1333c, 0x13340, 0x13378, 0x13386, 0x13398, 0x133b0, 0x133be, 0x133ce, 0x133dc, 0x133e2, 0x133e4, 0x133e8, 0x133f6, 0x1340e, 0x1341c, 0x13438, 0x13470, 0x1347e, 0x134e0, 0x134fc, 0x135c0, 0x135f8, 0x13608, 0x13610, 0x1361e, 0x13620, 0x1363c, 0x13640, 0x13678, 0x136f0, 0x1370c, 0x13718, 0x13730, 0x1373e, 0x13760, 0x1377c, 0x1379c, 0x137b8, 0x137c2, 0x137c4, 0x137c8, 0x137d0, 0x137de, 0x137e6, 0x137ec, 0x13816, 0x13826, 0x1382c, 0x13846, 0x1384c, 0x13858, 0x1386e, 0x13874, 0x13886, 0x13898, 0x138b0, 0x138be, 0x138ce, 0x138dc, 0x138e2, 0x138e4, 0x138e8, 0x13906, 0x1390c, 0x13930, 0x1393e, 0x13960, 0x1397c, 0x1398e, 0x1399c, 0x139b8, 0x139c8, 0x139d0, 0x139de, 0x139e6, 0x139ec, 0x139fa, 0x13a06, 0x13a0c, 0x13a18, 0x13a30, 0x13a3e, 0x13a60, 0x13a7c, 0x13ac0, 0x13af8, 0x13b0e, 0x13b1c, 0x13b38, 0x13b70, 0x13b7e, 0x13b88, 0x13b90, 0x13b9e, 0x13ba0, 0x13bbc, 0x13bcc, 0x13bd8, 0x13bee, 0x13bf2, 0x13bf4, 0x13c12, 0x13c14, 0x13c22, 0x13c24, 0x13c28, 0x13c36, 0x13c42, 0x13c48, 0x13c50, 0x13c5e, 0x13c66, 0x13c6c, 0x13c82, 0x13c84, 0x13c90, - 0x13c9e, 0x13ca0, 0x13cbc, 0x13cc6, 0x13ccc, 0x13cd8, 0x13cee, 0x13d02, 0x13d04, 0x13d08, 0x13d10, 0x13d1e, 0x13d20, 0x13d3c, 0x13d40, 0x13d78, 0x13d86, 0x13d8c, 0x13d98, 0x13db0, 0x13dbe, 0x13dce, 0x13ddc, 0x13de4, 0x13de8, 0x13df6, 0x13e1a, 0x13e2e, 0x13e32, 0x13e34, 0x13e4e, 0x13e5c, 0x13e62, 0x13e64, 0x13e68, 0x13e76, 0x13e8e, 0x13e9c, 0x13eb8, 0x13ec2, 0x13ec4, 0x13ec8, 0x13ed0, 0x13ede, 0x13ee6, 0x13eec, 0x13f26, 0x13f2c, 0x13f3a, 0x13f46, 0x13f4c, 0x13f58, 0x13f6e, 0x13f72, 0x13f74, 0x14082, 0x1409e, 0x140a0, 0x140bc, 0x14104, 0x14108, 0x14110, 0x1411e, 0x14120, 0x1413c, 0x14140, 0x14178, 0x1418c, 0x14198, 0x141b0, 0x141be, 0x141e2, 0x141e4, 0x141e8, 0x14208, 0x14210, 0x1421e, 0x14220, 0x1423c, 0x14240, 0x14278, 0x142f0, 0x14306, 0x1430c, 0x14318, 0x14330, 0x1433e, 0x14360, 0x1437c, 0x1438e, 0x143c2, 0x143c4, 0x143c8, 0x143d0, 0x143e6, 0x143ec, 0x14408, 0x14410, 0x1441e, 0x14420, 0x1443c, 0x14440, 0x14478, 0x144f0, 0x145e0, 0x1460c, 0x14618, 0x14630, 0x1463e, 0x14660, 0x1467c, 0x146c0, 0x146f8, 0x1471c, 0x14738, 0x14770, 0x1477e, 0x14782, 0x14784, 0x14788, 0x14790, 0x147a0, 0x147bc, 0x147c6, 0x147cc, 0x147d8, 0x147ee, 0x14810, 0x14820, 0x1483c, 0x14840, 0x14878, 0x148f0, 0x149e0, 0x14bc0, 0x14c30, 0x14c3e, 0x14c60, 0x14c7c, 0x14cc0, 0x14cf8, 0x14df0, 0x14e38, 0x14e70, 0x14e7e, 0x14ee0, 0x14efc, 0x14f04, 0x14f08, 0x14f10, 0x14f1e, 0x14f20, 0x14f3c, 0x14f40, 0x14f78, 0x14f86, 0x14f8c, 0x14f98, 0x14fb0, 0x14fce, 0x14fdc, 0x15020, 0x15040, 0x15078, 0x150f0, 0x151e0, 0x153c0, 0x15860, 0x1587c, 0x158c0, 0x158f8, 0x159f0, 0x15be0, 0x15c70, 0x15c7e, 0x15ce0, 0x15cfc, 0x15dc0, 0x15df8, 0x15e08, 0x15e10, 0x15e20, 0x15e40, 0x15e78, 0x15ef0, 0x15f0c, 0x15f18, 0x15f30, 0x15f60, 0x15f7c, 0x15f8e, 0x15f9c, 0x15fb8, 0x1604e, 0x1605c, 0x1608e, 0x1609c, 0x160b8, 0x160c2, 0x160c4, 0x160c8, 0x160de, 0x1610e, 0x1611c, 0x16138, 0x16170, 0x1617e, 0x16184, 0x16188, 0x16190, 0x1619e, 0x161a0, 0x161bc, 0x161c6, 0x161cc, 0x161d8, 0x161f2, 0x161f4, 0x1620e, 0x1621c, 0x16238, 0x16270, 0x1627e, 0x162e0, 0x162fc, - 0x16304, 0x16308, 0x16310, 0x1631e, 0x16320, 0x1633c, 0x16340, 0x16378, 0x16386, 0x1638c, 0x16398, 0x163b0, 0x163be, 0x163ce, 0x163dc, 0x163e2, 0x163e4, 0x163e8, 0x163f6, 0x1640e, 0x1641c, 0x16438, 0x16470, 0x1647e, 0x164e0, 0x164fc, 0x165c0, 0x165f8, 0x16610, 0x1661e, 0x16620, 0x1663c, 0x16640, 0x16678, 0x166f0, 0x16718, 0x16730, 0x1673e, 0x16760, 0x1677c, 0x1678e, 0x1679c, 0x167b8, 0x167c2, 0x167c4, 0x167c8, 0x167d0, 0x167de, 0x167e6, 0x167ec, 0x1681c, 0x16838, 0x16870, 0x168e0, 0x168fc, 0x169c0, 0x169f8, 0x16bf0, 0x16c10, 0x16c1e, 0x16c20, 0x16c3c, 0x16c40, 0x16c78, 0x16cf0, 0x16de0, 0x16e18, 0x16e30, 0x16e3e, 0x16e60, 0x16e7c, 0x16ec0, 0x16ef8, 0x16f1c, 0x16f38, 0x16f70, 0x16f7e, 0x16f84, 0x16f88, 0x16f90, 0x16f9e, 0x16fa0, 0x16fbc, 0x16fc6, 0x16fcc, 0x16fd8, 0x17026, 0x1702c, 0x17046, 0x1704c, 0x17058, 0x1706e, 0x17086, 0x1708c, 0x17098, 0x170b0, 0x170be, 0x170ce, 0x170dc, 0x170e8, 0x17106, 0x1710c, 0x17118, 0x17130, 0x1713e, 0x17160, 0x1717c, 0x1718e, 0x1719c, 0x171b8, 0x171c2, 0x171c4, 0x171c8, 0x171d0, 0x171de, 0x171e6, 0x171ec, 0x171fa, 0x17206, 0x1720c, 0x17218, 0x17230, 0x1723e, 0x17260, 0x1727c, 0x172c0, 0x172f8, 0x1730e, 0x1731c, 0x17338, 0x17370, 0x1737e, 0x17388, 0x17390, 0x1739e, 0x173a0, 0x173bc, 0x173cc, 0x173d8, 0x173ee, 0x173f2, 0x173f4, 0x1740c, 0x17418, 0x17430, 0x1743e, 0x17460, 0x1747c, 0x174c0, 0x174f8, 0x175f0, 0x1760e, 0x1761c, 0x17638, 0x17670, 0x1767e, 0x176e0, 0x176fc, 0x17708, 0x17710, 0x1771e, 0x17720, 0x1773c, 0x17740, 0x17778, 0x17798, 0x177b0, 0x177be, 0x177dc, 0x177e2, 0x177e4, 0x177e8, 0x17822, 0x17824, 0x17828, 0x17836, 0x17842, 0x17844, 0x17848, 0x17850, 0x1785e, 0x17866, 0x1786c, 0x17882, 0x17884, 0x17888, 0x17890, 0x1789e, 0x178a0, 0x178bc, 0x178c6, 0x178cc, 0x178d8, 0x178ee, 0x178f2, 0x178f4, 0x17902, 0x17904, 0x17908, 0x17910, 0x1791e, 0x17920, 0x1793c, 0x17940, 0x17978, 0x17986, 0x1798c, 0x17998, 0x179b0, 0x179be, 0x179ce, 0x179dc, 0x179e2, 0x179e4, 0x179e8, 0x179f6, 0x17a04, 0x17a08, 0x17a10, 0x17a1e, 0x17a20, 0x17a3c, 0x17a40, 0x17a78, 0x17af0, - 0x17b06, 0x17b0c, 0x17b18, 0x17b30, 0x17b3e, 0x17b60, 0x17b7c, 0x17b8e, 0x17b9c, 0x17bb8, 0x17bc4, 0x17bc8, 0x17bd0, 0x17bde, 0x17be6, 0x17bec, 0x17c2e, 0x17c32, 0x17c34, 0x17c4e, 0x17c5c, 0x17c62, 0x17c64, 0x17c68, 0x17c76, 0x17c8e, 0x17c9c, 0x17cb8, 0x17cc2, 0x17cc4, 0x17cc8, 0x17cd0, 0x17cde, 0x17ce6, 0x17cec, 0x17d0e, 0x17d1c, 0x17d38, 0x17d70, 0x17d82, 0x17d84, 0x17d88, 0x17d90, 0x17d9e, 0x17da0, 0x17dbc, 0x17dc6, 0x17dcc, 0x17dd8, 0x17dee, 0x17e26, 0x17e2c, 0x17e3a, 0x17e46, 0x17e4c, 0x17e58, 0x17e6e, 0x17e72, 0x17e74, 0x17e86, 0x17e8c, 0x17e98, 0x17eb0, 0x17ece, 0x17edc, 0x17ee2, 0x17ee4, 0x17ee8, 0x17ef6, 0x1813a, 0x18172, 0x18174, 0x18216, 0x18226, 0x1823a, 0x1824c, 0x18258, 0x1826e, 0x18272, 0x18274, 0x18298, 0x182be, 0x182e2, 0x182e4, 0x182e8, 0x182f6, 0x1835e, 0x1837a, 0x183ae, 0x183d6, 0x18416, 0x18426, 0x1842c, 0x1843a, 0x18446, 0x18458, 0x1846e, 0x18472, 0x18474, 0x18486, 0x184b0, 0x184be, 0x184ce, 0x184dc, 0x184e2, 0x184e4, 0x184e8, 0x184f6, 0x18506, 0x1850c, 0x18518, 0x18530, 0x1853e, 0x18560, 0x1857c, 0x1858e, 0x1859c, 0x185b8, 0x185c2, 0x185c4, 0x185c8, 0x185d0, 0x185de, 0x185e6, 0x185ec, 0x185fa, 0x18612, 0x18614, 0x18622, 0x18628, 0x18636, 0x18642, 0x18650, 0x1865e, 0x1867a, 0x18682, 0x18684, 0x18688, 0x18690, 0x1869e, 0x186a0, 0x186bc, 0x186c6, 0x186cc, 0x186d8, 0x186ee, 0x186f2, 0x186f4, 0x1872e, 0x1874e, 0x1875c, 0x18796, 0x187a6, 0x187ac, 0x187d2, 0x187d4, 0x18826, 0x1882c, 0x1883a, 0x18846, 0x1884c, 0x18858, 0x1886e, 0x18872, 0x18874, 0x18886, 0x18898, 0x188b0, 0x188be, 0x188ce, 0x188dc, 0x188e2, 0x188e4, 0x188e8, 0x188f6, 0x1890c, 0x18930, 0x1893e, 0x18960, 0x1897c, 0x1898e, 0x189b8, 0x189c2, 0x189c8, 0x189d0, 0x189de, 0x189e6, 0x189ec, 0x189fa, 0x18a18, 0x18a30, 0x18a3e, 0x18a60, 0x18a7c, 0x18ac0, 0x18af8, 0x18b1c, 0x18b38, 0x18b70, 0x18b7e, 0x18b82, 0x18b84, 0x18b88, 0x18b90, 0x18b9e, 0x18ba0, 0x18bbc, 0x18bc6, 0x18bcc, 0x18bd8, 0x18bee, 0x18bf2, 0x18bf4, 0x18c22, 0x18c24, 0x18c28, 0x18c36, 0x18c42, 0x18c48, 0x18c50, 0x18c5e, 0x18c66, 0x18c7a, 0x18c82, 0x18c84, - 0x18c90, 0x18c9e, 0x18ca0, 0x18cbc, 0x18ccc, 0x18cf2, 0x18cf4, 0x18d04, 0x18d08, 0x18d10, 0x18d1e, 0x18d20, 0x18d3c, 0x18d40, 0x18d78, 0x18d86, 0x18d98, 0x18dce, 0x18de2, 0x18de4, 0x18de8, 0x18e2e, 0x18e32, 0x18e34, 0x18e4e, 0x18e5c, 0x18e62, 0x18e64, 0x18e68, 0x18e8e, 0x18e9c, 0x18eb8, 0x18ec2, 0x18ec4, 0x18ec8, 0x18ed0, 0x18efa, 0x18f16, 0x18f26, 0x18f2c, 0x18f46, 0x18f4c, 0x18f58, 0x18f6e, 0x18f8a, 0x18f92, 0x18f94, 0x18fa2, 0x18fa4, 0x18fa8, 0x18fb6, 0x1902c, 0x1903a, 0x19046, 0x1904c, 0x19058, 0x19072, 0x19074, 0x19086, 0x19098, 0x190b0, 0x190be, 0x190ce, 0x190dc, 0x190e2, 0x190e8, 0x190f6, 0x19106, 0x1910c, 0x19130, 0x1913e, 0x19160, 0x1917c, 0x1918e, 0x1919c, 0x191b8, 0x191c2, 0x191c8, 0x191d0, 0x191de, 0x191e6, 0x191ec, 0x191fa, 0x19218, 0x1923e, 0x19260, 0x1927c, 0x192c0, 0x192f8, 0x19338, 0x19370, 0x1937e, 0x19382, 0x19384, 0x19390, 0x1939e, 0x193a0, 0x193bc, 0x193c6, 0x193cc, 0x193d8, 0x193ee, 0x193f2, 0x193f4, 0x19430, 0x1943e, 0x19460, 0x1947c, 0x194c0, 0x194f8, 0x195f0, 0x19638, 0x19670, 0x1967e, 0x196e0, 0x196fc, 0x19702, 0x19704, 0x19708, 0x19710, 0x19720, 0x1973c, 0x19740, 0x19778, 0x19786, 0x1978c, 0x19798, 0x197b0, 0x197be, 0x197ce, 0x197dc, 0x197e2, 0x197e4, 0x197e8, 0x19822, 0x19824, 0x19842, 0x19848, 0x19850, 0x1985e, 0x19866, 0x1987a, 0x19882, 0x19884, 0x19890, 0x1989e, 0x198a0, 0x198bc, 0x198cc, 0x198f2, 0x198f4, 0x19902, 0x19908, 0x1991e, 0x19920, 0x1993c, 0x19940, 0x19978, 0x19986, 0x19998, 0x199ce, 0x199e2, 0x199e4, 0x199e8, 0x19a08, 0x19a10, 0x19a1e, 0x19a20, 0x19a3c, 0x19a40, 0x19a78, 0x19af0, 0x19b18, 0x19b3e, 0x19b60, 0x19b9c, 0x19bc2, 0x19bc4, 0x19bc8, 0x19bd0, 0x19be6, 0x19c2e, 0x19c34, 0x19c4e, 0x19c5c, 0x19c62, 0x19c64, 0x19c68, 0x19c8e, 0x19c9c, 0x19cb8, 0x19cc2, 0x19cc8, 0x19cd0, 0x19ce6, 0x19cfa, 0x19d0e, 0x19d1c, 0x19d38, 0x19d70, 0x19d7e, 0x19d82, 0x19d84, 0x19d88, 0x19d90, 0x19da0, 0x19dcc, 0x19df2, 0x19df4, 0x19e16, 0x19e26, 0x19e2c, 0x19e46, 0x19e4c, 0x19e58, 0x19e74, 0x19e86, 0x19e8c, 0x19e98, 0x19eb0, 0x19ebe, 0x19ece, 0x19ee2, 0x19ee4, 0x19ee8, - 0x19f0a, 0x19f12, 0x19f14, 0x19f22, 0x19f24, 0x19f28, 0x19f42, 0x19f44, 0x19f48, 0x19f50, 0x19f5e, 0x19f6c, 0x19f9a, 0x19fae, 0x19fb2, 0x19fb4, 0x1a046, 0x1a04c, 0x1a072, 0x1a074, 0x1a086, 0x1a08c, 0x1a098, 0x1a0b0, 0x1a0be, 0x1a0e2, 0x1a0e4, 0x1a0e8, 0x1a0f6, 0x1a106, 0x1a10c, 0x1a118, 0x1a130, 0x1a13e, 0x1a160, 0x1a17c, 0x1a18e, 0x1a19c, 0x1a1b8, 0x1a1c2, 0x1a1c4, 0x1a1c8, 0x1a1d0, 0x1a1de, 0x1a1e6, 0x1a1ec, 0x1a218, 0x1a230, 0x1a23e, 0x1a260, 0x1a27c, 0x1a2c0, 0x1a2f8, 0x1a31c, 0x1a338, 0x1a370, 0x1a37e, 0x1a382, 0x1a384, 0x1a388, 0x1a390, 0x1a39e, 0x1a3a0, 0x1a3bc, 0x1a3c6, 0x1a3cc, 0x1a3d8, 0x1a3ee, 0x1a3f2, 0x1a3f4, 0x1a418, 0x1a430, 0x1a43e, 0x1a460, 0x1a47c, 0x1a4c0, 0x1a4f8, 0x1a5f0, 0x1a61c, 0x1a638, 0x1a670, 0x1a67e, 0x1a6e0, 0x1a6fc, 0x1a702, 0x1a704, 0x1a708, 0x1a710, 0x1a71e, 0x1a720, 0x1a73c, 0x1a740, 0x1a778, 0x1a786, 0x1a78c, 0x1a798, 0x1a7b0, 0x1a7be, 0x1a7ce, 0x1a7dc, 0x1a7e2, 0x1a7e4, 0x1a7e8, 0x1a830, 0x1a860, 0x1a87c, 0x1a8c0, 0x1a8f8, 0x1a9f0, 0x1abe0, 0x1ac70, 0x1ac7e, 0x1ace0, 0x1acfc, 0x1adc0, 0x1adf8, 0x1ae04, 0x1ae08, 0x1ae10, 0x1ae20, 0x1ae3c, 0x1ae40, 0x1ae78, 0x1aef0, 0x1af06, 0x1af0c, 0x1af18, 0x1af30, 0x1af3e, 0x1af60, 0x1af7c, 0x1af8e, 0x1af9c, 0x1afb8, 0x1afc4, 0x1afc8, 0x1afd0, 0x1afde, 0x1b042, 0x1b05e, 0x1b07a, 0x1b082, 0x1b084, 0x1b088, 0x1b090, 0x1b09e, 0x1b0a0, 0x1b0bc, 0x1b0cc, 0x1b0f2, 0x1b0f4, 0x1b102, 0x1b104, 0x1b108, 0x1b110, 0x1b11e, 0x1b120, 0x1b13c, 0x1b140, 0x1b178, 0x1b186, 0x1b198, 0x1b1ce, 0x1b1e2, 0x1b1e4, 0x1b1e8, 0x1b204, 0x1b208, 0x1b210, 0x1b21e, 0x1b220, 0x1b23c, 0x1b240, 0x1b278, 0x1b2f0, 0x1b30c, 0x1b33e, 0x1b360, 0x1b39c, 0x1b3c2, 0x1b3c4, 0x1b3c8, 0x1b3d0, 0x1b3e6, 0x1b410, 0x1b41e, 0x1b420, 0x1b43c, 0x1b440, 0x1b478, 0x1b4f0, 0x1b5e0, 0x1b618, 0x1b660, 0x1b67c, 0x1b6c0, 0x1b738, 0x1b782, 0x1b784, 0x1b788, 0x1b790, 0x1b79e, 0x1b7a0, 0x1b7cc, 0x1b82e, 0x1b84e, 0x1b85c, 0x1b88e, 0x1b89c, 0x1b8b8, 0x1b8c2, 0x1b8c4, 0x1b8c8, 0x1b8d0, 0x1b8e6, 0x1b8fa, 0x1b90e, 0x1b91c, 0x1b938, 0x1b970, 0x1b97e, 0x1b982, 0x1b984, 0x1b988, 0x1b990, - 0x1b99e, 0x1b9a0, 0x1b9cc, 0x1b9f2, 0x1b9f4, 0x1ba0e, 0x1ba1c, 0x1ba38, 0x1ba70, 0x1ba7e, 0x1bae0, 0x1bafc, 0x1bb08, 0x1bb10, 0x1bb20, 0x1bb3c, 0x1bb40, 0x1bb98, 0x1bbce, 0x1bbe2, 0x1bbe4, 0x1bbe8, 0x1bc16, 0x1bc26, 0x1bc2c, 0x1bc46, 0x1bc4c, 0x1bc58, 0x1bc72, 0x1bc74, 0x1bc86, 0x1bc8c, 0x1bc98, 0x1bcb0, 0x1bcbe, 0x1bcce, 0x1bce2, 0x1bce4, 0x1bce8, 0x1bd06, 0x1bd0c, 0x1bd18, 0x1bd30, 0x1bd3e, 0x1bd60, 0x1bd7c, 0x1bd9c, 0x1bdc2, 0x1bdc4, 0x1bdc8, 0x1bdd0, 0x1bde6, 0x1bdfa, 0x1be12, 0x1be14, 0x1be22, 0x1be24, 0x1be28, 0x1be42, 0x1be44, 0x1be48, 0x1be50, 0x1be5e, 0x1be66, 0x1be82, 0x1be84, 0x1be88, 0x1be90, 0x1be9e, 0x1bea0, 0x1bebc, 0x1becc, 0x1bef4, 0x1bf1a, 0x1bf2e, 0x1bf32, 0x1bf34, 0x1bf4e, 0x1bf5c, 0x1bf62, 0x1bf64, 0x1bf68, 0x1c09a, 0x1c0b2, 0x1c0b4, 0x1c11a, 0x1c132, 0x1c134, 0x1c162, 0x1c164, 0x1c168, 0x1c176, 0x1c1ba, 0x1c21a, 0x1c232, 0x1c234, 0x1c24e, 0x1c25c, 0x1c262, 0x1c264, 0x1c268, 0x1c276, 0x1c28e, 0x1c2c2, 0x1c2c4, 0x1c2c8, 0x1c2d0, 0x1c2de, 0x1c2e6, 0x1c2ec, 0x1c2fa, 0x1c316, 0x1c326, 0x1c33a, 0x1c346, 0x1c34c, 0x1c372, 0x1c374, 0x1c41a, 0x1c42e, 0x1c432, 0x1c434, 0x1c44e, 0x1c45c, 0x1c462, 0x1c464, 0x1c468, 0x1c476, 0x1c48e, 0x1c49c, 0x1c4b8, 0x1c4c2, 0x1c4c8, 0x1c4d0, 0x1c4de, 0x1c4e6, 0x1c4ec, 0x1c4fa, 0x1c51c, 0x1c538, 0x1c570, 0x1c57e, 0x1c582, 0x1c584, 0x1c588, 0x1c590, 0x1c59e, 0x1c5a0, 0x1c5bc, 0x1c5c6, 0x1c5cc, 0x1c5d8, 0x1c5ee, 0x1c5f2, 0x1c5f4, 0x1c616, 0x1c626, 0x1c62c, 0x1c63a, 0x1c646, 0x1c64c, 0x1c658, 0x1c66e, 0x1c672, 0x1c674, 0x1c686, 0x1c68c, 0x1c698, 0x1c6b0, 0x1c6be, 0x1c6ce, 0x1c6dc, 0x1c6e2, 0x1c6e4, 0x1c6e8, 0x1c712, 0x1c714, 0x1c722, 0x1c728, 0x1c736, 0x1c742, 0x1c744, 0x1c748, 0x1c750, 0x1c75e, 0x1c766, 0x1c76c, 0x1c77a, 0x1c7ae, 0x1c7d6, 0x1c7ea, 0x1c81a, 0x1c82e, 0x1c832, 0x1c834, 0x1c84e, 0x1c85c, 0x1c862, 0x1c864, 0x1c868, 0x1c876, 0x1c88e, 0x1c89c, 0x1c8b8, 0x1c8c2, 0x1c8c8, 0x1c8d0, 0x1c8de, 0x1c8e6, 0x1c8ec, 0x1c8fa, 0x1c90e, 0x1c938, 0x1c970, 0x1c97e, 0x1c982, 0x1c984, 0x1c990, 0x1c99e, 0x1c9a0, 0x1c9bc, 0x1c9c6, 0x1c9cc, 0x1c9d8, 0x1c9ee, - 0x1c9f2, 0x1c9f4, 0x1ca38, 0x1ca70, 0x1ca7e, 0x1cae0, 0x1cafc, 0x1cb02, 0x1cb04, 0x1cb08, 0x1cb10, 0x1cb20, 0x1cb3c, 0x1cb40, 0x1cb78, 0x1cb86, 0x1cb8c, 0x1cb98, 0x1cbb0, 0x1cbbe, 0x1cbce, 0x1cbdc, 0x1cbe2, 0x1cbe4, 0x1cbe8, 0x1cbf6, 0x1cc16, 0x1cc26, 0x1cc2c, 0x1cc3a, 0x1cc46, 0x1cc58, 0x1cc72, 0x1cc74, 0x1cc86, 0x1ccb0, 0x1ccbe, 0x1ccce, 0x1cce2, 0x1cce4, 0x1cce8, 0x1cd06, 0x1cd0c, 0x1cd18, 0x1cd30, 0x1cd3e, 0x1cd60, 0x1cd7c, 0x1cd9c, 0x1cdc2, 0x1cdc4, 0x1cdc8, 0x1cdd0, 0x1cdde, 0x1cde6, 0x1cdfa, 0x1ce22, 0x1ce28, 0x1ce42, 0x1ce50, 0x1ce5e, 0x1ce66, 0x1ce7a, 0x1ce82, 0x1ce84, 0x1ce88, 0x1ce90, 0x1ce9e, 0x1cea0, 0x1cebc, 0x1cecc, 0x1cef2, 0x1cef4, 0x1cf2e, 0x1cf32, 0x1cf34, 0x1cf4e, 0x1cf5c, 0x1cf62, 0x1cf64, 0x1cf68, 0x1cf96, 0x1cfa6, 0x1cfac, 0x1cfca, 0x1cfd2, 0x1cfd4, 0x1d02e, 0x1d032, 0x1d034, 0x1d04e, 0x1d05c, 0x1d062, 0x1d064, 0x1d068, 0x1d076, 0x1d08e, 0x1d09c, 0x1d0b8, 0x1d0c2, 0x1d0c4, 0x1d0c8, 0x1d0d0, 0x1d0de, 0x1d0e6, 0x1d0ec, 0x1d0fa, 0x1d11c, 0x1d138, 0x1d170, 0x1d17e, 0x1d182, 0x1d184, 0x1d188, 0x1d190, 0x1d19e, 0x1d1a0, 0x1d1bc, 0x1d1c6, 0x1d1cc, 0x1d1d8, 0x1d1ee, 0x1d1f2, 0x1d1f4, 0x1d21c, 0x1d238, 0x1d270, 0x1d27e, 0x1d2e0, 0x1d2fc, 0x1d302, 0x1d304, 0x1d308, 0x1d310, 0x1d31e, 0x1d320, 0x1d33c, 0x1d340, 0x1d378, 0x1d386, 0x1d38c, 0x1d398, 0x1d3b0, 0x1d3be, 0x1d3ce, 0x1d3dc, 0x1d3e2, 0x1d3e4, 0x1d3e8, 0x1d3f6, 0x1d470, 0x1d47e, 0x1d4e0, 0x1d4fc, 0x1d5c0, 0x1d5f8, 0x1d604, 0x1d608, 0x1d610, 0x1d620, 0x1d640, 0x1d678, 0x1d6f0, 0x1d706, 0x1d70c, 0x1d718, 0x1d730, 0x1d73e, 0x1d760, 0x1d77c, 0x1d78e, 0x1d79c, 0x1d7b8, 0x1d7c2, 0x1d7c4, 0x1d7c8, 0x1d7d0, 0x1d7de, 0x1d7e6, 0x1d7ec, 0x1d826, 0x1d82c, 0x1d83a, 0x1d846, 0x1d84c, 0x1d858, 0x1d872, 0x1d874, 0x1d886, 0x1d88c, 0x1d898, 0x1d8b0, 0x1d8be, 0x1d8ce, 0x1d8e2, 0x1d8e4, 0x1d8e8, 0x1d8f6, 0x1d90c, 0x1d918, 0x1d930, 0x1d93e, 0x1d960, 0x1d97c, 0x1d99c, 0x1d9c2, 0x1d9c4, 0x1d9c8, 0x1d9d0, 0x1d9e6, 0x1d9fa, 0x1da0c, 0x1da18, 0x1da30, 0x1da3e, 0x1da60, 0x1da7c, 0x1dac0, 0x1daf8, 0x1db38, 0x1db82, 0x1db84, 0x1db88, 0x1db90, 0x1db9e, - 0x1dba0, 0x1dbcc, 0x1dbf2, 0x1dbf4, 0x1dc22, 0x1dc42, 0x1dc44, 0x1dc48, 0x1dc50, 0x1dc5e, 0x1dc66, 0x1dc7a, 0x1dc82, 0x1dc84, 0x1dc88, 0x1dc90, 0x1dc9e, 0x1dca0, 0x1dcbc, 0x1dccc, 0x1dcf2, 0x1dcf4, 0x1dd04, 0x1dd08, 0x1dd10, 0x1dd1e, 0x1dd20, 0x1dd3c, 0x1dd40, 0x1dd78, 0x1dd86, 0x1dd98, 0x1ddce, 0x1dde2, 0x1dde4, 0x1dde8, 0x1de2e, 0x1de32, 0x1de34, 0x1de4e, 0x1de5c, 0x1de62, 0x1de64, 0x1de68, 0x1de8e, 0x1de9c, 0x1deb8, 0x1dec2, 0x1dec4, 0x1dec8, 0x1ded0, 0x1dee6, 0x1defa, 0x1df16, 0x1df26, 0x1df2c, 0x1df46, 0x1df4c, 0x1df58, 0x1df72, 0x1df74, 0x1df8a, 0x1df92, 0x1df94, 0x1dfa2, 0x1dfa4, 0x1dfa8, 0x1e08a, 0x1e092, 0x1e094, 0x1e0a2, 0x1e0a4, 0x1e0a8, 0x1e0b6, 0x1e0da, 0x1e10a, 0x1e112, 0x1e114, 0x1e122, 0x1e124, 0x1e128, 0x1e136, 0x1e142, 0x1e144, 0x1e148, 0x1e150, 0x1e166, 0x1e16c, 0x1e17a, 0x1e19a, 0x1e1b2, 0x1e1b4, 0x1e20a, 0x1e212, 0x1e214, 0x1e222, 0x1e224, 0x1e228, 0x1e236, 0x1e242, 0x1e248, 0x1e250, 0x1e25e, 0x1e266, 0x1e26c, 0x1e27a, 0x1e282, 0x1e284, 0x1e288, 0x1e290, 0x1e2a0, 0x1e2bc, 0x1e2c6, 0x1e2cc, 0x1e2d8, 0x1e2ee, 0x1e2f2, 0x1e2f4, 0x1e31a, 0x1e332, 0x1e334, 0x1e35c, 0x1e362, 0x1e364, 0x1e368, 0x1e3ba, 0x1e40a, 0x1e412, 0x1e414, 0x1e422, 0x1e428, 0x1e436, 0x1e442, 0x1e448, 0x1e450, 0x1e45e, 0x1e466, 0x1e46c, 0x1e47a, 0x1e482, 0x1e484, 0x1e490, 0x1e49e, 0x1e4a0, 0x1e4bc, 0x1e4c6, 0x1e4cc, 0x1e4d8, 0x1e4ee, 0x1e4f2, 0x1e4f4, 0x1e502, 0x1e504, 0x1e508, 0x1e510, 0x1e51e, 0x1e520, 0x1e53c, 0x1e540, 0x1e578, 0x1e586, 0x1e58c, 0x1e598, 0x1e5b0, 0x1e5be, 0x1e5ce, 0x1e5dc, 0x1e5e2, 0x1e5e4, 0x1e5e8, 0x1e5f6, 0x1e61a, 0x1e62e, 0x1e632, 0x1e634, 0x1e64e, 0x1e65c, 0x1e662, 0x1e668, 0x1e68e, 0x1e69c, 0x1e6b8, 0x1e6c2, 0x1e6c4, 0x1e6c8, 0x1e6d0, 0x1e6e6, 0x1e6fa, 0x1e716, 0x1e726, 0x1e72c, 0x1e73a, 0x1e746, 0x1e74c, 0x1e758, 0x1e772, 0x1e774, 0x1e792, 0x1e794, 0x1e7a2, 0x1e7a4, 0x1e7a8, 0x1e7b6, 0x1e812, 0x1e814, 0x1e822, 0x1e824, 0x1e828, 0x1e836, 0x1e842, 0x1e844, 0x1e848, 0x1e850, 0x1e85e, 0x1e866, 0x1e86c, 0x1e87a, 0x1e882, 0x1e884, 0x1e888, 0x1e890, 0x1e89e, 0x1e8a0, 0x1e8bc, 0x1e8c6, - 0x1e8cc, 0x1e8d8, 0x1e8ee, 0x1e8f2, 0x1e8f4, 0x1e902, 0x1e904, 0x1e908, 0x1e910, 0x1e920, 0x1e93c, 0x1e940, 0x1e978, 0x1e986, 0x1e98c, 0x1e998, 0x1e9b0, 0x1e9be, 0x1e9ce, 0x1e9dc, 0x1e9e2, 0x1e9e4, 0x1e9e8, 0x1e9f6, 0x1ea04, 0x1ea08, 0x1ea10, 0x1ea20, 0x1ea40, 0x1ea78, 0x1eaf0, 0x1eb06, 0x1eb0c, 0x1eb18, 0x1eb30, 0x1eb3e, 0x1eb60, 0x1eb7c, 0x1eb8e, 0x1eb9c, 0x1ebb8, 0x1ebc2, 0x1ebc4, 0x1ebc8, 0x1ebd0, 0x1ebde, 0x1ebe6, 0x1ebec, 0x1ec1a, 0x1ec2e, 0x1ec32, 0x1ec34, 0x1ec4e, 0x1ec5c, 0x1ec62, 0x1ec64, 0x1ec68, 0x1ec8e, 0x1ec9c, 0x1ecb8, 0x1ecc2, 0x1ecc4, 0x1ecc8, 0x1ecd0, 0x1ece6, 0x1ecfa, 0x1ed0e, 0x1ed1c, 0x1ed38, 0x1ed70, 0x1ed7e, 0x1ed82, 0x1ed84, 0x1ed88, 0x1ed90, 0x1ed9e, 0x1eda0, 0x1edcc, 0x1edf2, 0x1edf4, 0x1ee16, 0x1ee26, 0x1ee2c, 0x1ee3a, 0x1ee46, 0x1ee4c, 0x1ee58, 0x1ee6e, 0x1ee72, 0x1ee74, 0x1ee86, 0x1ee8c, 0x1ee98, 0x1eeb0, 0x1eebe, 0x1eece, 0x1eedc, 0x1eee2, 0x1eee4, 0x1eee8, 0x1ef12, 0x1ef22, 0x1ef24, 0x1ef28, 0x1ef36, 0x1ef42, 0x1ef44, 0x1ef48, 0x1ef50, 0x1ef5e, 0x1ef66, 0x1ef6c, 0x1ef7a, 0x1efae, 0x1efb2, 0x1efb4, 0x1efd6, 0x1f096, 0x1f0a6, 0x1f0ac, 0x1f0ba, 0x1f0ca, 0x1f0d2, 0x1f0d4, 0x1f116, 0x1f126, 0x1f12c, 0x1f13a, 0x1f146, 0x1f14c, 0x1f158, 0x1f16e, 0x1f172, 0x1f174, 0x1f18a, 0x1f192, 0x1f194, 0x1f1a2, 0x1f1a4, 0x1f1a8, 0x1f1da, 0x1f216, 0x1f226, 0x1f22c, 0x1f23a, 0x1f246, 0x1f258, 0x1f26e, 0x1f272, 0x1f274, 0x1f286, 0x1f28c, 0x1f298, 0x1f2b0, 0x1f2be, 0x1f2ce, 0x1f2dc, 0x1f2e2, 0x1f2e4, 0x1f2e8, 0x1f2f6, 0x1f30a, 0x1f312, 0x1f314, 0x1f322, 0x1f328, 0x1f342, 0x1f344, 0x1f348, 0x1f350, 0x1f35e, 0x1f366, 0x1f37a, 0x1f39a, 0x1f3ae, 0x1f3b2, 0x1f3b4, 0x1f416, 0x1f426, 0x1f42c, 0x1f43a, 0x1f446, 0x1f44c, 0x1f458, 0x1f46e, 0x1f472, 0x1f474, 0x1f486, 0x1f48c, 0x1f498, 0x1f4b0, 0x1f4be, 0x1f4ce, 0x1f4dc, 0x1f4e2, 0x1f4e4, 0x1f4e8, 0x1f4f6, 0x1f506, 0x1f50c, 0x1f518, 0x1f530, 0x1f53e, 0x1f560, 0x1f57c, 0x1f58e, 0x1f59c, 0x1f5b8, 0x1f5c2, 0x1f5c4, 0x1f5c8, 0x1f5d0, 0x1f5de, 0x1f5e6, 0x1f5ec, 0x1f5fa, 0x1f60a, 0x1f612, 0x1f614, 0x1f622, 0x1f624, 0x1f628, 0x1f636, 0x1f642, 0x1f644, - 0x1f648, 0x1f650, 0x1f65e, 0x1f666, 0x1f67a, 0x1f682, 0x1f684, 0x1f688, 0x1f690, 0x1f69e, 0x1f6a0, 0x1f6bc, 0x1f6cc, 0x1f6f2, 0x1f6f4, 0x1f71a, 0x1f72e, 0x1f732, 0x1f734, 0x1f74e, 0x1f75c, 0x1f762, 0x1f764, 0x1f768, 0x1f776, 0x1f796, 0x1f7a6, 0x1f7ac, 0x1f7ba, 0x1f7d2, 0x1f7d4, 0x1f89a, 0x1f8ae, 0x1f8b2, 0x1f8b4, 0x1f8d6, 0x1f8ea, 0x1f91a, 0x1f92e, 0x1f932, 0x1f934, 0x1f94e, 0x1f95c, 0x1f962, 0x1f964, 0x1f968, 0x1f976, 0x1f996, 0x1f9a6, 0x1f9ac, 0x1f9ba, 0x1f9ca, 0x1f9d2, 0x1f9d4, 0x1fa1a, 0x1fa2e, 0x1fa32, 0x1fa34, 0x1fa4e, 0x1fa5c, 0x1fa62, 0x1fa64, 0x1fa68, 0x1fa76, 0x1fa8e, 0x1fa9c, 0x1fab8, 0x1fac2, 0x1fac4, 0x1fac8, 0x1fad0, 0x1fade, 0x1fae6, 0x1faec, 0x1fb16, 0x1fb26, 0x1fb2c, 0x1fb3a, 0x1fb46, 0x1fb4c, 0x1fb58, 0x1fb6e, 0x1fb72, 0x1fb74, 0x1fb8a, 0x1fb92, 0x1fb94, 0x1fba2, 0x1fba4, 0x1fba8, 0x1fbb6, 0x1fbda}; - - /// This table contains to codewords for all symbols. - //UPGRADE_NOTE: Final was removed from the declaration of 'CODEWORD_TABLE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] CODEWORD_TABLE = new int[]{2627, 1819, 2622, 2621, 1813, 1812, 2729, 2724, 2723, 2779, 2774, 2773, 902, 896, 908, 868, 865, 861, 859, 2511, 873, 871, 1780, 835, 2493, 825, 2491, 842, 837, 844, 1764, 1762, 811, 810, 809, 2483, 807, 2482, 806, 2480, 815, 814, 813, 812, 2484, 817, 816, 1745, 1744, 1742, 1746, 2655, 2637, 2635, 2626, 2625, 2623, 2628, 1820, 2752, 2739, 2737, 2728, 2727, 2725, 2730, 2785, 2783, 2778, 2777, 2775, 2780, 787, 781, 747, 739, 736, 2413, 754, 752, 1719, 692, 689, 681, 2371, 678, 2369, 700, 697, 694, 703, 1688, 1686, 642, 638, 2343, 631, 2341, 627, 2338, 651, 646, 643, 2345, 654, 652, 1652, 1650, 1647, 1654, 601, 599, 2322, 596, 2321, 594, 2319, 2317, 611, 610, 608, 606, 2324, 603, 2323, 615, 614, 612, 1617, 1616, 1614, 1612, 616, 1619, 1618, 2575, 2538, 2536, 905, 901, 898, 909, 2509, 2507, 2504, 870, 867, 864, 860, 2512, 875, 872, 1781, 2490, 2489, 2487, 2485, 1748, 836, 834, 832, 830, 2494, 827, 2492, 843, 841, 839, 845, 1765, 1763, 2701, 2676, 2674, 2653, 2648, 2656, 2634, 2633, 2631, 2629, 1821, 2638, 2636, 2770, 2763, 2761, 2750, 2745, 2753, 2736, 2735, 2733, 2731, 1848, 2740, 2738, 2786, 2784, 591, 588, 576, 569, 566, 2296, 1590, 537, 534, 526, 2276, 522, 2274, 545, 542, 539, 548, 1572, 1570, 481, 2245, 466, 2242, 462, 2239, 492, 485, 482, 2249, 496, 494, 1534, 1531, 1528, 1538, 413, 2196, 406, 2191, 2188, 425, 419, 2202, 415, 2199, 432, 430, 427, 1472, 1467, 1464, 433, 1476, 1474, 368, 367, 2160, 365, 2159, 362, 2157, 2155, 2152, 378, 377, 375, 2166, 372, 2165, 369, 2162, 383, 381, 379, 2168, 1419, 1418, 1416, 1414, 385, 1411, 384, 1423, 1422, 1420, 1424, 2461, 802, 2441, 2439, 790, 786, 783, 794, 2409, 2406, 2403, 750, 742, 738, 2414, 756, 753, 1720, 2367, 2365, 2362, 2359, 1663, 693, 691, 684, 2373, 680, 2370, 702, 699, 696, 704, 1690, 1687, 2337, 2336, 2334, 2332, 1624, 2329, 1622, 640, 637, 2344, 634, 2342, 630, 2340, 650, 648, 645, 2346, 655, 653, 1653, 1651, 1649, 1655, 2612, 2597, 2595, 2571, 2568, 2565, 2576, 2534, 2529, 2526, 1787, - 2540, 2537, 907, 904, 900, 910, 2503, 2502, 2500, 2498, 1768, 2495, 1767, 2510, 2508, 2506, 869, 866, 863, 2513, 876, 874, 1782, 2720, 2713, 2711, 2697, 2694, 2691, 2702, 2672, 2670, 2664, 1828, 2678, 2675, 2647, 2646, 2644, 2642, 1823, 2639, 1822, 2654, 2652, 2650, 2657, 2771, 1855, 2765, 2762, 1850, 1849, 2751, 2749, 2747, 2754, 353, 2148, 344, 342, 336, 2142, 332, 2140, 345, 1375, 1373, 306, 2130, 299, 2128, 295, 2125, 319, 314, 311, 2132, 1354, 1352, 1349, 1356, 262, 257, 2101, 253, 2096, 2093, 274, 273, 267, 2107, 263, 2104, 280, 278, 275, 1316, 1311, 1308, 1320, 1318, 2052, 202, 2050, 2044, 2040, 219, 2063, 212, 2060, 208, 2055, 224, 221, 2066, 1260, 1258, 1252, 231, 1248, 229, 1266, 1264, 1261, 1268, 155, 1998, 153, 1996, 1994, 1991, 1988, 165, 164, 2007, 162, 2006, 159, 2003, 2000, 172, 171, 169, 2012, 166, 2010, 1186, 1184, 1182, 1179, 175, 1176, 173, 1192, 1191, 1189, 1187, 176, 1194, 1193, 2313, 2307, 2305, 592, 589, 2294, 2292, 2289, 578, 572, 568, 2297, 580, 1591, 2272, 2267, 2264, 1547, 538, 536, 529, 2278, 525, 2275, 547, 544, 541, 1574, 1571, 2237, 2235, 2229, 1493, 2225, 1489, 478, 2247, 470, 2244, 465, 2241, 493, 488, 484, 2250, 498, 495, 1536, 1533, 1530, 1539, 2187, 2186, 2184, 2182, 1432, 2179, 1430, 2176, 1427, 414, 412, 2197, 409, 2195, 405, 2193, 2190, 426, 424, 421, 2203, 418, 2201, 431, 429, 1473, 1471, 1469, 1466, 434, 1477, 1475, 2478, 2472, 2470, 2459, 2457, 2454, 2462, 803, 2437, 2432, 2429, 1726, 2443, 2440, 792, 789, 785, 2401, 2399, 2393, 1702, 2389, 1699, 2411, 2408, 2405, 745, 741, 2415, 758, 755, 1721, 2358, 2357, 2355, 2353, 1661, 2350, 1660, 2347, 1657, 2368, 2366, 2364, 2361, 1666, 690, 687, 2374, 683, 2372, 701, 698, 705, 1691, 1689, 2619, 2617, 2610, 2608, 2605, 2613, 2593, 2588, 2585, 1803, 2599, 2596, 2563, 2561, 2555, 1797, 2551, 1795, 2573, 2570, 2567, 2577, 2525, 2524, 2522, 2520, 1786, 2517, 1785, 2514, 1783, 2535, 2533, 2531, 2528, 1788, 2541, 2539, 906, 903, 911, 2721, 1844, 2715, 2712, 1838, 1836, 2699, 2696, 2693, 2703, 1827, 1826, 1824, 2673, - 2671, 2669, 2666, 1829, 2679, 2677, 1858, 1857, 2772, 1854, 1853, 1851, 1856, 2766, 2764, 143, 1987, 139, 1986, 135, 133, 131, 1984, 128, 1983, 125, 1981, 138, 137, 136, 1985, 1133, 1132, 1130, 112, 110, 1974, 107, 1973, 104, 1971, 1969, 122, 121, 119, 117, 1977, 114, 1976, 124, 1115, 1114, 1112, 1110, 1117, 1116, 84, 83, 1953, 81, 1952, 78, 1950, 1948, 1945, 94, 93, 91, 1959, 88, 1958, 85, 1955, 99, 97, 95, 1961, 1086, 1085, 1083, 1081, 1078, 100, 1090, 1089, 1087, 1091, 49, 47, 1917, 44, 1915, 1913, 1910, 1907, 59, 1926, 56, 1925, 53, 1922, 1919, 66, 64, 1931, 61, 1929, 1042, 1040, 1038, 71, 1035, 70, 1032, 68, 1048, 1047, 1045, 1043, 1050, 1049, 12, 10, 1869, 1867, 1864, 1861, 21, 1880, 19, 1877, 1874, 1871, 28, 1888, 25, 1886, 22, 1883, 982, 980, 977, 974, 32, 30, 991, 989, 987, 984, 34, 995, 994, 992, 2151, 2150, 2147, 2146, 2144, 356, 355, 354, 2149, 2139, 2138, 2136, 2134, 1359, 343, 341, 338, 2143, 335, 2141, 348, 347, 346, 1376, 1374, 2124, 2123, 2121, 2119, 1326, 2116, 1324, 310, 308, 305, 2131, 302, 2129, 298, 2127, 320, 318, 316, 313, 2133, 322, 321, 1355, 1353, 1351, 1357, 2092, 2091, 2089, 2087, 1276, 2084, 1274, 2081, 1271, 259, 2102, 256, 2100, 252, 2098, 2095, 272, 269, 2108, 266, 2106, 281, 279, 277, 1317, 1315, 1313, 1310, 282, 1321, 1319, 2039, 2037, 2035, 2032, 1203, 2029, 1200, 1197, 207, 2053, 205, 2051, 201, 2049, 2046, 2043, 220, 218, 2064, 215, 2062, 211, 2059, 228, 226, 223, 2069, 1259, 1257, 1254, 232, 1251, 230, 1267, 1265, 1263, 2316, 2315, 2312, 2311, 2309, 2314, 2304, 2303, 2301, 2299, 1593, 2308, 2306, 590, 2288, 2287, 2285, 2283, 1578, 2280, 1577, 2295, 2293, 2291, 579, 577, 574, 571, 2298, 582, 581, 1592, 2263, 2262, 2260, 2258, 1545, 2255, 1544, 2252, 1541, 2273, 2271, 2269, 2266, 1550, 535, 532, 2279, 528, 2277, 546, 543, 549, 1575, 1573, 2224, 2222, 2220, 1486, 2217, 1485, 2214, 1482, 1479, 2238, 2236, 2234, 2231, 1496, 2228, 1492, 480, 477, 2248, 473, 2246, 469, 2243, 490, 487, 2251, 497, 1537, 1535, 1532, 2477, 2476, 2474, 2479, 2469, 2468, 2466, 2464, 1730 - , 2473, 2471, 2453, 2452, 2450, 2448, 1729, 2445, 1728, 2460, 2458, 2456, 2463, 805, 804, 2428, 2427, 2425, 2423, 1725, 2420, 1724, 2417, 1722, 2438, 2436, 2434, 2431, 1727, 2444, 2442, 793, 791, 788, 795, 2388, 2386, 2384, 1697, 2381, 1696, 2378, 1694, 1692, 2402, 2400, 2398, 2395, 1703, 2392, 1701, 2412, 2410, 2407, 751, 748, 744, 2416, 759, 757, 1807, 2620, 2618, 1806, 1805, 2611, 2609, 2607, 2614, 1802, 1801, 1799, 2594, 2592, 2590, 2587, 1804, 2600, 2598, 1794, 1793, 1791, 1789, 2564, 2562, 2560, 2557, 1798, 2554, 1796, 2574, 2572, 2569, 2578, 1847, 1846, 2722, 1843, 1842, 1840, 1845, 2716, 2714, 1835, 1834, 1832, 1830, 1839, 1837, 2700, 2698, 2695, 2704, 1817, 1811, 1810, 897, 862, 1777, 829, 826, 838, 1760, 1758, 808, 2481, 1741, 1740, 1738, 1743, 2624, 1818, 2726, 2776, 782, 740, 737, 1715, 686, 679, 695, 1682, 1680, 639, 628, 2339, 647, 644, 1645, 1643, 1640, 1648, 602, 600, 597, 595, 2320, 593, 2318, 609, 607, 604, 1611, 1610, 1608, 1606, 613, 1615, 1613, 2328, 926, 924, 892, 886, 899, 857, 850, 2505, 1778, 824, 823, 821, 819, 2488, 818, 2486, 833, 831, 828, 840, 1761, 1759, 2649, 2632, 2630, 2746, 2734, 2732, 2782, 2781, 570, 567, 1587, 531, 527, 523, 540, 1566, 1564, 476, 467, 463, 2240, 486, 483, 1524, 1521, 1518, 1529, 411, 403, 2192, 399, 2189, 423, 416, 1462, 1457, 1454, 428, 1468, 1465, 2210, 366, 363, 2158, 360, 2156, 357, 2153, 376, 373, 370, 2163, 1410, 1409, 1407, 1405, 382, 1402, 380, 1417, 1415, 1412, 1421, 2175, 2174, 777, 774, 771, 784, 732, 725, 722, 2404, 743, 1716, 676, 674, 668, 2363, 665, 2360, 685, 1684, 1681, 626, 624, 622, 2335, 620, 2333, 617, 2330, 641, 635, 649, 1646, 1644, 1642, 2566, 928, 925, 2530, 2527, 894, 891, 888, 2501, 2499, 2496, 858, 856, 854, 851, 1779, 2692, 2668, 2665, 2645, 2643, 2640, 2651, 2768, 2759, 2757, 2744, 2743, 2741, 2748, 352, 1382, 340, 337, 333, 1371, 1369, 307, 300, 296, 2126, 315, 312, 1347, 1342, 1350, 261, 258, 250, 2097, 246, 2094, 271, 268, 264, 1306, 1301, 1298, 276, 1312, 1309, 2115, 203, 2048, 195, 2045, 191, 2041, 213, 209 - , 2056, 1246, 1244, 1238, 225, 1234, 222, 1256, 1253, 1249, 1262, 2080, 2079, 154, 1997, 150, 1995, 147, 1992, 1989, 163, 160, 2004, 156, 2001, 1175, 1174, 1172, 1170, 1167, 170, 1164, 167, 1185, 1183, 1180, 1177, 174, 1190, 1188, 2025, 2024, 2022, 587, 586, 564, 559, 556, 2290, 573, 1588, 520, 518, 512, 2268, 508, 2265, 530, 1568, 1565, 461, 457, 2233, 450, 2230, 446, 2226, 479, 471, 489, 1526, 1523, 1520, 397, 395, 2185, 392, 2183, 389, 2180, 2177, 410, 2194, 402, 422, 1463, 1461, 1459, 1456, 1470, 2455, 799, 2433, 2430, 779, 776, 773, 2397, 2394, 2390, 734, 728, 724, 746, 1717, 2356, 2354, 2351, 2348, 1658, 677, 675, 673, 670, 667, 688, 1685, 1683, 2606, 2589, 2586, 2559, 2556, 2552, 927, 2523, 2521, 2518, 2515, 1784, 2532, 895, 893, 890, 2718, 2709, 2707, 2689, 2687, 2684, 2663, 2662, 2660, 2658, 1825, 2667, 2769, 1852, 2760, 2758, 142, 141, 1139, 1138, 134, 132, 129, 126, 1982, 1129, 1128, 1126, 1131, 113, 111, 108, 105, 1972, 101, 1970, 120, 118, 115, 1109, 1108, 1106, 1104, 123, 1113, 1111, 82, 79, 1951, 75, 1949, 72, 1946, 92, 89, 86, 1956, 1077, 1076, 1074, 1072, 98, 1069, 96, 1084, 1082, 1079, 1088, 1968, 1967, 48, 45, 1916, 42, 1914, 39, 1911, 1908, 60, 57, 54, 1923, 50, 1920, 1031, 1030, 1028, 1026, 67, 1023, 65, 1020, 62, 1041, 1039, 1036, 1033, 69, 1046, 1044, 1944, 1943, 1941, 11, 9, 1868, 7, 1865, 1862, 1859, 20, 1878, 16, 1875, 13, 1872, 970, 968, 966, 963, 29, 960, 26, 23, 983, 981, 978, 975, 33, 971, 31, 990, 988, 985, 1906, 1904, 1902, 993, 351, 2145, 1383, 331, 330, 328, 326, 2137, 323, 2135, 339, 1372, 1370, 294, 293, 291, 289, 2122, 286, 2120, 283, 2117, 309, 303, 317, 1348, 1346, 1344, 245, 244, 242, 2090, 239, 2088, 236, 2085, 2082, 260, 2099, 249, 270, 1307, 1305, 1303, 1300, 1314, 189, 2038, 186, 2036, 183, 2033, 2030, 2026, 206, 198, 2047, 194, 216, 1247, 1245, 1243, 1240, 227, 1237, 1255, 2310, 2302, 2300, 2286, 2284, 2281, 565, 563, 561, 558, 575, 1589, 2261, 2259, 2256, 2253, 1542, 521, 519, 517, 514, 2270, 511, 533, 1569, 1567, 2223, 2221, 2218, 2215, 1483, 2211, - 1480, 459, 456, 453, 2232, 449, 474, 491, 1527, 1525, 1522, 2475, 2467, 2465, 2451, 2449, 2446, 801, 800, 2426, 2424, 2421, 2418, 1723, 2435, 780, 778, 775, 2387, 2385, 2382, 2379, 1695, 2375, 1693, 2396, 735, 733, 730, 727, 749, 1718, 2616, 2615, 2604, 2603, 2601, 2584, 2583, 2581, 2579, 1800, 2591, 2550, 2549, 2547, 2545, 1792, 2542, 1790, 2558, 929, 2719, 1841, 2710, 2708, 1833, 1831, 2690, 2688, 2686, 1815, 1809, 1808, 1774, 1756, 1754, 1737, 1736, 1734, 1739, 1816, 1711, 1676, 1674, 633, 629, 1638, 1636, 1633, 1641, 598, 1605, 1604, 1602, 1600, 605, 1609, 1607, 2327, 887, 853, 1775, 822, 820, 1757, 1755, 1584, 524, 1560, 1558, 468, 464, 1514, 1511, 1508, 1519, 408, 404, 400, 1452, 1447, 1444, 417, 1458, 1455, 2208, 364, 361, 358, 2154, 1401, 1400, 1398, 1396, 374, 1393, 371, 1408, 1406, 1403, 1413, 2173, 2172, 772, 726, 723, 1712, 672, 669, 666, 682, 1678, 1675, 625, 623, 621, 618, 2331, 636, 632, 1639, 1637, 1635, 920, 918, 884, 880, 889, 849, 848, 847, 846, 2497, 855, 852, 1776, 2641, 2742, 2787, 1380, 334, 1367, 1365, 301, 297, 1340, 1338, 1335, 1343, 255, 251, 247, 1296, 1291, 1288, 265, 1302, 1299, 2113, 204, 196, 192, 2042, 1232, 1230, 1224, 214, 1220, 210, 1242, 1239, 1235, 1250, 2077, 2075, 151, 148, 1993, 144, 1990, 1163, 1162, 1160, 1158, 1155, 161, 1152, 157, 1173, 1171, 1168, 1165, 168, 1181, 1178, 2021, 2020, 2018, 2023, 585, 560, 557, 1585, 516, 509, 1562, 1559, 458, 447, 2227, 472, 1516, 1513, 1510, 398, 396, 393, 390, 2181, 386, 2178, 407, 1453, 1451, 1449, 1446, 420, 1460, 2209, 769, 764, 720, 712, 2391, 729, 1713, 664, 663, 661, 659, 2352, 656, 2349, 671, 1679, 1677, 2553, 922, 919, 2519, 2516, 885, 883, 881, 2685, 2661, 2659, 2767, 2756, 2755, 140, 1137, 1136, 130, 127, 1125, 1124, 1122, 1127, 109, 106, 102, 1103, 1102, 1100, 1098, 116, 1107, 1105, 1980, 80, 76, 73, 1947, 1068, 1067, 1065, 1063, 90, 1060, 87, 1075, 1073, 1070, 1080, 1966, 1965, 46, 43, 40, 1912, 36, 1909, 1019, 1018, 1016, 1014, 58, 1011, 55, 1008, 51, 1029, 1027, 1024, 1021, 63, 1037, 1034, 1940, 1939, - 1937, 1942, 8, 1866, 4, 1863, 1, 1860, 956, 954, 952, 949, 946, 17, 14, 969, 967, 964, 961, 27, 957, 24, 979, 976, 972, 1901, 1900, 1898, 1896, 986, 1905, 1903, 350, 349, 1381, 329, 327, 324, 1368, 1366, 292, 290, 287, 284, 2118, 304, 1341, 1339, 1337, 1345, 243, 240, 237, 2086, 233, 2083, 254, 1297, 1295, 1293, 1290, 1304, 2114, 190, 187, 184, 2034, 180, 2031, 177, 2027, 199, 1233, 1231, 1229, 1226, 217, 1223, 1241, 2078, 2076, 584, 555, 554, 552, 550, 2282, 562, 1586, 507, 506, 504, 502, 2257, 499, 2254, 515, 1563, 1561, 445, 443, 441, 2219, 438, 2216, 435, 2212, 460, 454, 475, 1517, 1515, 1512, 2447, 798, 797, 2422, 2419, 770, 768, 766, 2383, 2380, 2376, 721, 719, 717, 714, 731, 1714, 2602, 2582, 2580, 2548, 2546, 2543, 923, 921, 2717, 2706, 2705, 2683, 2682, 2680, 1771, 1752, 1750, 1733, 1732, 1731, 1735, 1814, 1707, 1670, 1668, 1631, 1629, 1626, 1634, 1599, 1598, 1596, 1594, 1603, 1601, 2326, 1772, 1753, 1751, 1581, 1554, 1552, 1504, 1501, 1498, 1509, 1442, 1437, 1434, 401, 1448, 1445, 2206, 1392, 1391, 1389, 1387, 1384, 359, 1399, 1397, 1394, 1404, 2171, 2170, 1708, 1672, 1669, 619, 1632, 1630, 1628, 1773, 1378, 1363, 1361, 1333, 1328, 1336, 1286, 1281, 1278, 248, 1292, 1289, 2111, 1218, 1216, 1210, 197, 1206, 193, 1228, 1225, 1221, 1236, 2073, 2071, 1151, 1150, 1148, 1146, 152, 1143, 149, 1140, 145, 1161, 1159, 1156, 1153, 158, 1169, 1166, 2017, 2016, 2014, 2019, 1582, 510, 1556, 1553, 452, 448, 1506, 1500, 394, 391, 387, 1443, 1441, 1439, 1436, 1450, 2207, 765, 716, 713, 1709, 662, 660, 657, 1673, 1671, 916, 914, 879, 878, 877, 882, 1135, 1134, 1121, 1120, 1118, 1123, 1097, 1096, 1094, 1092, 103, 1101, 1099, 1979, 1059, 1058, 1056, 1054, 77, 1051, 74, 1066, 1064, 1061, 1071, 1964, 1963, 1007, 1006, 1004, 1002, 999, 41, 996, 37, 1017, 1015, 1012, 1009, 52, 1025, 1022, 1936, 1935, 1933, 1938, 942, 940, 938, 935, 932, 5, 2, 955, 953, 950, 947, 18, 943, 15, 965, 962, 958, 1895, 1894, 1892, 1890, 973, 1899, 1897, 1379, 325, 1364, 1362, 288, 285, 1334, 1332, 1330, 241, 238, 234, 1287, 1285, - 1283, 1280, 1294, 2112, 188, 185, 181, 178, 2028, 1219, 1217, 1215, 1212, 200, 1209, 1227, 2074, 2072, 583, 553, 551, 1583, 505, 503, 500, 513, 1557, 1555, 444, 442, 439, 436, 2213, 455, 451, 1507, 1505, 1502, 796, 763, 762, 760, 767, 711, 710, 708, 706, 2377, 718, 715, 1710, 2544, 917, 915, 2681, 1627, 1597, 1595, 2325, 1769, 1749, 1747, 1499, 1438, 1435, 2204, 1390, 1388, 1385, 1395, 2169, 2167, 1704, 1665, 1662, 1625, 1623, 1620, 1770, 1329, 1282, 1279, 2109, 1214, 1207, 1222, 2068, 2065, 1149, 1147, 1144, 1141, 146, 1157, 1154, 2013, 2011, 2008, 2015, 1579, 1549, 1546, 1495, 1487, 1433, 1431, 1428, 1425, 388, 1440, 2205, 1705, 658, 1667, 1664, 1119, 1095, 1093, 1978, 1057, 1055, 1052, 1062, 1962, 1960, 1005, 1003, 1000, 997, 38, 1013, 1010, 1932, 1930, 1927, 1934, 941, 939, 936, 933, 6, 930, 3, 951, 948, 944, 1889, 1887, 1884, 1881, 959, 1893, 1891, 35, 1377, 1360, 1358, 1327, 1325, 1322, 1331, 1277, 1275, 1272, 1269, 235, 1284, 2110, 1205, 1204, 1201, 1198, 182, 1195, 179, 1213, 2070, 2067, 1580, 501, 1551, 1548, 440, 437, 1497, 1494, 1490, 1503, 761, 709, 707, 1706, 913, 912, 2198, 1386, 2164, 2161, 1621, 1766, 2103, 1208, 2058, 2054, 1145, 1142, 2005, 2002, 1999, 2009, 1488, 1429, 1426, 2200, 1698, 1659, 1656, 1975, 1053, 1957, 1954, 1001, 998, 1924, 1921, 1918, 1928, 937, 934, 931, 1879, 1876, 1873, 1870, 945, 1885, 1882, 1323, 1273, 1270, 2105, 1202, 1199, 1196, 1211, 2061, 2057, 1576, 1543, 1540, 1484, 1481, 1478, 1491, 1700}; - } -} \ No newline at end of file diff --git a/zxing-csharp/pdf417/decoder/DecodedBitStreamParser.cs b/zxing-csharp/pdf417/decoder/DecodedBitStreamParser.cs deleted file mode 100644 index f3bbaf6..0000000 --- a/zxing-csharp/pdf417/decoder/DecodedBitStreamParser.cs +++ /dev/null @@ -1,735 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using DecoderResult = com.google.zxing.common.DecoderResult; -namespace com.google.zxing.pdf417.decoder -{ - - ///

This class contains the methods for decoding the PDF417 codewords.

- /// - ///
- /// SITA Lab (kevin.osullivan@sita.aero) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class DecodedBitStreamParser - { - - private const int TEXT_COMPACTION_MODE_LATCH = 900; - private const int BYTE_COMPACTION_MODE_LATCH = 901; - private const int NUMERIC_COMPACTION_MODE_LATCH = 902; - private const int BYTE_COMPACTION_MODE_LATCH_6 = 924; - private const int BEGIN_MACRO_PDF417_CONTROL_BLOCK = 928; - private const int BEGIN_MACRO_PDF417_OPTIONAL_FIELD = 923; - private const int MACRO_PDF417_TERMINATOR = 922; - private const int MODE_SHIFT_TO_BYTE_COMPACTION_MODE = 913; - private const int MAX_NUMERIC_CODEWORDS = 15; - - private const int ALPHA = 0; - private const int LOWER = 1; - private const int MIXED = 2; - private const int PUNCT = 3; - private const int PUNCT_SHIFT = 4; - - private const int PL = 25; - private const int LL = 27; - private const int AS = 27; - private const int ML = 28; - private const int AL = 28; - private const int PS = 29; - private const int PAL = 29; - - //UPGRADE_NOTE: Final was removed from the declaration of 'PUNCT_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] PUNCT_CHARS = new char[]{';', '<', '>', '@', '[', (char) (92), '}', '_', (char) (96), '~', '!', (char) (13), (char) (9), ',', ':', (char) (10), '-', '.', '$', '/', (char) (34), '|', '*', '(', ')', '?', '{', '}', (char) (39)}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'MIXED_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] MIXED_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '&', (char) (13), (char) (9), ',', ':', '#', '-', '.', '$', '/', '+', '%', '*', '=', '^'}; - - // Table containing values for the exponent of 900. - // This is used in the numeric compaction decode algorithm. - //UPGRADE_NOTE: Final was removed from the declaration of 'EXP900'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly System.String[] EXP900 = new System.String[]{"000000000000000000000000000000000000000000001", "000000000000000000000000000000000000000000900", "000000000000000000000000000000000000000810000", "000000000000000000000000000000000000729000000", "000000000000000000000000000000000656100000000", "000000000000000000000000000000590490000000000", "000000000000000000000000000531441000000000000", "000000000000000000000000478296900000000000000", "000000000000000000000430467210000000000000000", "000000000000000000387420489000000000000000000", "000000000000000348678440100000000000000000000", "000000000000313810596090000000000000000000000", "000000000282429536481000000000000000000000000", "000000254186582832900000000000000000000000000", "000228767924549610000000000000000000000000000", "205891132094649000000000000000000000000000000"}; - - private DecodedBitStreamParser() - { - } - - internal static DecoderResult decode(int[] codewords) - { - System.Text.StringBuilder result = new System.Text.StringBuilder(100); - // Get compaction mode - int codeIndex = 1; - int code = codewords[codeIndex++]; - while (codeIndex < codewords[0]) - { - switch (code) - { - - case TEXT_COMPACTION_MODE_LATCH: { - codeIndex = textCompaction(codewords, codeIndex, result); - break; - } - - case BYTE_COMPACTION_MODE_LATCH: { - codeIndex = byteCompaction(code, codewords, codeIndex, result); - break; - } - - case NUMERIC_COMPACTION_MODE_LATCH: { - codeIndex = numericCompaction(codewords, codeIndex, result); - break; - } - - case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: { - codeIndex = byteCompaction(code, codewords, codeIndex, result); - break; - } - - case BYTE_COMPACTION_MODE_LATCH_6: { - codeIndex = byteCompaction(code, codewords, codeIndex, result); - break; - } - - default: { - // Default to text compaction. During testing numerous barcodes - // appeared to be missing the starting mode. In these cases defaulting - // to text compaction seems to work. - codeIndex--; - codeIndex = textCompaction(codewords, codeIndex, result); - break; - } - - } - if (codeIndex < codewords.Length) - { - code = codewords[codeIndex++]; - } - else - { - throw ReaderException.Instance; - } - } - return new DecoderResult(null, result.ToString(), null, null); - } - - /// Text Compaction mode (see 5.4.1.5) permits all printable ASCII characters to be - /// encoded, i.e. values 32 - 126 inclusive in accordance with ISO/IEC 646 (IRV), as - /// well as selected control characters. - /// - /// - /// The array of codewords (data + error) - /// - /// The current index into the codeword array. - /// - /// The decoded data is appended to the result. - /// - /// The next index into the codeword array. - /// - private static int textCompaction(int[] codewords, int codeIndex, System.Text.StringBuilder result) - { - // 2 character per codeword - int[] textCompactionData = new int[codewords[0] << 1]; - // Used to hold the byte compaction value if there is a mode shift - int[] byteCompactionData = new int[codewords[0] << 1]; - - int index = 0; - bool end = false; - while ((codeIndex < codewords[0]) && !end) - { - int code = codewords[codeIndex++]; - if (code < TEXT_COMPACTION_MODE_LATCH) - { - textCompactionData[index] = code / 30; - textCompactionData[index + 1] = code % 30; - index += 2; - } - else - { - switch (code) - { - - case TEXT_COMPACTION_MODE_LATCH: { - codeIndex--; - end = true; - break; - } - - case BYTE_COMPACTION_MODE_LATCH: { - codeIndex--; - end = true; - break; - } - - case NUMERIC_COMPACTION_MODE_LATCH: { - codeIndex--; - end = true; - break; - } - - case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: { - // The Mode Shift codeword 913 shall cause a temporary - // switch from Text Compaction mode to Byte Compaction mode. - // This switch shall be in effect for only the next codeword, - // after which the mode shall revert to the prevailing sub-mode - // of the Text Compaction mode. Codeword 913 is only available - // in Text Compaction mode; its use is described in 5.4.2.4. - textCompactionData[index] = MODE_SHIFT_TO_BYTE_COMPACTION_MODE; - byteCompactionData[index] = code; //Integer.toHexString(code); - index++; - break; - } - - case BYTE_COMPACTION_MODE_LATCH_6: { - codeIndex--; - end = true; - break; - } - } - } - } - decodeTextCompaction(textCompactionData, byteCompactionData, index, result); - return codeIndex; - } - - /// The Text Compaction mode includes all the printable ASCII characters - /// (i.e. values from 32 to 126) and three ASCII control characters: HT or tab - /// (ASCII value 9), LF or line feed (ASCII value 10), and CR or carriage - /// return (ASCII value 13). The Text Compaction mode also includes various latch - /// and shift characters which are used exclusively within the mode. The Text - /// Compaction mode encodes up to 2 characters per codeword. The compaction rules - /// for converting data into PDF417 codewords are defined in 5.4.2.2. The sub-mode - /// switches are defined in 5.4.2.3. - /// - /// - /// The text compaction data. - /// - /// The byte compaction data if there - /// was a mode shift. - /// - /// The size of the text compaction and byte compaction data. - /// - /// The decoded data is appended to the result. - /// - private static void decodeTextCompaction(int[] textCompactionData, int[] byteCompactionData, int length, System.Text.StringBuilder result) - { - // Beginning from an initial state of the Alpha sub-mode - // The default compaction mode for PDF417 in effect at the start of each symbol shall always be Text - // Compaction mode Alpha sub-mode (uppercase alphabetic). A latch codeword from another mode to the Text - // Compaction mode shall always switch to the Text Compaction Alpha sub-mode. - int subMode = ALPHA; - int priorToShiftMode = ALPHA; - int i = 0; - while (i < length) - { - int subModeCh = textCompactionData[i]; - char ch = (char) (0); - switch (subMode) - { - - case ALPHA: - // Alpha (uppercase alphabetic) - if (subModeCh < 26) - { - // Upper case Alpha Character - ch = (char) ('A' + subModeCh); - } - else - { - if (subModeCh == 26) - { - ch = ' '; - } - else if (subModeCh == LL) - { - subMode = LOWER; - } - else if (subModeCh == ML) - { - subMode = MIXED; - } - else if (subModeCh == PS) - { - // Shift to punctuation - priorToShiftMode = subMode; - subMode = PUNCT_SHIFT; - } - else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) - { - result.Append((char) byteCompactionData[i]); - } - } - break; - - - case LOWER: - // Lower (lowercase alphabetic) - if (subModeCh < 26) - { - ch = (char) ('a' + subModeCh); - } - else - { - if (subModeCh == 26) - { - ch = ' '; - } - else if (subModeCh == AL) - { - subMode = ALPHA; - } - else if (subModeCh == ML) - { - subMode = MIXED; - } - else if (subModeCh == PS) - { - // Shift to punctuation - priorToShiftMode = subMode; - subMode = PUNCT_SHIFT; - } - else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) - { - result.Append((char) byteCompactionData[i]); - } - } - break; - - - case MIXED: - // Mixed (numeric and some punctuation) - if (subModeCh < PL) - { - ch = MIXED_CHARS[subModeCh]; - } - else - { - if (subModeCh == PL) - { - subMode = PUNCT; - } - else if (subModeCh == 26) - { - ch = ' '; - } - else if (subModeCh == AS) - { - //mode_change = true; - } - else if (subModeCh == AL) - { - subMode = ALPHA; - } - else if (subModeCh == PS) - { - // Shift to punctuation - priorToShiftMode = subMode; - subMode = PUNCT_SHIFT; - } - else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) - { - result.Append((char) byteCompactionData[i]); - } - } - break; - - - case PUNCT: - // Punctuation - if (subModeCh < PS) - { - ch = PUNCT_CHARS[subModeCh]; - } - else - { - if (subModeCh == PAL) - { - subMode = ALPHA; - } - else if (subModeCh == MODE_SHIFT_TO_BYTE_COMPACTION_MODE) - { - result.Append((char) byteCompactionData[i]); - } - } - break; - - - case PUNCT_SHIFT: - // Restore sub-mode - subMode = priorToShiftMode; - if (subModeCh < PS) - { - ch = PUNCT_CHARS[subModeCh]; - } - else - { - if (subModeCh == PAL) - { - subMode = ALPHA; - } - } - break; - } - if (ch != 0) - { - // Append decoded character to result - result.Append(ch); - } - i++; - } - } - - /// Byte Compaction mode (see 5.4.3) permits all 256 possible 8-bit byte values to be encoded. - /// This includes all ASCII characters value 0 to 127 inclusive and provides for international - /// character set support. - /// - /// - /// The byte compaction mode i.e. 901 or 924 - /// - /// The array of codewords (data + error) - /// - /// The current index into the codeword array. - /// - /// The decoded data is appended to the result. - /// - /// The next index into the codeword array. - /// - private static int byteCompaction(int mode, int[] codewords, int codeIndex, System.Text.StringBuilder result) - { - if (mode == BYTE_COMPACTION_MODE_LATCH) - { - // Total number of Byte Compaction characters to be encoded - // is not a multiple of 6 - int count = 0; - long value_Renamed = 0; - char[] decodedData = new char[6]; - int[] byteCompactedCodewords = new int[6]; - bool end = false; - while ((codeIndex < codewords[0]) && !end) - { - int code = codewords[codeIndex++]; - if (code < TEXT_COMPACTION_MODE_LATCH) - { - byteCompactedCodewords[count] = code; - count++; - // Base 900 - value_Renamed *= 900; - value_Renamed += code; - } - else - { - if ((code == TEXT_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH) || (code == NUMERIC_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH_6) || (code == BEGIN_MACRO_PDF417_CONTROL_BLOCK) || (code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD) || (code == MACRO_PDF417_TERMINATOR)) - { - } - codeIndex--; - end = true; - } - if ((count % 5 == 0) && (count > 0)) - { - // Decode every 5 codewords - // Convert to Base 256 - for (int j = 0; j < 6; ++j) - { - decodedData[5 - j] = (char) (value_Renamed % 256); - value_Renamed >>= 8; - } - result.Append(decodedData); - count = 0; - } - } - // If Byte Compaction mode is invoked with codeword 901, - // the final group of codewords is interpreted directly - // as one byte per codeword, without compaction. - for (int i = ((count / 5) * 5); i < count; i++) - { - result.Append((char) byteCompactedCodewords[i]); - } - } - else if (mode == BYTE_COMPACTION_MODE_LATCH_6) - { - // Total number of Byte Compaction characters to be encoded - // is an integer multiple of 6 - int count = 0; - long value_Renamed = 0; - bool end = false; - while ((codeIndex < codewords[0]) && !end) - { - int code = codewords[codeIndex++]; - if (code < TEXT_COMPACTION_MODE_LATCH) - { - count += 1; - // Base 900 - value_Renamed *= 900; - value_Renamed += code; - } - else - { - if ((code == TEXT_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH) || (code == NUMERIC_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH_6) || (code == BEGIN_MACRO_PDF417_CONTROL_BLOCK) || (code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD) || (code == MACRO_PDF417_TERMINATOR)) - { - } - codeIndex--; - end = true; - } - if ((count % 5 == 0) && (count > 0)) - { - // Decode every 5 codewords - // Convert to Base 256 - char[] decodedData = new char[6]; - for (int j = 0; j < 6; ++j) - { - decodedData[5 - j] = (char) (value_Renamed % 256); - value_Renamed >>= 8; - } - result.Append(decodedData); - } - } - } - return codeIndex; - } - - /// Numeric Compaction mode (see 5.4.4) permits efficient encoding of numeric data strings. - /// - /// - /// The array of codewords (data + error) - /// - /// The current index into the codeword array. - /// - /// The decoded data is appended to the result. - /// - /// The next index into the codeword array. - /// - private static int numericCompaction(int[] codewords, int codeIndex, System.Text.StringBuilder result) - { - int count = 0; - bool end = false; - - int[] numericCodewords = new int[MAX_NUMERIC_CODEWORDS]; - - while ((codeIndex < codewords.Length) && !end) - { - int code = codewords[codeIndex++]; - if (code < TEXT_COMPACTION_MODE_LATCH) - { - numericCodewords[count] = code; - count++; - } - else - { - if ((code == TEXT_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH) || (code == BYTE_COMPACTION_MODE_LATCH_6) || (code == BEGIN_MACRO_PDF417_CONTROL_BLOCK) || (code == BEGIN_MACRO_PDF417_OPTIONAL_FIELD) || (code == MACRO_PDF417_TERMINATOR)) - { - } - codeIndex--; - end = true; - } - if ((count % MAX_NUMERIC_CODEWORDS) == 0 || code == NUMERIC_COMPACTION_MODE_LATCH) - { - // Re-invoking Numeric Compaction mode (by using codeword 902 - // while in Numeric Compaction mode) serves to terminate the - // current Numeric Compaction mode grouping as described in 5.4.4.2, - // and then to start a new one grouping. - System.String s = decodeBase900toBase10(numericCodewords, count); - result.Append(s); - count = 0; - } - } - return codeIndex; - } - - /// Convert a list of Numeric Compacted codewords from Base 900 to Base 10. - /// - /// - /// The array of codewords - /// - /// The number of codewords - /// - /// The decoded string representing the Numeric data. - /// - /* - EXAMPLE - Encode the fifteen digit numeric string 000213298174000 - Prefix the numeric string with a 1 and set the initial value of - t = 1 000 213 298 174 000 - Calculate codeword 0 - d0 = 1 000 213 298 174 000 mod 900 = 200 - - t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082 - Calculate codeword 1 - d1 = 1 111 348 109 082 mod 900 = 282 - - t = 1 111 348 109 082 div 900 = 1 234 831 232 - Calculate codeword 2 - d2 = 1 234 831 232 mod 900 = 632 - - t = 1 234 831 232 div 900 = 1 372 034 - Calculate codeword 3 - d3 = 1 372 034 mod 900 = 434 - - t = 1 372 034 div 900 = 1 524 - Calculate codeword 4 - d4 = 1 524 mod 900 = 624 - - t = 1 524 div 900 = 1 - Calculate codeword 5 - d5 = 1 mod 900 = 1 - t = 1 div 900 = 0 - Codeword sequence is: 1, 624, 434, 632, 282, 200 - - Decode the above codewords involves - 1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 + - 632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000 - - Remove leading 1 => Result is 000213298174000 - - As there are huge numbers involved here we must use fake out the maths using string - tokens for the numbers. - BigDecimal is not supported by J2ME. - */ - private static System.String decodeBase900toBase10(int[] codewords, int count) - { - System.Text.StringBuilder accum = null; - for (int i = 0; i < count; i++) - { - System.Text.StringBuilder value_Renamed = multiply(EXP900[count - i - 1], codewords[i]); - if (accum == null) - { - // First time in accum=0 - accum = value_Renamed; - } - else - { - accum = add(accum.ToString(), value_Renamed.ToString()); - } - } - System.String result = null; - // Remove leading '1' which was inserted to preserve - // leading zeros - for (int i = 0; i < accum.Length; i++) - { - if (accum[i] == '1') - { - //result = accum.substring(i + 1); - result = accum.ToString().Substring(i + 1); - break; - } - } - if (result == null) - { - // No leading 1 => just write the converted number. - result = accum.ToString(); - } - return result; - } - - /// Multiplies two String numbers - /// - /// - /// Any number represented as a string. - /// - /// A number <= 999. - /// - /// the result of value1 * value2. - /// - private static System.Text.StringBuilder multiply(System.String value1, int value2) - { - System.Text.StringBuilder result = new System.Text.StringBuilder(value1.Length); - for (int i = 0; i < value1.Length; i++) - { - // Put zeros into the result. - result.Append('0'); - } - int hundreds = value2 / 100; - int tens = (value2 / 10) % 10; - int ones = value2 % 10; - // Multiply by ones - for (int j = 0; j < ones; j++) - { - result = add(result.ToString(), value1); - } - // Multiply by tens - for (int j = 0; j < tens; j++) - { - result = add(result.ToString(), (value1 + '0').Substring(1)); - } - // Multiply by hundreds - for (int j = 0; j < hundreds; j++) - { - result = add(result.ToString(), (value1 + "00").Substring(2)); - } - return result; - } - - /// Add two numbers which are represented as strings. - /// - /// - /// - /// - /// - /// - /// the result of value1 + value2 - /// - private static System.Text.StringBuilder add(System.String value1, System.String value2) - { - System.Text.StringBuilder temp1 = new System.Text.StringBuilder(5); - System.Text.StringBuilder temp2 = new System.Text.StringBuilder(5); - System.Text.StringBuilder result = new System.Text.StringBuilder(value1.Length); - for (int i = 0; i < value1.Length; i++) - { - // Put zeros into the result. - result.Append('0'); - } - int carry = 0; - for (int i = value1.Length - 3; i > - 1; i -= 3) - { - - temp1.Length = 0; - temp1.Append(value1[i]); - temp1.Append(value1[i + 1]); - temp1.Append(value1[i + 2]); - - temp2.Length = 0; - temp2.Append(value2[i]); - temp2.Append(value2[i + 1]); - temp2.Append(value2[i + 2]); - - int intValue1 = System.Int32.Parse(temp1.ToString()); - int intValue2 = System.Int32.Parse(temp2.ToString()); - - int sumval = (intValue1 + intValue2 + carry) % 1000; - carry = (intValue1 + intValue2 + carry) / 1000; - - result[i + 2] = (char) ((sumval % 10) + '0'); - result[i + 1] = (char) (((sumval / 10) % 10) + '0'); - result[i] = (char) ((sumval / 100) + '0'); - } - return result; - } - - /* - private static String decodeBase900toBase10(int codewords[], int count) { - BigInteger accum = BigInteger.valueOf(0); - BigInteger value = null; - for (int i = 0; i < count; i++) { - value = BigInteger.valueOf(900).pow(count - i - 1); - value = value.multiply(BigInteger.valueOf(codewords[i])); - accum = accum.add(value); - } - if (debug) System.out.println("Big Integer " + accum); - String result = accum.toString().substring(1); - return result; - } - */ - } -} \ No newline at end of file diff --git a/zxing-csharp/pdf417/decoder/Decoder.cs b/zxing-csharp/pdf417/decoder/Decoder.cs deleted file mode 100644 index d3fc47f..0000000 --- a/zxing-csharp/pdf417/decoder/Decoder.cs +++ /dev/null @@ -1,171 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using BitMatrix = com.google.zxing.common.BitMatrix; -using DecoderResult = com.google.zxing.common.DecoderResult; -namespace com.google.zxing.pdf417.decoder -{ - //import com.google.zxing.pdf417.reedsolomon.ReedSolomonDecoder; - - ///

The main class which implements PDF417 Code decoding -- as - /// opposed to locating and extracting the PDF417 Code from an image.

- /// - ///
- /// SITA Lab (kevin.osullivan@sita.aero) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Decoder - { - - private const int MAX_ERRORS = 3; - private const int MAX_EC_CODEWORDS = 512; - //private final ReedSolomonDecoder rsDecoder; - - public Decoder() - { - // TODO MGMG - //rsDecoder = new ReedSolomonDecoder(); - } - - ///

Convenience method that can decode a PDF417 Code represented as a 2D array of booleans. - /// "true" is taken to mean a black module.

- /// - ///
- /// booleans representing white/black PDF417 modules - /// - /// text and bytes encoded within the PDF417 Code - /// - /// ReaderException if the PDF417 Code cannot be decoded - public DecoderResult decode(bool[][] image) - { - int dimension = image.Length; - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) - { - for (int j = 0; j < dimension; j++) - { - if (image[j][i]) - { - bits.set_Renamed(j, i); - } - } - } - return decode(bits); - } - - ///

Decodes a PDF417 Code represented as a {@link BitMatrix}. - /// A 1 or "true" is taken to mean a black module.

- /// - ///
- /// booleans representing white/black PDF417 Code modules - /// - /// text and bytes encoded within the PDF417 Code - /// - /// ReaderException if the PDF417 Code cannot be decoded - public DecoderResult decode(BitMatrix bits) - { - // Construct a parser to read the data codewords and error-correction level - BitMatrixParser parser = new BitMatrixParser(bits); - int[] codewords = parser.readCodewords(); - if (codewords == null || codewords.Length == 0) - { - throw ReaderException.Instance; - } - - int ecLevel = parser.ECLevel; - int numECCodewords = 1 << (ecLevel + 1); - int[] erasures = parser.Erasures; - - correctErrors(codewords, erasures, numECCodewords); - verifyCodewordCount(codewords, numECCodewords); - - // Decode the codewords - return DecodedBitStreamParser.decode(codewords); - } - - /// Verify that all is OK with the codeword array. - /// - /// - /// - /// - /// an index to the first data codeword. - /// - /// ReaderException - private static void verifyCodewordCount(int[] codewords, int numECCodewords) - { - if (codewords.Length < 4) - { - // Codeword array size should be at least 4 allowing for - // Count CW, At least one Data CW, Error Correction CW, Error Correction CW - throw ReaderException.Instance; - } - // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data - // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad - // codewords, but excluding the number of error correction codewords. - int numberOfCodewords = codewords[0]; - if (numberOfCodewords > codewords.Length) - { - throw ReaderException.Instance; - } - if (numberOfCodewords == 0) - { - // Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords) - if (numECCodewords < codewords.Length) - { - codewords[0] = codewords.Length - numECCodewords; - } - else - { - throw ReaderException.Instance; - } - } - } - - ///

Given data and error-correction codewords received, possibly corrupted by errors, attempts to - /// correct the errors in-place using Reed-Solomon error correction.

- /// - ///
- /// data and error correction codewords - /// - /// ReaderException if error correction fails - private static int correctErrors(int[] codewords, int[] erasures, int numECCodewords) - { - if ((erasures != null && erasures.Length > numECCodewords / 2 + MAX_ERRORS) || (numECCodewords < 0 || numECCodewords > MAX_EC_CODEWORDS)) - { - // Too many errors or EC Codewords is corrupted - throw ReaderException.Instance; - } - // Try to correct the errors - int result = 0; // rsDecoder.correctErrors(codewords, numECCodewords); - if (erasures != null) - { - int numErasures = erasures.Length; - if (result > 0) - { - numErasures -= result; - } - if (numErasures > MAX_ERRORS) - { - // Still too many errors - throw ReaderException.Instance; - } - } - return result; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/pdf417/detector/Detector.cs b/zxing-csharp/pdf417/detector/Detector.cs deleted file mode 100644 index b7b5c70..0000000 --- a/zxing-csharp/pdf417/detector/Detector.cs +++ /dev/null @@ -1,574 +0,0 @@ -/* -* Copyright 2009 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using ReaderException = com.google.zxing.ReaderException; -using ResultPoint = com.google.zxing.ResultPoint; -using BitMatrix = com.google.zxing.common.BitMatrix; -using DetectorResult = com.google.zxing.common.DetectorResult; -using GridSampler = com.google.zxing.common.GridSampler; -namespace com.google.zxing.pdf417.detector -{ - - ///

Encapsulates logic that can detect a PDF417 Code in an image, even if the - /// PDF417 Code is rotated or skewed, or partially obscured.

- /// - ///
- /// SITA Lab (kevin.osullivan@sita.aero) - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Detector - { - - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - private static int MAX_AVG_VARIANCE = (int) SupportClass.Identity(((1 << 8) * 0.42f)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - private static int MAX_INDIVIDUAL_VARIANCE = (int) SupportClass.Identity(((1 << 8) * 0.8f)); - private const int SKEW_THRESHOLD = 2; - - // B S B S B S B S Bar/Space pattern - // 11111111 0 1 0 1 0 1 000 - //UPGRADE_NOTE: Final was removed from the declaration of 'START_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] START_PATTERN = new int[]{8, 1, 1, 1, 1, 1, 1, 3}; - - // 11111111 0 1 0 1 0 1 000 - //UPGRADE_NOTE: Final was removed from the declaration of 'START_PATTERN_REVERSE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] START_PATTERN_REVERSE = new int[]{3, 1, 1, 1, 1, 1, 1, 8}; - - // 1111111 0 1 000 1 0 1 00 1 - //UPGRADE_NOTE: Final was removed from the declaration of 'STOP_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] STOP_PATTERN = new int[]{7, 1, 1, 3, 1, 1, 1, 2, 1}; - - // B S B S B S B S B Bar/Space pattern - // 1111111 0 1 000 1 0 1 00 1 - //UPGRADE_NOTE: Final was removed from the declaration of 'STOP_PATTERN_REVERSE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] STOP_PATTERN_REVERSE = new int[]{1, 2, 1, 1, 1, 3, 1, 1, 7}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BinaryBitmap image; - - public Detector(BinaryBitmap image) - { - this.image = image; - } - - ///

Detects a PDF417 Code in an image, simply.

- /// - ///
- /// {@link DetectorResult} encapsulating results of detecting a PDF417 Code - /// - /// ReaderException if no QR Code can be found - public DetectorResult detect() - { - return detect(null); - } - - ///

Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.

- /// - ///
- /// optional hints to detector - /// - /// {@link DetectorResult} encapsulating results of detecting a PDF417 Code - /// - /// ReaderException if no PDF417 Code can be found - public DetectorResult detect(System.Collections.Hashtable hints) - { - // Fetch the 1 bit matrix once up front. - BitMatrix matrix = image.BlackMatrix; - - // Try to find the vertices assuming the image is upright. - ResultPoint[] vertices = findVertices(matrix); - if (vertices == null) - { - // Maybe the image is rotated 180 degrees? - vertices = findVertices180(matrix); - if (vertices != null) - { - correctCodeWordVertices(vertices, true); - } - } - else - { - correctCodeWordVertices(vertices, false); - } - - if (vertices != null) - { - float moduleWidth = computeModuleWidth(vertices); - if (moduleWidth < 1.0f) - { - throw ReaderException.Instance; - } - - int dimension = computeDimension(vertices[4], vertices[6], vertices[5], vertices[7], moduleWidth); - if (dimension < 1) - { - throw ReaderException.Instance; - } - - // Deskew and sample image. - BitMatrix bits = sampleGrid(matrix, vertices[4], vertices[5], vertices[6], vertices[7], dimension); - return new DetectorResult(bits, new ResultPoint[]{vertices[4], vertices[5], vertices[6], vertices[7]}); - } - else - { - throw ReaderException.Instance; - } - } - - /// Locate the vertices and the codewords area of a black blob using the Start - /// and Stop patterns as locators. Assumes that the barcode begins in the left half - /// of the image, and ends in the right half. - /// TODO: Fix this assumption, allowing the barcode to be anywhere in the image. - /// TODO: Scanning every row is very expensive. We should only do this for TRY_HARDER. - /// - /// - /// the scanned barcode image. - /// - /// an array containing the vertices: - /// vertices[0] x, y top left barcode - /// vertices[1] x, y bottom left barcode - /// vertices[2] x, y top right barcode - /// vertices[3] x, y bottom right barcode - /// vertices[4] x, y top left codeword area - /// vertices[5] x, y bottom left codeword area - /// vertices[6] x, y top right codeword area - /// vertices[7] x, y bottom right codeword area - /// - private static ResultPoint[] findVertices(BitMatrix matrix) - { - int height = matrix.Height; - int width = matrix.Width; - int halfWidth = width >> 1; - - ResultPoint[] result = new ResultPoint[8]; - bool found = false; - - // Top Left - for (int i = 0; i < height; i++) - { - int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, START_PATTERN); - if (loc != null) - { - result[0] = new ResultPoint(loc[0], i); - result[4] = new ResultPoint(loc[1], i); - found = true; - break; - } - } - // Bottom left - if (found) - { - // Found the Top Left vertex - found = false; - for (int i = height - 1; i > 0; i--) - { - int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, START_PATTERN); - if (loc != null) - { - result[1] = new ResultPoint(loc[0], i); - result[5] = new ResultPoint(loc[1], i); - found = true; - break; - } - } - } - // Top right - if (found) - { - // Found the Bottom Left vertex - found = false; - for (int i = 0; i < height; i++) - { - int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, false, STOP_PATTERN); - if (loc != null) - { - result[2] = new ResultPoint(loc[1], i); - result[6] = new ResultPoint(loc[0], i); - found = true; - break; - } - } - } - // Bottom right - if (found) - { - // Found the Top right vertex - found = false; - for (int i = height - 1; i > 0; i--) - { - int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, false, STOP_PATTERN); - if (loc != null) - { - result[3] = new ResultPoint(loc[1], i); - result[7] = new ResultPoint(loc[0], i); - found = true; - break; - } - } - } - return found?result:null; - } - - /// Locate the vertices and the codewords area of a black blob using the Start - /// and Stop patterns as locators. This assumes that the image is rotated 180 - /// degrees and if it locates the start and stop patterns at it will re-map - /// the vertices for a 0 degree rotation. - /// TODO: Change assumption about barcode location. - /// TODO: Scanning every row is very expensive. We should only do this for TRY_HARDER. - /// - /// - /// the scanned barcode image. - /// - /// an array containing the vertices: - /// vertices[0] x, y top left barcode - /// vertices[1] x, y bottom left barcode - /// vertices[2] x, y top right barcode - /// vertices[3] x, y bottom right barcode - /// vertices[4] x, y top left codeword area - /// vertices[5] x, y bottom left codeword area - /// vertices[6] x, y top right codeword area - /// vertices[7] x, y bottom right codeword area - /// - private static ResultPoint[] findVertices180(BitMatrix matrix) - { - int height = matrix.Height; - int width = matrix.Width; - int halfWidth = width >> 1; - - ResultPoint[] result = new ResultPoint[8]; - bool found = false; - - // Top Left - for (int i = height - 1; i > 0; i--) - { - int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, true, START_PATTERN_REVERSE); - if (loc != null) - { - result[0] = new ResultPoint(loc[1], i); - result[4] = new ResultPoint(loc[0], i); - found = true; - break; - } - } - // Bottom Left - if (found) - { - // Found the Top Left vertex - found = false; - for (int i = 0; i < height; i++) - { - int[] loc = findGuardPattern(matrix, halfWidth, i, halfWidth, true, START_PATTERN_REVERSE); - if (loc != null) - { - result[1] = new ResultPoint(loc[1], i); - result[5] = new ResultPoint(loc[0], i); - found = true; - break; - } - } - } - // Top Right - if (found) - { - // Found the Bottom Left vertex - found = false; - for (int i = height - 1; i > 0; i--) - { - int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, STOP_PATTERN_REVERSE); - if (loc != null) - { - result[2] = new ResultPoint(loc[0], i); - result[6] = new ResultPoint(loc[1], i); - found = true; - break; - } - } - } - // Bottom Right - if (found) - { - // Found the Top Right vertex - found = false; - for (int i = 0; i < height; i++) - { - int[] loc = findGuardPattern(matrix, 0, i, halfWidth, false, STOP_PATTERN_REVERSE); - if (loc != null) - { - result[3] = new ResultPoint(loc[0], i); - result[7] = new ResultPoint(loc[1], i); - found = true; - break; - } - } - } - return found?result:null; - } - - /// Because we scan horizontally to detect the start and stop patterns, the vertical component of - /// the codeword coordinates will be slightly wrong if there is any skew or rotation in the image. - /// This method moves those points back onto the edges of the theoretically perfect bounding - /// quadrilateral if needed. - /// - /// - /// The eight vertices located by findVertices(). - /// - private static void correctCodeWordVertices(ResultPoint[] vertices, bool upsideDown) - { - float skew = vertices[4].Y - vertices[6].Y; - if (upsideDown) - { - skew = - skew; - } - if (skew > SKEW_THRESHOLD) - { - // Fix v4 - float length = vertices[4].X - vertices[0].X; - float deltax = vertices[6].X - vertices[0].X; - float deltay = vertices[6].Y - vertices[0].Y; - float correction = length * deltay / deltax; - vertices[4] = new ResultPoint(vertices[4].X, vertices[4].Y + correction); - } - else if (- skew > SKEW_THRESHOLD) - { - // Fix v6 - float length = vertices[2].X - vertices[6].X; - float deltax = vertices[2].X - vertices[4].X; - float deltay = vertices[2].Y - vertices[4].Y; - float correction = length * deltay / deltax; - vertices[6] = new ResultPoint(vertices[6].X, vertices[6].Y - correction); - } - - skew = vertices[7].Y - vertices[5].Y; - if (upsideDown) - { - skew = - skew; - } - if (skew > SKEW_THRESHOLD) - { - // Fix v5 - float length = vertices[5].X - vertices[1].X; - float deltax = vertices[7].X - vertices[1].X; - float deltay = vertices[7].Y - vertices[1].Y; - float correction = length * deltay / deltax; - vertices[5] = new ResultPoint(vertices[5].X, vertices[5].Y + correction); - } - else if (- skew > SKEW_THRESHOLD) - { - // Fix v7 - float length = vertices[3].X - vertices[7].X; - float deltax = vertices[3].X - vertices[5].X; - float deltay = vertices[3].Y - vertices[5].Y; - float correction = length * deltay / deltax; - vertices[7] = new ResultPoint(vertices[7].X, vertices[7].Y - correction); - } - } - - ///

Estimates module size (pixels in a module) based on the Start and End - /// finder patterns.

- /// - ///
- /// an array of vertices: - /// vertices[0] x, y top left barcode - /// vertices[1] x, y bottom left barcode - /// vertices[2] x, y top right barcode - /// vertices[3] x, y bottom right barcode - /// vertices[4] x, y top left codeword area - /// vertices[5] x, y bottom left codeword area - /// vertices[6] x, y top right codeword area - /// vertices[7] x, y bottom right codeword area - /// - /// the module size. - /// - private static float computeModuleWidth(ResultPoint[] vertices) - { - float pixels1 = ResultPoint.distance(vertices[0], vertices[4]); - float pixels2 = ResultPoint.distance(vertices[1], vertices[5]); - float moduleWidth1 = (pixels1 + pixels2) / (17 * 2.0f); - float pixels3 = ResultPoint.distance(vertices[6], vertices[2]); - float pixels4 = ResultPoint.distance(vertices[7], vertices[3]); - float moduleWidth2 = (pixels3 + pixels4) / (18 * 2.0f); - return (moduleWidth1 + moduleWidth2) / 2.0f; - } - - /// Computes the dimension (number of modules in a row) of the PDF417 Code - /// based on vertices of the codeword area and estimated module size. - /// - /// - /// of codeword area - /// - /// of codeword area - /// - /// of codeword area - /// - /// of codeword are - /// - /// estimated module size - /// - /// the number of modules in a row. - /// - private static int computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, ResultPoint bottomRight, float moduleWidth) - { - int topRowDimension = round(ResultPoint.distance(topLeft, topRight) / moduleWidth); - int bottomRowDimension = round(ResultPoint.distance(bottomLeft, bottomRight) / moduleWidth); - return ((((topRowDimension + bottomRowDimension) >> 1) + 8) / 17) * 17; - /* - * int topRowDimension = round(ResultPoint.distance(topLeft, - * topRight)); //moduleWidth); int bottomRowDimension = - * round(ResultPoint.distance(bottomLeft, bottomRight)); // - * moduleWidth); int dimension = ((topRowDimension + bottomRowDimension) - * >> 1); // Round up to nearest 17 modules i.e. there are 17 modules per - * codeword //int dimension = ((((topRowDimension + bottomRowDimension) >> - * 1) + 8) / 17) * 17; return dimension; - */ - } - - private static BitMatrix sampleGrid(BitMatrix matrix, ResultPoint topLeft, ResultPoint bottomLeft, ResultPoint topRight, ResultPoint bottomRight, int dimension) - { - - // Note that unlike the QR Code sampler, we didn't find the center of modules, but the - // very corners. So there is no 0.5f here; 0.0f is right. - GridSampler sampler = GridSampler.Instance; - - return sampler.sampleGrid(matrix, dimension, 0.0f, 0.0f, dimension, 0.0f, dimension, dimension, 0.0f, dimension, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRight.X, bottomRight.Y, bottomLeft.X, bottomLeft.Y); // p4FromY - } - - /// Ends up being a bit faster than Math.round(). This merely rounds its - /// argument to the nearest int, where x.5 rounds up. - /// - private static int round(float d) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (int) (d + 0.5f); - } - - /// row of black/white values to search - /// - /// x position to start search - /// - /// y position to start search - /// - /// the number of pixels to search on this row - /// - /// pattern of counts of number of black and white pixels that are - /// being searched for as a pattern - /// - /// start/end horizontal offset of guard pattern, as an array of two ints. - /// - private static int[] findGuardPattern(BitMatrix matrix, int column, int row, int width, bool whiteFirst, int[] pattern) - { - int patternLength = pattern.Length; - // TODO: Find a way to cache this array, as this method is called hundreds of times - // per image, and we want to allocate as seldom as possible. - int[] counters = new int[patternLength]; - bool isWhite = whiteFirst; - - int counterPosition = 0; - int patternStart = column; - for (int x = column; x < column + width; x++) - { - bool pixel = matrix.get_Renamed(x, row); - if (pixel ^ isWhite) - { - counters[counterPosition]++; - } - else - { - if (counterPosition == patternLength - 1) - { - if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) - { - return new int[]{patternStart, x}; - } - patternStart += counters[0] + counters[1]; - for (int y = 2; y < patternLength; y++) - { - counters[y - 2] = counters[y]; - } - counters[patternLength - 2] = 0; - counters[patternLength - 1] = 0; - counterPosition--; - } - else - { - counterPosition++; - } - counters[counterPosition] = 1; - isWhite = !isWhite; - } - } - return null; - } - - /// Determines how closely a set of observed counts of runs of black/white - /// values matches a given target pattern. This is reported as the ratio of - /// the total variance from the expected pattern proportions across all - /// pattern elements, to the length of the pattern. - /// - /// - /// observed counters - /// - /// expected pattern - /// - /// The most any counter can differ before we give up - /// - /// ratio of total variance between counters and pattern compared to - /// total pattern size, where the ratio has been multiplied by 256. - /// So, 0 means no variance (perfect match); 256 means the total - /// variance between counters and patterns equals the pattern length, - /// higher values mean even more variance - /// - private static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) - { - int numCounters = counters.Length; - int total = 0; - int patternLength = 0; - for (int i = 0; i < numCounters; i++) - { - total += counters[i]; - patternLength += pattern[i]; - } - if (total < patternLength) - { - // If we don't even have one pixel per unit of bar width, assume this - // is too small to reliably match, so fail: - return System.Int32.MaxValue; - } - // We're going to fake floating-point math in integers. We just need to use more bits. - // Scale up patternLength so that intermediate values below like scaledCounter will have - // more "significant digits". - int unitBarWidth = (total << 8) / patternLength; - maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> 8; - - int totalVariance = 0; - for (int x = 0; x < numCounters; x++) - { - int counter = counters[x] << 8; - int scaledPattern = pattern[x] * unitBarWidth; - int variance = counter > scaledPattern?counter - scaledPattern:scaledPattern - counter; - if (variance > maxIndividualVariance) - { - return System.Int32.MaxValue; - } - totalVariance += variance; - } - return totalVariance / total; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/QRCodeReader.cs b/zxing-csharp/qrcode/QRCodeReader.cs deleted file mode 100644 index d5d8590..0000000 --- a/zxing-csharp/qrcode/QRCodeReader.cs +++ /dev/null @@ -1,180 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using DecodeHintType = com.google.zxing.DecodeHintType; -using Reader = com.google.zxing.Reader; -using ReaderException = com.google.zxing.ReaderException; -using Result = com.google.zxing.Result; -using ResultPoint = com.google.zxing.ResultPoint; -using ResultMetadataType = com.google.zxing.ResultMetadataType; -using BinaryBitmap = com.google.zxing.BinaryBitmap; -using BitMatrix = com.google.zxing.common.BitMatrix; -using DecoderResult = com.google.zxing.common.DecoderResult; -using DetectorResult = com.google.zxing.common.DetectorResult; -using Decoder = com.google.zxing.qrcode.decoder.Decoder; -using Detector = com.google.zxing.qrcode.detector.Detector; -namespace com.google.zxing.qrcode -{ - - /// This implementation can detect and decode QR Codes in an image. - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public class QRCodeReader : Reader - { - virtual protected internal Decoder Decoder - { - get - { - return decoder; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'NO_POINTS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0]; - - //UPGRADE_NOTE: Final was removed from the declaration of 'decoder '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private Decoder decoder = new Decoder(); - - /// Locates and decodes a QR code in an image. - /// - /// - /// a String representing the content encoded by the QR code - /// - /// ReaderException if a QR code cannot be found, or cannot be decoded - public virtual Result decode(BinaryBitmap image) - { - return decode(image, null); - } - - public virtual Result decode(BinaryBitmap image, System.Collections.Hashtable hints) - { - DecoderResult decoderResult; - ResultPoint[] points; - if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) - { - BitMatrix bits = extractPureBits(image.BlackMatrix); - decoderResult = decoder.decode(bits); - points = NO_POINTS; - } - else - { - DetectorResult detectorResult = new Detector(image.BlackMatrix).detect(hints); - decoderResult = decoder.decode(detectorResult.Bits); - points = detectorResult.Points; - } - - Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE); - if (decoderResult.ByteSegments != null) - { - result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.ByteSegments); - } - if (decoderResult.ECLevel != null) - { - result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.ECLevel.ToString()); - } - return result; - } - - /// This method detects a barcode in a "pure" image -- that is, pure monochrome image - /// which contains only an unrotated, unskewed, image of a barcode, with some white border - /// around it. This is a specialized method that works exceptionally fast in this special - /// case. - /// - private static BitMatrix extractPureBits(BitMatrix image) - { - // Now need to determine module size in pixels - - int height = image.Height; - int width = image.Width; - int minDimension = System.Math.Min(height, width); - - // First, skip white border by tracking diagonally from the top left down and to the right: - int borderWidth = 0; - while (borderWidth < minDimension && !image.get_Renamed(borderWidth, borderWidth)) - { - borderWidth++; - } - if (borderWidth == minDimension) - { - throw ReaderException.Instance; - } - - // And then keep tracking across the top-left black module to determine module size - int moduleEnd = borderWidth; - while (moduleEnd < minDimension && image.get_Renamed(moduleEnd, moduleEnd)) - { - moduleEnd++; - } - if (moduleEnd == minDimension) - { - throw ReaderException.Instance; - } - - int moduleSize = moduleEnd - borderWidth; - - // And now find where the rightmost black module on the first row ends - int rowEndOfSymbol = width - 1; - while (rowEndOfSymbol >= 0 && !image.get_Renamed(rowEndOfSymbol, borderWidth)) - { - rowEndOfSymbol--; - } - if (rowEndOfSymbol < 0) - { - throw ReaderException.Instance; - } - rowEndOfSymbol++; - - // Make sure width of barcode is a multiple of module size - if ((rowEndOfSymbol - borderWidth) % moduleSize != 0) - { - throw ReaderException.Instance; - } - int dimension = (rowEndOfSymbol - borderWidth) / moduleSize; - - // Push in the "border" by half the module width so that we start - // sampling in the middle of the module. Just in case the image is a - // little off, this will help recover. - borderWidth += (moduleSize >> 1); - - int sampleDimension = borderWidth + (dimension - 1) * moduleSize; - if (sampleDimension >= width || sampleDimension >= height) - { - throw ReaderException.Instance; - } - - // Now just read off the bits - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) - { - int iOffset = borderWidth + i * moduleSize; - for (int j = 0; j < dimension; j++) - { - if (image.get_Renamed(borderWidth + j * moduleSize, iOffset)) - { - bits.set_Renamed(j, i); - } - } - } - return bits; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/QRCodeWriter.cs b/zxing-csharp/qrcode/QRCodeWriter.cs deleted file mode 100644 index 1fb1947..0000000 --- a/zxing-csharp/qrcode/QRCodeWriter.cs +++ /dev/null @@ -1,170 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BarcodeFormat = com.google.zxing.BarcodeFormat; -using EncodeHintType = com.google.zxing.EncodeHintType; -using Writer = com.google.zxing.Writer; -using WriterException = com.google.zxing.WriterException; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -using Encoder = com.google.zxing.qrcode.encoder.Encoder; -using QRCode = com.google.zxing.qrcode.encoder.QRCode; -using ErrorCorrectionLevel = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; -namespace com.google.zxing.qrcode -{ - - /// This object renders a QR Code as a ByteMatrix 2D array of greyscale values. - /// - /// - /// dswitkin@google.com (Daniel Switkin) - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class QRCodeWriter : Writer - { - - private const int QUIET_ZONE_SIZE = 4; - - public ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height) - { - - return encode(contents, format, width, height, null); - } - - public ByteMatrix encode(System.String contents, BarcodeFormat format, int width, int height, System.Collections.Hashtable hints) - { - - if (contents == null || contents.Length == 0) - { - throw new System.ArgumentException("Found empty contents"); - } - - if (format != BarcodeFormat.QR_CODE) - { - throw new System.ArgumentException("Can only encode QR_CODE, but got " + format); - } - - if (width < 0 || height < 0) - { - throw new System.ArgumentException("Requested dimensions are too small: " + width + 'x' + height); - } - - ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; - if (hints != null) - { - ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints[EncodeHintType.ERROR_CORRECTION]; - if (requestedECLevel != null) - { - errorCorrectionLevel = requestedECLevel; - } - } - - QRCode code = new QRCode(); - Encoder.encode(contents, errorCorrectionLevel, hints, code); - return renderResult(code, width, height); - } - - // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses - // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap). - private static ByteMatrix renderResult(QRCode code, int width, int height) - { - ByteMatrix input = code.Matrix; - int inputWidth = input.Width; - int inputHeight = input.Height; - int qrWidth = inputWidth + (QUIET_ZONE_SIZE << 1); - int qrHeight = inputHeight + (QUIET_ZONE_SIZE << 1); - int outputWidth = System.Math.Max(width, qrWidth); - int outputHeight = System.Math.Max(height, qrHeight); - - int multiple = System.Math.Min(outputWidth / qrWidth, outputHeight / qrHeight); - // Padding includes both the quiet zone and the extra white pixels to accommodate the requested - // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone. - // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will - // handle all the padding from 100x100 (the actual QR) up to 200x160. - int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; - int topPadding = (outputHeight - (inputHeight * multiple)) / 2; - - ByteMatrix output = new ByteMatrix(outputWidth, outputHeight); - sbyte[][] outputArray = output.Array; - - // We could be tricky and use the first row in each set of multiple as the temporary storage, - // instead of allocating this separate array. - sbyte[] row = new sbyte[outputWidth]; - - // 1. Write the white lines at the top - for (int y = 0; y < topPadding; y++) - { - setRowColor(outputArray[y], (sbyte) SupportClass.Identity(255)); - } - - // 2. Expand the QR image to the multiple - sbyte[][] inputArray = input.Array; - for (int y = 0; y < inputHeight; y++) - { - // a. Write the white pixels at the left of each row - for (int x = 0; x < leftPadding; x++) - { - row[x] = (sbyte) SupportClass.Identity(255); - } - - // b. Write the contents of this row of the barcode - int offset = leftPadding; - for (int x = 0; x < inputWidth; x++) - { - // Redivivus.in Java to c# Porting update - Type cased sbyte - // 30/01/2010 - // sbyte value_Renamed = (inputArray[y][x] == 1)?0:(sbyte) SupportClass.Identity(255); - sbyte value_Renamed = (sbyte)((inputArray[y][x] == 1) ? 0 : SupportClass.Identity(255)); - for (int z = 0; z < multiple; z++) - { - row[offset + z] = value_Renamed; - } - offset += multiple; - } - - // c. Write the white pixels at the right of each row - offset = leftPadding + (inputWidth * multiple); - for (int x = offset; x < outputWidth; x++) - { - row[x] = (sbyte) SupportClass.Identity(255); - } - - // d. Write the completed row multiple times - offset = topPadding + (y * multiple); - for (int z = 0; z < multiple; z++) - { - Array.Copy(row, 0, outputArray[offset + z], 0, outputWidth); - } - } - - // 3. Write the white lines at the bottom - int offset2 = topPadding + (inputHeight * multiple); - for (int y = offset2; y < outputHeight; y++) - { - setRowColor(outputArray[y], (sbyte) SupportClass.Identity(255)); - } - - return output; - } - - private static void setRowColor(sbyte[] row, sbyte value_Renamed) - { - for (int x = 0; x < row.Length; x++) - { - row[x] = value_Renamed; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/decoder/BitMatrixParser.cs b/zxing-csharp/qrcode/decoder/BitMatrixParser.cs deleted file mode 100644 index 505b1f8..0000000 --- a/zxing-csharp/qrcode/decoder/BitMatrixParser.cs +++ /dev/null @@ -1,241 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing.qrcode.decoder -{ - - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class BitMatrixParser - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'bitMatrix '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix bitMatrix; - private Version parsedVersion; - private FormatInformation parsedFormatInfo; - - /// {@link BitMatrix} to parse - /// - /// ReaderException if dimension is not >= 21 and 1 mod 4 - internal BitMatrixParser(BitMatrix bitMatrix) - { - int dimension = bitMatrix.Dimension; - if (dimension < 21 || (dimension & 0x03) != 1) - { - throw ReaderException.Instance; - } - this.bitMatrix = bitMatrix; - } - - ///

Reads format information from one of its two locations within the QR Code.

- /// - ///
- /// {@link FormatInformation} encapsulating the QR Code's format info - /// - /// ReaderException if both format information locations cannot be parsed as - /// the valid encoding of format information - /// - internal FormatInformation readFormatInformation() - { - - if (parsedFormatInfo != null) - { - return parsedFormatInfo; - } - - // Read top-left format info bits - int formatInfoBits = 0; - for (int i = 0; i < 6; i++) - { - formatInfoBits = copyBit(i, 8, formatInfoBits); - } - // .. and skip a bit in the timing pattern ... - formatInfoBits = copyBit(7, 8, formatInfoBits); - formatInfoBits = copyBit(8, 8, formatInfoBits); - formatInfoBits = copyBit(8, 7, formatInfoBits); - // .. and skip a bit in the timing pattern ... - for (int j = 5; j >= 0; j--) - { - formatInfoBits = copyBit(8, j, formatInfoBits); - } - - parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); - if (parsedFormatInfo != null) - { - return parsedFormatInfo; - } - - // Hmm, failed. Try the top-right/bottom-left pattern - int dimension = bitMatrix.Dimension; - formatInfoBits = 0; - int iMin = dimension - 8; - for (int i = dimension - 1; i >= iMin; i--) - { - formatInfoBits = copyBit(i, 8, formatInfoBits); - } - for (int j = dimension - 7; j < dimension; j++) - { - formatInfoBits = copyBit(8, j, formatInfoBits); - } - - parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); - if (parsedFormatInfo != null) - { - return parsedFormatInfo; - } - throw ReaderException.Instance; - } - - ///

Reads version information from one of its two locations within the QR Code.

- /// - ///
- /// {@link Version} encapsulating the QR Code's version - /// - /// ReaderException if both version information locations cannot be parsed as - /// the valid encoding of version information - /// - internal Version readVersion() - { - - if (parsedVersion != null) - { - return parsedVersion; - } - - int dimension = bitMatrix.Dimension; - - int provisionalVersion = (dimension - 17) >> 2; - if (provisionalVersion <= 6) - { - return Version.getVersionForNumber(provisionalVersion); - } - - // Read top-right version info: 3 wide by 6 tall - int versionBits = 0; - int ijMin = dimension - 11; - for (int j = 5; j >= 0; j--) - { - for (int i = dimension - 9; i >= ijMin; i--) - { - versionBits = copyBit(i, j, versionBits); - } - } - - parsedVersion = Version.decodeVersionInformation(versionBits); - if (parsedVersion != null && parsedVersion.DimensionForVersion == dimension) - { - return parsedVersion; - } - - // Hmm, failed. Try bottom left: 6 wide by 3 tall - versionBits = 0; - for (int i = 5; i >= 0; i--) - { - for (int j = dimension - 9; j >= ijMin; j--) - { - versionBits = copyBit(i, j, versionBits); - } - } - - parsedVersion = Version.decodeVersionInformation(versionBits); - if (parsedVersion != null && parsedVersion.DimensionForVersion == dimension) - { - return parsedVersion; - } - throw ReaderException.Instance; - } - - private int copyBit(int i, int j, int versionBits) - { - return bitMatrix.get_Renamed(i, j)?(versionBits << 1) | 0x1:versionBits << 1; - } - - ///

Reads the bits in the {@link BitMatrix} representing the finder pattern in the - /// correct order in order to reconstitute the codewords bytes contained within the - /// QR Code.

- /// - ///
- /// bytes encoded within the QR Code - /// - /// ReaderException if the exact number of bytes expected is not read - internal sbyte[] readCodewords() - { - - FormatInformation formatInfo = readFormatInformation(); - Version version = readVersion(); - - // Get the data mask for the format used in this QR Code. This will exclude - // some bits from reading as we wind through the bit matrix. - DataMask dataMask = DataMask.forReference((int) formatInfo.DataMask); - int dimension = bitMatrix.Dimension; - dataMask.unmaskBitMatrix(bitMatrix, dimension); - - BitMatrix functionPattern = version.buildFunctionPattern(); - - bool readingUp = true; - sbyte[] result = new sbyte[version.TotalCodewords]; - int resultOffset = 0; - int currentByte = 0; - int bitsRead = 0; - // Read columns in pairs, from right to left - for (int j = dimension - 1; j > 0; j -= 2) - { - if (j == 6) - { - // Skip whole column with vertical alignment pattern; - // saves time and makes the other code proceed more cleanly - j--; - } - // Read alternatingly from bottom to top then top to bottom - for (int count = 0; count < dimension; count++) - { - int i = readingUp?dimension - 1 - count:count; - for (int col = 0; col < 2; col++) - { - // Ignore bits covered by the function pattern - if (!functionPattern.get_Renamed(j - col, i)) - { - // Read a bit - bitsRead++; - currentByte <<= 1; - if (bitMatrix.get_Renamed(j - col, i)) - { - currentByte |= 1; - } - // If we've made a whole byte, save it off - if (bitsRead == 8) - { - result[resultOffset++] = (sbyte) currentByte; - bitsRead = 0; - currentByte = 0; - } - } - } - } - readingUp ^= true; // readingUp = !readingUp; // switch directions - } - if (resultOffset != version.TotalCodewords) - { - throw ReaderException.Instance; - } - return result; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/decoder/DataBlock.cs b/zxing-csharp/qrcode/decoder/DataBlock.cs deleted file mode 100644 index 91925f2..0000000 --- a/zxing-csharp/qrcode/decoder/DataBlock.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.qrcode.decoder -{ - - ///

Encapsulates a block of data within a QR Code. QR Codes may split their data into - /// multiple blocks, each of which is a unit of data and error-correction codewords. Each - /// is represented by an instance of this class.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class DataBlock - { - internal int NumDataCodewords - { - get - { - return numDataCodewords; - } - - } - internal sbyte[] Codewords - { - get - { - return codewords; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'numDataCodewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int numDataCodewords; - //UPGRADE_NOTE: Final was removed from the declaration of 'codewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte[] codewords; - - private DataBlock(int numDataCodewords, sbyte[] codewords) - { - this.numDataCodewords = numDataCodewords; - this.codewords = codewords; - } - - ///

When QR Codes use multiple data blocks, they are actually interleaved. - /// That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This - /// method will separate the data into original blocks.

- /// - ///
- /// bytes as read directly from the QR Code - /// - /// version of the QR Code - /// - /// error-correction level of the QR Code - /// - /// {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the - /// QR Code - /// - internal static DataBlock[] getDataBlocks(sbyte[] rawCodewords, Version version, ErrorCorrectionLevel ecLevel) - { - - if (rawCodewords.Length != version.TotalCodewords) - { - throw new System.ArgumentException(); - } - - // Figure out the number and size of data blocks used by this version and - // error correction level - Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); - - // First count the total number of data blocks - int totalBlocks = 0; - Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); - for (int i = 0; i < ecBlockArray.Length; i++) - { - totalBlocks += ecBlockArray[i].Count; - } - - // Now establish DataBlocks of the appropriate size and number of data codewords - DataBlock[] result = new DataBlock[totalBlocks]; - int numResultBlocks = 0; - for (int j = 0; j < ecBlockArray.Length; j++) - { - Version.ECB ecBlock = ecBlockArray[j]; - for (int i = 0; i < ecBlock.Count; i++) - { - int numDataCodewords = ecBlock.DataCodewords; - int numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords; - result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]); - } - } - - // All blocks have the same amount of data, except that the last n - // (where n may be 0) have 1 more byte. Figure out where these start. - int shorterBlocksTotalCodewords = result[0].codewords.Length; - int longerBlocksStartAt = result.Length - 1; - while (longerBlocksStartAt >= 0) - { - int numCodewords = result[longerBlocksStartAt].codewords.Length; - if (numCodewords == shorterBlocksTotalCodewords) - { - break; - } - longerBlocksStartAt--; - } - longerBlocksStartAt++; - - int shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock; - // The last elements of result may be 1 element longer; - // first fill out as many elements as all of them have - int rawCodewordsOffset = 0; - for (int i = 0; i < shorterBlocksNumDataCodewords; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; - } - } - // Fill out the last data block in the longer ones - for (int j = longerBlocksStartAt; j < numResultBlocks; j++) - { - result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; - } - // Now add in error correction blocks - int max = result[0].codewords.Length; - for (int i = shorterBlocksNumDataCodewords; i < max; i++) - { - for (int j = 0; j < numResultBlocks; j++) - { - int iOffset = j < longerBlocksStartAt?i:i + 1; - result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; - } - } - return result; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/decoder/DataMask.cs b/zxing-csharp/qrcode/decoder/DataMask.cs deleted file mode 100644 index e2ecaa0..0000000 --- a/zxing-csharp/qrcode/decoder/DataMask.cs +++ /dev/null @@ -1,157 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing.qrcode.decoder -{ - - ///

Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations - /// of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix, - /// including areas used for finder patterns, timing patterns, etc. These areas should be unused - /// after the point they are unmasked anyway.

- /// - ///

Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position - /// and j is row position. In fact, as the text says, i is row position and j is column position.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - abstract class DataMask - { - - /// See ISO 18004:2006 6.8.1 - //UPGRADE_NOTE: Final was removed from the declaration of 'DATA_MASKS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly DataMask[] DATA_MASKS = new DataMask[]{new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111()}; - - private DataMask() - { - } - - ///

Implementations of this method reverse the data masking process applied to a QR Code and - /// make its bits ready to read.

- /// - ///
- /// representation of QR Code bits - /// - /// dimension of QR Code, represented by bits, being unmasked - /// - internal void unmaskBitMatrix(BitMatrix bits, int dimension) - { - for (int i = 0; i < dimension; i++) - { - for (int j = 0; j < dimension; j++) - { - if (isMasked(i, j)) - { - bits.flip(j, i); - } - } - } - } - - internal abstract bool isMasked(int i, int j); - - /// a value between 0 and 7 indicating one of the eight possible - /// data mask patterns a QR Code may use - /// - /// {@link DataMask} encapsulating the data mask pattern - /// - internal static DataMask forReference(int reference) - { - if (reference < 0 || reference > 7) - { - throw new System.ArgumentException(); - } - return DATA_MASKS[reference]; - } - - /// 000: mask bits for which (x + y) mod 2 == 0 - private class DataMask000:DataMask - { - internal override bool isMasked(int i, int j) - { - return ((i + j) & 0x01) == 0; - } - } - - /// 001: mask bits for which x mod 2 == 0 - private class DataMask001:DataMask - { - internal override bool isMasked(int i, int j) - { - return (i & 0x01) == 0; - } - } - - /// 010: mask bits for which y mod 3 == 0 - private class DataMask010:DataMask - { - internal override bool isMasked(int i, int j) - { - return j % 3 == 0; - } - } - - /// 011: mask bits for which (x + y) mod 3 == 0 - private class DataMask011:DataMask - { - internal override bool isMasked(int i, int j) - { - return (i + j) % 3 == 0; - } - } - - /// 100: mask bits for which (x/2 + y/3) mod 2 == 0 - private class DataMask100:DataMask - { - internal override bool isMasked(int i, int j) - { - return (((SupportClass.URShift(i, 1)) + (j / 3)) & 0x01) == 0; - } - } - - /// 101: mask bits for which xy mod 2 + xy mod 3 == 0 - private class DataMask101:DataMask - { - internal override bool isMasked(int i, int j) - { - int temp = i * j; - return (temp & 0x01) + (temp % 3) == 0; - } - } - - /// 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0 - private class DataMask110:DataMask - { - internal override bool isMasked(int i, int j) - { - int temp = i * j; - return (((temp & 0x01) + (temp % 3)) & 0x01) == 0; - } - } - - /// 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0 - private class DataMask111:DataMask - { - internal override bool isMasked(int i, int j) - { - return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) == 0; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/decoder/DecodedBitStreamParser.cs b/zxing-csharp/qrcode/decoder/DecodedBitStreamParser.cs deleted file mode 100644 index e2c2fec..0000000 --- a/zxing-csharp/qrcode/decoder/DecodedBitStreamParser.cs +++ /dev/null @@ -1,437 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using BitSource = com.google.zxing.common.BitSource; -using CharacterSetECI = com.google.zxing.common.CharacterSetECI; -using DecoderResult = com.google.zxing.common.DecoderResult; -namespace com.google.zxing.qrcode.decoder -{ - - ///

QR Codes can encode text as bits in one of several modes, and can use multiple modes - /// in one QR Code. This class decodes the bits back into text.

- /// - ///

See ISO 18004:2006, 6.4.3 - 6.4.7

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class DecodedBitStreamParser - { - - /// See ISO 18004:2006, 6.4.4 Table 5 - //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly char[] ALPHANUMERIC_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'}; - private const System.String SHIFT_JIS = "SJIS"; - private const System.String EUC_JP = "EUC_JP"; - private static bool ASSUME_SHIFT_JIS; - private const System.String UTF8 = "UTF8"; - // Redivivus.in Java to c# Porting update - // 30/01/2010 - // Commented & Added - private const System.String ISO88591 = "ISO-8859-1"; - - private DecodedBitStreamParser() - { - } - - internal static DecoderResult decode(sbyte[] bytes, Version version, ErrorCorrectionLevel ecLevel) - { - BitSource bits = new BitSource(bytes); - System.Text.StringBuilder result = new System.Text.StringBuilder(50); - CharacterSetECI currentCharacterSetECI = null; - bool fc1InEffect = false; - System.Collections.ArrayList byteSegments = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(1)); - Mode mode; - do - { - // While still another segment to read... - if (bits.available() < 4) - { - // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here - mode = Mode.TERMINATOR; - } - else - { - try - { - mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits - } - catch (System.ArgumentException iae) - { - throw ReaderException.Instance; - } - } - if (!mode.Equals(Mode.TERMINATOR)) - { - if (mode.Equals(Mode.FNC1_FIRST_POSITION) || mode.Equals(Mode.FNC1_SECOND_POSITION)) - { - // We do little with FNC1 except alter the parsed result a bit according to the spec - fc1InEffect = true; - } - else if (mode.Equals(Mode.STRUCTURED_APPEND)) - { - // not really supported; all we do is ignore it - // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue - bits.readBits(16); - } - else if (mode.Equals(Mode.ECI)) - { - // Count doesn't apply to ECI - int value_Renamed = parseECIValue(bits); - currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value_Renamed); - if (currentCharacterSetECI == null) - { - throw ReaderException.Instance; - } - } - else - { - // How many characters will follow, encoded in this mode? - int count = bits.readBits(mode.getCharacterCountBits(version)); - if (mode.Equals(Mode.NUMERIC)) - { - decodeNumericSegment(bits, result, count); - } - else if (mode.Equals(Mode.ALPHANUMERIC)) - { - decodeAlphanumericSegment(bits, result, count, fc1InEffect); - } - else if (mode.Equals(Mode.BYTE)) - { - decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments); - } - else if (mode.Equals(Mode.KANJI)) - { - decodeKanjiSegment(bits, result, count); - } - else - { - throw ReaderException.Instance; - } - } - } - } - while (!mode.Equals(Mode.TERMINATOR)); - - return new DecoderResult(bytes, result.ToString(), (byteSegments.Count == 0)?null:byteSegments, ecLevel); - } - - private static void decodeKanjiSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - // Each character will require 2 bytes. Read the characters as 2-byte pairs - // and decode as Shift_JIS afterwards - sbyte[] buffer = new sbyte[2 * count]; - int offset = 0; - while (count > 0) - { - // Each 13 bits encodes a 2-byte character - int twoBytes = bits.readBits(13); - int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0); - if (assembledTwoBytes < 0x01F00) - { - // In the 0x8140 to 0x9FFC range - assembledTwoBytes += 0x08140; - } - else - { - // In the 0xE040 to 0xEBBF range - assembledTwoBytes += 0x0C140; - } - buffer[offset] = (sbyte) (assembledTwoBytes >> 8); - buffer[offset + 1] = (sbyte) assembledTwoBytes; - offset += 2; - count--; - } - // Shift_JIS may not be supported in some environments: - try - { - //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" - result.Append(System.Text.Encoding.GetEncoding(SHIFT_JIS).GetString(SupportClass.ToByteArray(buffer))); - } - catch (System.IO.IOException uee) - { - throw ReaderException.Instance; - } - } - - private static void decodeByteSegment(BitSource bits, System.Text.StringBuilder result, int count, CharacterSetECI currentCharacterSetECI, System.Collections.ArrayList byteSegments) - { - sbyte[] readBytes = new sbyte[count]; - if (count << 3 > bits.available()) - { - throw ReaderException.Instance; - } - for (int i = 0; i < count; i++) - { - readBytes[i] = (sbyte) bits.readBits(8); - } - System.String encoding; - if (currentCharacterSetECI == null) - { - // The spec isn't clear on this mode; see - // section 6.4.5: t does not say which encoding to assuming - // upon decoding. I have seen ISO-8859-1 used as well as - // Shift_JIS -- without anything like an ECI designator to - // give a hint. - encoding = guessEncoding(readBytes); - } - else - { - encoding = currentCharacterSetECI.EncodingName; - } - try - { - //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" - result.Append(System.Text.Encoding.GetEncoding(encoding).GetString(SupportClass.ToByteArray(readBytes))); - } - catch (System.IO.IOException uce) - { - throw ReaderException.Instance; - } - byteSegments.Add(SupportClass.ToByteArray(readBytes)); - } - - private static void decodeAlphanumericSegment(BitSource bits, System.Text.StringBuilder result, int count, bool fc1InEffect) - { - // Read two characters at a time - int start = result.Length; - while (count > 1) - { - int nextTwoCharsBits = bits.readBits(11); - result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]); - result.Append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]); - count -= 2; - } - if (count == 1) - { - // special case: one character left - result.Append(ALPHANUMERIC_CHARS[bits.readBits(6)]); - } - // See section 6.4.8.1, 6.4.8.2 - if (fc1InEffect) - { - // We need to massage the result a bit if in an FNC1 mode: - for (int i = start; i < result.Length; i++) - { - if (result[i] == '%') - { - if (i < result.Length - 1 && result[i + 1] == '%') - { - // %% is rendered as % - result.Remove(i + 1, 1); - } - else - { - // In alpha mode, % should be converted to FNC1 separator 0x1D - result[i] = (char) 0x1D; - } - } - } - } - } - - private static void decodeNumericSegment(BitSource bits, System.Text.StringBuilder result, int count) - { - // Read three digits at a time - while (count >= 3) - { - // Each 10 bits encodes three digits - int threeDigitsBits = bits.readBits(10); - if (threeDigitsBits >= 1000) - { - throw ReaderException.Instance; - } - result.Append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]); - result.Append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]); - result.Append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]); - count -= 3; - } - if (count == 2) - { - // Two digits left over to read, encoded in 7 bits - int twoDigitsBits = bits.readBits(7); - if (twoDigitsBits >= 100) - { - throw ReaderException.Instance; - } - result.Append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]); - result.Append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]); - } - else if (count == 1) - { - // One digit left over to read - int digitBits = bits.readBits(4); - if (digitBits >= 10) - { - throw ReaderException.Instance; - } - result.Append(ALPHANUMERIC_CHARS[digitBits]); - } - } - - private static System.String guessEncoding(sbyte[] bytes) - { - if (ASSUME_SHIFT_JIS) - { - return SHIFT_JIS; - } - // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 - if (bytes.Length > 3 && bytes[0] == (sbyte) SupportClass.Identity(0xEF) && bytes[1] == (sbyte) SupportClass.Identity(0xBB) && bytes[2] == (sbyte) SupportClass.Identity(0xBF)) - { - return UTF8; - } - // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, - // which should be by far the most common encodings. ISO-8859-1 - // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS - // uses this as a first byte of a two-byte character. If we see this - // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. - // If we see something else in that second byte, we'll make the risky guess - // that it's UTF-8. - int length = bytes.Length; - bool canBeISO88591 = true; - bool canBeShiftJIS = true; - int maybeDoubleByteCount = 0; - int maybeSingleByteKatakanaCount = 0; - bool sawLatin1Supplement = false; - bool lastWasPossibleDoubleByteStart = false; - for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) - { - int value_Renamed = bytes[i] & 0xFF; - if ((value_Renamed == 0xC2 || value_Renamed == 0xC3) && i < length - 1) - { - // This is really a poor hack. The slightly more exotic characters people might want to put in - // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings - // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF]. - int nextValue = bytes[i + 1] & 0xFF; - if (nextValue <= 0xBF && ((value_Renamed == 0xC2 && nextValue >= 0xA0) || (value_Renamed == 0xC3 && nextValue >= 0x80))) - { - sawLatin1Supplement = true; - } - } - if (value_Renamed >= 0x7F && value_Renamed <= 0x9F) - { - canBeISO88591 = false; - } - if (value_Renamed >= 0xA1 && value_Renamed <= 0xDF) - { - // count the number of characters that might be a Shift_JIS single-byte Katakana character - if (!lastWasPossibleDoubleByteStart) - { - maybeSingleByteKatakanaCount++; - } - } - if (!lastWasPossibleDoubleByteStart && ((value_Renamed >= 0xF0 && value_Renamed <= 0xFF) || value_Renamed == 0x80 || value_Renamed == 0xA0)) - { - canBeShiftJIS = false; - } - if (((value_Renamed >= 0x81 && value_Renamed <= 0x9F) || (value_Renamed >= 0xE0 && value_Renamed <= 0xEF))) - { - // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid - // second byte. - if (lastWasPossibleDoubleByteStart) - { - // If we just checked this and the last byte for being a valid double-byte - // char, don't check starting on this byte. If this and the last byte - // formed a valid pair, then this shouldn't be checked to see if it starts - // a double byte pair of course. - lastWasPossibleDoubleByteStart = false; - } - else - { - // ... otherwise do check to see if this plus the next byte form a valid - // double byte pair encoding a character. - lastWasPossibleDoubleByteStart = true; - if (i >= bytes.Length - 1) - { - canBeShiftJIS = false; - } - else - { - int nextValue = bytes[i + 1] & 0xFF; - if (nextValue < 0x40 || nextValue > 0xFC) - { - canBeShiftJIS = false; - } - else - { - maybeDoubleByteCount++; - } - // There is some conflicting information out there about which bytes can follow which in - // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice. - } - } - } - else - { - lastWasPossibleDoubleByteStart = false; - } - } - // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is: - // - If we saw - // - at least three byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or - // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1), - // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS - if (canBeShiftJIS && (maybeDoubleByteCount >= 3 || 20 * maybeSingleByteKatakanaCount > length)) - { - return SHIFT_JIS; - } - // Otherwise, we default to ISO-8859-1 unless we know it can't be - if (!sawLatin1Supplement && canBeISO88591) - { - return ISO88591; - } - // Otherwise, we take a wild guess with UTF-8 - return UTF8; - } - - private static int parseECIValue(BitSource bits) - { - int firstByte = bits.readBits(8); - if ((firstByte & 0x80) == 0) - { - // just one byte - return firstByte & 0x7F; - } - else if ((firstByte & 0xC0) == 0x80) - { - // two bytes - int secondByte = bits.readBits(8); - return ((firstByte & 0x3F) << 8) | secondByte; - } - else if ((firstByte & 0xE0) == 0xC0) - { - // three bytes - int secondThirdBytes = bits.readBits(16); - return ((firstByte & 0x1F) << 16) | secondThirdBytes; - } - throw new System.ArgumentException("Bad ECI bits starting with byte " + firstByte); - } - static DecodedBitStreamParser() - { - { - // Redivivus.in Java to c# Porting update - // 30/01/2010 - // Commented & Added - //System.String platformDefault = System_Renamed.getProperty("file.encoding"); - //ASSUME_SHIFT_JIS = SHIFT_JIS.ToUpper().Equals(platformDefault.ToUpper()) || EUC_JP.ToUpper().Equals(platformDefault.ToUpper()); - ASSUME_SHIFT_JIS = false; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/decoder/Decoder.cs b/zxing-csharp/qrcode/decoder/Decoder.cs deleted file mode 100644 index 9762202..0000000 --- a/zxing-csharp/qrcode/decoder/Decoder.cs +++ /dev/null @@ -1,153 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using BitMatrix = com.google.zxing.common.BitMatrix; -using DecoderResult = com.google.zxing.common.DecoderResult; -using GF256 = com.google.zxing.common.reedsolomon.GF256; -using ReedSolomonDecoder = com.google.zxing.common.reedsolomon.ReedSolomonDecoder; -using ReedSolomonException = com.google.zxing.common.reedsolomon.ReedSolomonException; -namespace com.google.zxing.qrcode.decoder -{ - - ///

The main class which implements QR Code decoding -- as opposed to locating and extracting - /// the QR Code from an image.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Decoder - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'rsDecoder '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ReedSolomonDecoder rsDecoder; - - public Decoder() - { - rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD); - } - - ///

Convenience method that can decode a QR Code represented as a 2D array of booleans. - /// "true" is taken to mean a black module.

- /// - ///
- /// booleans representing white/black QR Code modules - /// - /// text and bytes encoded within the QR Code - /// - /// ReaderException if the QR Code cannot be decoded - public DecoderResult decode(bool[][] image) - { - int dimension = image.Length; - BitMatrix bits = new BitMatrix(dimension); - for (int i = 0; i < dimension; i++) - { - for (int j = 0; j < dimension; j++) - { - if (image[i][j]) - { - bits.set_Renamed(j, i); - } - } - } - return decode(bits); - } - - ///

Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.

- /// - ///
- /// booleans representing white/black QR Code modules - /// - /// text and bytes encoded within the QR Code - /// - /// ReaderException if the QR Code cannot be decoded - public DecoderResult decode(BitMatrix bits) - { - - // Construct a parser and read version, error-correction level - BitMatrixParser parser = new BitMatrixParser(bits); - Version version = parser.readVersion(); - ErrorCorrectionLevel ecLevel = parser.readFormatInformation().ErrorCorrectionLevel; - - // Read codewords - sbyte[] codewords = parser.readCodewords(); - // Separate into data blocks - DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); - - // Count total number of data bytes - int totalBytes = 0; - for (int i = 0; i < dataBlocks.Length; i++) - { - totalBytes += dataBlocks[i].NumDataCodewords; - } - sbyte[] resultBytes = new sbyte[totalBytes]; - int resultOffset = 0; - - // Error-correct and copy data blocks together into a stream of bytes - for (int j = 0; j < dataBlocks.Length; j++) - { - DataBlock dataBlock = dataBlocks[j]; - sbyte[] codewordBytes = dataBlock.Codewords; - int numDataCodewords = dataBlock.NumDataCodewords; - correctErrors(codewordBytes, numDataCodewords); - for (int i = 0; i < numDataCodewords; i++) - { - resultBytes[resultOffset++] = codewordBytes[i]; - } - } - - // Decode the contents of that stream of bytes - return DecodedBitStreamParser.decode(resultBytes, version, ecLevel); - } - - ///

Given data and error-correction codewords received, possibly corrupted by errors, attempts to - /// correct the errors in-place using Reed-Solomon error correction.

- /// - ///
- /// data and error correction codewords - /// - /// number of codewords that are data bytes - /// - /// ReaderException if error correction fails - private void correctErrors(sbyte[] codewordBytes, int numDataCodewords) - { - int numCodewords = codewordBytes.Length; - // First read into an array of ints - int[] codewordsInts = new int[numCodewords]; - for (int i = 0; i < numCodewords; i++) - { - codewordsInts[i] = codewordBytes[i] & 0xFF; - } - int numECCodewords = codewordBytes.Length - numDataCodewords; - try - { - rsDecoder.decode(codewordsInts, numECCodewords); - } - catch (ReedSolomonException rse) - { - throw ReaderException.Instance; - } - // Copy back into array of bytes -- only need to worry about the bytes that were data - // We don't care about errors in the error-correction codewords - for (int i = 0; i < numDataCodewords; i++) - { - codewordBytes[i] = (sbyte) codewordsInts[i]; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/decoder/ErrorCorrectionLevel.cs b/zxing-csharp/qrcode/decoder/ErrorCorrectionLevel.cs deleted file mode 100644 index 1b65cc9..0000000 --- a/zxing-csharp/qrcode/decoder/ErrorCorrectionLevel.cs +++ /dev/null @@ -1,102 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.qrcode.decoder -{ - - ///

See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels - /// defined by the QR code standard.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class ErrorCorrectionLevel - { - public int Bits - { - get - { - return bits; - } - - } - public System.String Name - { - get - { - return name; - } - - } - - // No, we can't use an enum here. J2ME doesn't support it. - - /// L = ~7% correction - //UPGRADE_NOTE: Final was removed from the declaration of 'L '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ErrorCorrectionLevel L = new ErrorCorrectionLevel(0, 0x01, "L"); - /// M = ~15% correction - //UPGRADE_NOTE: Final was removed from the declaration of 'M '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ErrorCorrectionLevel M = new ErrorCorrectionLevel(1, 0x00, "M"); - /// Q = ~25% correction - //UPGRADE_NOTE: Final was removed from the declaration of 'Q '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ErrorCorrectionLevel Q = new ErrorCorrectionLevel(2, 0x03, "Q"); - /// H = ~30% correction - //UPGRADE_NOTE: Final was removed from the declaration of 'H '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly ErrorCorrectionLevel H = new ErrorCorrectionLevel(3, 0x02, "H"); - - //UPGRADE_NOTE: Final was removed from the declaration of 'FOR_BITS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly ErrorCorrectionLevel[] FOR_BITS = new ErrorCorrectionLevel[]{M, L, H, Q}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'ordinal '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int ordinal_Renamed_Field; - //UPGRADE_NOTE: Final was removed from the declaration of 'bits '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int bits; - //UPGRADE_NOTE: Final was removed from the declaration of 'name '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String name; - - private ErrorCorrectionLevel(int ordinal, int bits, System.String name) - { - this.ordinal_Renamed_Field = ordinal; - this.bits = bits; - this.name = name; - } - - public int ordinal() - { - return ordinal_Renamed_Field; - } - - public override System.String ToString() - { - return name; - } - - /// int containing the two bits encoding a QR Code's error correction level - /// - /// {@link ErrorCorrectionLevel} representing the encoded error correction level - /// - public static ErrorCorrectionLevel forBits(int bits) - { - if (bits < 0 || bits >= FOR_BITS.Length) - { - throw new System.ArgumentException(); - } - return FOR_BITS[bits]; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/decoder/FormatInformation.cs b/zxing-csharp/qrcode/decoder/FormatInformation.cs deleted file mode 100644 index cf820d6..0000000 --- a/zxing-csharp/qrcode/decoder/FormatInformation.cs +++ /dev/null @@ -1,144 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.qrcode.decoder -{ - - ///

Encapsulates a QR Code's format information, including the data mask used and - /// error correction level.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - /// - /// - /// - /// - sealed class FormatInformation - { - internal ErrorCorrectionLevel ErrorCorrectionLevel - { - get - { - return errorCorrectionLevel; - } - - } - internal sbyte DataMask - { - get - { - return dataMask; - } - - } - - private const int FORMAT_INFO_MASK_QR = 0x5412; - - /// See ISO 18004:2006, Annex C, Table C.1 - //UPGRADE_NOTE: Final was removed from the declaration of 'FORMAT_INFO_DECODE_LOOKUP'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] FORMAT_INFO_DECODE_LOOKUP = new int[][]{new int[]{0x5412, 0x00}, new int[]{0x5125, 0x01}, new int[]{0x5E7C, 0x02}, new int[]{0x5B4B, 0x03}, new int[]{0x45F9, 0x04}, new int[]{0x40CE, 0x05}, new int[]{0x4F97, 0x06}, new int[]{0x4AA0, 0x07}, new int[]{0x77C4, 0x08}, new int[]{0x72F3, 0x09}, new int[]{0x7DAA, 0x0A}, new int[]{0x789D, 0x0B}, new int[]{0x662F, 0x0C}, new int[]{0x6318, 0x0D}, new int[]{0x6C41, 0x0E}, new int[]{0x6976, 0x0F}, new int[]{0x1689, 0x10}, new int[]{0x13BE, 0x11}, new int[]{0x1CE7, 0x12}, new int[]{0x19D0, 0x13}, new int[]{0x0762, 0x14}, new int[]{0x0255, 0x15}, new int[]{0x0D0C, 0x16}, new int[]{0x083B, 0x17}, new int[]{0x355F, 0x18}, new int[]{0x3068, 0x19}, new int[]{0x3F31, 0x1A}, new int[]{0x3A06, 0x1B}, new int[]{0x24B4, 0x1C}, new int[]{0x2183, 0x1D}, new int[]{0x2EDA, 0x1E}, new int[]{0x2BED, 0x1F}}; - - /// Offset i holds the number of 1 bits in the binary representation of i - //UPGRADE_NOTE: Final was removed from the declaration of 'BITS_SET_IN_HALF_BYTE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] BITS_SET_IN_HALF_BYTE = new int[]{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'errorCorrectionLevel '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ErrorCorrectionLevel errorCorrectionLevel; - //UPGRADE_NOTE: Final was removed from the declaration of 'dataMask '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private sbyte dataMask; - - private FormatInformation(int formatInfo) - { - // Bits 3,4 - errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); - // Bottom 3 bits - dataMask = (sbyte) (formatInfo & 0x07); - } - - internal static int numBitsDiffering(int a, int b) - { - a ^= b; // a now has a 1 bit exactly where its bit differs with b's - // Count bits set quickly with a series of lookups: - return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(SupportClass.URShift(a, 28) & 0x0F)]; - } - - /// format info indicator, with mask still applied - /// - /// information about the format it specifies, or null - /// if doesn't seem to match any known pattern - /// - internal static FormatInformation decodeFormatInformation(int maskedFormatInfo) - { - FormatInformation formatInfo = doDecodeFormatInformation(maskedFormatInfo); - if (formatInfo != null) - { - return formatInfo; - } - // Should return null, but, some QR codes apparently - // do not mask this info. Try again by actually masking the pattern - // first - return doDecodeFormatInformation(maskedFormatInfo ^ FORMAT_INFO_MASK_QR); - } - - private static FormatInformation doDecodeFormatInformation(int maskedFormatInfo) - { - // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing - int bestDifference = System.Int32.MaxValue; - int bestFormatInfo = 0; - for (int i = 0; i < FORMAT_INFO_DECODE_LOOKUP.Length; i++) - { - int[] decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; - int targetInfo = decodeInfo[0]; - if (targetInfo == maskedFormatInfo) - { - // Found an exact match - return new FormatInformation(decodeInfo[1]); - } - int bitsDifference = numBitsDiffering(maskedFormatInfo, targetInfo); - if (bitsDifference < bestDifference) - { - bestFormatInfo = decodeInfo[1]; - bestDifference = bitsDifference; - } - } - // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits - // differing means we found a match - if (bestDifference <= 3) - { - return new FormatInformation(bestFormatInfo); - } - return null; - } - - public override int GetHashCode() - { - return (errorCorrectionLevel.ordinal() << 3) | (int) dataMask; - } - - public override bool Equals(System.Object o) - { - if (!(o is FormatInformation)) - { - return false; - } - FormatInformation other = (FormatInformation) o; - return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/decoder/Mode.cs b/zxing-csharp/qrcode/decoder/Mode.cs deleted file mode 100644 index 86843f8..0000000 --- a/zxing-csharp/qrcode/decoder/Mode.cs +++ /dev/null @@ -1,158 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.qrcode.decoder -{ - - ///

See ISO 18004:2006, 6.4.1, Tables 2 and 3. This enum encapsulates the various modes in which - /// data can be encoded to bits in the QR code standard.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Mode - { - public int Bits - { - get - { - return bits; - } - - } - public System.String Name - { - get - { - return name; - } - - } - - // No, we can't use an enum here. J2ME doesn't support it. - - //UPGRADE_NOTE: Final was removed from the declaration of 'TERMINATOR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly Mode TERMINATOR = new Mode(new int[]{0, 0, 0}, 0x00, "TERMINATOR"); // Not really a mode... - //UPGRADE_NOTE: Final was removed from the declaration of 'NUMERIC '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly Mode NUMERIC = new Mode(new int[]{10, 12, 14}, 0x01, "NUMERIC"); - //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly Mode ALPHANUMERIC = new Mode(new int[]{9, 11, 13}, 0x02, "ALPHANUMERIC"); - //UPGRADE_NOTE: Final was removed from the declaration of 'STRUCTURED_APPEND '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly Mode STRUCTURED_APPEND = new Mode(new int[]{0, 0, 0}, 0x03, "STRUCTURED_APPEND"); // Not supported - //UPGRADE_NOTE: Final was removed from the declaration of 'BYTE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly Mode BYTE = new Mode(new int[]{8, 16, 16}, 0x04, "BYTE"); - //UPGRADE_NOTE: Final was removed from the declaration of 'ECI '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly Mode ECI = new Mode(null, 0x07, "ECI"); // character counts don't apply - //UPGRADE_NOTE: Final was removed from the declaration of 'KANJI '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly Mode KANJI = new Mode(new int[]{8, 10, 12}, 0x08, "KANJI"); - //UPGRADE_NOTE: Final was removed from the declaration of 'FNC1_FIRST_POSITION '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly Mode FNC1_FIRST_POSITION = new Mode(null, 0x05, "FNC1_FIRST_POSITION"); - //UPGRADE_NOTE: Final was removed from the declaration of 'FNC1_SECOND_POSITION '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - public static readonly Mode FNC1_SECOND_POSITION = new Mode(null, 0x09, "FNC1_SECOND_POSITION"); - - //UPGRADE_NOTE: Final was removed from the declaration of 'characterCountBitsForVersions '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] characterCountBitsForVersions; - //UPGRADE_NOTE: Final was removed from the declaration of 'bits '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int bits; - //UPGRADE_NOTE: Final was removed from the declaration of 'name '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.String name; - - private Mode(int[] characterCountBitsForVersions, int bits, System.String name) - { - this.characterCountBitsForVersions = characterCountBitsForVersions; - this.bits = bits; - this.name = name; - } - - /// four bits encoding a QR Code data mode - /// - /// {@link Mode} encoded by these bits - /// - /// IllegalArgumentException if bits do not correspond to a known mode - public static Mode forBits(int bits) - { - switch (bits) - { - - case 0x0: - return TERMINATOR; - - case 0x1: - return NUMERIC; - - case 0x2: - return ALPHANUMERIC; - - case 0x3: - return STRUCTURED_APPEND; - - case 0x4: - return BYTE; - - case 0x5: - return FNC1_FIRST_POSITION; - - case 0x7: - return ECI; - - case 0x8: - return KANJI; - - case 0x9: - return FNC1_SECOND_POSITION; - - default: - throw new System.ArgumentException(); - - } - } - - /// version in question - /// - /// number of bits used, in this QR Code symbol {@link Version}, to encode the - /// count of characters that will follow encoded in this {@link Mode} - /// - public int getCharacterCountBits(Version version) - { - if (characterCountBitsForVersions == null) - { - throw new System.ArgumentException("Character count doesn't apply to this mode"); - } - int number = version.VersionNumber; - int offset; - if (number <= 9) - { - offset = 0; - } - else if (number <= 26) - { - offset = 1; - } - else - { - offset = 2; - } - return characterCountBitsForVersions[offset]; - } - - public override System.String ToString() - { - return name; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/decoder/Version.cs b/zxing-csharp/qrcode/decoder/Version.cs deleted file mode 100644 index c28be0c..0000000 --- a/zxing-csharp/qrcode/decoder/Version.cs +++ /dev/null @@ -1,320 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing.qrcode.decoder -{ - - /// See ISO 18004:2006 Annex D - /// - /// - /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Version - { - public int VersionNumber - { - get - { - return versionNumber; - } - - } - public int[] AlignmentPatternCenters - { - get - { - return alignmentPatternCenters; - } - - } - public int TotalCodewords - { - get - { - return totalCodewords; - } - - } - public int DimensionForVersion - { - get - { - return 17 + 4 * versionNumber; - } - - } - - /// See ISO 18004:2006 Annex D. - /// Element i represents the raw version bits that specify version i + 7 - /// - //UPGRADE_NOTE: Final was removed from the declaration of 'VERSION_DECODE_INFO'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] VERSION_DECODE_INFO = new int[]{0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'VERSIONS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly Version[] VERSIONS = buildVersions(); - - //UPGRADE_NOTE: Final was removed from the declaration of 'versionNumber '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int versionNumber; - //UPGRADE_NOTE: Final was removed from the declaration of 'alignmentPatternCenters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] alignmentPatternCenters; - //UPGRADE_NOTE: Final was removed from the declaration of 'ecBlocks '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ECBlocks[] ecBlocks; - //UPGRADE_NOTE: Final was removed from the declaration of 'totalCodewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int totalCodewords; - - private Version(int versionNumber, int[] alignmentPatternCenters, ECBlocks ecBlocks1, ECBlocks ecBlocks2, ECBlocks ecBlocks3, ECBlocks ecBlocks4) - { - this.versionNumber = versionNumber; - this.alignmentPatternCenters = alignmentPatternCenters; - this.ecBlocks = new ECBlocks[]{ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4}; - int total = 0; - int ecCodewords = ecBlocks1.ECCodewordsPerBlock; - ECB[] ecbArray = ecBlocks1.getECBlocks(); - for (int i = 0; i < ecbArray.Length; i++) - { - ECB ecBlock = ecbArray[i]; - total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); - } - this.totalCodewords = total; - } - - public ECBlocks getECBlocksForLevel(ErrorCorrectionLevel ecLevel) - { - return ecBlocks[ecLevel.ordinal()]; - } - - ///

Deduces version information purely from QR Code dimensions.

- /// - ///
- /// dimension in modules - /// - /// {@link Version} for a QR Code of that dimension - /// - /// ReaderException if dimension is not 1 mod 4 - public static Version getProvisionalVersionForDimension(int dimension) - { - if (dimension % 4 != 1) - { - throw ReaderException.Instance; - } - try - { - return getVersionForNumber((dimension - 17) >> 2); - } - catch (System.ArgumentException iae) - { - throw ReaderException.Instance; - } - } - - public static Version getVersionForNumber(int versionNumber) - { - if (versionNumber < 1 || versionNumber > 40) - { - throw new System.ArgumentException(); - } - return VERSIONS[versionNumber - 1]; - } - - internal static Version decodeVersionInformation(int versionBits) - { - int bestDifference = System.Int32.MaxValue; - int bestVersion = 0; - for (int i = 0; i < VERSION_DECODE_INFO.Length; i++) - { - int targetVersion = VERSION_DECODE_INFO[i]; - // Do the version info bits match exactly? done. - if (targetVersion == versionBits) - { - return getVersionForNumber(i + 7); - } - // Otherwise see if this is the closest to a real version info bit string - // we have seen so far - int bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); - if (bitsDifference < bestDifference) - { - bestVersion = i + 7; - bestDifference = bitsDifference; - } - } - // We can tolerate up to 3 bits of error since no two version info codewords will - // differ in less than 4 bits. - if (bestDifference <= 3) - { - return getVersionForNumber(bestVersion); - } - // If we didn't find a close enough match, fail - return null; - } - - /// See ISO 18004:2006 Annex E - internal BitMatrix buildFunctionPattern() - { - int dimension = DimensionForVersion; - BitMatrix bitMatrix = new BitMatrix(dimension); - - // Top left finder pattern + separator + format - bitMatrix.setRegion(0, 0, 9, 9); - // Top right finder pattern + separator + format - bitMatrix.setRegion(dimension - 8, 0, 8, 9); - // Bottom left finder pattern + separator + format - bitMatrix.setRegion(0, dimension - 8, 9, 8); - - // Alignment patterns - int max = alignmentPatternCenters.Length; - for (int x = 0; x < max; x++) - { - int i = alignmentPatternCenters[x] - 2; - for (int y = 0; y < max; y++) - { - if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) - { - // No alignment patterns near the three finder paterns - continue; - } - bitMatrix.setRegion(alignmentPatternCenters[y] - 2, i, 5, 5); - } - } - - // Vertical timing pattern - bitMatrix.setRegion(6, 9, 1, dimension - 17); - // Horizontal timing pattern - bitMatrix.setRegion(9, 6, dimension - 17, 1); - - if (versionNumber > 6) - { - // Version info, top right - bitMatrix.setRegion(dimension - 11, 0, 3, 6); - // Version info, bottom left - bitMatrix.setRegion(0, dimension - 11, 6, 3); - } - - return bitMatrix; - } - - ///

Encapsulates a set of error-correction blocks in one symbol version. Most versions will - /// use blocks of differing sizes within one version, so, this encapsulates the parameters for - /// each set of blocks. It also holds the number of error-correction codewords per block since it - /// will be the same across all blocks within one version.

- ///
- public sealed class ECBlocks - { - public int ECCodewordsPerBlock - { - get - { - return ecCodewordsPerBlock; - } - - } - public int NumBlocks - { - get - { - int total = 0; - for (int i = 0; i < ecBlocks.Length; i++) - { - total += ecBlocks[i].Count; - } - return total; - } - - } - public int TotalECCodewords - { - get - { - return ecCodewordsPerBlock * NumBlocks; - } - - } - //UPGRADE_NOTE: Final was removed from the declaration of 'ecCodewordsPerBlock '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int ecCodewordsPerBlock; - //UPGRADE_NOTE: Final was removed from the declaration of 'ecBlocks '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ECB[] ecBlocks; - - internal ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks) - { - this.ecCodewordsPerBlock = ecCodewordsPerBlock; - this.ecBlocks = new ECB[]{ecBlocks}; - } - - internal ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks1, ECB ecBlocks2) - { - this.ecCodewordsPerBlock = ecCodewordsPerBlock; - this.ecBlocks = new ECB[]{ecBlocks1, ecBlocks2}; - } - - public ECB[] getECBlocks() - { - return ecBlocks; - } - } - - ///

Encapsualtes the parameters for one error-correction block in one symbol version. - /// This includes the number of data codewords, and the number of times a block with these - /// parameters is used consecutively in the QR code version's format.

- ///
- public sealed class ECB - { - public int Count - { - get - { - return count; - } - - } - public int DataCodewords - { - get - { - return dataCodewords; - } - - } - //UPGRADE_NOTE: Final was removed from the declaration of 'count '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int count; - //UPGRADE_NOTE: Final was removed from the declaration of 'dataCodewords '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int dataCodewords; - - internal ECB(int count, int dataCodewords) - { - this.count = count; - this.dataCodewords = dataCodewords; - } - } - - public override System.String ToString() - { - return System.Convert.ToString(versionNumber); - } - - /// See ISO 18004:2006 6.5.1 Table 9 - private static Version[] buildVersions() - { - return new Version[]{new Version(1, new int[]{}, new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))), new Version(2, new int[]{6, 18}, new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))), new Version(3, new int[]{6, 22}, new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))), new Version(4, new int[]{6, 26}, new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))), new Version(5, new int[]{6, 30}, new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))), new Version(6, new int[]{6, 34}, new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))), new Version(7, new int[]{6, 22, 38}, new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))), new Version(8, new int[]{6, 24, 42}, new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))), new Version(9, new int[]{6, 26, 46}, new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))), new Version(10, new int[]{6, 28, 50}, new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))), new Version(11, new int[]{6, 30, 54}, new ECBlocks(20, new ECB(4, 81)), - new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), new Version(12, new int[]{6, 32, 58}, new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), new Version(13, new int[]{6, 34, 62}, new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), new Version(14, new int[]{6, 26, 46, 66}, new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), new Version(15, new int[]{6, 26, 48, 70}, new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), new Version(16, new int[]{6, 26, 50, 74}, new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), new Version(17, new int[]{6, 30, 54, 78}, new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), new Version(18, new int[]{6, 30, 56, 82}, new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), new Version(19, new int[]{6, 30, 58, 86}, new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), - new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), new Version(20, new int[]{6, 34, 62, 90}, new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), new Version(21, new int[]{6, 28, 50, 72, 94}, new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), new Version(22, new int[]{6, 26, 50, 74, 98}, new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), new Version(23, new int[]{6, 30, 54, 74, 102}, new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), new Version(24, new int[]{6, 28, 54, 80, 106}, new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), new Version(25, new int[]{6, 32, 58, 84, 110}, new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), new Version(26, new int[]{6, 30, 58, 86, 114}, new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), new Version(27, new int[]{6, 34, 62, 90, 118}, new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), - new ECB(28, 16))), new Version(28, new int[]{6, 26, 50, 74, 98, 122}, new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), new Version(29, new int[]{6, 30, 54, 78, 102, 126}, new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), new Version(30, new int[]{6, 26, 52, 78, 104, 130}, new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), new Version(31, new int[]{6, 30, 56, 82, 108, 134}, new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), new Version(32, new int[]{6, 34, 60, 86, 112, 138}, new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), new Version(33, new int[]{6, 30, 58, 86, 114, 142}, new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), new Version(34, new int[]{6, 34, 62, 90, 118, 146}, new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), new Version(35, new int[]{6, 30, 54, 78, 102, 126, 150}, new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new - ECB(14, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), new Version(36, new int[]{6, 24, 50, 76, 102, 128, 154}, new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), new Version(37, new int[]{6, 28, 54, 80, 106, 132, 158}, new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), new Version(38, new int[]{6, 32, 58, 84, 110, 136, 162}, new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), new Version(39, new int[]{6, 26, 54, 82, 110, 138, 166}, new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), new Version(40, new int[]{6, 30, 58, 86, 114, 142, 170}, new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16)))}; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/detector/AlignmentPattern.cs b/zxing-csharp/qrcode/detector/AlignmentPattern.cs deleted file mode 100644 index e406657..0000000 --- a/zxing-csharp/qrcode/detector/AlignmentPattern.cs +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ResultPoint = com.google.zxing.ResultPoint; -namespace com.google.zxing.qrcode.detector -{ - - ///

Encapsulates an alignment pattern, which are the smaller square patterns found in - /// all but the simplest QR Codes.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class AlignmentPattern:ResultPoint - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'estimatedModuleSize '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private float estimatedModuleSize; - - internal AlignmentPattern(float posX, float posY, float estimatedModuleSize):base(posX, posY) - { - this.estimatedModuleSize = estimatedModuleSize; - } - - ///

Determines if this alignment pattern "about equals" an alignment pattern at the stated - /// position and size -- meaning, it is at nearly the same center with nearly the same size.

- ///
- internal bool aboutEquals(float moduleSize, float i, float j) - { - if (System.Math.Abs(i - Y) <= moduleSize && System.Math.Abs(j - X) <= moduleSize) - { - float moduleSizeDiff = System.Math.Abs(moduleSize - estimatedModuleSize); - return moduleSizeDiff <= 1.0f || moduleSizeDiff / estimatedModuleSize <= 1.0f; - } - return false; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/detector/AlignmentPatternFinder.cs b/zxing-csharp/qrcode/detector/AlignmentPatternFinder.cs deleted file mode 100644 index 44aca15..0000000 --- a/zxing-csharp/qrcode/detector/AlignmentPatternFinder.cs +++ /dev/null @@ -1,339 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ReaderException = com.google.zxing.ReaderException; -using ResultPoint = com.google.zxing.ResultPoint; -using ResultPointCallback = com.google.zxing.ResultPointCallback; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing.qrcode.detector -{ - - ///

This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder - /// patterns but are smaller and appear at regular intervals throughout the image.

- /// - ///

At the moment this only looks for the bottom-right alignment pattern.

- /// - ///

This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied, - /// pasted and stripped down here for maximum performance but does unfortunately duplicate - /// some code.

- /// - ///

This class is thread-safe but not reentrant. Each thread must allocate its own object. - /// - ///

- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - sealed class AlignmentPatternFinder - { - - //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix image; - //UPGRADE_NOTE: Final was removed from the declaration of 'possibleCenters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Collections.ArrayList possibleCenters; - //UPGRADE_NOTE: Final was removed from the declaration of 'startX '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int startX; - //UPGRADE_NOTE: Final was removed from the declaration of 'startY '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int startY; - //UPGRADE_NOTE: Final was removed from the declaration of 'width '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int width; - //UPGRADE_NOTE: Final was removed from the declaration of 'height '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int height; - //UPGRADE_NOTE: Final was removed from the declaration of 'moduleSize '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private float moduleSize; - //UPGRADE_NOTE: Final was removed from the declaration of 'crossCheckStateCount '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] crossCheckStateCount; - //UPGRADE_NOTE: Final was removed from the declaration of 'resultPointCallback '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ResultPointCallback resultPointCallback; - - ///

Creates a finder that will look in a portion of the whole image.

- /// - ///
- /// image to search - /// - /// left column from which to start searching - /// - /// top row from which to start searching - /// - /// width of region to search - /// - /// height of region to search - /// - /// estimated module size so far - /// - internal AlignmentPatternFinder(BitMatrix image, int startX, int startY, int width, int height, float moduleSize, ResultPointCallback resultPointCallback) - { - this.image = image; - this.possibleCenters = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(5)); - this.startX = startX; - this.startY = startY; - this.width = width; - this.height = height; - this.moduleSize = moduleSize; - this.crossCheckStateCount = new int[3]; - this.resultPointCallback = resultPointCallback; - } - - ///

This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since - /// it's pretty performance-critical and so is written to be fast foremost.

- /// - ///
- /// {@link AlignmentPattern} if found - /// - /// ReaderException if not found - internal AlignmentPattern find() - { - int startX = this.startX; - int height = this.height; - int maxJ = startX + width; - int middleI = startY + (height >> 1); - // We are looking for black/white/black modules in 1:1:1 ratio; - // this tracks the number of black/white/black modules seen so far - int[] stateCount = new int[3]; - for (int iGen = 0; iGen < height; iGen++) - { - // Search from middle outwards - int i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1)); - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - int j = startX; - // Burn off leading white pixels before anything else; if we start in the middle of - // a white run, it doesn't make sense to count its length, since we don't know if the - // white run continued to the left of the start point - while (j < maxJ && !image.get_Renamed(j, i)) - { - j++; - } - int currentState = 0; - while (j < maxJ) - { - if (image.get_Renamed(j, i)) - { - // Black pixel - if (currentState == 1) - { - // Counting black pixels - stateCount[currentState]++; - } - else - { - // Counting white pixels - if (currentState == 2) - { - // A winner? - if (foundPatternCross(stateCount)) - { - // Yes - AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j); - if (confirmed != null) - { - return confirmed; - } - } - stateCount[0] = stateCount[2]; - stateCount[1] = 1; - stateCount[2] = 0; - currentState = 1; - } - else - { - stateCount[++currentState]++; - } - } - } - else - { - // White pixel - if (currentState == 1) - { - // Counting black pixels - currentState++; - } - stateCount[currentState]++; - } - j++; - } - if (foundPatternCross(stateCount)) - { - AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ); - if (confirmed != null) - { - return confirmed; - } - } - } - - // Hmm, nothing we saw was observed and confirmed twice. If we had - // any guess at all, return it. - if (!(possibleCenters.Count == 0)) - { - return (AlignmentPattern) possibleCenters[0]; - } - - throw ReaderException.Instance; - } - - /// Given a count of black/white/black pixels just seen and an end position, - /// figures the location of the center of this black/white/black run. - /// - private static float centerFromEnd(int[] stateCount, int end) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (float) (end - stateCount[2]) - stateCount[1] / 2.0f; - } - - /// count of black/white/black pixels just read - /// - /// true iff the proportions of the counts is close enough to the 1/1/1 ratios - /// used by alignment patterns to be considered a match - /// - private bool foundPatternCross(int[] stateCount) - { - float moduleSize = this.moduleSize; - float maxVariance = moduleSize / 2.0f; - for (int i = 0; i < 3; i++) - { - if (System.Math.Abs(moduleSize - stateCount[i]) >= maxVariance) - { - return false; - } - } - return true; - } - - ///

After a horizontal scan finds a potential alignment pattern, this method - /// "cross-checks" by scanning down vertically through the center of the possible - /// alignment pattern to see if the same proportion is detected.

- /// - ///
- /// row where an alignment pattern was detected - /// - /// center of the section that appears to cross an alignment pattern - /// - /// maximum reasonable number of modules that should be - /// observed in any reading state, based on the results of the horizontal scan - /// - /// vertical center of alignment pattern, or {@link Float#NaN} if not found - /// - private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) - { - BitMatrix image = this.image; - - int maxI = image.Height; - int[] stateCount = crossCheckStateCount; - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - - // Start counting up from center - int i = startI; - while (i >= 0 && image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount) - { - stateCount[1]++; - i--; - } - // If already too many modules in this state or ran off the edge: - if (i < 0 || stateCount[1] > maxCount) - { - return System.Single.NaN; - } - while (i >= 0 && !image.get_Renamed(centerJ, i) && stateCount[0] <= maxCount) - { - stateCount[0]++; - i--; - } - if (stateCount[0] > maxCount) - { - return System.Single.NaN; - } - - // Now also count down from center - i = startI + 1; - while (i < maxI && image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount) - { - stateCount[1]++; - i++; - } - if (i == maxI || stateCount[1] > maxCount) - { - return System.Single.NaN; - } - while (i < maxI && !image.get_Renamed(centerJ, i) && stateCount[2] <= maxCount) - { - stateCount[2]++; - i++; - } - if (stateCount[2] > maxCount) - { - return System.Single.NaN; - } - - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; - if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) - { - return System.Single.NaN; - } - - return foundPatternCross(stateCount)?centerFromEnd(stateCount, i):System.Single.NaN; - } - - ///

This is called when a horizontal scan finds a possible alignment pattern. It will - /// cross check with a vertical scan, and if successful, will see if this pattern had been - /// found on a previous horizontal scan. If so, we consider it confirmed and conclude we have - /// found the alignment pattern.

- /// - ///
- /// reading state module counts from horizontal scan - /// - /// row where alignment pattern may be found - /// - /// end of possible alignment pattern in row - /// - /// {@link AlignmentPattern} if we have found the same pattern twice, or null if not - /// - private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) - { - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; - float centerJ = centerFromEnd(stateCount, j); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1], stateCountTotal); - if (!System.Single.IsNaN(centerI)) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f; - int max = possibleCenters.Count; - for (int index = 0; index < max; index++) - { - AlignmentPattern center = (AlignmentPattern) possibleCenters[index]; - // Look for about the same center and module size: - if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) - { - return new AlignmentPattern(centerJ, centerI, estimatedModuleSize); - } - } - // Hadn't found this before; save it - ResultPoint point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize); - possibleCenters.Add(point); - if (resultPointCallback != null) - { - resultPointCallback.foundPossibleResultPoint(point); - } - } - return null; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/detector/Detector.cs b/zxing-csharp/qrcode/detector/Detector.cs deleted file mode 100644 index 08f4008..0000000 --- a/zxing-csharp/qrcode/detector/Detector.cs +++ /dev/null @@ -1,420 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using DecodeHintType = com.google.zxing.DecodeHintType; -using ReaderException = com.google.zxing.ReaderException; -using ResultPoint = com.google.zxing.ResultPoint; -using ResultPointCallback = com.google.zxing.ResultPointCallback; -using BitMatrix = com.google.zxing.common.BitMatrix; -using DetectorResult = com.google.zxing.common.DetectorResult; -using GridSampler = com.google.zxing.common.GridSampler; -using PerspectiveTransform = com.google.zxing.common.PerspectiveTransform; -using Version = com.google.zxing.qrcode.decoder.Version; -namespace com.google.zxing.qrcode.detector -{ - - ///

Encapsulates logic that can detect a QR Code in an image, even if the QR Code - /// is rotated or skewed, or partially obscured.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public class Detector - { - virtual protected internal BitMatrix Image - { - get - { - return image; - } - - } - virtual protected internal ResultPointCallback ResultPointCallback - { - get - { - return resultPointCallback; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix image; - private ResultPointCallback resultPointCallback; - - public Detector(BitMatrix image) - { - this.image = image; - } - - ///

Detects a QR Code in an image, simply.

- /// - ///
- /// {@link DetectorResult} encapsulating results of detecting a QR Code - /// - /// ReaderException if no QR Code can be found - public virtual DetectorResult detect() - { - return detect(null); - } - - ///

Detects a QR Code in an image, simply.

- /// - ///
- /// optional hints to detector - /// - /// {@link DetectorResult} encapsulating results of detecting a QR Code - /// - /// ReaderException if no QR Code can be found - public virtual DetectorResult detect(System.Collections.Hashtable hints) - { - - resultPointCallback = hints == null?null:(ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK]; - - FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback); - FinderPatternInfo info = finder.find(hints); - - return processFinderPatternInfo(info); - } - - protected internal virtual DetectorResult processFinderPatternInfo(FinderPatternInfo info) - { - - FinderPattern topLeft = info.TopLeft; - FinderPattern topRight = info.TopRight; - FinderPattern bottomLeft = info.BottomLeft; - - float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft); - if (moduleSize < 1.0f) - { - throw ReaderException.Instance; - } - int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize); - Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension); - int modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7; - - AlignmentPattern alignmentPattern = null; - // Anything above version 1 has an alignment pattern - if (provisionalVersion.AlignmentPatternCenters.Length > 0) - { - - // Guess where a "bottom right" finder pattern would have been - float bottomRightX = topRight.X - topLeft.X + bottomLeft.X; - float bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y; - - // Estimate that alignment pattern is closer by 3 modules - // from "bottom right" to known top left location - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int estAlignmentX = (int) (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X)); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int estAlignmentY = (int) (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y)); - - // Kind of arbitrary -- expand search radius before giving up - for (int i = 4; i <= 16; i <<= 1) - { - try - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float) i); - break; - } - catch (ReaderException re) - { - // try next round - } - } - // If we didn't find alignment pattern... well try anyway without it - } - - PerspectiveTransform transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); - - BitMatrix bits = sampleGrid(image, transform, dimension); - - ResultPoint[] points; - if (alignmentPattern == null) - { - points = new ResultPoint[]{bottomLeft, topLeft, topRight}; - } - else - { - points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern}; - } - return new DetectorResult(bits, points); - } - - public virtual PerspectiveTransform createTransform(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, ResultPoint alignmentPattern, int dimension) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float dimMinusThree = (float) dimension - 3.5f; - float bottomRightX; - float bottomRightY; - float sourceBottomRightX; - float sourceBottomRightY; - if (alignmentPattern != null) - { - bottomRightX = alignmentPattern.X; - bottomRightY = alignmentPattern.Y; - sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0f; - } - else - { - // Don't have an alignment pattern, just make up the bottom-right point - bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X; - bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y; - sourceBottomRightX = sourceBottomRightY = dimMinusThree; - } - - PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5f, 3.5f, dimMinusThree, 3.5f, sourceBottomRightX, sourceBottomRightY, 3.5f, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y); - - return transform; - } - - private static BitMatrix sampleGrid(BitMatrix image, PerspectiveTransform transform, int dimension) - { - - GridSampler sampler = GridSampler.Instance; - return sampler.sampleGrid(image, dimension, transform); - } - - ///

Computes the dimension (number of modules on a size) of the QR Code based on the position - /// of the finder patterns and estimated module size.

- ///
- protected internal static int computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, float moduleSize) - { - int tltrCentersDimension = round(ResultPoint.distance(topLeft, topRight) / moduleSize); - int tlblCentersDimension = round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize); - int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; - switch (dimension & 0x03) - { - - // mod 4 - case 0: - dimension++; - break; - // 1? do nothing - - case 2: - dimension--; - break; - - case 3: - throw ReaderException.Instance; - } - return dimension; - } - - ///

Computes an average estimated module size based on estimated derived from the positions - /// of the three finder patterns.

- ///
- protected internal virtual float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) - { - // Take the average - return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f; - } - - ///

Estimates module size based on two finder patterns -- it uses - /// {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the - /// width of each, measuring along the axis between their centers.

- ///
- private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.X, (int) pattern.Y, (int) otherPattern.X, (int) otherPattern.Y); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.X, (int) otherPattern.Y, (int) pattern.X, (int) pattern.Y); - if (System.Single.IsNaN(moduleSizeEst1)) - { - return moduleSizeEst2 / 7.0f; - } - if (System.Single.IsNaN(moduleSizeEst2)) - { - return moduleSizeEst1 / 7.0f; - } - // Average them, and divide by 7 since we've counted the width of 3 black modules, - // and 1 white and 1 black module on either side. Ergo, divide sum by 14. - return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; - } - - /// See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of - /// a finder pattern by looking for a black-white-black run from the center in the direction - /// of another point (another finder pattern center), and in the opposite direction too.

- ///
- private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) - { - - float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); - - // Now count other way -- don't run off image though of course - float scale = 1.0f; - int otherToX = fromX - (toX - fromX); - if (otherToX < 0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - scale = (float) fromX / (float) (fromX - otherToX); - otherToX = 0; - } - else if (otherToX >= image.Width) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - scale = (float) (image.Width - 1 - fromX) / (float) (otherToX - fromX); - otherToX = image.Width - 1; - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int otherToY = (int) (fromY - (toY - fromY) * scale); - - scale = 1.0f; - if (otherToY < 0) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - scale = (float) fromY / (float) (fromY - otherToY); - otherToY = 0; - } - else if (otherToY >= image.Height) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - scale = (float) (image.Height - 1 - fromY) / (float) (otherToY - fromY); - otherToY = image.Height - 1; - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - otherToX = (int) (fromX + (otherToX - fromX) * scale); - - result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); - return result - 1.0f; // -1 because we counted the middle pixel twice - } - - ///

This method traces a line from a point in the image, in the direction towards another point. - /// It begins in a black region, and keeps going until it finds white, then black, then white again. - /// It reports the distance from the start to this point.

- /// - ///

This is used when figuring out how wide a finder pattern is, when the finder pattern - /// may be skewed or rotated.

- ///
- private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) - { - // Mild variant of Bresenham's algorithm; - // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm - bool steep = System.Math.Abs(toY - fromY) > System.Math.Abs(toX - fromX); - if (steep) - { - int temp = fromX; - fromX = fromY; - fromY = temp; - temp = toX; - toX = toY; - toY = temp; - } - - int dx = System.Math.Abs(toX - fromX); - int dy = System.Math.Abs(toY - fromY); - int error = - dx >> 1; - int ystep = fromY < toY?1:- 1; - int xstep = fromX < toX?1:- 1; - int state = 0; // In black pixels, looking for white, first or second time - for (int x = fromX, y = fromY; x != toX; x += xstep) - { - - int realX = steep?y:x; - int realY = steep?x:y; - if (state == 1) - { - // In white pixels, looking for black - if (image.get_Renamed(realX, realY)) - { - state++; - } - } - else - { - if (!image.get_Renamed(realX, realY)) - { - state++; - } - } - - if (state == 3) - { - // Found black, white, black, and stumbled back onto white; done - int diffX = x - fromX; - int diffY = y - fromY; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (float) System.Math.Sqrt((double) (diffX * diffX + diffY * diffY)); - } - error += dy; - if (error > 0) - { - if (y == toY) - { - break; - } - y += ystep; - error -= dx; - } - } - int diffX2 = toX - fromX; - int diffY2 = toY - fromY; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (float) System.Math.Sqrt((double) (diffX2 * diffX2 + diffY2 * diffY2)); - } - - ///

Attempts to locate an alignment pattern in a limited region of the image, which is - /// guessed to contain it. This method uses {@link AlignmentPattern}.

- /// - ///
- /// estimated module size so far - /// - /// x coordinate of center of area probably containing alignment pattern - /// - /// y coordinate of above - /// - /// number of pixels in all directions to search from the center - /// - /// {@link AlignmentPattern} if found, or null otherwise - /// - /// ReaderException if an unexpected error occurs during detection - protected internal virtual AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor) - { - // Look for an alignment pattern (3 modules in size) around where it - // should be - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - int allowance = (int) (allowanceFactor * overallEstModuleSize); - int alignmentAreaLeftX = System.Math.Max(0, estAlignmentX - allowance); - int alignmentAreaRightX = System.Math.Min(image.Width - 1, estAlignmentX + allowance); - if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) - { - throw ReaderException.Instance; - } - - int alignmentAreaTopY = System.Math.Max(0, estAlignmentY - allowance); - int alignmentAreaBottomY = System.Math.Min(image.Height - 1, estAlignmentY + allowance); - - AlignmentPatternFinder alignmentFinder = new AlignmentPatternFinder(image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, resultPointCallback); - return alignmentFinder.find(); - } - - /// Ends up being a bit faster than Math.round(). This merely rounds its argument to the nearest int, - /// where x.5 rounds up. - /// - private static int round(float d) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (int) (d + 0.5f); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/detector/FinderPattern.cs b/zxing-csharp/qrcode/detector/FinderPattern.cs deleted file mode 100644 index 8b01a47..0000000 --- a/zxing-csharp/qrcode/detector/FinderPattern.cs +++ /dev/null @@ -1,77 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ResultPoint = com.google.zxing.ResultPoint; -namespace com.google.zxing.qrcode.detector -{ - - ///

Encapsulates a finder pattern, which are the three square patterns found in - /// the corners of QR Codes. It also encapsulates a count of similar finder patterns, - /// as a convenience to the finder's bookkeeping.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class FinderPattern:ResultPoint - { - public float EstimatedModuleSize - { - get - { - return estimatedModuleSize; - } - - } - internal int Count - { - get - { - return count; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'estimatedModuleSize '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private float estimatedModuleSize; - private int count; - - internal FinderPattern(float posX, float posY, float estimatedModuleSize):base(posX, posY) - { - this.estimatedModuleSize = estimatedModuleSize; - this.count = 1; - } - - internal void incrementCount() - { - this.count++; - } - - ///

Determines if this finder pattern "about equals" a finder pattern at the stated - /// position and size -- meaning, it is at nearly the same center with nearly the same size.

- ///
- internal bool aboutEquals(float moduleSize, float i, float j) - { - if (System.Math.Abs(i - Y) <= moduleSize && System.Math.Abs(j - X) <= moduleSize) - { - float moduleSizeDiff = System.Math.Abs(moduleSize - estimatedModuleSize); - return moduleSizeDiff <= 1.0f || moduleSizeDiff / estimatedModuleSize <= 1.0f; - } - return false; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/detector/FinderPatternFinder.cs b/zxing-csharp/qrcode/detector/FinderPatternFinder.cs deleted file mode 100644 index 9ba8049..0000000 --- a/zxing-csharp/qrcode/detector/FinderPatternFinder.cs +++ /dev/null @@ -1,646 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using DecodeHintType = com.google.zxing.DecodeHintType; -using ReaderException = com.google.zxing.ReaderException; -using ResultPoint = com.google.zxing.ResultPoint; -using ResultPointCallback = com.google.zxing.ResultPointCallback; -using Collections = com.google.zxing.common.Collections; -using Comparator = com.google.zxing.common.Comparator; -using BitMatrix = com.google.zxing.common.BitMatrix; -namespace com.google.zxing.qrcode.detector -{ - - ///

This class attempts to find finder patterns in a QR Code. Finder patterns are the square - /// markers at three corners of a QR Code.

- /// - ///

This class is thread-safe but not reentrant. Each thread must allocate its own object. - /// - ///

- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public class FinderPatternFinder - { - virtual protected internal BitMatrix Image - { - get - { - return image; - } - - } - virtual protected internal System.Collections.ArrayList PossibleCenters - { - get - { - return possibleCenters; - } - - } - private int[] CrossCheckStateCount - { - get - { - crossCheckStateCount[0] = 0; - crossCheckStateCount[1] = 0; - crossCheckStateCount[2] = 0; - crossCheckStateCount[3] = 0; - crossCheckStateCount[4] = 0; - return crossCheckStateCount; - } - - } - - private const int CENTER_QUORUM = 2; - protected internal const int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center - protected internal const int MAX_MODULES = 57; // support up to version 10 for mobile clients - private const int INTEGER_MATH_SHIFT = 8; - - //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private BitMatrix image; - //UPGRADE_NOTE: Final was removed from the declaration of 'possibleCenters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private System.Collections.ArrayList possibleCenters; - private bool hasSkipped; - //UPGRADE_NOTE: Final was removed from the declaration of 'crossCheckStateCount '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private int[] crossCheckStateCount; - //UPGRADE_NOTE: Final was removed from the declaration of 'resultPointCallback '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ResultPointCallback resultPointCallback; - - ///

Creates a finder that will search the image for three finder patterns.

- /// - ///
- /// image to search - /// - public FinderPatternFinder(BitMatrix image):this(image, null) - { - } - - public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) - { - this.image = image; - this.possibleCenters = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); - this.crossCheckStateCount = new int[5]; - this.resultPointCallback = resultPointCallback; - } - - internal virtual FinderPatternInfo find(System.Collections.Hashtable hints) - { - bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); - int maxI = image.Height; - int maxJ = image.Width; - // We are looking for black/white/black/white/black modules in - // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far - - // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the - // image, and then account for the center being 3 modules in size. This gives the smallest - // number of pixels the center could be, so skip this often. When trying harder, look for all - // QR versions regardless of how dense they are. - int iSkip = (3 * maxI) / (4 * MAX_MODULES); - if (iSkip < MIN_SKIP || tryHarder) - { - iSkip = MIN_SKIP; - } - - bool done = false; - int[] stateCount = new int[5]; - for (int i = iSkip - 1; i < maxI && !done; i += iSkip) - { - // Get a row of black/white values - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - int currentState = 0; - for (int j = 0; j < maxJ; j++) - { - if (image.get_Renamed(j, i)) - { - // Black pixel - if ((currentState & 1) == 1) - { - // Counting white pixels - currentState++; - } - stateCount[currentState]++; - } - else - { - // White pixel - if ((currentState & 1) == 0) - { - // Counting black pixels - if (currentState == 4) - { - // A winner? - if (foundPatternCross(stateCount)) - { - // Yes - bool confirmed = handlePossibleCenter(stateCount, i, j); - if (confirmed) - { - // Start examining every other line. Checking each line turned out to be too - // expensive and didn't improve performance. - iSkip = 2; - if (hasSkipped) - { - done = haveMultiplyConfirmedCenters(); - } - else - { - int rowSkip = findRowSkip(); - if (rowSkip > stateCount[2]) - { - // Skip rows between row of lower confirmed center - // and top of presumed third confirmed center - // but back up a bit to get a full chance of detecting - // it, entire width of center of finder pattern - - // Skip by rowSkip, but back off by stateCount[2] (size of last center - // of pattern we saw) to be conservative, and also back off by iSkip which - // is about to be re-added - i += rowSkip - stateCount[2] - iSkip; - j = maxJ - 1; - } - } - } - else - { - // Advance to next black pixel - do - { - j++; - } - while (j < maxJ && !image.get_Renamed(j, i)); - j--; // back up to that last white pixel - } - // Clear state to start looking again - currentState = 0; - stateCount[0] = 0; - stateCount[1] = 0; - stateCount[2] = 0; - stateCount[3] = 0; - stateCount[4] = 0; - } - else - { - // No, shift counts back by two - stateCount[0] = stateCount[2]; - stateCount[1] = stateCount[3]; - stateCount[2] = stateCount[4]; - stateCount[3] = 1; - stateCount[4] = 0; - currentState = 3; - } - } - else - { - stateCount[++currentState]++; - } - } - else - { - // Counting white pixels - stateCount[currentState]++; - } - } - } - if (foundPatternCross(stateCount)) - { - bool confirmed = handlePossibleCenter(stateCount, i, maxJ); - if (confirmed) - { - iSkip = stateCount[0]; - if (hasSkipped) - { - // Found a third one - done = haveMultiplyConfirmedCenters(); - } - } - } - } - - FinderPattern[] patternInfo = selectBestPatterns(); - ResultPoint.orderBestPatterns(patternInfo); - - return new FinderPatternInfo(patternInfo); - } - - /// Given a count of black/white/black/white/black pixels just seen and an end position, - /// figures the location of the center of this run. - /// - private static float centerFromEnd(int[] stateCount, int end) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; - } - - /// count of black/white/black/white/black pixels just read - /// - /// true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios - /// used by finder patterns to be considered a match - /// - protected internal static bool foundPatternCross(int[] stateCount) - { - int totalModuleSize = 0; - for (int i = 0; i < 5; i++) - { - int count = stateCount[i]; - if (count == 0) - { - return false; - } - totalModuleSize += count; - } - if (totalModuleSize < 7) - { - return false; - } - int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; - int maxVariance = moduleSize / 2; - // Allow less than 50% variance from 1-1-3-1-1 proportions - return System.Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && System.Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; - } - - ///

After a horizontal scan finds a potential finder pattern, this method - /// "cross-checks" by scanning down vertically through the center of the possible - /// finder pattern to see if the same proportion is detected.

- /// - ///
- /// row where a finder pattern was detected - /// - /// center of the section that appears to cross a finder pattern - /// - /// maximum reasonable number of modules that should be - /// observed in any reading state, based on the results of the horizontal scan - /// - /// vertical center of finder pattern, or {@link Float#NaN} if not found - /// - private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) - { - BitMatrix image = this.image; - - int maxI = image.Height; - int[] stateCount = CrossCheckStateCount; - - // Start counting up from center - int i = startI; - while (i >= 0 && image.get_Renamed(centerJ, i)) - { - stateCount[2]++; - i--; - } - if (i < 0) - { - return System.Single.NaN; - } - while (i >= 0 && !image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount) - { - stateCount[1]++; - i--; - } - // If already too many modules in this state or ran off the edge: - if (i < 0 || stateCount[1] > maxCount) - { - return System.Single.NaN; - } - while (i >= 0 && image.get_Renamed(centerJ, i) && stateCount[0] <= maxCount) - { - stateCount[0]++; - i--; - } - if (stateCount[0] > maxCount) - { - return System.Single.NaN; - } - - // Now also count down from center - i = startI + 1; - while (i < maxI && image.get_Renamed(centerJ, i)) - { - stateCount[2]++; - i++; - } - if (i == maxI) - { - return System.Single.NaN; - } - while (i < maxI && !image.get_Renamed(centerJ, i) && stateCount[3] < maxCount) - { - stateCount[3]++; - i++; - } - if (i == maxI || stateCount[3] >= maxCount) - { - return System.Single.NaN; - } - while (i < maxI && image.get_Renamed(centerJ, i) && stateCount[4] < maxCount) - { - stateCount[4]++; - i++; - } - if (stateCount[4] >= maxCount) - { - return System.Single.NaN; - } - - // If we found a finder-pattern-like section, but its size is more than 40% different than - // the original, assume it's a false positive - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) - { - return System.Single.NaN; - } - - return foundPatternCross(stateCount)?centerFromEnd(stateCount, i):System.Single.NaN; - } - - ///

Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical, - /// except it reads horizontally instead of vertically. This is used to cross-cross - /// check a vertical cross check and locate the real center of the alignment pattern.

- ///
- private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) - { - BitMatrix image = this.image; - - int maxJ = image.Width; - int[] stateCount = CrossCheckStateCount; - - int j = startJ; - while (j >= 0 && image.get_Renamed(j, centerI)) - { - stateCount[2]++; - j--; - } - if (j < 0) - { - return System.Single.NaN; - } - while (j >= 0 && !image.get_Renamed(j, centerI) && stateCount[1] <= maxCount) - { - stateCount[1]++; - j--; - } - if (j < 0 || stateCount[1] > maxCount) - { - return System.Single.NaN; - } - while (j >= 0 && image.get_Renamed(j, centerI) && stateCount[0] <= maxCount) - { - stateCount[0]++; - j--; - } - if (stateCount[0] > maxCount) - { - return System.Single.NaN; - } - - j = startJ + 1; - while (j < maxJ && image.get_Renamed(j, centerI)) - { - stateCount[2]++; - j++; - } - if (j == maxJ) - { - return System.Single.NaN; - } - while (j < maxJ && !image.get_Renamed(j, centerI) && stateCount[3] < maxCount) - { - stateCount[3]++; - j++; - } - if (j == maxJ || stateCount[3] >= maxCount) - { - return System.Single.NaN; - } - while (j < maxJ && image.get_Renamed(j, centerI) && stateCount[4] < maxCount) - { - stateCount[4]++; - j++; - } - if (stateCount[4] >= maxCount) - { - return System.Single.NaN; - } - - // If we found a finder-pattern-like section, but its size is significantly different than - // the original, assume it's a false positive - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) - { - return System.Single.NaN; - } - - return foundPatternCross(stateCount)?centerFromEnd(stateCount, j):System.Single.NaN; - } - - ///

This is called when a horizontal scan finds a possible alignment pattern. It will - /// cross check with a vertical scan, and if successful, will, ah, cross-cross-check - /// with another horizontal scan. This is needed primarily to locate the real horizontal - /// center of the pattern in cases of extreme skew.

- /// - ///

If that succeeds the finder pattern location is added to a list that tracks - /// the number of times each location has been nearly-matched as a finder pattern. - /// Each additional find is more evidence that the location is in fact a finder - /// pattern center - /// - ///

- /// reading state module counts from horizontal scan - /// - /// row where finder pattern may be found - /// - /// end of possible finder pattern in row - /// - /// true if a finder pattern candidate was found this time - /// - protected internal virtual bool handlePossibleCenter(int[] stateCount, int i, int j) - { - int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; - float centerJ = centerFromEnd(stateCount, j); - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal); - if (!System.Single.IsNaN(centerI)) - { - // Re-cross check - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal); - if (!System.Single.IsNaN(centerJ)) - { - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float estimatedModuleSize = (float) stateCountTotal / 7.0f; - bool found = false; - int max = possibleCenters.Count; - for (int index = 0; index < max; index++) - { - FinderPattern center = (FinderPattern) possibleCenters[index]; - // Look for about the same center and module size: - if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) - { - center.incrementCount(); - found = true; - break; - } - } - if (!found) - { - ResultPoint point = new FinderPattern(centerJ, centerI, estimatedModuleSize); - possibleCenters.Add(point); - if (resultPointCallback != null) - { - resultPointCallback.foundPossibleResultPoint(point); - } - } - return true; - } - } - return false; - } - - /// number of rows we could safely skip during scanning, based on the first - /// two finder patterns that have been located. In some cases their position will - /// allow us to infer that the third pattern must lie below a certain point farther - /// down in the image. - /// - private int findRowSkip() - { - int max = possibleCenters.Count; - if (max <= 1) - { - return 0; - } - FinderPattern firstConfirmedCenter = null; - for (int i = 0; i < max; i++) - { - FinderPattern center = (FinderPattern) possibleCenters[i]; - if (center.Count >= CENTER_QUORUM) - { - if (firstConfirmedCenter == null) - { - firstConfirmedCenter = center; - } - else - { - // We have two confirmed centers - // How far down can we skip before resuming looking for the next - // pattern? In the worst case, only the difference between the - // difference in the x / y coordinates of the two centers. - // This is the case where you find top left last. - hasSkipped = true; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return (int) (System.Math.Abs(firstConfirmedCenter.X - center.X) - System.Math.Abs(firstConfirmedCenter.Y - center.Y)) / 2; - } - } - } - return 0; - } - - /// true iff we have found at least 3 finder patterns that have been detected - /// at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the - /// candidates is "pretty similar" - /// - private bool haveMultiplyConfirmedCenters() - { - int confirmedCount = 0; - float totalModuleSize = 0.0f; - int max = possibleCenters.Count; - for (int i = 0; i < max; i++) - { - FinderPattern pattern = (FinderPattern) possibleCenters[i]; - if (pattern.Count >= CENTER_QUORUM) - { - confirmedCount++; - totalModuleSize += pattern.EstimatedModuleSize; - } - } - if (confirmedCount < 3) - { - return false; - } - // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" - // and that we need to keep looking. We detect this by asking if the estimated module sizes - // vary too much. We arbitrarily say that when the total deviation from average exceeds - // 5% of the total module size estimates, it's too much. - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float average = totalModuleSize / (float) max; - float totalDeviation = 0.0f; - for (int i = 0; i < max; i++) - { - FinderPattern pattern = (FinderPattern) possibleCenters[i]; - totalDeviation += System.Math.Abs(pattern.EstimatedModuleSize - average); - } - return totalDeviation <= 0.05f * totalModuleSize; - } - - /// the 3 best {@link FinderPattern}s from our list of candidates. The "best" are - /// those that have been detected at least {@link #CENTER_QUORUM} times, and whose module - /// size differs from the average among those patterns the least - /// - /// ReaderException if 3 such finder patterns do not exist - private FinderPattern[] selectBestPatterns() - { - - int startSize = possibleCenters.Count; - if (startSize < 3) - { - // Couldn't find enough finder patterns - throw ReaderException.Instance; - } - - // Filter outlier possibilities whose module size is too different - if (startSize > 3) - { - // But we can only afford to do so if we have at least 4 possibilities to choose from - float totalModuleSize = 0.0f; - for (int i = 0; i < startSize; i++) - { - totalModuleSize += ((FinderPattern) possibleCenters[i]).EstimatedModuleSize; - } - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - float average = totalModuleSize / (float) startSize; - for (int i = 0; i < possibleCenters.Count && possibleCenters.Count > 3; i++) - { - FinderPattern pattern = (FinderPattern) possibleCenters[i]; - if (System.Math.Abs(pattern.EstimatedModuleSize - average) > 0.2f * average) - { - possibleCenters.RemoveAt(i); - i--; - } - } - } - - if (possibleCenters.Count > 3) - { - // Throw away all but those first size candidate points we found. - Collections.insertionSort(possibleCenters, new CenterComparator()); - SupportClass.SetCapacity(possibleCenters, 3); - } - - return new FinderPattern[]{(FinderPattern) possibleCenters[0], (FinderPattern) possibleCenters[1], (FinderPattern) possibleCenters[2]}; - } - - ///

Orders by {@link FinderPattern#getCount()}, descending.

- private class CenterComparator : Comparator - { - public virtual int compare(System.Object center1, System.Object center2) - { - return ((FinderPattern) center2).Count - ((FinderPattern) center1).Count; - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/detector/FinderPatternInfo.cs b/zxing-csharp/qrcode/detector/FinderPatternInfo.cs deleted file mode 100644 index eaa8dfa..0000000 --- a/zxing-csharp/qrcode/detector/FinderPatternInfo.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* -* Copyright 2007 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.qrcode.detector -{ - - ///

Encapsulates information about finder patterns in an image, including the location of - /// the three finder patterns, and their estimated module size.

- /// - ///
- /// Sean Owen - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class FinderPatternInfo - { - public FinderPattern BottomLeft - { - get - { - return bottomLeft; - } - - } - public FinderPattern TopLeft - { - get - { - return topLeft; - } - - } - public FinderPattern TopRight - { - get - { - return topRight; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'bottomLeft '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private FinderPattern bottomLeft; - //UPGRADE_NOTE: Final was removed from the declaration of 'topLeft '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private FinderPattern topLeft; - //UPGRADE_NOTE: Final was removed from the declaration of 'topRight '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private FinderPattern topRight; - - public FinderPatternInfo(FinderPattern[] patternCenters) - { - this.bottomLeft = patternCenters[0]; - this.topLeft = patternCenters[1]; - this.topRight = patternCenters[2]; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/encoder/BitVector.cs b/zxing-csharp/qrcode/encoder/BitVector.cs deleted file mode 100644 index 60ac22d..0000000 --- a/zxing-csharp/qrcode/encoder/BitVector.cs +++ /dev/null @@ -1,196 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -namespace com.google.zxing.qrcode.encoder -{ - - /// JAVAPORT: This should be combined with BitArray in the future, although that class is not yet - /// dynamically resizeable. This implementation is reasonable but there is a lot of function calling - /// in loops I'd like to get rid of. - /// - /// - /// satorux@google.com (Satoru Takabayashi) - creator - /// - /// dswitkin@google.com (Daniel Switkin) - ported from C++ - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class BitVector - { - public sbyte[] Array - { - // Callers should not assume that array.length is the exact number of bytes needed to hold - // sizeInBits - it will typically be larger for efficiency. - - get - { - return array; - } - - } - - private int sizeInBits; - private sbyte[] array; - - // For efficiency, start out with some room to work. - private const int DEFAULT_SIZE_IN_BYTES = 32; - - public BitVector() - { - sizeInBits = 0; - array = new sbyte[DEFAULT_SIZE_IN_BYTES]; - } - - // Return the bit value at "index". - public int at(int index) - { - if (index < 0 || index >= sizeInBits) - { - throw new System.ArgumentException("Bad index: " + index); - } - int value_Renamed = array[index >> 3] & 0xff; - return (value_Renamed >> (7 - (index & 0x7))) & 1; - } - - // Return the number of bits in the bit vector. - public int size() - { - return sizeInBits; - } - - // Return the number of bytes in the bit vector. - public int sizeInBytes() - { - return (sizeInBits + 7) >> 3; - } - - // Append one bit to the bit vector. - public void appendBit(int bit) - { - if (!(bit == 0 || bit == 1)) - { - throw new System.ArgumentException("Bad bit"); - } - int numBitsInLastByte = sizeInBits & 0x7; - // We'll expand array if we don't have bits in the last byte. - if (numBitsInLastByte == 0) - { - appendByte(0); - sizeInBits -= 8; - } - // Modify the last byte. - array[sizeInBits >> 3] |= (sbyte) ((bit << (7 - numBitsInLastByte))); - ++sizeInBits; - } - - // Append "numBits" bits in "value" to the bit vector. - // REQUIRES: 0<= numBits <= 32. - // - // Examples: - // - appendBits(0x00, 1) adds 0. - // - appendBits(0x00, 4) adds 0000. - // - appendBits(0xff, 8) adds 11111111. - public void appendBits(int value_Renamed, int numBits) - { - if (numBits < 0 || numBits > 32) - { - throw new System.ArgumentException("Num bits must be between 0 and 32"); - } - int numBitsLeft = numBits; - while (numBitsLeft > 0) - { - // Optimization for byte-oriented appending. - if ((sizeInBits & 0x7) == 0 && numBitsLeft >= 8) - { - int newByte = (value_Renamed >> (numBitsLeft - 8)) & 0xff; - appendByte(newByte); - numBitsLeft -= 8; - } - else - { - int bit = (value_Renamed >> (numBitsLeft - 1)) & 1; - appendBit(bit); - --numBitsLeft; - } - } - } - - // Append "bits". - public void appendBitVector(BitVector bits) - { - int size = bits.size(); - for (int i = 0; i < size; ++i) - { - appendBit(bits.at(i)); - } - } - - // Modify the bit vector by XOR'ing with "other" - public void xor(BitVector other) - { - if (sizeInBits != other.size()) - { - throw new System.ArgumentException("BitVector sizes don't match"); - } - int sizeInBytes = (sizeInBits + 7) >> 3; - for (int i = 0; i < sizeInBytes; ++i) - { - // The last byte could be incomplete (i.e. not have 8 bits in - // it) but there is no problem since 0 XOR 0 == 0. - array[i] ^= other.array[i]; - } - } - - // Return String like "01110111" for debugging. - public override System.String ToString() - { - System.Text.StringBuilder result = new System.Text.StringBuilder(sizeInBits); - for (int i = 0; i < sizeInBits; ++i) - { - if (at(i) == 0) - { - result.Append('0'); - } - else if (at(i) == 1) - { - result.Append('1'); - } - else - { - throw new System.ArgumentException("Byte isn't 0 or 1"); - } - } - return result.ToString(); - } - - // Add a new byte to the end, possibly reallocating and doubling the size of the array if we've - // run out of room. - private void appendByte(int value_Renamed) - { - if ((sizeInBits >> 3) == array.Length) - { - sbyte[] newArray = new sbyte[(array.Length << 1)]; - // Redivivus.in Java to c# Porting update - // 30/01/2010 - // added namespace system - System.Array.Copy(array, 0, newArray, 0, array.Length); - array = newArray; - } - array[sizeInBits >> 3] = (sbyte) value_Renamed; - sizeInBits += 8; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/encoder/BlockPair.cs b/zxing-csharp/qrcode/encoder/BlockPair.cs deleted file mode 100644 index 6f3a298..0000000 --- a/zxing-csharp/qrcode/encoder/BlockPair.cs +++ /dev/null @@ -1,51 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ByteArray = com.google.zxing.common.ByteArray; -namespace com.google.zxing.qrcode.encoder -{ - - sealed class BlockPair - { - public ByteArray DataBytes - { - get - { - return dataBytes; - } - - } - public ByteArray ErrorCorrectionBytes - { - get - { - return errorCorrectionBytes; - } - - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'dataBytes '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ByteArray dataBytes; - //UPGRADE_NOTE: Final was removed from the declaration of 'errorCorrectionBytes '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private ByteArray errorCorrectionBytes; - - internal BlockPair(ByteArray data, ByteArray errorCorrection) - { - dataBytes = data; - errorCorrectionBytes = errorCorrection; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/encoder/Encoder.cs b/zxing-csharp/qrcode/encoder/Encoder.cs deleted file mode 100644 index 19a51bf..0000000 --- a/zxing-csharp/qrcode/encoder/Encoder.cs +++ /dev/null @@ -1,642 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using WriterException = com.google.zxing.WriterException; -using EncodeHintType = com.google.zxing.EncodeHintType; -using ByteArray = com.google.zxing.common.ByteArray; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -using CharacterSetECI = com.google.zxing.common.CharacterSetECI; -using GF256 = com.google.zxing.common.reedsolomon.GF256; -using ReedSolomonEncoder = com.google.zxing.common.reedsolomon.ReedSolomonEncoder; -using ErrorCorrectionLevel = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; -using Mode = com.google.zxing.qrcode.decoder.Mode; -using Version = com.google.zxing.qrcode.decoder.Version; -namespace com.google.zxing.qrcode.encoder -{ - - /// satorux@google.com (Satoru Takabayashi) - creator - /// - /// dswitkin@google.com (Daniel Switkin) - ported from C++ - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class Encoder - { - - // The original table is defined in the table 5 of JISX0510:2004 (p.19). - //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_TABLE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[] ALPHANUMERIC_TABLE = new int[]{- 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, 36, - 1, - 1, - 1, 37, 38, - 1, - 1, - 1, - 1, 39, 40, - 1, 41, 42, 43, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, - 1, - 1, - 1, - 1, - 1, - 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 1, - 1, - 1, - 1, - 1}; - - internal const System.String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1"; - - private Encoder() - { - } - - // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details. - // Basically it applies four rules and summate all penalties. - private static int calculateMaskPenalty(ByteMatrix matrix) - { - int penalty = 0; - penalty += MaskUtil.applyMaskPenaltyRule1(matrix); - penalty += MaskUtil.applyMaskPenaltyRule2(matrix); - penalty += MaskUtil.applyMaskPenaltyRule3(matrix); - penalty += MaskUtil.applyMaskPenaltyRule4(matrix); - return penalty; - } - - /// Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen - /// internally by chooseMode(). On success, store the result in "qrCode". - /// - /// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for - /// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very - /// strong error correction for this purpose. - /// - /// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode() - /// with which clients can specify the encoding mode. For now, we don't need the functionality. - /// - public static void encode(System.String content, ErrorCorrectionLevel ecLevel, QRCode qrCode) - { - encode(content, ecLevel, null, qrCode); - } - - public static void encode(System.String content, ErrorCorrectionLevel ecLevel, System.Collections.Hashtable hints, QRCode qrCode) - { - - System.String encoding = hints == null?null:(System.String) hints[EncodeHintType.CHARACTER_SET]; - if (encoding == null) - { - encoding = DEFAULT_BYTE_MODE_ENCODING; - } - - // Step 1: Choose the mode (encoding). - Mode mode = chooseMode(content, encoding); - - // Step 2: Append "bytes" into "dataBits" in appropriate encoding. - BitVector dataBits = new BitVector(); - appendBytes(content, mode, dataBits, encoding); - // Step 3: Initialize QR code that can contain "dataBits". - int numInputBytes = dataBits.sizeInBytes(); - initQRCode(numInputBytes, ecLevel, mode, qrCode); - - // Step 4: Build another bit vector that contains header and data. - BitVector headerAndDataBits = new BitVector(); - - // Step 4.5: Append ECI message if applicable - if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding)) - { - CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding); - if (eci != null) - { - appendECI(eci, headerAndDataBits); - } - } - - appendModeInfo(mode, headerAndDataBits); - - int numLetters = mode.Equals(Mode.BYTE)?dataBits.sizeInBytes():content.Length; - appendLengthInfo(numLetters, qrCode.Version, mode, headerAndDataBits); - headerAndDataBits.appendBitVector(dataBits); - - // Step 5: Terminate the bits properly. - terminateBits(qrCode.NumDataBytes, headerAndDataBits); - - // Step 6: Interleave data bits with error correction code. - BitVector finalBits = new BitVector(); - interleaveWithECBytes(headerAndDataBits, qrCode.NumTotalBytes, qrCode.NumDataBytes, qrCode.NumRSBlocks, finalBits); - - // Step 7: Choose the mask pattern and set to "qrCode". - ByteMatrix matrix = new ByteMatrix(qrCode.MatrixWidth, qrCode.MatrixWidth); - qrCode.MaskPattern = chooseMaskPattern(finalBits, qrCode.ECLevel, qrCode.Version, matrix); - - // Step 8. Build the matrix and set it to "qrCode". - MatrixUtil.buildMatrix(finalBits, qrCode.ECLevel, qrCode.Version, qrCode.MaskPattern, matrix); - qrCode.Matrix = matrix; - // Step 9. Make sure we have a valid QR Code. - if (!qrCode.Valid) - { - throw new WriterException("Invalid QR code: " + qrCode.ToString()); - } - } - - /// the code point of the table used in alphanumeric mode or - /// -1 if there is no corresponding code in the table. - /// - internal static int getAlphanumericCode(int code) - { - if (code < ALPHANUMERIC_TABLE.Length) - { - return ALPHANUMERIC_TABLE[code]; - } - return - 1; - } - - public static Mode chooseMode(System.String content) - { - return chooseMode(content, null); - } - - /// Choose the best mode by examining the content. Note that 'encoding' is used as a hint; - /// if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}. - /// - public static Mode chooseMode(System.String content, System.String encoding) - { - if ("Shift_JIS".Equals(encoding)) - { - // Choose Kanji mode if all input are double-byte characters - return isOnlyDoubleByteKanji(content)?Mode.KANJI:Mode.BYTE; - } - bool hasNumeric = false; - bool hasAlphanumeric = false; - for (int i = 0; i < content.Length; ++i) - { - char c = content[i]; - if (c >= '0' && c <= '9') - { - hasNumeric = true; - } - else if (getAlphanumericCode(c) != - 1) - { - hasAlphanumeric = true; - } - else - { - return Mode.BYTE; - } - } - if (hasAlphanumeric) - { - return Mode.ALPHANUMERIC; - } - else if (hasNumeric) - { - return Mode.NUMERIC; - } - return Mode.BYTE; - } - - private static bool isOnlyDoubleByteKanji(System.String content) - { - sbyte[] bytes; - try - { - //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'" - bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(content)); - } - catch (System.IO.IOException uee) - { - return false; - } - int length = bytes.Length; - if (length % 2 != 0) - { - return false; - } - for (int i = 0; i < length; i += 2) - { - int byte1 = bytes[i] & 0xFF; - if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) - { - return false; - } - } - return true; - } - - private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version, ByteMatrix matrix) - { - - int minPenalty = System.Int32.MaxValue; // Lower penalty is better. - int bestMaskPattern = - 1; - // We try all mask patterns to choose the best one. - for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) - { - MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); - int penalty = calculateMaskPenalty(matrix); - if (penalty < minPenalty) - { - minPenalty = penalty; - bestMaskPattern = maskPattern; - } - } - return bestMaskPattern; - } - - /// Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success, - /// modify "qrCode". - /// - private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode) - { - qrCode.ECLevel = ecLevel; - qrCode.Mode = mode; - - // In the following comments, we use numbers of Version 7-H. - for (int versionNum = 1; versionNum <= 40; versionNum++) - { - Version version = Version.getVersionForNumber(versionNum); - // numBytes = 196 - int numBytes = version.TotalCodewords; - // getNumECBytes = 130 - Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); - int numEcBytes = ecBlocks.TotalECCodewords; - // getNumRSBlocks = 5 - int numRSBlocks = ecBlocks.NumBlocks; - // getNumDataBytes = 196 - 130 = 66 - int numDataBytes = numBytes - numEcBytes; - // We want to choose the smallest version which can contain data of "numInputBytes" + some - // extra bits for the header (mode info and length info). The header can be three bytes - // (precisely 4 + 16 bits) at most. Hence we do +3 here. - if (numDataBytes >= numInputBytes + 3) - { - // Yay, we found the proper rs block info! - qrCode.Version = versionNum; - qrCode.NumTotalBytes = numBytes; - qrCode.NumDataBytes = numDataBytes; - qrCode.NumRSBlocks = numRSBlocks; - // getNumECBytes = 196 - 66 = 130 - qrCode.NumECBytes = numEcBytes; - // matrix width = 21 + 6 * 4 = 45 - qrCode.MatrixWidth = version.DimensionForVersion; - return ; - } - } - throw new WriterException("Cannot find proper rs block info (input data too big?)"); - } - - /// Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24). - internal static void terminateBits(int numDataBytes, BitVector bits) - { - int capacity = numDataBytes << 3; - if (bits.size() > capacity) - { - throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); - } - // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. - // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if - // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes - // either way. - for (int i = 0; i < 4 && bits.size() < capacity; ++i) - { - bits.appendBit(0); - } - int numBitsInLastByte = bits.size() % 8; - // If the last byte isn't 8-bit aligned, we'll add padding bits. - if (numBitsInLastByte > 0) - { - int numPaddingBits = 8 - numBitsInLastByte; - for (int i = 0; i < numPaddingBits; ++i) - { - bits.appendBit(0); - } - } - // Should be 8-bit aligned here. - if (bits.size() % 8 != 0) - { - throw new WriterException("Number of bits is not a multiple of 8"); - } - // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). - int numPaddingBytes = numDataBytes - bits.sizeInBytes(); - for (int i = 0; i < numPaddingBytes; ++i) - { - if (i % 2 == 0) - { - bits.appendBits(0xec, 8); - } - else - { - bits.appendBits(0x11, 8); - } - } - if (bits.size() != capacity) - { - throw new WriterException("Bits size does not equal capacity"); - } - } - - /// Get number of data bytes and number of error correction bytes for block id "blockID". Store - /// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of - /// JISX0510:2004 (p.30) - /// - internal static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) - { - if (blockID >= numRSBlocks) - { - throw new WriterException("Block ID too large"); - } - // numRsBlocksInGroup2 = 196 % 5 = 1 - int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; - // numRsBlocksInGroup1 = 5 - 1 = 4 - int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; - // numTotalBytesInGroup1 = 196 / 5 = 39 - int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; - // numTotalBytesInGroup2 = 39 + 1 = 40 - int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; - // numDataBytesInGroup1 = 66 / 5 = 13 - int numDataBytesInGroup1 = numDataBytes / numRSBlocks; - // numDataBytesInGroup2 = 13 + 1 = 14 - int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; - // numEcBytesInGroup1 = 39 - 13 = 26 - int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; - // numEcBytesInGroup2 = 40 - 14 = 26 - int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; - // Sanity checks. - // 26 = 26 - if (numEcBytesInGroup1 != numEcBytesInGroup2) - { - throw new WriterException("EC bytes mismatch"); - } - // 5 = 4 + 1. - if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) - { - throw new WriterException("RS blocks mismatch"); - } - // 196 = (13 + 26) * 4 + (14 + 26) * 1 - if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) - { - throw new WriterException("Total bytes mismatch"); - } - - if (blockID < numRsBlocksInGroup1) - { - numDataBytesInBlock[0] = numDataBytesInGroup1; - numECBytesInBlock[0] = numEcBytesInGroup1; - } - else - { - numDataBytesInBlock[0] = numDataBytesInGroup2; - numECBytesInBlock[0] = numEcBytesInGroup2; - } - } - - /// Interleave "bits" with corresponding error correction bytes. On success, store the result in - /// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details. - /// - internal static void interleaveWithECBytes(BitVector bits, int numTotalBytes, int numDataBytes, int numRSBlocks, BitVector result) - { - - // "bits" must have "getNumDataBytes" bytes of data. - if (bits.sizeInBytes() != numDataBytes) - { - throw new WriterException("Number of bits and data bytes does not match"); - } - - // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll - // store the divided data bytes blocks and error correction bytes blocks into "blocks". - int dataBytesOffset = 0; - int maxNumDataBytes = 0; - int maxNumEcBytes = 0; - - // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. - System.Collections.ArrayList blocks = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(numRSBlocks)); - - for (int i = 0; i < numRSBlocks; ++i) - { - int[] numDataBytesInBlock = new int[1]; - int[] numEcBytesInBlock = new int[1]; - getNumDataBytesAndNumECBytesForBlockID(numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock); - - ByteArray dataBytes = new ByteArray(); - dataBytes.set_Renamed(bits.Array, dataBytesOffset, numDataBytesInBlock[0]); - ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); - blocks.Add(new BlockPair(dataBytes, ecBytes)); - - maxNumDataBytes = System.Math.Max(maxNumDataBytes, dataBytes.size()); - maxNumEcBytes = System.Math.Max(maxNumEcBytes, ecBytes.size()); - dataBytesOffset += numDataBytesInBlock[0]; - } - if (numDataBytes != dataBytesOffset) - { - throw new WriterException("Data bytes does not match offset"); - } - - // First, place data blocks. - for (int i = 0; i < maxNumDataBytes; ++i) - { - for (int j = 0; j < blocks.Count; ++j) - { - ByteArray dataBytes = ((BlockPair) blocks[j]).DataBytes; - if (i < dataBytes.size()) - { - result.appendBits(dataBytes.at(i), 8); - } - } - } - // Then, place error correction blocks. - for (int i = 0; i < maxNumEcBytes; ++i) - { - for (int j = 0; j < blocks.Count; ++j) - { - ByteArray ecBytes = ((BlockPair) blocks[j]).ErrorCorrectionBytes; - if (i < ecBytes.size()) - { - result.appendBits(ecBytes.at(i), 8); - } - } - } - if (numTotalBytes != result.sizeInBytes()) - { - // Should be same. - throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + " differ."); - } - } - - internal static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) - { - int numDataBytes = dataBytes.size(); - int[] toEncode = new int[numDataBytes + numEcBytesInBlock]; - for (int i = 0; i < numDataBytes; i++) - { - toEncode[i] = dataBytes.at(i); - } - new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock); - - ByteArray ecBytes = new ByteArray(numEcBytesInBlock); - for (int i = 0; i < numEcBytesInBlock; i++) - { - ecBytes.set_Renamed(i, toEncode[numDataBytes + i]); - } - return ecBytes; - } - - /// Append mode info. On success, store the result in "bits". - internal static void appendModeInfo(Mode mode, BitVector bits) - { - bits.appendBits(mode.Bits, 4); - } - - - /// Append length info. On success, store the result in "bits". - internal static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits) - { - int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version)); - if (numLetters > ((1 << numBits) - 1)) - { - throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1)); - } - bits.appendBits(numLetters, numBits); - } - - /// Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits". - internal static void appendBytes(System.String content, Mode mode, BitVector bits, System.String encoding) - { - if (mode.Equals(Mode.NUMERIC)) - { - appendNumericBytes(content, bits); - } - else if (mode.Equals(Mode.ALPHANUMERIC)) - { - appendAlphanumericBytes(content, bits); - } - else if (mode.Equals(Mode.BYTE)) - { - append8BitBytes(content, bits, encoding); - } - else if (mode.Equals(Mode.KANJI)) - { - appendKanjiBytes(content, bits); - } - else - { - throw new WriterException("Invalid mode: " + mode); - } - } - - internal static void appendNumericBytes(System.String content, BitVector bits) - { - int length = content.Length; - int i = 0; - while (i < length) - { - int num1 = content[i] - '0'; - if (i + 2 < length) - { - // Encode three numeric letters in ten bits. - int num2 = content[i + 1] - '0'; - int num3 = content[i + 2] - '0'; - bits.appendBits(num1 * 100 + num2 * 10 + num3, 10); - i += 3; - } - else if (i + 1 < length) - { - // Encode two numeric letters in seven bits. - int num2 = content[i + 1] - '0'; - bits.appendBits(num1 * 10 + num2, 7); - i += 2; - } - else - { - // Encode one numeric letter in four bits. - bits.appendBits(num1, 4); - i++; - } - } - } - - internal static void appendAlphanumericBytes(System.String content, BitVector bits) - { - int length = content.Length; - int i = 0; - while (i < length) - { - int code1 = getAlphanumericCode(content[i]); - if (code1 == - 1) - { - throw new WriterException(); - } - if (i + 1 < length) - { - int code2 = getAlphanumericCode(content[i + 1]); - if (code2 == - 1) - { - throw new WriterException(); - } - // Encode two alphanumeric letters in 11 bits. - bits.appendBits(code1 * 45 + code2, 11); - i += 2; - } - else - { - // Encode one alphanumeric letter in six bits. - bits.appendBits(code1, 6); - i++; - } - } - } - - internal static void append8BitBytes(System.String content, BitVector bits, System.String encoding) - { - sbyte[] bytes; - try - { - //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'" - bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding(encoding).GetBytes(content)); - } - catch (System.IO.IOException uee) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new WriterException(uee.ToString()); - } - for (int i = 0; i < bytes.Length; ++i) - { - bits.appendBits(bytes[i], 8); - } - } - - internal static void appendKanjiBytes(System.String content, BitVector bits) - { - sbyte[] bytes; - try - { - //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'" - bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(content)); - } - catch (System.IO.IOException uee) - { - //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" - throw new WriterException(uee.ToString()); - } - int length = bytes.Length; - for (int i = 0; i < length; i += 2) - { - int byte1 = bytes[i] & 0xFF; - int byte2 = bytes[i + 1] & 0xFF; - int code = (byte1 << 8) | byte2; - int subtracted = - 1; - if (code >= 0x8140 && code <= 0x9ffc) - { - subtracted = code - 0x8140; - } - else if (code >= 0xe040 && code <= 0xebbf) - { - subtracted = code - 0xc140; - } - if (subtracted == - 1) - { - throw new WriterException("Invalid byte sequence"); - } - int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); - bits.appendBits(encoded, 13); - } - } - - private static void appendECI(CharacterSetECI eci, BitVector bits) - { - bits.appendBits(Mode.ECI.Bits, 4); - // This is correct for values up to 127, which is all we need now. - bits.appendBits(eci.Value, 8); - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/encoder/MaskUtil.cs b/zxing-csharp/qrcode/encoder/MaskUtil.cs deleted file mode 100644 index e561171..0000000 --- a/zxing-csharp/qrcode/encoder/MaskUtil.cs +++ /dev/null @@ -1,226 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -namespace com.google.zxing.qrcode.encoder -{ - - /// satorux@google.com (Satoru Takabayashi) - creator - /// - /// dswitkin@google.com (Daniel Switkin) - ported from C++ - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class MaskUtil - { - - private MaskUtil() - { - // do nothing - } - - // Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and - // give penalty to them. Example: 00000 or 11111. - public static int applyMaskPenaltyRule1(ByteMatrix matrix) - { - return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false); - } - - // Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give - // penalty to them. - public static int applyMaskPenaltyRule2(ByteMatrix matrix) - { - int penalty = 0; - sbyte[][] array = matrix.Array; - int width = matrix.Width; - int height = matrix.Height; - for (int y = 0; y < height - 1; ++y) - { - for (int x = 0; x < width - 1; ++x) - { - int value_Renamed = array[y][x]; - if (value_Renamed == array[y][x + 1] && value_Renamed == array[y + 1][x] && value_Renamed == array[y + 1][x + 1]) - { - penalty += 3; - } - } - } - return penalty; - } - - // Apply mask penalty rule 3 and return the penalty. Find consecutive cells of 00001011101 or - // 10111010000, and give penalty to them. If we find patterns like 000010111010000, we give - // penalties twice (i.e. 40 * 2). - public static int applyMaskPenaltyRule3(ByteMatrix matrix) - { - int penalty = 0; - sbyte[][] array = matrix.Array; - int width = matrix.Width; - int height = matrix.Height; - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - // Tried to simplify following conditions but failed. - if (x + 6 < width && array[y][x] == 1 && array[y][x + 1] == 0 && array[y][x + 2] == 1 && array[y][x + 3] == 1 && array[y][x + 4] == 1 && array[y][x + 5] == 0 && array[y][x + 6] == 1 && ((x + 10 < width && array[y][x + 7] == 0 && array[y][x + 8] == 0 && array[y][x + 9] == 0 && array[y][x + 10] == 0) || (x - 4 >= 0 && array[y][x - 1] == 0 && array[y][x - 2] == 0 && array[y][x - 3] == 0 && array[y][x - 4] == 0))) - { - penalty += 40; - } - if (y + 6 < height && array[y][x] == 1 && array[y + 1][x] == 0 && array[y + 2][x] == 1 && array[y + 3][x] == 1 && array[y + 4][x] == 1 && array[y + 5][x] == 0 && array[y + 6][x] == 1 && ((y + 10 < height && array[y + 7][x] == 0 && array[y + 8][x] == 0 && array[y + 9][x] == 0 && array[y + 10][x] == 0) || (y - 4 >= 0 && array[y - 1][x] == 0 && array[y - 2][x] == 0 && array[y - 3][x] == 0 && array[y - 4][x] == 0))) - { - penalty += 40; - } - } - } - return penalty; - } - - // Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give - // penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance. Examples: - // - 0% => 100 - // - 40% => 20 - // - 45% => 10 - // - 50% => 0 - // - 55% => 10 - // - 55% => 20 - // - 100% => 100 - public static int applyMaskPenaltyRule4(ByteMatrix matrix) - { - int numDarkCells = 0; - sbyte[][] array = matrix.Array; - int width = matrix.Width; - int height = matrix.Height; - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - if (array[y][x] == 1) - { - numDarkCells += 1; - } - } - } - int numTotalCells = matrix.Height * matrix.Width; - double darkRatio = (double) numDarkCells / numTotalCells; - //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" - return System.Math.Abs((int) (darkRatio * 100 - 50)) / 5 * 10; - } - - // Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask - // pattern conditions. - public static bool getDataMaskBit(int maskPattern, int x, int y) - { - if (!QRCode.isValidMaskPattern(maskPattern)) - { - throw new System.ArgumentException("Invalid mask pattern"); - } - int intermediate, temp; - switch (maskPattern) - { - - case 0: - intermediate = (y + x) & 0x1; - break; - - case 1: - intermediate = y & 0x1; - break; - - case 2: - intermediate = x % 3; - break; - - case 3: - intermediate = (y + x) % 3; - break; - - case 4: - intermediate = ((SupportClass.URShift(y, 1)) + (x / 3)) & 0x1; - break; - - case 5: - temp = y * x; - intermediate = (temp & 0x1) + (temp % 3); - break; - - case 6: - temp = y * x; - intermediate = (((temp & 0x1) + (temp % 3)) & 0x1); - break; - - case 7: - temp = y * x; - intermediate = (((temp % 3) + ((y + x) & 0x1)) & 0x1); - break; - - default: - throw new System.ArgumentException("Invalid mask pattern: " + maskPattern); - - } - return intermediate == 0; - } - - // Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both - // vertical and horizontal orders respectively. - private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, bool isHorizontal) - { - int penalty = 0; - int numSameBitCells = 0; - int prevBit = - 1; - // Horizontal mode: - // for (int i = 0; i < matrix.height(); ++i) { - // for (int j = 0; j < matrix.width(); ++j) { - // int bit = matrix.get(i, j); - // Vertical mode: - // for (int i = 0; i < matrix.width(); ++i) { - // for (int j = 0; j < matrix.height(); ++j) { - // int bit = matrix.get(j, i); - int iLimit = isHorizontal?matrix.Height:matrix.Width; - int jLimit = isHorizontal?matrix.Width:matrix.Height; - sbyte[][] array = matrix.Array; - for (int i = 0; i < iLimit; ++i) - { - for (int j = 0; j < jLimit; ++j) - { - int bit = isHorizontal?array[i][j]:array[j][i]; - if (bit == prevBit) - { - numSameBitCells += 1; - // Found five repetitive cells with the same color (bit). - // We'll give penalty of 3. - if (numSameBitCells == 5) - { - penalty += 3; - } - else if (numSameBitCells > 5) - { - // After five repetitive cells, we'll add the penalty one - // by one. - penalty += 1; - } - } - else - { - numSameBitCells = 1; // Include the cell itself. - prevBit = bit; - } - } - numSameBitCells = 0; // Clear at each row/column. - } - return penalty; - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/encoder/MatrixUtil.cs b/zxing-csharp/qrcode/encoder/MatrixUtil.cs deleted file mode 100644 index b461a66..0000000 --- a/zxing-csharp/qrcode/encoder/MatrixUtil.cs +++ /dev/null @@ -1,518 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using WriterException = com.google.zxing.WriterException; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -using ErrorCorrectionLevel = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; -namespace com.google.zxing.qrcode.encoder -{ - - /// satorux@google.com (Satoru Takabayashi) - creator - /// - /// dswitkin@google.com (Daniel Switkin) - ported from C++ - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class MatrixUtil - { - - private MatrixUtil() - { - // do nothing - } - - //UPGRADE_NOTE: Final was removed from the declaration of 'POSITION_DETECTION_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] POSITION_DETECTION_PATTERN = new int[][]{new int[]{1, 1, 1, 1, 1, 1, 1}, new int[]{1, 0, 0, 0, 0, 0, 1}, new int[]{1, 0, 1, 1, 1, 0, 1}, new int[]{1, 0, 1, 1, 1, 0, 1}, new int[]{1, 0, 1, 1, 1, 0, 1}, new int[]{1, 0, 0, 0, 0, 0, 1}, new int[]{1, 1, 1, 1, 1, 1, 1}}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'HORIZONTAL_SEPARATION_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] HORIZONTAL_SEPARATION_PATTERN = new int[][]{new int[]{0, 0, 0, 0, 0, 0, 0, 0}}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'VERTICAL_SEPARATION_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] VERTICAL_SEPARATION_PATTERN = new int[][]{new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0}}; - - //UPGRADE_NOTE: Final was removed from the declaration of 'POSITION_ADJUSTMENT_PATTERN'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] POSITION_ADJUSTMENT_PATTERN = new int[][]{new int[]{1, 1, 1, 1, 1}, new int[]{1, 0, 0, 0, 1}, new int[]{1, 0, 1, 0, 1}, new int[]{1, 0, 0, 0, 1}, new int[]{1, 1, 1, 1, 1}}; - - // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu. - //UPGRADE_NOTE: Final was removed from the declaration of 'POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = new int[][]{new int[]{- 1, - 1, - 1, - 1, - 1, - 1, - 1}, new int[]{6, 18, - 1, - 1, - 1, - 1, - 1}, new int[]{6, 22, - 1, - 1, - 1, - 1, - 1}, new int[]{6, 26, - 1, - 1, - 1, - 1, - 1}, new int[]{6, 30, - 1, - 1, - 1, - 1, - 1}, new int[]{6, 34, - 1, - 1, - 1, - 1, - 1}, new int[]{6, 22, 38, - 1, - 1, - 1, - 1}, new int[]{6, 24, 42, - 1, - 1, - 1, - 1}, new int[]{6, 26, 46, - 1, - 1, - 1, - 1}, new int[]{6, 28, 50, - 1, - 1, - 1, - 1}, new int[]{6, 30, 54, - 1, - 1, - 1, - 1}, new int[]{6, 32, 58, - 1, - 1, - 1, - 1}, new int[]{6, 34, 62, - 1, - 1, - 1, - 1}, new int[]{6, 26, 46, 66, - 1, - 1, - 1}, new int[]{6, 26, 48, 70, - 1, - 1, - 1}, new int[]{6, 26, 50, 74, - 1, - 1, - 1}, new int[]{6, 30, 54, 78, - 1, - 1, - 1}, new int[]{6, 30, 56, 82, - 1, - 1, - 1}, new int[]{6, 30, 58, 86, - 1, - 1, - 1}, new int[]{6, 34, 62, 90, - 1, - 1, - 1}, new int[]{6, 28, 50, 72, 94, - 1, - 1}, new int[]{6, 26, 50, 74, 98, - 1, - 1}, new int[]{6, 30, 54, 78, 102, - 1, - 1}, new int[]{6, 28, 54, 80, 106, - 1, - 1}, new int[]{6, 32, 58, 84, 110, - 1, - 1}, new int[]{6, 30, 58, 86, 114, - 1, - 1}, new int[]{6, 34, 62, 90, 118, - 1, - 1}, new int[]{6, 26, 50, 74, 98, 122, - 1}, new int[]{6, 30, 54, 78, 102, 126, - 1}, new int[]{6, 26, 52, 78, 104, 130, - 1}, new int[]{6, 30, 56, 82, 108, 134, - 1}, new int[]{6, 34, 60, 86, 112, 138, - 1}, new int[]{6, 30, 58, 86, 114, 142, - 1}, new int[]{6, 34, 62, 90, 118, 146, - 1}, new int[]{6, 30, 54, 78, 102, 126, 150}, new int[]{6, 24, 50, 76, 102, 128, 154}, new int[]{6, 28, 54, 80, 106, 132, 158}, new int[]{6, 32, 58, 84, 110, 136, 162}, new int[]{6, 26, 54, 82, 110, 138, 166}, new int[]{6, 30, 58, 86, 114, 142, 170}}; - - // Type info cells at the left top corner. - //UPGRADE_NOTE: Final was removed from the declaration of 'TYPE_INFO_COORDINATES'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" - private static readonly int[][] TYPE_INFO_COORDINATES = new int[][]{new int[]{8, 0}, new int[]{8, 1}, new int[]{8, 2}, new int[]{8, 3}, new int[]{8, 4}, new int[]{8, 5}, new int[]{8, 7}, new int[]{8, 8}, new int[]{7, 8}, new int[]{5, 8}, new int[]{4, 8}, new int[]{3, 8}, new int[]{2, 8}, new int[]{1, 8}, new int[]{0, 8}}; - - // From Appendix D in JISX0510:2004 (p. 67) - private const int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101 - - // From Appendix C in JISX0510:2004 (p.65). - private const int TYPE_INFO_POLY = 0x537; - private const int TYPE_INFO_MASK_PATTERN = 0x5412; - - // Set all cells to -1. -1 means that the cell is empty (not set yet). - // - // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding - // with the ByteMatrix initialized all to zero. - public static void clearMatrix(ByteMatrix matrix) - { - matrix.clear((sbyte) (- 1)); - } - - // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On - // success, store the result in "matrix" and return true. - public static void buildMatrix(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version, int maskPattern, ByteMatrix matrix) - { - clearMatrix(matrix); - embedBasicPatterns(version, matrix); - // Type information appear with any version. - embedTypeInfo(ecLevel, maskPattern, matrix); - // Version info appear if version >= 7. - maybeEmbedVersionInfo(version, matrix); - // Data should be embedded at end. - embedDataBits(dataBits, maskPattern, matrix); - } - - // Embed basic patterns. On success, modify the matrix and return true. - // The basic patterns are: - // - Position detection patterns - // - Timing patterns - // - Dark dot at the left bottom corner - // - Position adjustment patterns, if need be - public static void embedBasicPatterns(int version, ByteMatrix matrix) - { - // Let's get started with embedding big squares at corners. - embedPositionDetectionPatternsAndSeparators(matrix); - // Then, embed the dark dot at the left bottom corner. - embedDarkDotAtLeftBottomCorner(matrix); - - // Position adjustment patterns appear if version >= 2. - maybeEmbedPositionAdjustmentPatterns(version, matrix); - // Timing patterns should be embedded after position adj. patterns. - embedTimingPatterns(matrix); - } - - // Embed type information. On success, modify the matrix. - public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) - { - BitVector typeInfoBits = new BitVector(); - makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); - - for (int i = 0; i < typeInfoBits.size(); ++i) - { - // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in - // "typeInfoBits". - int bit = typeInfoBits.at(typeInfoBits.size() - 1 - i); - - // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). - int x1 = TYPE_INFO_COORDINATES[i][0]; - int y1 = TYPE_INFO_COORDINATES[i][1]; - matrix.set_Renamed(x1, y1, bit); - - if (i < 8) - { - // Right top corner. - int x2 = matrix.Width - i - 1; - int y2 = 8; - matrix.set_Renamed(x2, y2, bit); - } - else - { - // Left bottom corner. - int x2 = 8; - int y2 = matrix.Height - 7 + (i - 8); - matrix.set_Renamed(x2, y2, bit); - } - } - } - - // Embed version information if need be. On success, modify the matrix and return true. - // See 8.10 of JISX0510:2004 (p.47) for how to embed version information. - public static void maybeEmbedVersionInfo(int version, ByteMatrix matrix) - { - if (version < 7) - { - // Version info is necessary if version >= 7. - return ; // Don't need version info. - } - BitVector versionInfoBits = new BitVector(); - makeVersionInfoBits(version, versionInfoBits); - - int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. - for (int i = 0; i < 6; ++i) - { - for (int j = 0; j < 3; ++j) - { - // Place bits in LSB (least significant bit) to MSB order. - int bit = versionInfoBits.at(bitIndex); - bitIndex--; - // Left bottom corner. - matrix.set_Renamed(i, matrix.Height - 11 + j, bit); - // Right bottom corner. - matrix.set_Renamed(matrix.Height - 11 + j, i, bit); - } - } - } - - // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. - // For debugging purposes, it skips masking process if "getMaskPattern" is -1. - // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. - public static void embedDataBits(BitVector dataBits, int maskPattern, ByteMatrix matrix) - { - int bitIndex = 0; - int direction = - 1; - // Start from the right bottom cell. - int x = matrix.Width - 1; - int y = matrix.Height - 1; - while (x > 0) - { - // Skip the vertical timing pattern. - if (x == 6) - { - x -= 1; - } - while (y >= 0 && y < matrix.Height) - { - for (int i = 0; i < 2; ++i) - { - int xx = x - i; - // Skip the cell if it's not empty. - if (!isEmpty(matrix.get_Renamed(xx, y))) - { - continue; - } - int bit; - if (bitIndex < dataBits.size()) - { - bit = dataBits.at(bitIndex); - ++bitIndex; - } - else - { - // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described - // in 8.4.9 of JISX0510:2004 (p. 24). - bit = 0; - } - - // Skip masking if mask_pattern is -1. - if (maskPattern != - 1) - { - if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) - { - bit ^= 0x1; - } - } - matrix.set_Renamed(xx, y, bit); - } - y += direction; - } - direction = - direction; // Reverse the direction. - y += direction; - x -= 2; // Move to the left. - } - // All bits should be consumed. - if (bitIndex != dataBits.size()) - { - throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size()); - } - } - - // Return the position of the most significant bit set (to one) in the "value". The most - // significant bit is position 32. If there is no bit set, return 0. Examples: - // - findMSBSet(0) => 0 - // - findMSBSet(1) => 1 - // - findMSBSet(255) => 8 - public static int findMSBSet(int value_Renamed) - { - int numDigits = 0; - while (value_Renamed != 0) - { - value_Renamed = SupportClass.URShift(value_Renamed, 1); - ++numDigits; - } - return numDigits; - } - - // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH - // code is used for encoding type information and version information. - // Example: Calculation of version information of 7. - // f(x) is created from 7. - // - 7 = 000111 in 6 bits - // - f(x) = x^2 + x^2 + x^1 - // g(x) is given by the standard (p. 67) - // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 - // Multiply f(x) by x^(18 - 6) - // - f'(x) = f(x) * x^(18 - 6) - // - f'(x) = x^14 + x^13 + x^12 - // Calculate the remainder of f'(x) / g(x) - // x^2 - // __________________________________________________ - // g(x) )x^14 + x^13 + x^12 - // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2 - // -------------------------------------------------- - // x^11 + x^10 + x^7 + x^4 + x^2 - // - // The remainder is x^11 + x^10 + x^7 + x^4 + x^2 - // Encode it in binary: 110010010100 - // The return value is 0xc94 (1100 1001 0100) - // - // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit - // operations. We don't care if cofficients are positive or negative. - public static int calculateBCHCode(int value_Renamed, int poly) - { - // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 - // from 13 to make it 12. - int msbSetInPoly = findMSBSet(poly); - value_Renamed <<= msbSetInPoly - 1; - // Do the division business using exclusive-or operations. - while (findMSBSet(value_Renamed) >= msbSetInPoly) - { - value_Renamed ^= poly << (findMSBSet(value_Renamed) - msbSetInPoly); - } - // Now the "value" is the remainder (i.e. the BCH code) - return value_Renamed; - } - - // Make bit vector of type information. On success, store the result in "bits" and return true. - // Encode error correction level and mask pattern. See 8.9 of - // JISX0510:2004 (p.45) for details. - public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits) - { - if (!QRCode.isValidMaskPattern(maskPattern)) - { - throw new WriterException("Invalid mask pattern"); - } - int typeInfo = (ecLevel.Bits << 3) | maskPattern; - bits.appendBits(typeInfo, 5); - - int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); - bits.appendBits(bchCode, 10); - - BitVector maskBits = new BitVector(); - maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); - bits.xor(maskBits); - - if (bits.size() != 15) - { - // Just in case. - throw new WriterException("should not happen but we got: " + bits.size()); - } - } - - // Make bit vector of version information. On success, store the result in "bits" and return true. - // See 8.10 of JISX0510:2004 (p.45) for details. - public static void makeVersionInfoBits(int version, BitVector bits) - { - bits.appendBits(version, 6); - int bchCode = calculateBCHCode(version, VERSION_INFO_POLY); - bits.appendBits(bchCode, 12); - - if (bits.size() != 18) - { - // Just in case. - throw new WriterException("should not happen but we got: " + bits.size()); - } - } - - // Check if "value" is empty. - private static bool isEmpty(int value_Renamed) - { - return value_Renamed == - 1; - } - - // Check if "value" is valid. - private static bool isValidValue(int value_Renamed) - { - return (value_Renamed == - 1 || value_Renamed == 0 || value_Renamed == 1); // Dark (black). - } - - private static void embedTimingPatterns(ByteMatrix matrix) - { - // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical - // separation patterns (size 1). Thus, 8 = 7 + 1. - for (int i = 8; i < matrix.Width - 8; ++i) - { - int bit = (i + 1) % 2; - // Horizontal line. - if (!isValidValue(matrix.get_Renamed(i, 6))) - { - throw new WriterException(); - } - if (isEmpty(matrix.get_Renamed(i, 6))) - { - matrix.set_Renamed(i, 6, bit); - } - // Vertical line. - if (!isValidValue(matrix.get_Renamed(6, i))) - { - throw new WriterException(); - } - if (isEmpty(matrix.get_Renamed(6, i))) - { - matrix.set_Renamed(6, i, bit); - } - } - } - - // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) - private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) - { - if (matrix.get_Renamed(8, matrix.Height - 8) == 0) - { - throw new WriterException(); - } - matrix.set_Renamed(8, matrix.Height - 8, 1); - } - - private static void embedHorizontalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) - { - // We know the width and height. - if (HORIZONTAL_SEPARATION_PATTERN[0].Length != 8 || HORIZONTAL_SEPARATION_PATTERN.Length != 1) - { - throw new WriterException("Bad horizontal separation pattern"); - } - for (int x = 0; x < 8; ++x) - { - if (!isEmpty(matrix.get_Renamed(xStart + x, yStart))) - { - throw new WriterException(); - } - matrix.set_Renamed(xStart + x, yStart, HORIZONTAL_SEPARATION_PATTERN[0][x]); - } - } - - private static void embedVerticalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) - { - // We know the width and height. - if (VERTICAL_SEPARATION_PATTERN[0].Length != 1 || VERTICAL_SEPARATION_PATTERN.Length != 7) - { - throw new WriterException("Bad vertical separation pattern"); - } - for (int y = 0; y < 7; ++y) - { - if (!isEmpty(matrix.get_Renamed(xStart, yStart + y))) - { - throw new WriterException(); - } - matrix.set_Renamed(xStart, yStart + y, VERTICAL_SEPARATION_PATTERN[y][0]); - } - } - - // Note that we cannot unify the function with embedPositionDetectionPattern() despite they are - // almost identical, since we cannot write a function that takes 2D arrays in different sizes in - // C/C++. We should live with the fact. - private static void embedPositionAdjustmentPattern(int xStart, int yStart, ByteMatrix matrix) - { - // We know the width and height. - if (POSITION_ADJUSTMENT_PATTERN[0].Length != 5 || POSITION_ADJUSTMENT_PATTERN.Length != 5) - { - throw new WriterException("Bad position adjustment"); - } - for (int y = 0; y < 5; ++y) - { - for (int x = 0; x < 5; ++x) - { - if (!isEmpty(matrix.get_Renamed(xStart + x, yStart + y))) - { - throw new WriterException(); - } - matrix.set_Renamed(xStart + x, yStart + y, POSITION_ADJUSTMENT_PATTERN[y][x]); - } - } - } - - private static void embedPositionDetectionPattern(int xStart, int yStart, ByteMatrix matrix) - { - // We know the width and height. - if (POSITION_DETECTION_PATTERN[0].Length != 7 || POSITION_DETECTION_PATTERN.Length != 7) - { - throw new WriterException("Bad position detection pattern"); - } - for (int y = 0; y < 7; ++y) - { - for (int x = 0; x < 7; ++x) - { - if (!isEmpty(matrix.get_Renamed(xStart + x, yStart + y))) - { - throw new WriterException(); - } - matrix.set_Renamed(xStart + x, yStart + y, POSITION_DETECTION_PATTERN[y][x]); - } - } - } - - // Embed position detection patterns and surrounding vertical/horizontal separators. - private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) - { - // Embed three big squares at corners. - int pdpWidth = POSITION_DETECTION_PATTERN[0].Length; - // Left top corner. - embedPositionDetectionPattern(0, 0, matrix); - // Right top corner. - embedPositionDetectionPattern(matrix.Width - pdpWidth, 0, matrix); - // Left bottom corner. - embedPositionDetectionPattern(0, matrix.Width - pdpWidth, matrix); - - // Embed horizontal separation patterns around the squares. - int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].Length; - // Left top corner. - embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); - // Right top corner. - embedHorizontalSeparationPattern(matrix.Width - hspWidth, hspWidth - 1, matrix); - // Left bottom corner. - embedHorizontalSeparationPattern(0, matrix.Width - hspWidth, matrix); - - // Embed vertical separation patterns around the squares. - int vspSize = VERTICAL_SEPARATION_PATTERN.Length; - // Left top corner. - embedVerticalSeparationPattern(vspSize, 0, matrix); - // Right top corner. - embedVerticalSeparationPattern(matrix.Height - vspSize - 1, 0, matrix); - // Left bottom corner. - embedVerticalSeparationPattern(vspSize, matrix.Height - vspSize, matrix); - } - - // Embed position adjustment patterns if need be. - private static void maybeEmbedPositionAdjustmentPatterns(int version, ByteMatrix matrix) - { - if (version < 2) - { - // The patterns appear if version >= 2 - return ; - } - int index = version - 1; - int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; - int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].Length; - for (int i = 0; i < numCoordinates; ++i) - { - for (int j = 0; j < numCoordinates; ++j) - { - int y = coordinates[i]; - int x = coordinates[j]; - if (x == - 1 || y == - 1) - { - continue; - } - // If the cell is unset, we embed the position adjustment pattern here. - if (isEmpty(matrix.get_Renamed(x, y))) - { - // -2 is necessary since the x/y coordinates point to the center of the pattern, not the - // left top corner. - embedPositionAdjustmentPattern(x - 2, y - 2, matrix); - } - } - } - } - } -} \ No newline at end of file diff --git a/zxing-csharp/qrcode/encoder/QRCode.cs b/zxing-csharp/qrcode/encoder/QRCode.cs deleted file mode 100644 index 972fd02..0000000 --- a/zxing-csharp/qrcode/encoder/QRCode.cs +++ /dev/null @@ -1,299 +0,0 @@ -/* -* Copyright 2008 ZXing authors -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -using System; -using ByteMatrix = com.google.zxing.common.ByteMatrix; -using ErrorCorrectionLevel = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; -using Mode = com.google.zxing.qrcode.decoder.Mode; -namespace com.google.zxing.qrcode.encoder -{ - - /// satorux@google.com (Satoru Takabayashi) - creator - /// - /// dswitkin@google.com (Daniel Switkin) - ported from C++ - /// - /// www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source - /// - public sealed class QRCode - { - public Mode Mode - { - // Mode of the QR Code. - - get - { - return mode; - } - - set - { - mode = value; - } - - } - public ErrorCorrectionLevel ECLevel - { - // Error correction level of the QR Code. - - get - { - return ecLevel; - } - - set - { - ecLevel = value; - } - - } - public int Version - { - // Version of the QR Code. The bigger size, the bigger version. - - get - { - return version; - } - - set - { - version = value; - } - - } - public int MatrixWidth - { - // ByteMatrix width of the QR Code. - - get - { - return matrixWidth; - } - - set - { - matrixWidth = value; - } - - } - public int MaskPattern - { - // Mask pattern of the QR Code. - - get - { - return maskPattern; - } - - set - { - maskPattern = value; - } - - } - public int NumTotalBytes - { - // Number of total bytes in the QR Code. - - get - { - return numTotalBytes; - } - - set - { - numTotalBytes = value; - } - - } - public int NumDataBytes - { - // Number of data bytes in the QR Code. - - get - { - return numDataBytes; - } - - set - { - numDataBytes = value; - } - - } - public int NumECBytes - { - // Number of error correction bytes in the QR Code. - - get - { - return numECBytes; - } - - set - { - numECBytes = value; - } - - } - public int NumRSBlocks - { - // Number of Reedsolomon blocks in the QR Code. - - get - { - return numRSBlocks; - } - - set - { - numRSBlocks = value; - } - - } - public ByteMatrix Matrix - { - // ByteMatrix data of the QR Code. - - get - { - return matrix; - } - - // This takes ownership of the 2D array. - - set - { - matrix = value; - } - - } - public bool Valid - { - // Checks all the member variables are set properly. Returns true on success. Otherwise, returns - // false. - - get - { - return mode != null && ecLevel != null && version != - 1 && matrixWidth != - 1 && maskPattern != - 1 && numTotalBytes != - 1 && numDataBytes != - 1 && numECBytes != - 1 && numRSBlocks != - 1 && isValidMaskPattern(maskPattern) && numTotalBytes == numDataBytes + numECBytes && matrix != null && matrixWidth == matrix.Width && matrix.Width == matrix.Height; // Must be square. - } - - } - - public const int NUM_MASK_PATTERNS = 8; - - private Mode mode; - private ErrorCorrectionLevel ecLevel; - private int version; - private int matrixWidth; - private int maskPattern; - private int numTotalBytes; - private int numDataBytes; - private int numECBytes; - private int numRSBlocks; - private ByteMatrix matrix; - - public QRCode() - { - mode = null; - ecLevel = null; - version = - 1; - matrixWidth = - 1; - maskPattern = - 1; - numTotalBytes = - 1; - numDataBytes = - 1; - numECBytes = - 1; - numRSBlocks = - 1; - matrix = null; - } - - - // Return the value of the module (cell) pointed by "x" and "y" in the matrix of the QR Code. They - // call cells in the matrix "modules". 1 represents a black cell, and 0 represents a white cell. - public int at(int x, int y) - { - // The value must be zero or one. - int value_Renamed = matrix.get_Renamed(x, y); - if (!(value_Renamed == 0 || value_Renamed == 1)) - { - // this is really like an assert... not sure what better exception to use? - throw new System.SystemException("Bad value"); - } - return value_Renamed; - } - - // Return debug String. - public override System.String ToString() - { - System.Text.StringBuilder result = new System.Text.StringBuilder(200); - result.Append("<<\n"); - result.Append(" mode: "); - result.Append(mode); - result.Append("\n ecLevel: "); - result.Append(ecLevel); - result.Append("\n version: "); - result.Append(version); - result.Append("\n matrixWidth: "); - result.Append(matrixWidth); - result.Append("\n maskPattern: "); - result.Append(maskPattern); - result.Append("\n numTotalBytes: "); - result.Append(numTotalBytes); - result.Append("\n numDataBytes: "); - result.Append(numDataBytes); - result.Append("\n numECBytes: "); - result.Append(numECBytes); - result.Append("\n numRSBlocks: "); - result.Append(numRSBlocks); - if (matrix == null) - { - result.Append("\n matrix: null\n"); - } - else - { - result.Append("\n matrix:\n"); - result.Append(matrix.ToString()); - } - result.Append(">>\n"); - return result.ToString(); - } - - // Check if "mask_pattern" is valid. - public static bool isValidMaskPattern(int maskPattern) - { - return maskPattern >= 0 && maskPattern < NUM_MASK_PATTERNS; - } - - // Return true if the all values in the matrix are binary numbers. - // - // JAVAPORT: This is going to be super expensive and unnecessary, we should not call this in - // production. I'm leaving it because it may be useful for testing. It should be removed entirely - // if ByteMatrix is changed never to contain a -1. - /* - private static boolean EverythingIsBinary(final ByteMatrix matrix) { - for (int y = 0; y < matrix.height(); ++y) { - for (int x = 0; x < matrix.width(); ++x) { - int value = matrix.get(y, x); - if (!(value == 0 || value == 1)) { - // Found non zero/one value. - return false; - } - } - } - return true; - } - */ - } -} \ No newline at end of file diff --git a/zxing-csharp/zxing-sample/AssemblyInfo.cs b/zxing-csharp/zxing-sample/AssemblyInfo.cs deleted file mode 100644 index 49dbab6..0000000 --- a/zxing-csharp/zxing-sample/AssemblyInfo.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("zxing-sample")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". -// The form "{Major}.{Minor}.*" will automatically update the build and revision, -// and "{Major}.{Minor}.{Build}.*" will update just the revision. - -[assembly: AssemblyVersion("1.0.*")] - -// The following attributes are used to specify the signing key for the assembly, -// if desired. See the Mono documentation for more information about signing. - -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile("")] - diff --git a/zxing-csharp/zxing-sample/Main.cs b/zxing-csharp/zxing-sample/Main.cs deleted file mode 100644 index a2341db..0000000 --- a/zxing-csharp/zxing-sample/Main.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Windows.Forms; - -using com.google.zxing; -using com.google.zxing.common; - -namespace zxingsample -{ - class MainClass - { - public static void Main (string[] args) - { - WinForm form = new WinForm (); - Application.Run (form); - //Console.WriteLine("Hello World!"); - } - } - public class WinForm : Form - { - public WinForm () - { - InitializeComponent (); - } - - Button btn_File; - TextBox tb; - private void InitializeComponent () - { - this.Width = 400; - this.Height = 300; - this.Text = "My Dialog"; - Button btnOK = new Button (); - btnOK.Text = "OK"; - btnOK.Location = new System.Drawing.Point (10, 10); - btnOK.Size = new System.Drawing.Size (80, 24); - this.Controls.Add (btnOK); - btnOK.Click += new EventHandler (btnOK_Click); - - btn_File=new Button(); - btn_File.Text="File..."; - btn_File.Location=new System.Drawing.Point(100,10); - btn_File.Size=btnOK.Size; - this.Controls.Add(btn_File); - btn_File.Click+=new EventHandler(btn_File_Click); - - tb=new TextBox(); - tb.Location=new System.Drawing.Point(10,50); - tb.Size=new System.Drawing.Size(200, 24); - tb.Text=""; - this.Controls.Add(tb); - } - private void btn_File_Click (object sender, System.EventArgs e) - { - string sRes=""; - OpenFileDialog ofn=new OpenFileDialog(); - if(ofn.ShowDialog()==DialogResult.OK){ - try { - Reader barcodeReader= - new com.google.zxing.MultiFormatReader(); - System.Drawing.Bitmap srcbitmap = - new System.Drawing.Bitmap(ofn.FileName.ToString()); // Make a copy of the image in the Bitmap variable - //make a grey bitmap of it - bmp_util util=new bmp_util(); - srcbitmap = util.ConvertToGrayscale(srcbitmap); - - RGBLuminanceSource source = - new RGBLuminanceSource(srcbitmap, srcbitmap.Width, srcbitmap.Height); - com.google.zxing.BinaryBitmap bitmap= - new com.google.zxing.BinaryBitmap(new HybridBinarizer(source)); - com.google.zxing.Result result = barcodeReader.decode(bitmap); - System.Console.WriteLine(result.Text); - sRes=result.Text; - } - catch (com.google.zxing.ReaderException zex) { - sRes=zex.Message; - System.Console.WriteLine(zex.Message); - } - catch (Exception ex) { - sRes=ex.Message; - System.Console.WriteLine(ex.Message); - } - tb.Text=sRes; - } - } - private void btnOK_Click (object sender, System.EventArgs e) - { - this.DialogResult = DialogResult.OK; - this.Close (); - } - - } -} - diff --git a/zxing-csharp/zxing-sample/bin/Debug/zxing-sample.exe b/zxing-csharp/zxing-sample/bin/Debug/zxing-sample.exe deleted file mode 100755 index 93b98ce..0000000 Binary files a/zxing-csharp/zxing-sample/bin/Debug/zxing-sample.exe and /dev/null differ diff --git a/zxing-csharp/zxing-sample/bin/Debug/zxing-sample.exe.mdb b/zxing-csharp/zxing-sample/bin/Debug/zxing-sample.exe.mdb deleted file mode 100644 index 1f8f16c..0000000 Binary files a/zxing-csharp/zxing-sample/bin/Debug/zxing-sample.exe.mdb and /dev/null differ diff --git a/zxing-csharp/zxing-sample/bin/Debug/zxing.dll b/zxing-csharp/zxing-sample/bin/Debug/zxing.dll deleted file mode 100644 index 75b9bee..0000000 Binary files a/zxing-csharp/zxing-sample/bin/Debug/zxing.dll and /dev/null differ diff --git a/zxing-csharp/zxing-sample/bin/Debug/zxing.dll.mdb b/zxing-csharp/zxing-sample/bin/Debug/zxing.dll.mdb deleted file mode 100644 index 05e9a11..0000000 Binary files a/zxing-csharp/zxing-sample/bin/Debug/zxing.dll.mdb and /dev/null differ diff --git a/zxing-csharp/zxing-sample/bmp_util.cs b/zxing-csharp/zxing-sample/bmp_util.cs deleted file mode 100644 index fedd35e..0000000 --- a/zxing-csharp/zxing-sample/bmp_util.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Drawing; - -namespace zxingsample -{ - public class bmp_util - { - public Bitmap ConvertToGrayscale(Bitmap source) - - { - - Bitmap bm = new Bitmap(source.Width,source.Height); - - for(int y=0;y - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {5FE00089-0EB2-46EA-81EF-8CA437A327E5} - Exe - zxingsample - zxing-sample - v3.5 - - - true - full - false - bin\Debug - DEBUG - prompt - 4 - false - - - none - false - bin\Release - prompt - 4 - false - - - - - - - - - - - - - - {6431CF13-7A7B-4602-B96A-47CDA6F0B008} - zxing - - - - \ No newline at end of file diff --git a/zxing-csharp/zxing-sample/zxing-sample.pidb b/zxing-csharp/zxing-sample/zxing-sample.pidb deleted file mode 100644 index 91bb092..0000000 Binary files a/zxing-csharp/zxing-sample/zxing-sample.pidb and /dev/null differ diff --git a/zxing-csharp/zxing-sample/zxing-sample.sln b/zxing-csharp/zxing-sample/zxing-sample.sln deleted file mode 100644 index 087413b..0000000 --- a/zxing-csharp/zxing-sample/zxing-sample.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "zxing-sample", "zxing-sample.csproj", "{5FE00089-0EB2-46EA-81EF-8CA437A327E5}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "zxing", "..\zxing.csproj", "{6431CF13-7A7B-4602-B96A-47CDA6F0B008}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5FE00089-0EB2-46EA-81EF-8CA437A327E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5FE00089-0EB2-46EA-81EF-8CA437A327E5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5FE00089-0EB2-46EA-81EF-8CA437A327E5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5FE00089-0EB2-46EA-81EF-8CA437A327E5}.Release|Any CPU.Build.0 = Release|Any CPU - {6431CF13-7A7B-4602-B96A-47CDA6F0B008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6431CF13-7A7B-4602-B96A-47CDA6F0B008}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6431CF13-7A7B-4602-B96A-47CDA6F0B008}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6431CF13-7A7B-4602-B96A-47CDA6F0B008}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = zxing-sample.csproj - EndGlobalSection -EndGlobal diff --git a/zxing-csharp/zxing-sample/zxing-sample.userprefs b/zxing-csharp/zxing-sample/zxing-sample.userprefs deleted file mode 100644 index f91d622..0000000 --- a/zxing-csharp/zxing-sample/zxing-sample.userprefs +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/zxing-csharp/zxing.csproj b/zxing-csharp/zxing.csproj deleted file mode 100644 index a6c74de..0000000 --- a/zxing-csharp/zxing.csproj +++ /dev/null @@ -1,227 +0,0 @@ - - - - Local - 2.0 - Debug - AnyCPU - - - zxing - JScript - Grid - IE50 - false - Library - zxing - false - OnBuildSuccess - - - {6431CF13-7A7B-4602-B96A-47CDA6F0B008} - - - 2.0 - 9.0.21022 - v2.0 - - - . - 285212672 - - - - - true - 4096 - false - false - 4 - full - prompt - false - - - . - 285212672 - - - - - true - 4096 - false - false - 4 - full - prompt - false - - - - mscorlib - - - System - - - System.Data - - - System.Design - - - System.Drawing - - - System.Management - - - System.Windows.Forms - - - System.Xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/zxing-csharp/zxing.dll b/zxing-csharp/zxing.dll deleted file mode 100644 index 75b9bee..0000000 Binary files a/zxing-csharp/zxing.dll and /dev/null differ diff --git a/zxing-csharp/zxing.dll.mdb b/zxing-csharp/zxing.dll.mdb deleted file mode 100644 index 05e9a11..0000000 Binary files a/zxing-csharp/zxing.dll.mdb and /dev/null differ diff --git a/zxing-csharp/zxing.pidb b/zxing-csharp/zxing.pidb deleted file mode 100644 index f81f299..0000000 Binary files a/zxing-csharp/zxing.pidb and /dev/null differ diff --git a/zxing-csharp/zxing.sln b/zxing-csharp/zxing.sln deleted file mode 100644 index 31a09a1..0000000 --- a/zxing-csharp/zxing.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "zxing", "zxing.csproj", "{6431CF13-7A7B-4602-B96A-47CDA6F0B008}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "zxing-sample", "zxing-sample\zxing-sample.csproj", "{5FE00089-0EB2-46EA-81EF-8CA437A327E5}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5FE00089-0EB2-46EA-81EF-8CA437A327E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5FE00089-0EB2-46EA-81EF-8CA437A327E5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5FE00089-0EB2-46EA-81EF-8CA437A327E5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5FE00089-0EB2-46EA-81EF-8CA437A327E5}.Release|Any CPU.Build.0 = Release|Any CPU - {6431CF13-7A7B-4602-B96A-47CDA6F0B008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6431CF13-7A7B-4602-B96A-47CDA6F0B008}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6431CF13-7A7B-4602-B96A-47CDA6F0B008}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6431CF13-7A7B-4602-B96A-47CDA6F0B008}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = zxing-sample\zxing-sample.csproj - EndGlobalSection -EndGlobal diff --git a/zxing-csharp/zxing.userprefs b/zxing-csharp/zxing.userprefs deleted file mode 100644 index 43813aa..0000000 --- a/zxing-csharp/zxing.userprefs +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file