#include <windows.h>
#include <Commdlg.h>
#include <tchar.h>
#include <Unknwn.h>
#include <Winspool.h>
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ERRNO.H>
#include <stdlib.h>
#include <direct.h>
#include <tlhelp32.h>
#include "Userenv.h"
#include <io.h>
#include <stdio.h>
#include "../logging.h"
#include "Base64coder.h"
#include "fax_tif.h"
#define USING_PAGE 1
#ifndef ULONG_PTR
#define ULONG_PTR DWORD
#endif
#include "gdiplus.h"
using namespace Gdiplus;
#pragma comment(lib, "Userenv.lib")
/*find new file*/
#define FF_REE_OK 0
#define FF_TRING 1
#define FF_FAIL 2
/*=== 错误码 ===*/
typedef enum {
DRM_UTIL_OK = 0,
DRM_UTIL_FAIL = 1
} DRM_UTIL_ERRCODE;
ULONG_PTR m_gdiplusToken;
typedef enum
{
VPRINT_MSG_NODEF = 0,
VPRINT_MSG_SUCCESS, /*printed and success*/
VPRINT_MSG_FAIL, /*printed but fail*/
VPRINT_MSG_PROGESS, /*printing and show progress*/
}VPRINT_MSG_TYPE;
typedef enum
{
VPRINT_FILE_XWB = 0,
VPRINT_FILE_TIFF_C4,
VPRINT_FILE_TIFF_C3,
}VPRINT_FILE_TYPE;
typedef struct EMFInf_s
{
int Signature;
int EMFsize;
} EMFInf_t;
const int EMFheaderSignature = 0x0C;
#define VPRINTF_MSG_RESULT (UINT)(WM_USER+0x26f)
#define HEAD_LEN 6
typedef struct TiffResolution_s
{
long x; /*xresolution per inch*/
long y; /*yresolution per inch*/
} *TiffResolutionPtr_t, TiffResolution_t;
typedef enum
{
wvUnknown = 0,
wvWin95,
wvWin95OSR2,
wvWin98,
wvWin98SE,
wvWinME,
wvWinNT3,
wvWinNT4,
wvWin2000,
wvWinXP,
wvWin2003,
wvVista,
wvVista_ia64,
wvVista_x64,
wvWin7,
wvWin7_ia64,
wvWin7_x64
} TWindowsVersion;
#define DEFAULT_X_RESOLUTION 200
#define DEFAULT_Y_RESOLUTION 200
TiffResolution_t g_TiffResolution[] = {{200, 100}, {300, 300}, {400, 400}, {204, 196}, {408, 391}};
int g_XTolResolution[] = {864, 1024, 1216, 1728, 2048, 2432, 2592, 3072, 3456, 3648, 4096, 4864};
char* PMON_KEY = "SYSTEM//CurrentControlSet//Control//Print//Environments//Windows NT x86//Print Processors//vprproc";
BOOL bAutoSaveFile(char *fname, char *windowName, VPRINT_FILE_TYPE *pVpType);
BOOL SendMessage2Win(WPARAM wparam, LPARAM lparam);
/*purge print job*/
BOOL PurgePrintJob(DWORD JobId);
/*get job inf*/
BOOL GetPrintJobInf(DWORD JobId, DWORD Level, LPBYTE pJobInf, DWORD cbBuf);
/*sleep untile file print ok*/
BOOL CanDealPrintFile(DWORD JobId);
/*get file name for des*/
BOOL GetDesFileName(char *filename, DWORD JobID, VPRINT_FILE_TYPE *pVpType);
/*parse command Line, get JobID print file name*/
BOOL MyParseCommandLine(char *printFname, DWORD *JobID);
/*wether the file exist*/
BOOL bFileExist(char *printFname/*file *.SPL*/, int nTimeLen);
/*get new file*/
BOOL FindNewFile(char *strDir, char *fname, time_t *mtime);
/*find printf file*/
BOOL FindPrintFile(char *strDir, char* fname);
/*init gdi plus-plus*/
void Instance();
/*free gdi res*/
void ExitInstance();
/*run process in current user's entironment*/
BOOL RunProcess(LPCSTR lpImage, LPSTR lpComdLine);
/*get save file name, func hook*/
UINT_PTR CALLBACK MyFileDlgHook(HWND hwnd, UINT msgType, WPARAM wparam, LPARAM lparam);
/*convert to white/black bmp*/
BOOL Convert2BitMap(Image *pEmfImage, char**ppBmpInfo, char *pathName);
/*get printer info (about resolution and page size)*/
BOOL GetMyPrinterInfo();
/*free bitmap*/
void DeleteMyBitmap();
/*convert bmp to stream*/
BOOL Convert2Stream(HDC hdc, HBITMAP hbitmap, PBITMAPINFO pbi);
static HBITMAP g_MyBitMap = NULL;/*save global bitmap using for convert emf to bmp*/
static char *g_MyBmpInfo = NULL;/*save all bmp info, for conver to tiff*/
static char *g_MyBmpBits = NULL;/*save all bmp bits*/
static long g_TotalPages = 0;/*vpinter total pages*/
/*printer resolution*/
static long g_XResolution = 200;
static long g_YResolution = 200;
/*page size*/
static long g_PageWidth = 210;
static long g_PageHeight = 279;
static UINT g_MyBmpWidth = -1;
static UINT g_MyBmpHeight = -1;
HWND g_hMsgWnd;
HINSTANCE g_HInstance;
char *g_pchPrintName = "zte-vprinter";
BOOL FormActivate(char *pathName/*result file/path name *.xwb*/,
char * printFname/*file *.SPL*/, VPRINT_FILE_TYPE vpType);
/*create white bord file *.xwb*/
/*tempName temp file name*/
BOOL CreateWhiteBoard(FILE *fFromF, UINT nPixFound/*page count*/, int *postArray, char *pathName);
/*create tiff file for fax*/
BOOL CreateTiffFile(FILE *fFromF, UINT nPixFound/*page count*/, int *postArray, char *pathName, VPRINT_FILE_TYPE vpType);
BOOL MyFileDelete(char *splFname, char *shdFname);
TWindowsVersion GetWindowsVersion();
DRM_UTIL_ERRCODE MakeWholeDir(const char *newdir);
void ShowMsg(char *pMsg);
#define TIFF_TEST 0
#if TIFF_TEST
#include <sys/types.h>
#include <sys/stat.h>
long get_file_len(char *fname)
{
struct stat buf;
if(NULL == fname)
{
return -1;
}
int result;
/* Get data associated with "crt_stat.c": */
result = stat(fname, &buf );
/* Check if statistics are valid: */
if( result != 0 )
{
return -1;
}
return buf.st_size;
}
char g_ReadBuf[3*1024*1024];
void fitt_test()
{
char *pName = "c://3.tif";
FILE *fp;
FILE *ft1;
void *handle;
long len, read;
fp = fopen(pName, "w+b");
len = get_file_len("c://1.bmp");
ft1 = fopen("c://1.bmp", "rb");
read = fread(g_ReadBuf, 1, len, ft1);
fclose(ft1);
handle = init_fax_encode_multi_page(fp, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
fax_encode_multi_page(handle, (PBITMAPFILEHEADER)g_ReadBuf, 204, 196, 1, TRUE, 4);
ft1 = fopen("c://2.bmp", "rb");
read = fread(g_ReadBuf, 1, len, ft1);
fclose(ft1);
fax_encode_multi_page(handle, (PBITMAPFILEHEADER)g_ReadBuf, 204, 196, 2, TRUE, 4);
ft1 = fopen("c://3.bmp", "rb");
read = fread(g_ReadBuf, 1, len, ft1);
fclose(ft1);
fax_encode_multi_page(handle, (PBITMAPFILEHEADER)g_ReadBuf, 204, 196, 3, FALSE, 4);
close_fax_encode(handle);
fclose(fp);
}
#endif
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
char filename[MAX_PATH] = {0};
char printFname[MAX_PATH] = {0};
DWORD JobID = 0;
TWindowsVersion vs;
VPRINT_FILE_TYPE vpType = VPRINT_FILE_XWB;
g_HInstance = hInstance;
GetSystemDirectory(filename, sizeof(filename));
strcat(filename ,"//zte_vprinter.log");
log_open(filename, LL_DEBUG, LL_ERROR);
#if TIFF_TEST
fitt_test();
log_close();
return 0;
#endif
vs = GetWindowsVersion();
if(!MyParseCommandLine(printFname, &JobID))
{
log_close();
return FALSE;
}
log_write("result printFname[%s]/n", (LPCTSTR)printFname);
if(!GetDesFileName(filename, JobID, &vpType))
{
Sleep(1500);
PurgePrintJob(JobID);
log_close();
return FALSE;
}
log_write("result fname[%s]/n", filename);
SendMessage2Win(VPRINT_MSG_PROGESS, 30);
Instance();
if(!CanDealPrintFile(JobID))
{
if(g_hMsgWnd)
{
log_write("auto print fail/n");
SendMessage2Win(VPRINT_MSG_FAIL, 0);
}
ExitInstance();
log_close();
return FALSE;
}
if(vs == wvWinXP)
{
char strSpoolDir[MAX_PATH];
char fname[MAX_PATH];
char *pos;
GetEnvironmentVariable("windir", strSpoolDir, sizeof(strSpoolDir));
strcat(strSpoolDir, "//system32//spool//PRINTERS//");
if(FindPrintFile(strSpoolDir, fname)
&& (pos = strrchr(fname, '//')))
{
strcpy(printFname, pos+1);
}
}
if(FormActivate(filename, printFname, vpType) && g_hMsgWnd)
{/*success*/
log_write("auto print success/n");
SendMessage2Win(VPRINT_MSG_SUCCESS, 0);
}else if(g_hMsgWnd)
{/*fail*/
log_write("auto print fail/n");
SendMessage2Win(VPRINT_MSG_FAIL, 0);
}
PurgePrintJob(JobID);
DeleteMyBitmap();
ExitInstance();
log_close();
return 0;
}
void Instance()
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL);
}
void ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
log_write("free gid plus/n");
Gdiplus::GdiplusShutdown(m_gdiplusToken);
return ;
}
/*check wether need auto print save*/
BOOL bAutoSaveFile(char *fname, char *windowName, VPRINT_FILE_TYPE *pVpType)
{
HKEY hKey;
char buf[MAX_PATH] = {0};
DWORD nLen = MAX_PATH-1;
DWORD reg;
DWORD type;
{
ShowMsg("bAutoSaveFile start");
ShowMsg(fname);
ShowMsg(windowName);
}
if(ERROR_SUCCESS != RegOpenKey(HKEY_LOCAL_MACHINE, PMON_KEY, &hKey))
{
return FALSE;
}
reg = RegQueryValueEx(hKey, "AutoSave", NULL, &type, (BYTE*)buf, &nLen);
if(ERROR_SUCCESS != reg || strcmp(buf, "1"))
{/*get auto print flag*/
RegCloseKey(hKey);
return FALSE;
}
nLen = MAX_PATH-1;
if(ERROR_SUCCESS != RegQueryValueEx(hKey, "DestDir", NULL, &type, (BYTE*)buf, &nLen))
{/*get dir name*/
RegCloseKey(hKey);
return FALSE;
}
buf[nLen -1] = '/0';
strcpy(fname, buf);
nLen = MAX_PATH-1;
if(ERROR_SUCCESS != RegQueryValueEx(hKey, "WindowName", NULL, &type, (BYTE*)buf, &nLen))
{/*get window name*/
RegCloseKey(hKey);
return FALSE;
}
buf[nLen -1] = '/0';
strcpy(windowName, buf);
nLen = MAX_PATH-1;
if(ERROR_SUCCESS != RegQueryValueEx(hKey, "vpType", NULL, &type, (BYTE*)buf, &nLen))
{/*get vprinter type*/
*pVpType = VPRINT_FILE_XWB;
}else
{
buf[nLen -1] = '/0';
*pVpType = (VPRINT_FILE_TYPE)atol(buf);
}
/*clear flag*/
RegSetValueEx(hKey, "DestDir", 0, REG_SZ, (const BYTE*)"", 1);
RegSetValueEx(hKey, "AutoSave", 0, REG_SZ, (const BYTE*)"0", 2);
RegSetValueEx(hKey, "WindowName", 0, REG_SZ, (const BYTE*)"", 1);
RegSetValueEx(hKey, "vpType", 0, REG_SZ, (const BYTE*)"", 1);
RegCloseKey(hKey);
ShowMsg("bAutoSaveFile end-----------------------");
ShowMsg(fname);
ShowMsg(windowName);
ShowMsg("-------------------------");
if(strlen(fname) >= 4 && strlen(windowName) >= 1)
{
ShowMsg("bAutoSaveFile: return TRUE");
return TRUE;
}
ShowMsg("bAutoSaveFile: return FALSE");
return FALSE;
}
/*send msg to auto print window*/
BOOL SendMessage2Win(WPARAM wparam, LPARAM lparam)
{
if(g_hMsgWnd)
{
return PostMessage(g_hMsgWnd, VPRINTF_MSG_RESULT, wparam, lparam);
}
return FALSE;
}
/*get job inf*/
BOOL GetPrintJobInf(DWORD JobId, DWORD Level, LPBYTE pJobInf, DWORD cbBuf)
{
HANDLE hPrinter = NULL;
DWORD op;
if(NULL==pJobInf || cbBuf < 10)
{
return FALSE;
}
/*open printer*/
if(!OpenPrinter((LPTSTR)g_pchPrintName, &hPrinter, NULL))
{
return FALSE;
}
log_write("GetJob print job[%lu]!/n", JobId);
if(GetJob(hPrinter, JobId, Level, (BYTE*)pJobInf, cbBuf, &op))
{/*get job inf*/
ClosePrinter(hPrinter);
return TRUE;
}
log_write("GetPrintJobInft job[%lu] fail {GetJob}!/n", JobId);
ClosePrinter(hPrinter);
return FALSE;
}
/*purge print job*/
BOOL PurgePrintJob(DWORD JobId)
{
HANDLE hPrinter = NULL;
char Buf[2048];
DWORD op;
/*open printer*/
if(!OpenPrinter((LPTSTR)g_pchPrintName, &hPrinter, NULL))
{
log_write("purge print job fail[OpenPrinter]!/n");
return FALSE;
}
if(!GetJob(hPrinter, JobId, 1, (BYTE*)Buf, sizeof(Buf), &op))
{/*get job inf*/
log_write("purge print job[%lu] fail {GetJob}!/n", JobId);
ClosePrinter(hPrinter);
return TRUE;
}
if(SetJob(hPrinter, JobId, 1, (BYTE*)Buf, JOB_CONTROL_DELETE))
{/*purge print job*/
log_write("purge print job[%lu] success!/n", JobId);
ClosePrinter(hPrinter);
return TRUE;
}
log_write("purge print job fail!/n");
ClosePrinter(hPrinter);
return FALSE;
}
/*find printf file*/
BOOL FindPrintFile(char *strDir, char* fname)
{
time_t mtime = 0;
int res = FF_TRING;
int nCont = 0;
while(nCont < 100)
{
if(FF_REE_OK == FindNewFile(strDir, fname, &mtime))
{
break;
}
SendMessage2Win(VPRINT_MSG_PROGESS, 50);
Sleep(1000);
nCont++;
}
log_write("find file[%s]/n", fname);
while(FF_TRING == res)
{
Sleep(2500);
res = FindNewFile(strDir, fname, &mtime);
if(FF_REE_OK == res)
{
Sleep(1500);
res = FindNewFile(strDir, fname, &mtime);
}
SendMessage2Win(VPRINT_MSG_PROGESS, 50);
}
if(FF_REE_OK == res)
{
log_write("find file[%s]ok/n", fname);
return TRUE;
}
return FALSE;
}
/*get new file*/
BOOL FindNewFile(char *strDir, char *fname, time_t *mtime)
{
WIN32_FIND_DATA FileData;
HANDLE hSearch;
char str[MAX_PATH];
time_t time0;
BOOL bFind = FF_FAIL;
struct stat sbuf;
double diff;
if(0 != *mtime)
{/*find out wether the file be modfyed*/
log_write("stat file name[%s]/n", fname);
if(stat(fname,&sbuf) == 0)
{
diff = difftime(*mtime, sbuf.st_mtime);
log_write("diff[%f]/n", diff);
if(diff < -0.0000001)
{
*mtime = sbuf.st_mtime;
return FF_TRING;
}else
{
return FF_REE_OK;
}
}
log_write("stat falil/n");
return FF_FAIL;
}
sprintf(str , "%s*.SPL", strDir);
hSearch = FindFirstFile(str, &FileData);
while(hSearch != INVALID_HANDLE_VALUE)
{
sprintf(str , "%s%s", strDir, FileData.cFileName);
if(stat(str,&sbuf) == 0)
{
if(FF_REE_OK != bFind)
{
strcpy(fname, str);
bFind = FF_REE_OK;
*mtime = time0 = sbuf.st_mtime;
}else
{
if(difftime(time0, sbuf.st_mtime) < -0.000001)
{
strcpy(fname, str);
*mtime = time0 = sbuf.st_mtime;
}
}
}
if(!FindNextFile(hSearch, &FileData))
{
break;
}
}
if(hSearch != INVALID_HANDLE_VALUE)
FindClose(hSearch);
return bFind;
}
/*sleep untile file printed ok*/
BOOL CanDealPrintFile(DWORD JobId)
{
char Buf[2048+1024];
PJOB_INFO_1 pJobInf;
int pos = 30;
int page = 0;
while(1)
{
if(GetPrintJobInf(JobId, 1, (BYTE*)Buf, sizeof(Buf)))
{
pJobInf = (PJOB_INFO_1)Buf;
page = pJobInf->TotalPages;
if(!(pJobInf->Status & JOB_STATUS_SPOOLING))
{
log_write("Status value[%lu]!/n", pJobInf->Status);
break;
}
if(pos+3 < 50)
{
pos += 3;
SendMessage2Win(VPRINT_MSG_PROGESS, pos);
}else
{
SendMessage2Win(VPRINT_MSG_PROGESS, 50);
}
log_write("result Document[%s] totalPage[%d] printed page[%d] postiion[%d]/n status[%ld] PageType[%s]/n",
pJobInf->pDocument, pJobInf->TotalPages, pJobInf->PagesPrinted,
pJobInf->Position, pJobInf->Status, pJobInf->pDatatype);
Sleep(1000);
}else
{
return FALSE;
}
}
g_TotalPages = page;
log_write("b spling ok pages[%d]/n", page);
return TRUE;
}
UINT_PTR CALLBACK MyFileDlgHook(HWND hwnd, UINT msgType, WPARAM wparam, LPARAM lparam)
{
if(msgType == WM_INITDIALOG)
{
HWND hwndOwner;
HWND hShow = hwnd;
RECT rc, rcDlg, rcOwner;
// Get the owner window and dialog box rectangles.
if ((hwndOwner = GetParent(hwnd)) == NULL)
{
hwndOwner = GetDesktopWindow();
}else
{
hShow = hwndOwner;
}
GetWindowRect(hwndOwner, &rcOwner);
GetWindowRect(hwnd, &rcDlg);
CopyRect(&rc, &rcOwner);
// Offset the owner and dialog box rectangles so that
// right and bottom values represent the width and
// height, and then offset the owner again to discard
// space taken up by the dialog box.
OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
OffsetRect(&rc, -rc.left, -rc.top);
OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
// The new position is the sum of half the remaining
// space and the owner's original position.
SetWindowPos(hShow,
HWND_TOP,
rcOwner.left + (rc.right / 2),
rcOwner.top + (rc.bottom / 2),
0, 0, // ignores size arguments
SWP_NOSIZE);
return TRUE;
}
return 0;
}
/*get file name for des*/
BOOL GetDesFileName(char *filename, DWORD JobID, VPRINT_FILE_TYPE *pVpType)
{
char winName[MAX_PATH];
char *pos;
char *pEx = "xwb";
if(!bAutoSaveFile(filename, winName, pVpType))
{
char *pchName = NULL;
char Buf[2048];
PJOB_INFO_1 pJobInf;
OPENFILENAME struFName = {0};
*filename = '/0';
if(GetPrintJobInf(JobID, 1, (BYTE*)Buf, sizeof(Buf)))
{
pJobInf = (PJOB_INFO_1)Buf;
pchName = pJobInf->pDocument;
log_write("result Document[%s] totalPage[%d] printed page[%d] postiion[%d] status[%ld] UserName[%s]/n",
pJobInf->pDocument, pJobInf->TotalPages, pJobInf->PagesPrinted,
pJobInf->Position, pJobInf->Status, pJobInf->pUserName);
strncpy(filename, pJobInf->pDocument, MAX_PATH-1);
pos = strrchr(filename, '.');
if(NULL!=pos && pos>strrchr(filename, '//'))
{
*pos = '/0';
}
}
struFName.lpstrFile = filename;
struFName.hInstance = g_HInstance;
struFName.lStructSize = sizeof(OPENFILENAME);
struFName.hwndOwner = GetDesktopWindow();
struFName.Flags = OFN_OVERWRITEPROMPT|OFN_ENABLESIZING|OFN_HIDEREADONLY|/
OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST|OFN_EXPLORER|OFN_ENABLEHOOK;
struFName.lpstrTitle = "ZTE Virtual Printer";
struFName.lpstrFilter = "While Board(*.xwb)/0*.xwb/0Fax CCITT(*.tif)/0*.tif/0/0";
/*"While Board(*.xwb)/0*.xwb/0Fax CCITT4(*.tif)/0*.tif/0Fax CCITT3(*.tif)/0*.tif/0/0"*/
struFName.lpstrInitialDir = "c://";
struFName.nMaxFile = MAX_PATH-1;
struFName.lpfnHook = (LPOFNHOOKPROC)MyFileDlgHook;
ShowMsg("GetDesFileName--------------");
if(!GetSaveFileName(&struFName))
{
return FALSE;
}
*pVpType = (VPRINT_FILE_TYPE)(struFName.nFilterIndex-1);
}else
{
g_hMsgWnd = (HWND)atol(winName);
log_write("winName handle[%lu]/n", (DWORD)g_hMsgWnd);
}
if(strlen(filename) < 2)
{
log_write("1result file name wrong [%s]/n", filename);
return FALSE;
}
pos = strrchr(filename, '.');
if(*pVpType != VPRINT_FILE_XWB)
{
GetMyPrinterInfo();
pEx = "tif";
}
if(NULL==pos || pos <= strrchr(filename, '//')
|| stricmp(pos+1, pEx))
{
strcat(filename, ".");
strcat(filename, pEx);
}
strcpy(winName, filename);
if(pos = strrchr(winName, '//'))
{
*pos = '/0';
MakeWholeDir(winName);
}else
{
log_write("2result file name wrong [%s]/n", filename);
return FALSE;
}
return TRUE;
}
/*parse command Line, get JobID print file name*/
// cmdLine = "/"Copier.exe/" zte-vprinter, Job 3 <cuizi>";
// cmdLine = "/"Copier.exe/" zte-vprinter, Job 3 <cuizi>#*#";
BOOL MyParseCommandLine(char* printFname, DWORD *JobID)
{
char *cmdLine;
char *pFlag = ", Job ";
LPCTSTR pInf;
DWORD Index = 0;
TWindowsVersion vs;
g_hMsgWnd = NULL;
cmdLine = GetCommandLine();
log_write("with tiff ^_^ result GetCommandLine[%s]/n", cmdLine);
if(!strstr(cmdLine, "<cuizi>"))
{
return FALSE;
}
if(!strstr(cmdLine, "<cuizi>#*#"))
{
char path[MAX_PATH];
char cmd[MAX_PATH];
/*添加标志信息,区分进程是由驱动启动还是Copier启动*/
sprintf(cmd, "%s#*#", cmdLine);
GetSystemDirectory(path, sizeof(path));
strcat(path ,"//Copier.exe");
if(RunProcess(path, cmd))
{/*终止当前进程,启用新的进程以获得当前用户的enviroment*/
return FALSE;
}
}
if(NULL == (pInf=strstr(cmdLine, pFlag)))
{
return FALSE;
}
*JobID = Index = atol(pInf+strlen(pFlag));
vs = GetWindowsVersion();
if((wvWin2003==vs || wvWinXP==vs)&& Index >=2
|| vs == wvVista || vs == wvVista_ia64 || vs == wvVista_x64
|| vs == wvWin7 || vs == wvWin7_ia64 || vs == wvWin7_x64
)
{
Index -= 2;
sprintf(printFname, "FP%05lu.SPL", Index);
}else
{
sprintf(printFname, "%05lu.SPL", Index);
}
return TRUE;
}
/*wvWin95, wvWin95OSR2, wvWin98, wvWin98SE, wvWinME, wvWinNT3, wvWinNT4, wvWin2000, wvWinXP wvWin2003*/
//=========================================================================================================================
// Win32Platform 1 1 1 1 1 2 2 2 2 2
// Win32MajorVersion 4 4 4 4 4 3 4 5 5 5
// Win32MinorVersion 0 0 10 10 90 ? 0 0 1 2
// Win32BuildNumber ? 67109975 67766222 67766446 73010104 ? 1381 2195 ? ?
// Win32CSDVersion ? 'B' '' A SP SP SP ? ? ?
typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD);
// INTEL ITANIUM64
#define PRODUCT_ENTERPRISE_SERVER_IA64 0x0000000F
// AMD 和 INTEL 64位
#define PROCESSOR_ARCHITECTURE_AMD64 0x00000009
TWindowsVersion GetWindowsVersion()
{
OSVERSIONINFO VersionInfo;
TWindowsVersion Result;
Result = wvUnknown;
VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx( &VersionInfo );
switch(VersionInfo.dwPlatformId)
{
case VER_PLATFORM_WIN32_WINDOWS:
{
switch(VersionInfo.dwMinorVersion)
{
case 0:
if (_T('B') == VersionInfo.szCSDVersion[1])
{
Result = wvWin95OSR2;
}
else
Result = wvWin95;
break;
case 10:
if (_T('A') == VersionInfo.szCSDVersion[1])
{
Result = wvWin98SE;
}
else
{
Result = wvWin98;
}
break;
case 90:
if (VersionInfo.dwBuildNumber = 73010104)
{
Result = wvWinME;
}
break;
default:
break;
}
}
break;
case VER_PLATFORM_WIN32_NT:
{
switch(VersionInfo.dwMajorVersion) {
case 3:
Result = wvWinNT3;
break;
case 4:
Result = wvWinNT4;
break;
case 5:
if(0 == VersionInfo.dwMinorVersion)
{
Result = wvWin2000;
}else if(1 == VersionInfo.dwMinorVersion)
{
Result = wvWinXP;
}else if(2 == VersionInfo.dwMinorVersion)
{
Result = wvWin2003;
}
break;
// case 6:
// if (0 == VersionInfo.dwMinorVersion)
// {
// Result = wvVista;
// }
// else if (1 == VersionInfo.dwMinorVersion)
// {
// Result = wvWin7;
// }
// break;
case 6:
{
if (0 == VersionInfo.dwMinorVersion)
{
Result = wvVista;
}
else if (1 == VersionInfo.dwMinorVersion)
{
Result = wvWin7;
}
DWORD dwType = 0;
PGPI pGPI = (PGPI) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo");
pGPI( VersionInfo.dwMajorVersion, VersionInfo.dwMinorVersion, 0, 0, &dwType);
if (dwType == PRODUCT_ENTERPRISE_SERVER_IA64)
{
if (Result == wvVista)
{
Result = wvVista_ia64;
}
else if (Result == wvWin7)
{
Result = wvWin7_ia64;
}
}
else
{
SYSTEM_INFO si;
ZeroMemory(&si, sizeof(SYSTEM_INFO));
PGNSI pGNSI = (PGNSI) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo");
if(NULL != pGNSI)
pGNSI(&si);
else GetSystemInfo(&si);
if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
{
if (Result == wvVista)
{
Result = wvVista_x64;
}
else if (Result == wvWin7)
{
Result = wvWin7_x64;
}
}
}
}
break;
default:
break;
}
}
break;
default:
break;
}
return Result;
}
/*send msg to auto print window*/
BOOL SendMessage2Win(WPARAM wparam, LPARAM lparam);
// USES_CONVERSION;
int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
UINT num = 0; // number of image encoders
UINT size = 0; // size of the image encoder array in bytes
using namespace Gdiplus;
ImageCodecInfo* pImageCodecInfo = NULL;
GetImageEncodersSize(&num, &size);
if(size == 0)
return -1; // Failure
pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
if(pImageCodecInfo == NULL)
return -1; // Failure
GetImageEncoders(num, size, pImageCodecInfo);
for(UINT j = 0; j < num; ++j)
{
if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
{
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
return j; // Success
}
}
free(pImageCodecInfo);
log_write("GetEncoderClsid fail/n");
return -1; // Failure
}
BOOL fDetectHeaderBytes(char *fileName, char *headBuf)
{
int i;
FILE *fp;
char Buf[HEAD_LEN];// six emf header bytes
EMFInf_t Head;
if(NULL == fileName || NULL == headBuf)
return FALSE;
if(NULL == (fp=fopen(fileName, "rb")))
{
log_write("file open fail[%s]", fileName);
return FALSE;
}
// Read SPL signature
fread(&i, 1, 4, fp);
if (i != 0x00010000)
{
log_write("This is not a valid spooler file");
fclose(fp);
return FALSE;
}
// Read first emf chunk
fread(&i, 4, 1, fp);
fseek(fp, i, SEEK_SET);
fread(&Head, sizeof(Head), 1, fp);
if ((Head.Signature != EMFheaderSignature) || Head.EMFsize == 0)
{
// bad file
log_write("This is not a valid spooler file");
return FALSE;
}
fread(Buf, sizeof(Buf), 1, fp);
fclose(fp);
// Buf contains the six emf header bytes
memcpy(headBuf, Buf, sizeof(Buf));
return TRUE;
}
char* memnmem(char *sMem, int sLen, char *dMem, int dLen)
{
int x, y;
char flag = 0;
if(NULL==sMem || NULL==dMem || sLen > dLen)
return NULL;
for(x=0; x<=dLen-sLen; x++)
{
flag = 1;
for(y=0; y<sLen && flag; y++)
{
if(*(sMem+y) != *(dMem+x+y))
{
flag = 0;
}
}
if(flag)
return (char*)(dMem+x);
}
return NULL;
}
#define MAX_3M_BUF 3*1024*1024
#define MAX_4M_BUF 4*1024*1024
#define IMAGE_TYPE "docpage"
#define VPRINT_MAX_PAGE 600
//功能描述: 按照文件指针获取文件尺寸
long drm_iGetFileSizeByFp(FILE *fp)
{
long size = 0;
long pos = 0;
if(NULL == fp)
{
return 0;
}
/* 暂存当前文件读写位置,操作后恢复 */
pos = ftell(fp);
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, pos, SEEK_SET);
return size;
}
#include "Shlwapi.h"
#pragma comment(lib, "Shlwapi.lib")
/**/
BOOL ReadBinaryDataFile(char *pathName, char *strFilename, char *strDestDir, VPRINT_FILE_TYPE vpType)
{
// this reads an nt spool file (.spl), extracts the emfs out of
// it and writes *.emf files into strDestDir
FILE *fFromF; // input / output files
int nRead, nReadTotal;
int IndexPos;
char Buf[2048]; // buffer to read emf data into
int nPixFound, test; // # of pictures found
char headBuf[HEAD_LEN+2] = {0};// six emf header bytes read from fDetectHeaderBytes
int postArray[VPRINT_MAX_PAGE+2];
char *pCh;
int contLen = 0;
BOOL res = FALSE;
log_write("ReadBinaryDataFile strFilename[%s] strDestDir[%s]/n", strFilename, strDestDir);
if(FALSE == fDetectHeaderBytes(strFilename, headBuf))
{
log_write("fDetectHeaderBytes fail/n");
return FALSE;
}
if(NULL == (fFromF=fopen(strFilename, "rb")))
{
log_write("file[%s] open fail/n", strFilename);
return FALSE;
}
nPixFound = 0;
nReadTotal = 0;
IndexPos = 0;
// check # of emf's in spl-file
do{
// #s of files: nPixFound
// PosList: Positions of file beginnings in emf
nRead = fread(Buf+IndexPos, 1, sizeof(Buf)-IndexPos, fFromF);
contLen = nRead+IndexPos;
pCh = memnmem(headBuf, HEAD_LEN, Buf, contLen);
if (NULL != pCh)
{
test = (int)(pCh - Buf);
postArray[nPixFound] = test + nReadTotal;
nPixFound++;
}
if(NULL==pCh)
{
memmove(Buf, Buf+(contLen-HEAD_LEN), HEAD_LEN);
IndexPos = HEAD_LEN;
}else
{
int len = contLen - (pCh-Buf+HEAD_LEN);
IndexPos = 0;
if(len > 0)
{
memmove(Buf, pCh+HEAD_LEN, len);
IndexPos = len;
}
}
nReadTotal += (contLen-IndexPos);
}while (nRead != 0 && nPixFound<VPRINT_MAX_PAGE && !feof(fFromF) && !ferror(fFromF)); //
log_write("vprint page count[%d]/n", nPixFound);
if(g_TotalPages && g_TotalPages<nPixFound)
{
log_write("modify pages num new-vaules[%d] old-values[%d]/n", g_TotalPages, nPixFound);
nPixFound = g_TotalPages;
}
if(vpType == VPRINT_FILE_XWB)
{
log_write("call CreateWhiteBoard vprint xwb/n");
res = CreateWhiteBoard(fFromF, nPixFound, postArray, pathName);
}else
{
log_write("call CreateTiffFile vprint tiff type[%d]/n", vpType);
res = CreateTiffFile(fFromF, nPixFound, postArray, pathName, vpType);
}
fclose(fFromF);
return res;
}
/*build xwb/tiff file*/
BOOL FormActivate(char *pathName/*result file/path name *.xwb/*.tif*/,
char *printFname/*file *.SPL*/, VPRINT_FILE_TYPE vpType)
{
char strSpoolDir[MAX_PATH]; // spool-directory (NT only)
char strDestDir[MAX_PATH]; // destination directory for emfs
char lpszSpoolDir[MAX_PATH]; // spool dir (nt only)
char fileCopy[MAX_PATH];
char vPrintFile[MAX_PATH];
BOOL res = FALSE;
{
// char szMsg[1024];
// sprintf(szMsg, "MsgBox.exe %s-%s", pathName, printFname);
// WinExec(szMsg, SW_SHOW);
ShowMsg("Form Activate-------------------------------");
ShowMsg(pathName);
ShowMsg(printFname);
ShowMsg("-------------------------------");
}
if(NULL == strrchr(pathName, '//'))
{
log_write("result file/path name error %s/n", pathName);
return FALSE;
}
ShowMsg("1 -------------------------------");
GetEnvironmentVariable("windir", lpszSpoolDir, sizeof(lpszSpoolDir));
sprintf(strDestDir, "%s//", lpszSpoolDir);
log_write("strDestDir[%s] lpszSpoolDir[%s]/n", strDestDir, lpszSpoolDir);
// get OS-Version
TWindowsVersion strOSVer = GetWindowsVersion();
if (wvWin2000==strOSVer || wvWinXP==strOSVer || wvWinNT3==strOSVer || wvWinNT4==strOSVer
|| wvWin2003==strOSVer
|| strOSVer == wvVista || strOSVer == wvVista_ia64 || strOSVer == wvVista_x64
|| strOSVer == wvWin7 || strOSVer == wvWin7_ia64 || strOSVer == wvWin7_x64
)
{
// NT or higher detected; locate spool-directory
sprintf(strSpoolDir, "%s//system32//spool//PRINTERS//", lpszSpoolDir);
}else
{
return FALSE;
}
ShowMsg("2 -------------------------------");
sprintf(fileCopy, "%s%s", strDestDir, printFname);
sprintf(vPrintFile, "%s%s", strSpoolDir, printFname);
SendMessage2Win(VPRINT_MSG_PROGESS, 50);
/**/
log_write("fileCopy[%s] filename[%s] strDestDir[%s]/n" , fileCopy, vPrintFile, strDestDir);
if(!CopyFile(vPrintFile, fileCopy, FALSE))
{
LPVOID lpMsgBuf;
GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), NULL,(LPTSTR) &lpMsgBuf, 0, NULL );
log_write("CopyFile faile reason[%s]/n", lpMsgBuf);
LocalFree( lpMsgBuf );
ShowMsg("CopyFile() failure ");
ShowMsg(vPrintFile);
ShowMsg(fileCopy);
return FALSE;
}
ShowMsg("3 -------------------------------");
res = ReadBinaryDataFile(pathName, fileCopy, strDestDir, vpType);
DeleteFile(fileCopy);
DeleteFile(vPrintFile);
return res;
}