twain3.0/huagao/Device/PublicFunc.cpp

750 lines
18 KiB
C++
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "stdafx.h"
#include "PublicFunc.h"
#include "CTwainMutex.h"
#include <io.h>
TCHAR* GetUserCustomFilePath(HWND hWin, TCHAR* lpFilePath, TCHAR* lp_head_text)
{
if (lpFilePath == NULL)
{
return NULL;
}
BROWSEINFO bi = { 0 };
TCHAR szBuffer[MAX_PATH] = { 0 };
memset(&bi, 0, sizeof(BROWSEINFO));
bi.hwndOwner = hWin;
bi.pszDisplayName = GetExistFileDir(lpFilePath);
bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_SHAREABLE | BIF_USENEWUI | BIF_RETURNFSANCESTORS;
LPITEMIDLIST pIDList = NULL;
LPMALLOC lpMalloc = NULL;
//m_pUI_INI->GetMessageBoxStr(szBuffer, sizeof(szBuffer), 1041);
//bi.lpszTitle = szBuffer;//1041=请选择文件存储路径
bi.lpszTitle = lp_head_text;//TEXT("请选择新建文件夹");
bi.lpfn = (BFFCALLBACK)BrowserCallbackProc; //回调函数
bi.lParam = (LPARAM)lpFilePath; //回调函数的使用的参数,用来设定默认路径
pIDList = SHBrowseForFolder(&bi);
if (pIDList != NULL)
{
SHGetPathFromIDList(pIDList, lpFilePath);
}
if (SHGetMalloc(&lpMalloc))
{
return NULL; //释放内存   
}
if (pIDList == NULL)
{
return NULL; //释放内存
}
lpMalloc->Free(pIDList);
lpMalloc->Release();
pIDList = NULL;
lpMalloc = NULL;
//_tcscpy(lpFilePath, szBuffer2);
return lpFilePath;
}
TCHAR* GetCurExeFilePath(HINSTANCE hInstance, TCHAR* lpPath, DWORD dwSize)
{
INT nRet = 0x0L;
TCHAR* p = NULL;
if (lpPath == NULL || dwSize == 0)
{
return NULL;
}
nRet = GetModuleFileName(hInstance, lpPath, dwSize);
if (nRet > 0)
{
p = _tcsrchr(lpPath, TEXT('\\'));
if (p != NULL)
{
*(p + 1) = TEXT('\0');
}
else
{
return NULL;
}
}
else
{
return NULL;
}
return lpPath;
}
TCHAR* GetExistFileDir(TCHAR* p_file_path)
{
WIN32_FIND_DATA wfd = { 0 };
LPSTR p_test = NULL;
HANDLE hFindFile = INVALID_HANDLE_VALUE;
if (p_file_path == NULL)
return NULL;
hFindFile = FindFirstFile(p_file_path, &wfd);
if (hFindFile != NULL)
{
FindClose(hFindFile);
hFindFile = INVALID_HANDLE_VALUE;
}
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
return p_file_path;
}
p_test = (LPSTR)(_tcsrchr(p_file_path, '\\'));
if (p_test != NULL)
{
*p_test = 0;
return GetExistFileDir(p_file_path);
}
else
{
return NULL;
}
}
DWORD CALLBACK BrowserCallbackProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case BFFM_INITIALIZED: //LPARAM(TEXT("D:\\test_adf_project"))
SendMessage(hWnd, BFFM_SETSELECTION, TRUE, lParam); //lpData就是上一个函数的 info.lParam ,也就是默认路径
break;
default:
break;
}
return 0;
}
BOOL isFolderExist(char* folder)
{
int ret = 0;
ret = _access(folder, 0);
if (ret == 0)
ret = TRUE;
else
ret = FALSE;
return ret;
}
BOOL isFileExist(std::string folder)
{
return _access(folder.c_str(), 4) == 0 ? TRUE : FALSE;
}
int32_t createDirectory(char* directoryPath)
{
uint32_t dirPathLen = 0;
if (directoryPath != NULL) {
dirPathLen = strlen(directoryPath);
}
if (dirPathLen > FILENAME_MAX)
{
return -1;
}
char tmpDirPath[FILENAME_MAX] = { 0 };
for (uint32_t i = 0; i < dirPathLen; ++i)
{
tmpDirPath[i] = directoryPath[i];
if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/')
{
if (!isFolderExist(tmpDirPath))
{
int ret = _mkdir(tmpDirPath);
if (ret != 0)
return -1;
}
}
}
return 0;
}
float GetContrast(int level)
{
float ret = 0.0;
switch (level)
{
case -3:
ret = -1000.0;
break;
case -2:
ret = -666.0;
break;
case -1:
ret = -333.0;
break;
case 1:
ret = 333.0;
break;
case 2:
ret = 666.0;
break;
case 3:
ret = 1000.0;
break;
}
return ret;
}
char* THCAR2char(TCHAR* tchStr)
{
int iLen = 2 * wcslen(tchStr);//CString,TCHAR汉字算一个字符因此不用普通计算长度
char* chRtn = new char[iLen + 1];
wcstombs(chRtn, tchStr, iLen + 1);//转换成功返回为非负值
return chRtn;
}
// CTwainUI 消息处理程序
BOOL CheckAndCreateFileDir(TCHAR* p_file_path, BOOL flg)
{
TCHAR szTmp[MAX_PATH] = { 0 };
WIN32_FIND_DATA wfd = { 0 };
INT len = 0;
INT pos = 0;
BOOL bFlg = FALSE;
HANDLE hFindFile = INVALID_HANDLE_VALUE;
if (p_file_path == NULL)
return FALSE;
if (*p_file_path >= 'a' && *p_file_path <= 'z' || *p_file_path >= 'A' && *p_file_path <= 'Z')
{
if (*(p_file_path + 1) != ':' && *(p_file_path + 2) != '\\')
{
return FALSE;
}
}
if (_access(THCAR2char(p_file_path), 0) == 0)
{
return TRUE;
}
if (!flg)
return FALSE;
if (CreateDirectory(p_file_path, NULL))
return TRUE;
_tcscpy(szTmp, p_file_path);
len = (INT)_tcslen(szTmp);
bFlg = FALSE;
while (len)
{
if (*(szTmp + len - 1) == '\\')
{
bFlg = TRUE;
break;
}
len--;
}
if (bFlg)
{
*(szTmp + len - 1) = 0;
CheckAndCreateFileDir(szTmp, flg);
return CreateDirectory(p_file_path, NULL);
}
else
return FALSE;
}
BOOL CheckDiskFreeBitM(HWND hWin, TCHAR* p_disk_name, DWORD dw_min_bit_m)
{
TCHAR* p = NULL;
TCHAR sz_root_path_name[MAX_PATH + 1] = { 0 };
INT len = 0;
DWORD dwTotalDiskSpace = 0;
DWORD dwFreeDiskSpace = 0;
DWORD dwUsedDiskSpace = 0;
ULARGE_INTEGER uiFreeBytesAvailableToCaller;
ULARGE_INTEGER uiTotalNumberOfBytes;
ULARGE_INTEGER uiTotalNumberOfFreeBytes;
UINT un_ret = 0;
if (p_disk_name == NULL)
return FALSE;
len = _tcslen(p_disk_name);
if (len > MAX_PATH)
{
len = MAX_PATH;
}
memcpy(sz_root_path_name, p_disk_name, (size_t)len);
p = sz_root_path_name;
//p = _tcsstr(sz_root_path_name, "\\");
if (p == NULL)
{
if (len == 2)
{
if (!((sz_root_path_name[0] >= 'A' && sz_root_path_name[0] <= 'Z' || sz_root_path_name[0] >= 'a' && sz_root_path_name[0] <= 'z') && sz_root_path_name[1] == ':'))
return FALSE;
}
else
return FALSE;
}
if (p != NULL)
*(p + 1) = 0;
un_ret = GetDriveType(sz_root_path_name);
if (un_ret == 0 || un_ret == 1)
{
return FALSE;
}
if (GetDiskFreeSpaceEx(sz_root_path_name, &uiFreeBytesAvailableToCaller, &uiTotalNumberOfBytes, &uiTotalNumberOfFreeBytes))
{
//dwTotalDiskSpace = (DWORD)(uiTotalNumberOfBytes.QuadPart / 1024 / 1024);
dwFreeDiskSpace = (DWORD)(uiFreeBytesAvailableToCaller.QuadPart >> 20);
//dwUsedDiskSpace = dwTotalDiskSpace - dwFreeDiskSpace;
if (dwFreeDiskSpace < dw_min_bit_m)
{
//ShowErrorStr(hWin, 1101);//1101=磁盘空间不足
return FALSE;
}
}
else
{
//GetErrorMessage(NULL, 0, FALSE);
return FALSE;
}
//ShowErrorStr(hWin, 1101);//1101=磁盘空间不足
//return FALSE;
return TRUE;
}
HBITMAP SetButtonStaticBkBmp(HINSTANCE hInst, HWND hWin, UINT id, UINT iamge_id)
{
UINT ctr_msg = 0;
UINT str_iamge_type = 0;
HBITMAP hBitmap = NULL;
HBITMAP hOldBitmap = NULL;
//BS_ICON BS_BITMAP
//SS_BITMAP|SS_CENTERIMAGE SS_ICON
LONG ctr_s = 0;
ctr_s = GetWindowLong(GetDlgItem(hWin, id), GWL_STYLE);
ctr_msg = STM_SETIMAGE;
ctr_s |= SS_BITMAP | SS_CENTERIMAGE | SS_RIGHT;
hBitmap = LoadBitmap(hInst, MAKEINTRESOURCE(iamge_id));
if (hBitmap == NULL)
{
return NULL;
}
SetWindowLong(GetDlgItem(hWin, id), GWL_STYLE, ctr_s);
hOldBitmap = (HBITMAP)SendDlgItemMessage(hWin, id, ctr_msg, IMAGE_BITMAP, (LPARAM)hBitmap);
if (hOldBitmap != NULL)
{
DeleteObject(hOldBitmap);
hOldBitmap = NULL;
}
DeleteObject(hBitmap);
hBitmap = NULL;
return hBitmap;
}
void writelog(std::string msg)
{
TCHAR cfFilePath[MAX_PATH] = { 0 };
SHGetSpecialFolderPath(NULL, cfFilePath, CSIDL_LOCAL_APPDATA, TRUE);
_tcscat(cfFilePath, HUAGAO_SCAN);
_tcscat(cfFilePath, TWAIN_ERROR_PATH);
std::string tmpstr = TCHAR2STRING(cfFilePath);
if (!isFolderExist((char*)tmpstr.c_str())) {
createDirectory((char*)tmpstr.c_str());
}
CString filePath(cfFilePath);
filePath += TWAIN_ERROR_LOG_NAME;
std::string savepath = TCHAR2STRING(filePath.GetBuffer());
std::ofstream ofs(savepath, std::ios::app);
SYSTEMTIME sys;
GetLocalTime(&sys);
ofs << sys.wYear << "/" << sys.wMonth << "/" << sys.wDay << " " << sys.wHour << ":" << sys.wMinute << ":" << sys.wSecond << ":" << sys.wMilliseconds << " " << msg << std::endl;
ofs.close();
}
std::string TCHAR2STRING(TCHAR* STR)
{
int iLen = WideCharToMultiByte(CP_ACP, 0, STR, -1, NULL, 0, NULL, NULL);
char* chRtn = new char[iLen * sizeof(char)];
WideCharToMultiByte(CP_ACP, 0, STR, -1, chRtn, iLen, NULL, NULL);
std::string str(chRtn);
return str;
}
std::string UtfToString(std::string strValue)
{
int nwLen = ::MultiByteToWideChar(CP_ACP, 0, strValue.c_str(), -1, NULL, 0);
wchar_t* pwBuf = new wchar_t[nwLen + 1];//加上末尾'\0'
ZeroMemory(pwBuf, nwLen * 2 + 2);
::MultiByteToWideChar(CP_ACP, 0, strValue.c_str(), strValue.length(), pwBuf, nwLen);
int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
char* pBuf = new char[nLen + 1];
ZeroMemory(pBuf, nLen + 1);
::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
std::string retStr(pBuf);
delete[]pwBuf;
delete[]pBuf;
pwBuf = NULL;
pBuf = NULL;
return retStr;
}
std::string StringToUtf(std::string strValue)
{
int nwLen = MultiByteToWideChar(CP_UTF8, 0, strValue.c_str(), -1, NULL, 0);
wchar_t* pwBuf = new wchar_t[nwLen + 1];//加上末尾'\0'
memset(pwBuf, 0, nwLen * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, strValue.c_str(), strValue.length(), pwBuf, nwLen);
int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
char* pBuf = new char[nLen + 1];
memset(pBuf, 0, nLen + 1);
WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
std::string retStr = pBuf;
delete[]pBuf;
delete[]pwBuf;
return retStr;
}
int GetContrastLevel(float contrast) {
int ret = 4;
if (contrast >= -1000.0f && contrast < -666.0f) { ret = 1; }
else if (contrast >= -666.0f && contrast < -333.0f) { ret = 2; }
else if (contrast >= -333.0f && contrast < 0.0f) { ret = 3; }
else if (contrast > 0.0f && contrast <= 333.0f) { ret = 5; }
else if (contrast > 333.0f && contrast <= 666.0f) { ret = 6; }
else if (contrast > 666.0f && contrast <= 1000.0f) { ret = 7; }
return ret;
}
CString GetHidedlgPath()
{
TCHAR szIniFile[MAX_PATH] = { 0 };
SHGetSpecialFolderPath(NULL, szIniFile, CSIDL_WINDOWS, TRUE);
#ifdef MAKEHUAGAO
_tcscat(szIniFile, _T("\\twain_32\\HuaGoScan\\hidedlg.exe"));
#elif defined LANXUM
_tcscat(szIniFile, _T("\\twain_32\\LANXUMSCAN\\hidedlg.exe"));
#else // MAKEHUAGAO
_tcscat(szIniFile, _T("\\twain_32\\ZhibenScan\\hidedlg.exe"));
#endif
int iLen = WideCharToMultiByte(CP_ACP, 0, szIniFile, -1, NULL, 0, NULL, NULL);
char* chRtn = new char[iLen * sizeof(char)];
WideCharToMultiByte(CP_ACP, 0, szIniFile, -1, chRtn, iLen, NULL, NULL);
CString ret(chRtn);
delete[] chRtn;
return ret;
}
int GetMappingBrightnessValue(float in)
{
float ratio = 254 / 2000.0f;
int ret = 0;
ret = (int)(ratio * in) + 128;
return ret;
}
int GetMappingContrastValue(float in) {
int ret = 0;
float ratio = 72 / 2000.0f;
ret = (int)(in * ratio);
return ret;
}
string getOSInfo() {
string iosinfo;
OSVERSIONINFOEX osver = { sizeof(OSVERSIONINFOEX) };
osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx((OSVERSIONINFO*)(&osver));
if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 0)
iosinfo = "Windows 2000";
else if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 1)
iosinfo = "Windows XP";
else if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 2) {
if (GetSystemMetrics(SM_SERVERR2) != 0) { iosinfo = "Windows Server 2003 R2"; }
else { iosinfo = "Windows Server 2003"; }
}
else if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 0) {
if (osver.wProductType == VER_NT_WORKSTATION) { iosinfo = "Windows Vista"; }
else { iosinfo = "Windows Server 2008"; }
}
else if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 1) {
if (osver.wProductType == VER_NT_WORKSTATION) { iosinfo = "Windows 7"; }
else { iosinfo = "Windows Server 2008 R2"; }
}
else if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 2) {
if (osver.wProductType == VER_NT_WORKSTATION) { iosinfo = "Windows 8"; }
else { iosinfo = "Windows Server 2012"; }
}
else if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 3) {
if (osver.wProductType == VER_NT_WORKSTATION) { iosinfo = "Windows 8.1"; }
else { iosinfo = "Windows Server 2012 R2"; }
}
else if (osver.dwMajorVersion == 10 && osver.dwMinorVersion == 0) {
if (osver.wProductType == VER_NT_WORKSTATION) { iosinfo = "Windows 10"; }
else { iosinfo = "Windows Server 2016"; }
}
else
iosinfo = "unkown system";
return iosinfo;
}
#ifdef _WIN64
// method 2: usde winapi, works for x86 and x64
#include <intrin.h>
string getCpuInfo()
{
string retinfo;
int cpuInfo[4] = { -1 };
char cpu_manufacture[32] = { 0 };
char cpu_type[32] = { 0 };
char cpu_freq[32] = { 0 };
__cpuid(cpuInfo, 0x80000002);
memcpy(cpu_manufacture, cpuInfo, sizeof(cpuInfo));
__cpuid(cpuInfo, 0x80000003);
memcpy(cpu_type, cpuInfo, sizeof(cpuInfo));
__cpuid(cpuInfo, 0x80000004);
memcpy(cpu_freq, cpuInfo, sizeof(cpuInfo));
string mfc(cpu_manufacture);
string cputype(cpu_type);
string cpufreq(cpu_freq);
retinfo = mfc + cputype + cpufreq;
return retinfo;
}
#else
// mothed 1: this kind asm embedded in code only works in x86 build
// save 4 register variables
DWORD deax;
DWORD debx;
DWORD decx;
DWORD dedx;
// init cpu in assembly language
void initCpu(DWORD veax)
{
__asm
{
mov eax, veax
cpuid
mov deax, eax
mov debx, ebx
mov decx, ecx
mov dedx, edx
}
}
long getCpuFreq()
{
int start, over;
_asm
{
RDTSC
mov start, eax
}
Sleep(50);
_asm
{
RDTSC
mov over, eax
}
return (over - start) / 50000;
}
std::string getManufactureID()
{
char manuID[25];
memset(manuID, 0, sizeof(manuID));
initCpu(0);
memcpy(manuID + 0, &debx, 4); // copy to array
memcpy(manuID + 4, &dedx, 4);
memcpy(manuID + 8, &decx, 4);
return string(manuID);
}
std::string getCpuType()
{
const DWORD id = 0x80000002; // start 0x80000002 end to 0x80000004
char cpuType[49];
memset(cpuType, 0, sizeof(cpuType));
for (DWORD t = 0; t < 3; t++)
{
initCpu(id + t);
memcpy(cpuType + 16 * t + 0, &deax, 4);
memcpy(cpuType + 16 * t + 4, &debx, 4);
memcpy(cpuType + 16 * t + 8, &decx, 4);
memcpy(cpuType + 16 * t + 12, &dedx, 4);
}
return string(cpuType);
}
#endif
// ---- get memory info ---- //
string getMemoryInfo()
{
std::string memory_info;
MEMORYSTATUSEX statusex;
statusex.dwLength = sizeof(statusex);
if (GlobalMemoryStatusEx(&statusex))
{
unsigned long long total = 0, remain_total = 0, avl = 0, remain_avl = 0;
double decimal_total = 0, decimal_avl = 0;
remain_total = statusex.ullTotalPhys % GBYTES;
total = statusex.ullTotalPhys / GBYTES;
avl = statusex.ullAvailPhys / GBYTES;
remain_avl = statusex.ullAvailPhys % GBYTES;
if (remain_total > 0)
decimal_total = (remain_total / MBYTES) / DKBYTES;
if (remain_avl > 0)
decimal_avl = (remain_avl / MBYTES) / DKBYTES;
decimal_total += (double)total;
decimal_avl += (double)avl;
char buffer[kMaxInfoBuffer];
sprintf_s(buffer, kMaxInfoBuffer, "total %.2f GB (%.2f GB available)", decimal_total, decimal_avl);
memory_info.append(buffer);
}
return memory_info;
}
void GetDiskInfo(DWORD& dwNum, CString chDriveInfo[])
{
DWORD DiskCount = 0;
//The number of logical drivers in the system can be obtained by using the GetLogicalDrives() function, which returns a 32-bit unsigned integer data.
DWORD DiskInfo = GetLogicalDrives();
//Cyclic operations are used to see if each bit of data is 1, if 1, the disk is true, and if 0, the disk does not exist.
while (DiskInfo)
{
//Through the logic and operation of bit operation, we can judge whether it is 1 or not.
Sleep(10);
if (DiskInfo & 1)
{
DiskCount++;
}
DiskInfo = DiskInfo >> 1;//The right-shift operation of bit operation ensures that the checked position moves one bit to the right once per cycle. * /
}
if (dwNum < DiskCount)
{
return;//The actual number of disks is greater than dwNum
}
dwNum = DiskCount;//Save the number of disk partitions
//-------------------------------------------------------------------//
//Get the length of all drive string information through the GetLogicalDriveStrings() function
int DSLength = GetLogicalDriveStrings(0, NULL);
WCHAR* DStr = new WCHAR[DSLength];
memset(DStr, 0, DSLength);
//The string information is copied into the heap area array by GetLogical Drive Strings, which stores the information of all drives.
GetLogicalDriveStrings(DSLength, DStr);
int DType;
int si = 0;
BOOL fResult;
unsigned _int64 i64FreeBytesToCaller;
unsigned _int64 i64TotalBytes;
unsigned _int64 i64FreeBytes;
//Read the driver information, because the DStr internal data format is A: NULLB: NULLC: NULL, so DSLength/4 can get specific large cycle range.
for (int i = 0; i < DSLength / 4; ++i)
{
Sleep(10);
CString strdriver = DStr + i * 4;
CString strTmp, strTotalBytes, strFreeBytes;
DType = GetDriveType(strdriver);//GetDriveType function, you can get the driver type, parameter is the root directory of the driver
switch (DType)
{
case DRIVE_FIXED:
{
strTmp.Format(_T("Local disk"));
}
break;
case DRIVE_CDROM:
{
strTmp.Format(_T("DVD Driver"));
}
break;
case DRIVE_REMOVABLE:
{
strTmp.Format(_T("Removable disk"));
}
break;
case DRIVE_REMOTE:
{
strTmp.Format(_T("Network disk"));
}
break;
case DRIVE_RAMDISK:
{
strTmp.Format(_T("fictitious RAM disk"));
}
break;
case DRIVE_UNKNOWN:
{
strTmp.Format(_T("fictitious RAM unknown device"));
}
break;
default:
strTmp.Format(_T("unknown device"));
break;
}
//GetDiskFreeSpaceEx function, which can get the space state of the drive disk, returns a BOOL-type data
fResult = GetDiskFreeSpaceEx(strdriver,
(PULARGE_INTEGER)&i64FreeBytesToCaller,
(PULARGE_INTEGER)&i64TotalBytes,
(PULARGE_INTEGER)&i64FreeBytes);
if (fResult)
{
strTotalBytes.Format(_T("Total disk capacity%fMB"), (float)i64TotalBytes / 1024 / 1024);
strFreeBytes.Format(_T("Disk Remaining Space%fMB"), (float)i64FreeBytesToCaller / 1024 / 1024);
}
else
{
strTotalBytes.Format(_T(""));
strFreeBytes.Format(_T(""));
}
chDriveInfo[i] = strTmp + _T("(") + strdriver + _T("):") + strTotalBytes + strFreeBytes;
si += 4;
}
}