1.first time update with GitHub

2.this Twain C++ Code has fixed with OpenCV Findcontours and fillploy error
3.now it might has some unknown error in the code ,while it need to be fixed later
This commit is contained in:
pm 2019-02-28 10:14:54 +08:00
parent 18bf319206
commit e0b42b7784
580 changed files with 444804 additions and 0 deletions

55
hugaotwainds.sln Normal file
View File

@ -0,0 +1,55 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "hugaotwainds", "hugaotwainds\hugaotwainds.vcxproj", "{F928F998-CD13-478E-8D23-5943C2B108F5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.WPF", "..\wpf源码\Sample.WPF.csproj", "{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F928F998-CD13-478E-8D23-5943C2B108F5}.Debug|Any CPU.ActiveCfg = Debug|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Debug|Mixed Platforms.ActiveCfg = Debug|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Debug|Mixed Platforms.Build.0 = Debug|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Debug|x64.ActiveCfg = Debug|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Debug|x64.Build.0 = Debug|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Debug|x86.ActiveCfg = Debug|Win32
{F928F998-CD13-478E-8D23-5943C2B108F5}.Debug|x86.Build.0 = Debug|Win32
{F928F998-CD13-478E-8D23-5943C2B108F5}.Release|Any CPU.ActiveCfg = Release|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Release|Mixed Platforms.ActiveCfg = Release|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Release|Mixed Platforms.Build.0 = Release|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Release|x64.ActiveCfg = Release|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Release|x64.Build.0 = Release|x64
{F928F998-CD13-478E-8D23-5943C2B108F5}.Release|x86.ActiveCfg = Release|Win32
{F928F998-CD13-478E-8D23-5943C2B108F5}.Release|x86.Build.0 = Release|Win32
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Debug|x64.ActiveCfg = Debug|x86
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Debug|x86.ActiveCfg = Debug|x86
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Debug|x86.Build.0 = Debug|x86
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Release|Any CPU.Build.0 = Release|Any CPU
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Release|x64.ActiveCfg = Release|x86
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Release|x86.ActiveCfg = Release|x86
{1715C2B7-5C35-4F8B-9D9B-8D68A3D5284D}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {93BB7BF9-5375-4DEB-B06A-EB8DF2E08909}
EndGlobalSection
EndGlobal

BIN
hugaotwainds.suo Normal file

Binary file not shown.

View File

@ -0,0 +1,54 @@
// AboutHuaGoDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "hugaotwainds.h"
#include "AboutHuaGoDlg.h"
#include "afxdialogex.h"
// AboutHuaGoDlg 对话框
IMPLEMENT_DYNAMIC(AboutHuaGoDlg, CDialog)
AboutHuaGoDlg::AboutHuaGoDlg(std::string scnrname,std::string serialNum,std::string hardVersion,CWnd* pParent /*=NULL*/)
: CDialog(IDD_DIALOGABOUT, pParent)
{
this->scanHardVersion=hardVersion;
this->scanName=scnrname;
this->scanSerialNum=serialNum;
}
AboutHuaGoDlg::~AboutHuaGoDlg()
{
}
void AboutHuaGoDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//DDX_Control(pDX,IDC_PICABOUTHUAGO,m_pic);
}
BEGIN_MESSAGE_MAP(AboutHuaGoDlg, CDialog)
END_MESSAGE_MAP()
// AboutHuaGoDlg 消息处理程序
BOOL AboutHuaGoDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: 在此添加额外的初始化
UpdateScannerInfo();
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
void AboutHuaGoDlg::UpdateScannerInfo()
{
((CStatic*)GetDlgItem(IDC_LBSCANNERNAMEVALUE))->SetWindowText(scanName.c_str());
((CStatic*)GetDlgItem(IDC_LBSERIALNUMVALUE))->SetWindowText(scanSerialNum.c_str());
((CStatic*)GetDlgItem(IDC_LBHARDWAREVALUE))->SetWindowText(scanHardVersion.c_str());
}

View File

@ -0,0 +1,30 @@
#pragma once
#include "resource.h"
#include <string>
using namespace std;
// AboutHuaGoDlg 对话框
class AboutHuaGoDlg : public CDialog
{
DECLARE_DYNAMIC(AboutHuaGoDlg)
public:
AboutHuaGoDlg(std::string scnrname="",std::string serialNum="",std::string hardVersion="", CWnd* pParent = NULL); // 标准构造函数
virtual ~AboutHuaGoDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOGABOUT };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
private:
void UpdateScannerInfo();
std::string scanName;
std::string scanSerialNum;
std::string scanHardVersion;
};

398
hugaotwainds/AutoCrop.cpp Normal file
View File

@ -0,0 +1,398 @@
#include "StdAfx.h"
#include "AutoCrop.h"
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif // !_USE_MATH_DEFINES
#include <math.h>
#include "PublicFunc.h"
CAutoCrop::CAutoCrop( bool bFill,bool bautoDeScrew, bool bCrop,SIZE dstsize,SIZE originSize)
:m_bAutoDescrew(bautoDeScrew), m_bCrop(bCrop), m_bFill(bFill),m_dstSize(dstsize),m_originSize(originSize)
{
}
CAutoCrop::~CAutoCrop()
{
}
void CAutoCrop::apply(cv::Mat & dib,int side)
{
//XdPrint("CAutoCrop");
RotatedRect rect;
vector<Point> contour;
double scale = 0.25;
double thresh = 70;
int blobSize = 200;
int edgeWidth =5;
ProcessRect(dib, rect, contour, scale, thresh, blobSize);
//XdPrint("Begin m_bFill \n");
if (m_bFill)
{
fillBlack(dib, contour,edgeWidth);
//XdPrint("m_bFill \n");
}
if (m_bAutoDescrew)//自动纠偏
{
//XdPrint("m_bAutoDescrew strart\n");
RotateImage(dib,rect,m_bCrop,m_bFill);//自动纠偏和自动裁切或自动纠偏 不自动裁切
//XdPrint("m_bAutoDescrew end\n");
}
if (m_bCrop&&!m_bAutoDescrew)//自动裁切 但不纠偏
{
vector<Point> vec(contour);
Rect rectOut=boundingRect(vec);
Mat temp=dib(rectOut);
dib=temp.clone();
temp.release();
}
if (!m_bCrop)
{
dib=FixedCut(dib,side);
//XdPrint("m_bCrop \n");
}
}
void CAutoCrop::setFill(bool val)
{
m_bFill = val;
}
bool CAutoCrop::getFill()
{
return m_bFill;
}
void CAutoCrop::setCrop(bool val)
{
m_bCrop = val;
}
bool CAutoCrop::getCrop()
{
return m_bCrop;
}
Point2f CAutoCrop::RotateP2P(Point2f p, Point2f center, double Angle)
{
double h = Angle * M_PI / 180;
float x = (p.x - center.x) * (float)cos(h) - (p.y - center.y) * (float)sin(h) + center.x;
float y = (p.y - center.y) * (float)cos(h) + (p.x - center.x) * (float)sin(h) + center.y;
return Point2f(x, y);
}
void CAutoCrop::RotateImage(Mat & image, RotatedRect rotatedRect, bool bCrop,bool fillBlack)
{
Point2f center(image.cols / 2, image.rows / 2);
Mat rot = getRotationMatrix2D(center, rotatedRect.angle, 1);
RotatedRect rotated = RotatedRect(center, image.size(), -rotatedRect.angle);
Rect bbox = rotated.boundingRect();
Scalar sc;
if (fillBlack)
{
warpAffine(image, image, rot, bbox.size(), CV_INTER_LINEAR,0,image.channels()==3?Scalar(255,255,255):Scalar(255));//CV_INTER_NN
}
else
{
warpAffine(image, image, rot, bbox.size(), CV_INTER_LINEAR,0,Scalar(0));//CV_INTER_NN
}
if(!bCrop)
return;
Point2f box[4];
vector<Point2f > vec;
rotatedRect.points(box);
for (int i = 0; i < 4; i++)
{
box[i] = RotateP2P(box[i], center, -rotatedRect.angle);
vec.push_back(box[i]);
}
RotatedRect rec = minAreaRect(vec);
Rect roi = rec.boundingRect();
Rect rectIm(0, 0, image.cols, image.rows);
roi = roi & rectIm;
image = image(roi);
}
int CAutoCrop::ProcessRect(Mat & image, RotatedRect & rotatedRect, vector<Point>& maxContour, double scale, double thresh, int blobAreaSize)
{
Mat gray;
int blockCount = 0;
if (image.channels() == 3)
{
if (scale != 1.0f)
{
Size ResImgSiz = Size(image.cols*scale, image.rows*scale);
resize(image, gray, cv::Size(), scale, scale, 0);
cvtColor(gray, gray, CV_BGR2GRAY);
}
}
else
{
if (scale != 1.0f)
{
resize(image, gray, cv::Size(), scale, scale, 0);
}
}
Mat threshold_img;
threshold(gray, threshold_img, thresh, 255.0, CV_THRESH_BINARY);
//imwrite("threshold_img.bmp",threshold_img);
//vector<Point> aaa;
//aaa.push_back(Point(0, 0));
//double bbb = contourArea(aaa);
vector<vector<Point>> contours;
//XdPrint("findContours Before \n");
vector<Vec4i> h1;
//findContours(threshold_img,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
GetContours(threshold_img, contours,h1,CV_RETR_EXTERNAL);
//XdPrint("threshold_img.release() Before \n");
threshold_img.release();
//XdPrint("findContours after \n");
//for (int i=0;i<contours.size();i++)
//{
// XdPrint("Conutours %d",contours[i].size());
//}
if (contours.size() == 0)
{
return blockCount;
}
vector<Point> list_com;
////XdPrint("contours.size() %d \n",contours.size());
for (int i = 0; i < contours.size(); i++)
{
double area = contourArea(contours[i]);
//XdPrint("area %f \n",area);
//XdPrint("contours.Cycle times %d \n",i);
if (area > blobAreaSize)
{
blockCount++;
for (int j = 0; j < contours[i].size(); j++)
{
list_com.push_back(contours[i][j]);
}
}
}
if (list_com.size() == 0)
{
return blockCount;
}
////XdPrint("minAreaRect Before \n ");
rotatedRect = minAreaRect(list_com);
rotatedRect.center.x /= (float)scale;
rotatedRect.center.y /= (float)scale;
rotatedRect.size.width /= (float)scale;
rotatedRect.size.height /= (float)scale;
////XdPrint("rotatedRect.angle < -45.0f \n");
if (rotatedRect.angle < -45.0f)
{
rotatedRect.angle += 90.0f;
float l_temp = rotatedRect.size.width;
rotatedRect.size.width = rotatedRect.size.height;
rotatedRect.size.height = l_temp;
}
vector<int> hull(list_com.size());
//for (int i=0;i<list_com.size();i++)
//{
// XdPrint("X :%d Y:%d \n",list_com[i].x,list_com[i].y);
//}
convexHull(list_com, hull);
for (int i = 0; i < hull.size(); i++)
{
Point temp = list_com[hull[i]];
int x = (int)(temp.x / scale);
int y = (int)(temp.y / scale);
maxContour.push_back(Point(x, y));
}
return blockCount;
}
void CAutoCrop::fillBlack(cv::Mat & dib, std::vector<cv::Point>& contour, int edge)
{
Mat mask(dib.rows, dib.cols, CV_8UC1);
if (contour.size() < 3)
{
return;
}
mask.setTo(255);
fillConvexPoly(mask, contour, Scalar(0));//填充轮廓构成的凸多边形
Mat dilateKer = getStructuringElement(MORPH_RECT, Size(3, 3));
dilate(mask, mask, dilateKer, Point(-1, -1), edge, BORDER_CONSTANT);//向内腐蚀灰边的宽度
//imwrite("mask1.bmp",mask);
dilateKer.release();
cv::vector<cv::vector<Point>> contours;
cv::vector<Vec4i> h1;
GetContours(mask, contours, h1,CV_RETR_LIST);//向内腐蚀后的轮廓
//XdPrint("GetContours after");
mask.release();
//vector<Point> temp=contours.at(0);
//const Point* pnt[1]={&temp[0]};
//int numofPoints=(int)temp.size();
//for (int i=0;i<contours.size();i++)
//{
// for (int j=0;j<contours[i].size();j++)
// {
// XdPrint(" X: %d Y: %d \n",contours[i][j].x,contours[i][j].y);
// }
//}
MyFillPoly(dib,contours,cv::Scalar::all(255));
}
Mat CAutoCrop::AutomaticDeskew(Mat image,int thres,float scale)
{
RotatedRect rotatedRect;
vector<Point> contour;
RotateImage(image, rotatedRect);
//XdPrint("AutomaticDeskew");
return image;
}
Mat CAutoCrop::FixedCut(Mat image,int side)
{
Size szActual;
szActual.width=m_dstSize.cx;
szActual.height=m_dstSize.cy;
Size szOrg;
szOrg.width=m_originSize.cx;
szOrg.height=m_originSize.cy;
Rect rectCrop;
rectCrop.x = (image.cols- szOrg.width) / 2 ;
rectCrop.y = 0;
rectCrop.width = szOrg.width;
rectCrop.height = szOrg.height;
Rect rectImage(0, 0, image.cols, image.rows);
if (side != 0)
{
rectCrop.y = 143; //调整反面
}else
{
rectCrop.y = 73; //调整正面
}
Size CropOrg = (rectCrop & rectImage).size ();
Mat roi = image(rectCrop);
//XdPrint("FixedCut");
return roi;
}
//void CAutoCrop::fillrect(InputOutputArray img, InputArrayOfArrays pts, const Scalar& color, int lineType, int shift, Point offset)
//{
// int i, ncontours = (int)pts.total();
// if( ncontours == 0 )
// return;
// AutoBuffer<Point*> _ptsptr(ncontours);
// AutoBuffer<int> _npts(ncontours);
// Point** ptsptr = _ptsptr.data();
// int* npts = _npts.data();
//
// for( i = 0; i < ncontours; i++ )
// {
// Mat p = pts.getMat(i);
// CV_Assert(p.checkVector(2, CV_32S) >= 0);
// ptsptr[i] = p.ptr<Point>();
// npts[i] = p.rows*p.cols*p.channels()/2;
// }
// fillPoly(img, (const Point**)ptsptr, npts, (int)ncontours, color, lineType, shift, offset);
//}
int CAutoCrop::range(int low, int up, int value)
{
if (low > up)
{
return value;
}
if (value < low)
{
return low;
}
if (value > up)
{
return up;
}
return value;
}
void CAutoCrop::GetContours(const Mat& src, vector<vector<Point>>& contours, vector<Vec4i>& hierarchy, int retr /*= RETR_CCOMP*/)
{
CvMat c_image = src;
MemStorage storage(cvCreateMemStorage());
CvSeq* _ccontours = 0;
cvFindContours(&c_image, storage, &_ccontours, sizeof(CvContour), retr, CHAIN_APPROX_SIMPLE);
if (!_ccontours)
{
contours.clear();
return;
}
Seq<CvSeq*> all_contours(cvTreeToNodeSeq(_ccontours, sizeof(CvSeq), storage));
int total = (int)all_contours.size();
contours.resize(total);
SeqIterator<CvSeq*> it = all_contours.begin();
for (int i = 0; i < total; i++, ++it)
{
CvSeq* c = *it;
((CvContour*)c)->color = (int)i;
int count = (int)c->total;
int* data = new int[count * 2];
cvCvtSeqToArray(c, data);
for (int j = 0; j < count; j++)
{
contours[i].push_back(Point(data[j * 2], data[j * 2 + 1]));
}
delete[] data;
}
hierarchy.resize(total);
it = all_contours.begin();
for (int i = 0; i < total; i++, ++it)
{
CvSeq* c = *it;
int h_next = c->h_next ? ((CvContour*)c->h_next)->color : -1;
int h_prev = c->h_prev ? ((CvContour*)c->h_prev)->color : -1;
int v_next = c->v_next ? ((CvContour*)c->v_next)->color : -1;
int v_prev = c->v_prev ? ((CvContour*)c->v_prev)->color : -1;
hierarchy[i] = Vec4i(h_next, h_prev, v_next, v_prev);
}
}
void CAutoCrop::MyFillPoly(Mat& img, vector<vector<Point>> contours, const Scalar& color, int lineType, int shift, Point offset)
{
Point** ptsptr = new Point*[contours.size()];
int length1 = contours.size();
int* npts = new int[length1];
for (size_t i = 0; i < length1; i++)
{
int length2 = contours[i].size();
npts[i] = length2;
ptsptr[i] = new Point[length2];
for (size_t j = 0; j < length2; j++)
{
ptsptr[i][j] = contours[i][j];
}
}
fillPoly(img, (const Point**)ptsptr, npts, length1, color, lineType, shift, offset);
for (size_t i = 0; i < length1; i++)
{
delete[] ptsptr[i];
}
delete[] ptsptr;
delete[] npts;
}

43
hugaotwainds/AutoCrop.h Normal file
View File

@ -0,0 +1,43 @@
#pragma once
#include "ImageApply.h"
#include "opencv2/opencv.hpp"
#include "opencv/cv.h"
#include "opencv2/core/core.hpp"
using namespace cv;
class CAutoCrop : public CImageApply
{
public:
CAutoCrop( bool bFill = true,bool bautoDeScrew = true,bool bCrop = true,SIZE dstsize = CSize(0, 0),SIZE originsize=CSize(0,0));
virtual ~CAutoCrop();
void apply(cv::Mat& dib,int side);
void setFill(bool val);
bool getFill();
void setCrop(bool val);
bool getCrop();
int m_side;
private:
cv::Point2f RotateP2P(cv::Point2f p, cv::Point2f center, double Angle);
void RotateImage(cv::Mat& image, cv::RotatedRect rotatedRect, bool bCrop = true,bool fillBlack=true);
int ProcessRect(cv::Mat& image, cv::RotatedRect &rotatedRect, std::vector<cv::Point> & maxContour, double scale, double thresh, int blobAreaSize);
void fillBlack(cv:: Mat & dib, std::vector<cv::Point>& contour, int edge = 10);
cv::Mat AutomaticDeskew(cv::Mat image,int thres,float scale);
cv::Mat FixedCut(cv::Mat image,int side);
void MyFillPoly(Mat& img, vector<vector<Point>> contours, const Scalar& color, int lineType=8, int shift=0,
Point offset=Point() );
//void fillrect(InputOutputArray img, InputArrayOfArrays pts,
// const Scalar& color, int lineType, int shift, Point offset);
int range(int low, int up, int value);
void GetContours(const Mat& src, cv::vector<cv::vector<Point>>& contours, cv::vector<Vec4i>& hierarchy, int retr = RETR_CCOMP);
bool m_bCrop;
bool m_bFill;
bool m_bAutoDescrew;
SIZE m_dstSize;
SIZE m_originSize;
};

Binary file not shown.

BIN
hugaotwainds/BasicSetting.h Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,887 @@
/***************************************************************************
* Copyright <EFBFBD> 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CScanner_FreeImage.cpp
* Defines a scanner.
* Create a virtual scanner.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CScanner_FreeImage.h"
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "scn_config.h"
#include "gscn_drv.h"
#include "PublicFunc.h"
#include "AutoCrop.h"
#include "ImageAdjustColors.h"
#include "ImageChannel.h"
#include "ImageApplyResize.h"
#include "ImageRotation.h"
#include "ImageProcDiscardBlank.h"
#ifdef TWH_CMP_MSC
#include <io.h>
#elif __APPLE__
//#include <io.h>
#else //#ifdef TWH_CMP_MSC
#include <sys/io.h>
#endif //#ifdef TWH_CMP_MSC
#ifdef TWNDS_OS_LINUX
#define kTWAIN_DS_DIR "/usr/local/lib/twain/sample2"
#endif
#include "DSMInterface.h"
using namespace std;
#ifdef TWNDS_OS_APPLE
#include "CoreFoundation/CoreFoundation.h"
#include "CoreFoundation/CFBundle.h"
#include "CoreFoundation/CFURL.h"
#include <Carbon/Carbon.h>
#endif
/**
* Environment vars to get the Xfer Count. Create this enviroment Varable on your system to simulate the
* number of pages sitting in the scanner waiting to be scanned.
*/
#define kGETENV_XFERCOUNT "CAP_XFERCOUNT"
#ifdef TWH_CMP_MSC
extern HINSTANCE g_hinstance;
#endif
class ImageTranferMat : public ImageTransfer
{
public:
ImageTranferMat(cv::Mat& mat):m_mat(mat)
{
//imwrite("Gray.bmp",mat);
}
virtual ~ImageTranferMat(){}
virtual unsigned char* getLineBits(int line = 0)
{
return m_mat.ptr<BYTE>(line);
}
virtual int step()
{
return m_mat.step1();
}
virtual int bpp()
{
return m_mat.elemSize()*8;
}
virtual int width()
{
return m_mat.cols;
}
virtual int height()
{
return m_mat.rows;
}
private:
cv::Mat m_mat;
};
class ImageTranferBW : public ImageTransfer
{
public:
ImageTranferBW(cv::Mat& mat)
{
threshold(mat,mat,128.0,255.0,CV_THRESH_BINARY);
//imwrite("threshold.bmp",mat);
m_width = mat.cols;
m_height = mat.rows;
//!< 生成图像
m_buffer = new unsigned char[height()*step()];
memset(m_buffer,0,height()*step());
unsigned char* binary = m_buffer;
int n_lineByte = (m_width + 7) >> 3;
unsigned char * imageData = mat.data;
unsigned char temp;
for(int row = 0 ; row<m_height; row++)
{
for(int col =0; col < m_width; col++ )
{
int pos = col % 8;
int pix = *(imageData+ row * mat.step1() + col);
temp = 1 << (7 - pos );
if( pix == 255 )
{
*(binary+row*m_lineByte + col /8) |= temp;
}
else
{
*(binary+row*m_lineByte + col / 8 ) &= (~temp);
}
}
}
}
virtual ~ImageTranferBW()
{
if(m_buffer != NULL)
{
delete[] m_buffer;
}
}
virtual unsigned char* getLineBits(int line = 0)
{
return m_buffer+step()*line;
}
virtual int step()
{
int n_lineByte = (m_width + 7) >> 3;
m_lineByte = ((n_lineByte * 8 + 31)>>5)<<2 ;
return m_lineByte;
}
virtual int bpp()
{
return 1;
}
virtual int width()
{
return m_width;
}
virtual int height()
{
return m_height;
}
private:
unsigned char* m_buffer;
int m_width;
int m_height;
int m_lineByte;
};
static std::map<int, SIZE> sizeS;
#define TWSS_A4R 60
enum TwSS : ushort
{
None = 0,
A4Letter = 1,
A4 = 1,
B5Letter = 2,
JISB5 = 2,
B5 = 2,
USLetter = 3,
USLegal = 4,
A5 = 5,
B4 = 6,
ISOB4 = 6,
B6 = 7,
ISOB6 = 7,
USLedger = 9,
USExecutive = 10,
A3 = 11,
B3 = 12,
ISOB3 = 12,
A6 = 13,
C4 = 14,
C5 = 15,
C6 = 16,
_4A0 = 17,
_2A0 = 18,
A0 = 19,
A1 = 20,
A2 = 21,
A7 = 22,
A8 = 23,
A9 = 24,
A10 = 25,
ISOB0 = 26,
ISOB1 = 27,
ISOB2 = 28,
ISOB5 = 29,
ISOB7 = 30,
ISOB8 = 31,
ISOB9 = 32,
ISOB10 = 33,
JISB0 = 34,
JISB1 = 35,
JISB2 = 36,
JISB3 = 37,
JISB4 = 38,
JISB6 = 39,
JISB7 = 40,
JISB8 = 41,
JISB9 = 42,
JISB10 = 43,
C0 = 44,
C1 = 45,
C2 = 46,
C3 = 47,
C7 = 48,
C8 = 49,
C9 = 50,
C10 = 51,
USStatement = 52,
BusinessCard = 53,
A4R = 60,
A5R = 61,
A6R = 62,
B5R = 70,
B6R = 71,
USLetterR = 80,
DOUBLELetter = 81,
AUTO = 90
};
static map<pair<TwSS, float>, CSize> dpiDct;
static void initialDictionary()
{
//自适应
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)90, 50.0),CSize(594, 898)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)90, 75),CSize(892, 1347)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)90, 100),CSize(1189, 1795)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)90, 150),CSize(1784, 2693)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)90, 200),CSize(2338, 3307)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)90, 240), CSize(2854, 4308)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)90, 300),CSize(3567, 5385)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)90, 400), CSize(4756, 7180) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)90, 600), CSize(7134, 10770)));
//A3
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A3, 50), CSize(585, 827)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A3, 75), CSize(877, 1240)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A3, 100), CSize(1169, 1653)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A3, 150), CSize(1753, 2480)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A3, 200), CSize(2338, 3307)));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A3, 240), CSize(2806, 3968) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A3, 300), CSize(3507, 4960) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A3, 400), CSize(4677, 6614) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A3, 600), CSize(7015, 9921) ));
//A4
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4, 50), CSize(413, 585) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4, 75), CSize(620, 877) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4, 100), CSize(826, 1169) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4, 150), CSize(1240, 1753) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4, 200), CSize(1653, 2338) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4, 240), CSize(1984, 2806) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4, 300), CSize(2480, 3507) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4, 400), CSize(3307, 4677) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4, 600), CSize(4960, 7015) ));
//A4R
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4R, 50), CSize(585, 413) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4R, 75), CSize(877, 620) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4R, 100), CSize(1169, 826) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4R, 150), CSize(1753, 1240) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4R, 200), CSize(2338,1653) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4R, 240), CSize(2806,1984) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4R, 300), CSize(3507,2480) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4R, 400), CSize(4677,3307) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A4R, 600), CSize(7015,4960) ));
//A5
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5, 50), CSize(291, 413) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5, 75), CSize(437, 620) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5, 100), CSize(582, 826) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5, 150), CSize(874, 1240) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5, 200), CSize(1165, 1653) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5, 240), CSize(1398, 1984) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5, 300), CSize(1748, 2480) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5, 400), CSize(2330, 3307) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5, 600), CSize(3496, 4960) ));
//A5R
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5R, 50), CSize(413, 291) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5R, 75), CSize(620, 437) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5R, 100), CSize(826, 582) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5R, 150), CSize(1240, 874) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5R, 200), CSize(1653, 1165) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5R, 240), CSize(1984, 1398) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5R, 300), CSize(2480, 1748) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5R, 400), CSize(3307, 2330) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A5R, 600), CSize(4960, 3496) ));
//A6
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6, 50), CSize(207, 291) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6, 75), CSize(310, 437) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6, 100), CSize(413, 582) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6, 150), CSize(620, 874) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6, 200), CSize(826, 1165) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6, 240), CSize(992, 1398) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6, 300), CSize(1240, 1748) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6, 400), CSize(1653, 2330) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6, 600), CSize(2480, 3496) ));
//A6R
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6R, 50), CSize(291, 207) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6R, 75), CSize(437, 310) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6R, 100), CSize(582, 413) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6R, 150), CSize(874, 620) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6R, 200), CSize(1165, 826) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6R, 240), CSize(1398, 992) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6R, 300), CSize(1748, 1240) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6R, 400), CSize(2330, 1653) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(A6R, 600), CSize(3496, 2480) ));
//长文稿2倍A3
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)91, 50), CSize(585, 1653) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)91, 75), CSize(877, 2480) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)91, 100), CSize(1169, 1653*2) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)91, 150), CSize(1753, 2480*2) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)91, 200), CSize(2338, 3307*2) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)91, 240), CSize(2806, 3968*2) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)91, 300), CSize(3507, 4960*2) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)91, 400), CSize(4677, 6614*2) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>((TwSS)91, 600), CSize(7015, 9921*2) ));
//B4
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B4, 50), CSize(506, 717) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B4, 75), CSize(759, 1075) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B4, 100), CSize(1011, 1433) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B4, 150), CSize(1517, 2149) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B4, 200), CSize(2023, 2866) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B4, 240), CSize(2428, 3439) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B4, 300), CSize(3035, 4299) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B4, 400), CSize(4047, 5732) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B4, 600), CSize(6070, 8598) ));
//B5
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5, 50), CSize(358, 506) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5, 75), CSize(537, 759) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5, 100), CSize(716, 1011) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5, 150), CSize(1074, 1517) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5, 200), CSize(1433, 2023) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5, 240), CSize(1719, 2428) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5, 300), CSize(2149, 3035) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5, 400), CSize(2866, 4047) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5, 600), CSize(4299, 6070) ));
//B5R
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5R, 50), CSize(506, 358) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5R, 75), CSize(759, 537) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5R, 100), CSize(1011, 716) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5R, 150), CSize(1517, 1075) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5R, 200), CSize(2023, 1433) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5R, 240), CSize(2428, 1719) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5R, 300), CSize(3035, 2149) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5R, 400), CSize(4047, 2866) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B5R, 600), CSize(6070, 4299) ));
//B6
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6, 50), CSize(252, 358) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6, 75), CSize(378, 537) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6, 100), CSize(503, 716) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6, 150), CSize(755, 1074) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6, 200), CSize(1007, 1433) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6, 240), CSize(1209, 1719) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6, 300), CSize(1511, 2149) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6, 400), CSize(2015, 2866) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6, 600), CSize(3023, 4299) ));
//B6R
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6R, 50), CSize(358, 252) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6R, 75), CSize(537, 378) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6R, 100), CSize(716, 503) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6R, 150), CSize(1074, 755) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6R, 200), CSize(1433, 1007) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6R, 240), CSize(1719, 1209) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6R, 300), CSize(2149, 1511) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6R, 400), CSize(2866, 2015) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(B6R, 600), CSize(4299, 3023) ));
//DOUBLE LETTER
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(DOUBLELetter, 50), CSize(550, 850) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(DOUBLELetter, 75), CSize(825, 1275) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(DOUBLELetter, 100), CSize(1100, 1700) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(DOUBLELetter, 150), CSize(1650, 2550) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(DOUBLELetter, 200), CSize(2200, 3400) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(DOUBLELetter, 240), CSize(2640, 4080) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(DOUBLELetter, 300), CSize(3300, 5100) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(DOUBLELetter, 400), CSize(4400, 6800) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(DOUBLELetter, 600), CSize(6600, 10200) ));
//LETTER
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetter, 50), CSize(425, 550) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetter, 75), CSize(638, 825) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetter, 100), CSize(850, 1100) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetter, 150), CSize(1275, 1650) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetter, 200), CSize(1700, 2200) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetter, 240), CSize(2040, 2640) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetter, 300), CSize(2550, 3300) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetter, 400), CSize(3400, 4400) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetter, 600), CSize(5100, 6600) ));
//LETTERR
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetterR, 50), CSize(550, 425) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetterR, 75), CSize(825, 638) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetterR, 100), CSize(1100, 850) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetterR, 150), CSize(1650, 1275) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetterR, 200), CSize(2200, 1700) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetterR, 240), CSize(2640, 2040) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetterR, 300), CSize(3300, 2550) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetterR, 400), CSize(4400, 3400) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLetterR, 600), CSize(6600, 5100) ));
//LETTERR
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLegal, 50), CSize(425, 700) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLegal, 75), CSize(638, 1050) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLegal, 100), CSize(850, 1400) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLegal, 150), CSize(1275, 2100) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLegal, 200), CSize(1700, 2800) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLegal, 240), CSize(2040, 3360) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLegal, 300), CSize(2550, 4200) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLegal, 400), CSize(3400, 5600) ));
dpiDct.insert(pair<pair<TwSS,float>,CSize>(pair<TwSS,float>(USLegal, 600), CSize(5100, 8400) ));
}
static CSize getSize(TwSS paperType, float dpi)
{
CSize retSize;
map<pair<TwSS, float>, CSize>::iterator iter;
iter = dpiDct.find(pair<TwSS, float>(paperType,dpi));
if(iter != dpiDct.end()){
retSize = (*iter).second;
return retSize;
}
return CSize(2338, 3307);
}
GScn_Drv g_drv;
//////////////////////////////////////////////////////////////////////////////
CScanner_FreeImage::CScanner_FreeImage() :
// m_pDIB(0),
m_nScanLine(0),
m_bReadOnly(false),
m_nDestBytesPerRow(0),
m_nRowOffset(0),
m_nDocCount(0),
m_nSourceWidth(0),
m_nSourceHeight(0)
{
memset(m_szSourceImagePath, 0, PATH_MAX);
initialDictionary();
// set default caps
resetScanner();
g_drv.open(0x064B, 0x7823);
}
//////////////////////////////////////////////////////////////////////////////
CScanner_FreeImage::~CScanner_FreeImage()
{
//g_drv.reset();
}
//////////////////////////////////////////////////////////////////////////////
bool CScanner_FreeImage::resetScanner()
{
bool bret = true;
// Unlock the scanner
Unlock();
m_nScanLine = 0;
m_nDestBytesPerRow = 0;
m_nRowOffset = 0;
m_nDocCount = m_nMaxDocCount = getDocumentCount();// Reloaded the scanner with paper
m_nPixelType = TWPT_RGB;
m_nPaperSource = SFI_PAPERSOURCE_ADF;
m_bDuplex = false;
m_fXResolution = 200.0;
m_fYResolution = 200.0;
if (g_drv.Get_IsImageQueueEmpty()!=0)
{
g_drv.reset();
}
return bret;
}
//////////////////////////////////////////////////////////////////////////////
SFreeImage* CScanner_FreeImage::getSetting() const
{
return (SFreeImage*)this;
}
//////////////////////////////////////////////////////////////////////////////
bool CScanner_FreeImage::acquireImage(bool bscan)
{
if (g_drv.IsConnected())
{
g_drv.run();
}
if (bscan)
{
if (getDeviceOnline())
{
while (!isPaperOn())
{
std::string cvt=StringToUtf("纸仓内无纸,请放纸!");
std::string notify=StringToUtf("提示");
int res= MessageBox(NULL, cvt.c_str(),notify.c_str(), MB_OKCANCEL | MB_ICONINFORMATION);
switch (res)
{
case IDCANCEL:
return false;
}
}
UpdateList();
g_drv.setlist(m_iaList);
hgConfigClass cf;
cf.setDoubleFeedEnable(m_HardWareParams.DoubleFeederOn);
cf.setResolution(200.0);
cf.setSkewDelection(m_HardWareParams.SkrewDetectOn);
switch (m_HardWareParams.SkrewDetectLevel)
{
case 1:
cf.setSkewLevel0bit(false);
cf.setSkewLevel1bit(false);
cf.setSkewLevel2bit(false);
break;
case 2:
cf.setSkewLevel0bit(true);
cf.setSkewLevel1bit(false);
cf.setSkewLevel2bit(false);
break;
case 3:
cf.setSkewLevel0bit(false);
cf.setSkewLevel1bit(true);
cf.setSkewLevel2bit(false);
break;
case 4:
cf.setSkewLevel0bit(true);
cf.setSkewLevel1bit(true);
cf.setSkewLevel2bit(false);
break;
case 5:
cf.setSkewLevel0bit(false);
cf.setSkewLevel1bit(false);
cf.setSkewLevel2bit(true);
break;
default:
break;
}
cf.setStapleEnable(m_HardWareParams.StapleDetectOn);
cf.setTwPixelType(m_HardWareParams.PixType);
cf.settwSS(m_HardWareParams.PaperType);
UINT32 cfg_Value =cf.GetData();
USBCB usbcb = { CONFIGURED_DATA , cfg_Value,0 };
g_drv.set_decompress_pix_type(m_HardWareParams.PixType);
g_drv.Config_Scanner(&usbcb);
g_drv.Scanner_StartScan(m_bDuplex?m_wScanCount/2:m_wScanCount);
}
else
{
std::string cvt=StringToUtf("请检查电源或USB通信是否正常!");
std::string notify=StringToUtf("提示");
MyMessageBox((TCHAR*)cvt.c_str(), (TCHAR*)notify.c_str(), MB_OK| MB_ICONINFORMATION);
return false;
}
}
#ifdef HW_VER
m_matDib.release();
int ret = g_drv.aquire_image(m_matDib);
//imwrite("1.bmp",m_matDib);
if (ret)
{
cout << "ds: Failed - could not acquire image" << endl;
return false;
}
#endif
if (m_matDib.empty())
{
cout << "ds: Failed - could not acquire image" << endl;
return false;
}
//Document scanned, remove it from simulated intray
m_nDocCount--;
// do whatever tranforms to the scanned image that was requested by the app
// before the image is sent to the app.
if (false == preScanPrep())
{
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
bool CScanner_FreeImage::preScanPrep()
{
m_nRight = m_nSourceWidth = m_matDib.cols;
m_nBottom = m_nSourceHeight = m_matDib.rows;
m_nLeft = 0;
m_nTop = 0;
switch (m_nPixelType)
{
case TWPT_BW:
m_nDestBytesPerRow = BYTES_PERLINE(m_nSourceWidth, 1);
m_nRowOffset = BYTES_PERLINE(0, 1);
//m_imageTrans.reset(new ImageTranferBW(m_matDib));
m_imageTrans.reset(new ImageTranferBW(m_matDib));
break;
case TWPT_GRAY:
m_nDestBytesPerRow = BYTES_PERLINE(m_nSourceWidth, 8);
m_nRowOffset = BYTES_PERLINE(0, 8);
//m_imageTrans.reset(new ImageTranferMat(m_matDib));
m_imageTrans.reset(new ImageTranferMat(m_matDib));
break;
case TWPT_RGB:
m_nDestBytesPerRow = BYTES_PERLINE(m_nSourceWidth, 24);
m_nRowOffset = BYTES_PERLINE(0, 24);
//m_imageTrans.reset(new ImageTranferMat(m_matDib));
m_imageTrans.reset(new ImageTranferMat(m_matDib));
break;
}
// setup some convenience vars because they are used during
// every strip request
m_nScanLine = 0;
//XdPrint("m_nDestBytesPerRow = %d, m_nSourceWidth = %d\n", m_nDestBytesPerRow, m_nSourceWidth);
return true;
}
//////////////////////////////////////////////////////////////////////////////
// We want to simulate getting a scan form a scanner.
// if a size larger than the paper is scanned then there will be black on the bottom
// and to the right of the image. We want to transfer the image top to bottom,
// the black will be transfered after the image if neccessary.
bool CScanner_FreeImage::getScanStrip(BYTE *pTransferBuffer, DWORD dwRead, DWORD &dwReceived)
{
dwReceived = 0;
if (NULL == pTransferBuffer || // Invalid paramiter
dwRead < m_nDestBytesPerRow) // Need enough memory to transfer at least an entire row
{
return false;
}
BYTE *pBits = NULL;
int nRow = 0;
int nMaxRows = dwRead / m_nDestBytesPerRow; //number of rows to be transfered during this call (function of buffer size and line size)
DWORD step = (DWORD)m_imageTrans->step();
//XdPrint("step = %d, image width = %d\n", step, m_matDib.cols);
m_nScanLine = 0;
if (m_nScanLine < m_nSourceHeight)
{
//fill the buffer line by line to take care of alignment differences
for (nRow = 0; nRow < nMaxRows; nRow++)
{
//get the next scan line position and copy it
pBits = m_imageTrans->getLineBits(m_nScanLine);
memcpy(pTransferBuffer, pBits + m_nRowOffset, MIN(m_nDestBytesPerRow, step));
// Check to see if the result image width is wider than what we have.
// If it is wider fill it in with 0es
if (m_nDestBytesPerRow > step)
{
memset(pTransferBuffer + step, 0, m_nDestBytesPerRow - step);
}
//increment the destination by the aligned line size
pTransferBuffer += m_nDestBytesPerRow;
// increment the current scanline for next pass
m_nScanLine++;
//update the number of bytes written
dwReceived += m_nDestBytesPerRow;
// check for finished scan
if (m_nScanLine >= m_nSourceHeight)
{
//we are done early
break;
}
}
}
// Check to see if the result image length is longer than we have.
// If it is longer fill it in with 0es
//if (m_nBottom > m_nScanLine)
//{
// nMaxRows = (WORD)((dwRead - dwReceived) / m_nDestBytesPerRow);
// memset(pTransferBuffer, 0, m_nDestBytesPerRow * nMaxRows);
// m_nScanLine += nMaxRows;
// dwReceived += m_nDestBytesPerRow * nMaxRows;
//}
return true;
}
///////////////////////////////////////////////////////////////////////////////
void CScanner_FreeImage::UpdateList(bool canUpdate/*=true*/)
{
m_iaList.clear();
if (m_bAutoDiscardBlank||m_bAutoDiscardBlankInvoice)
{
m_iaList.push_back(shared_ptr<CImageApply>(new CImageProcDiscardBlank(m_bAutoDiscardBlank?true:false)));
}
m_iaList.push_back(shared_ptr<CImageApply>(new CAutoCrop(m_bFillBlackRect, m_bAutoDeskew, m_bAutoCrop,getSize((TwSS)m_HardWareParams.PaperType,m_fXResolution),getSize((TwSS)m_HardWareParams.PaperType,200.0))));
if (m_nFilter)
{
m_iaList.push_back(shared_ptr<CImageApply>(new CImageChannel(m_nFilter)));
}
if (m_fBrightness!=0||m_fContrast!=0||m_fGamma!=1.0)
{
m_iaList.push_back(shared_ptr<CImageApply>(new CImageAdjustColors(m_fBrightness, m_fContrast, m_fGamma)));
}
if (m_fXResolution!=200.0)
{
m_iaList.push_back(ImageApplyPtr(new CImageApplyResize(200.0,m_fXResolution,m_bAutoCrop,getSize((TwSS)m_HardWareParams.PaperType,m_fXResolution))));
}
if (m_wRotation!=0||m_bBackRotate180)
{
m_iaList.push_back(shared_ptr<CImageApply>(new CImageRotation(m_wRotation,m_bBackRotate180)));
}
g_drv.SetIsDuplex(m_bDuplex);
}
//////////////////////////////////////////////////////////////////////////////
short CScanner_FreeImage::getDocumentCount() const
{
// Simulate the number of pages sitting in the scanner.
int nCount = 1;
// Read this value from the environment. This will allow the simulation
// of a sheet feeder.
// If the value is <= 0, then a random number of pages will be scanned, else
// the exact number will be used.
char szCount[10];
memset(szCount, 0, sizeof(szCount));
if (0 != SGETENV(szCount, sizeof(szCount), kGETENV_XFERCOUNT))
{
// something found, convert it to an int
nCount = atoi(szCount);
if (nCount <= 0)
{
srand(int(time(0)));
nCount = rand();
nCount = nCount % 15;// upto 15 pages
}
}
return nCount;
}
//////////////////////////////////////////////////////////////////////////////
bool CScanner_FreeImage::isFeederLoaded()
{
//bool rtn = true;
bool rtn=g_drv.Get_Scanner_PaperOn();
return rtn;
}
//////////////////////////////////////////////////////////////////////////////
bool CScanner_FreeImage::getDeviceOnline() const
{
//MessageBox(NULL,g_drv.IsConnected()?"true":"false","aa",MB_OK);
return g_drv.IsConnected();
}
//////////////////////////////////////////////////////////////////////////////
std::string CScanner_FreeImage::getSerialNum() const
{
return g_drv.GetSerialNum();
}
//////////////////////////////////////////////////////////////////////////////
std::string CScanner_FreeImage::getFWVersion() const
{
return g_drv.GetFWVersion();
}
///////////////////////////////////////////////////////////////////////////////
bool CScanner_FreeImage::StopScan()
{
g_drv.Stop_scan();
if (g_drv.is_scan())
{
Sleep(100);
}
g_drv.reset();//清空图像队列
return g_drv.Get_IsImageQueueEmpty();
}
//////////////////////////////////////////////////////////////////////////////
bool CScanner_FreeImage::isPaperOn() const
{
return g_drv.Get_Scanner_PaperOn();
}
bool CScanner_FreeImage::isImageQueueEmpty()
{
bool ret=true;
if (!g_drv.is_scan()&&g_drv.Get_IsImageQueueEmpty())
{
m_nDocCount=0;
}
else
{
m_nDocCount=1;
ret=false;
}
//XdPrint("m_nDocCount %d\n",m_nDocCount);
return ret;
}

View File

@ -0,0 +1,311 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CScanner_FreeImage.h
* Defines a scanner.
* Create a virtual scanner.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CSCANNER_H__
#define __CSCANNER_H__
#include "Common.h"
#include "FreeImage.h"
#include "twain.h"
#include "gscn_drv.h"
//#include "IndicatorDlg.h"
#include <vector>
#include <memory>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
/**
* This is a virtual scanner. The virtual scanner is used by the data source
* to try and somewhat simulate some real hardware interaction.
* - It acquires the same image each time from an image file on the hard disk.
* - It uses the FreeImage library to apply transforms to the base image.
*
* For simulation purposes the virtual Scanner is set up with the
* following specifications:
*
* - Scanner Types
* - ADF(Automatic Document Feeder)
* - Flatbed
*
* - Image sensors
* - CCD x 3 ( Front / Back / Flatbed )
*
* - Scanning area Minimum
* - ADF - A8 @ 127g/m2 paper
* - Flatbed - unlimited
*
* - Scanning area Maximum
* - ADF - Legal paper
* - Flatbed - A4 letter paper
*
* - Internal Optical Resolution
* - 600dpi
*
* - Output Resolution
* - Binary - 50, 100, 150, 200, 300, 400, 500, & 600
* - Grayscale - 50, 100, 150, 200, 300, 400, 500, & 600
* - Color - 50, 100, 150, 200, 300, 400, 500, & 600
*
* - Internal Bit Depth
* - 8 bits per color
*
* - Output Bit Depth
* - Binary - 1 bits
* - Grayscale - 8 bits
* - Color - 8 bits per color
*
* - Halftone Patterns
* - Dither /error diffusion
*
* - compression: JPEG, and FAX4 (CCITT G4)
*
*/
// Defines used by Scanner FreeImage class to set and get attributes of the vurtual scanner.
/**
* The FreeImage scanner define for PaperSource is ADF
*/
#define SFI_PAPERSOURCE_ADF 0
/**
* The FreeImage scanner define for PaperSource is Flatbed
*/
#define SFI_PAPERSOURCE_FB 1
/**
* The FreeImage scanner data structure. This data is passed back and forth between the scanner class and driver.
*
*/
struct tagHARDWAREPARAMS
{
DWORD PaperType;
DWORD PixType;
FLOAT Resolution;
BOOL DoubleFeederOn;
BOOL StapleDetectOn;
BOOL SkrewDetectOn;
DWORD SkrewDetectLevel;
};
typedef tagHARDWAREPARAMS HARDWAREPARAMS, *PHARDWAREPARAMS;
struct SFreeImage
{
WORD m_nPaperSource; /**< the current paper source ADF or Flatbed*/
bool m_bDuplex; /**< True to use duplex false for simplex, ignored if flatbed*/
WORD m_nPixelType; /**< type of pixels to transfer image as */
int m_nRight; /**< frame right edge */
int m_nBottom; /**< frame bottom edge */
int m_nLeft; /**< frame left edge */
int m_nTop; /**< frame top edge */
float m_fXResolution; /**< horizontal resolution */
float m_fYResolution; /**< vertical resolution */
float m_fGamma; /**< Gamma */
float m_fContrast; /**< Contrast */
float m_fBrightness; /**< Brightness */
float m_fThreshold; /**< Threshold */
//int m_nPaparType /**< 纸张类型*/
//后加
BOOL m_bAutoContrast; /**< 自动对比度*/
bool m_bAutoCrop; /**< 自动裁切*/
bool m_bAutoDiscardBlank; /**< 自动丢弃空白页通用*/
bool m_bAutoDiscardBlankInvoice;/**自动丢弃空白页发票*/
bool m_bAutoDeskew; /**< 自动纠偏*/
WORD m_nFilter; /**< 除色*/
bool m_bFillBlackRect; /**< 填黑框*/
UINT16 m_wScanCount; /**< 扫描张数*/
WORD m_wRotation; /**< 旋转方向*/
bool m_bBackRotate180; /**< 背面旋转180*/
HARDWAREPARAMS m_HardWareParams; /**< 硬件扫描参数*/
};
class CImageProc;
class CImageApply;
class ImageTransfer
{
public:
ImageTransfer(){}
virtual ~ImageTransfer(){}
virtual unsigned char* getLineBits(int line = 0) = 0;
virtual int step() = 0 ;
virtual int bpp()=0;
virtual int width() = 0;
virtual int height() = 0;
};
class twainImage;
/**
* The FreeImage scanner. The software scanner using FreeImage.
*
*/
class CScanner_FreeImage : public SFreeImage
{
public:
/**
* Constructor for CScanner_FreeImage.
*/
CScanner_FreeImage();
/**
* Deconstructor for CScanner_FreeImage.
*/
~CScanner_FreeImage();
/**
* Resets the scanner to factory default settings.
* Sets the scanners caps back to defaults.
* @return true if successfully reset.
*/
bool resetScanner();
/**
* Get a scan line and put it into the _ImageXfer, fill values in _ImageXfer.
* @param[out] pTransferBuffer a pointer to an array of bytes to store the image data
* @param[in] dwRead the number of bytes to read from scanner
* @param[out] dwReceived the actual number of bytes transfered
* @return true if successful
*/
bool getScanStrip(BYTE *pTransferBuffer, DWORD dwRead, DWORD &dwReceived);
/**
* Sets all the scanners capabilities to read only.
*/
void Lock(void) {m_bReadOnly = true;}
/**
* Sets all the scanners capabilities to read and write.
*/
void Unlock(void) {m_bReadOnly = false;}
/**
* Retrieves the image to scan from disk into memory.
* @return true if image was loaded into memory successfully.
*/
bool acquireImage(bool bscan = true);
////////////////
// Accessors
/**
* get the current settings
* @return the current scanner settngs
*/
SFreeImage* getSetting() const;
/**
* set the current settings
* @param[in] settings the new settings for the scanner
*/
//void setSetting(SFreeImage settings);
/**
* Determine if there is paper sitting in the feeder.
* IF empty loads again for next time.
* @return true if paper in feeder else return false.
*/
bool isFeederLoaded();
/**
* Return status of the device is online or not.
* @return true if online.
*/
bool getDeviceOnline() const;
bool isPaperOn() const;
/* get scannner hardware version*/
std::string getSerialNum() const;
std::string getFWVersion() const;
bool isImageQueueEmpty();
short GetMaxPagesInADF(void){return m_nMaxDocCount;}
void SetMaxPagesInADF(short nVal){m_nMaxDocCount = nVal;};
bool StopScan();
WORD m_nSourceWidth; /**< Width of image in FreeImage */
WORD m_nSourceHeight; /**< Height of image in FreeImage */
protected:
/**
* Return the number of documents sitting in the feeder.
* This number can be set with enviroment varible kGETENV_XFERCOUNT "CAP_XFERCOUNT"
* this is so we can tell when the feeder is empty
* - If CAP_XFERCOUNT is not set will return 1.
* - if < 0 will return random number.
* @return default number of documents.
*/
short getDocumentCount() const;
/**
* Transform the image according to the caps set by the application.
* @return true if successful
*/
bool preScanPrep();
protected:
//FIBITMAP *m_pDIB; /**< Pointer to current scanned image */
WORD m_nScanLine; /**< Current scan line of image in FreeImage */
bool m_bReadOnly; /**< current mode */
DWORD m_nDestBytesPerRow; /**< number of bytes needed for a row of data */
DWORD m_nRowOffset; /**< offset of the first byte on every row*/
short m_nDocCount; /**< number of documents waiting to transfer */
short m_nMaxDocCount; /**< Max number of documents waiting to transfer */
char m_szSourceImagePath[PATH_MAX]; /**< image used with FreeImage */
cv::Mat m_matDib;
//twainImage m_matDib_c;
private:
bool can_updateList;
void UpdateList(bool canUpdate=true);
std::vector<std::shared_ptr<CImageApply>> m_iaList;
std::shared_ptr<ImageTransfer> m_imageTrans;
};
#endif // __CSCANNER_H__
//extern IndicatorDlg* m_pIndicator;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,649 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CTWAINDS_Base.h
* Base class describing a TWAIN Data Source.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINBASE_H__
#define __CTWAINBASE_H__
#include "CommonDS.h"
/**
* possible States of the DS.
* The five possible states of the Data Source Manager
*/
typedef enum
{
dsState_Loaded = 3, /**< Source is loaded, but not open. */
dsState_Open, /**< Source is open, and ready to: List & Negotiate Capabilities,
* Request the Acquisition of data, and Close. */
dsState_Enabled, /**< If UI is being used it is displayed. */
dsState_XferReady, /**< Transfers are ready. */
dsState_Xferring /**< Transfering data. */
} DS_State;
/**
* This is a TWAIN compliant base class. It contains all of the capabilities
* and functions that are required to be a TWAIN compliant source. Simply
* inherit this class and implement the pure virtual functions.
* This basic version of a Data Source only supports connection of one
* application at a time.
*/
class CTWAINDS_Base
{
public:
CTWAINDS_Base();
virtual ~CTWAINDS_Base();
/**
* This is the same as the main DS_Entry function. Routes traffic
* to the proper location.
* @param[in] _pOrigin Identifies the source application of the message.
* @param[in] _DG The Data Group.
* @param[in] _DAT The Data Attribute Type.
* @param[in] _MSG The message with respect to the Data Group and the Data Attribute Type.
* @param[in,out] _pData A pointer to the data structure or variable identified
* by the Data Attribute Type.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_UINT16 DS_Entry( pTW_IDENTITY _pOrigin,
TW_UINT32 _DG,
TW_UINT16 _DAT,
TW_UINT16 _MSG,
TW_MEMREF _pData);
/**
* Fills _pStatus with the current condition code then resets the condition code.
* @param[in] _MSG valid message for DAT_STATUS.
* @param[out] _pStatus current condition code as pointer to TW_STATUS.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_status(TW_UINT16 _MSG,
pTW_STATUS _pStatus);
/**
* handles DAT_EVENT's
* @param[in] _MSG the message to handle.
* @param[in] _pEvent a pointer to a TW_EVENT structure of the data.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_event(TW_UINT16 _MSG,
pTW_EVENT _pEvent);
/**
* handles DAT_IDENTITY requests.
* @param[in] _pOrigin a pointer to a TW_IDENTITY of the sender of the message.
* @param[in] _MSG the message to handle.
* @param[in,out] _pData pointer to a TW_IDENTITY structure to pass or retrieve data based on message.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_identity(pTW_IDENTITY _pOrigin,
TW_UINT16 _MSG,
pTW_IDENTITY _pData);
/**
* handles DAT_PENDINGXFERS requests.
* @param[in] _MSG the message to handle.
* @param[out] _pXfers a pointer to a TW_PENDINGXFERS structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_pendingxfers(TW_UINT16 _MSG,
pTW_PENDINGXFERS _pXfers);
/**
* handles DAT_CAPABILITY requests.
* @param[in] _MSG the message to handle.
* @param[in] _pCap pointer to TW_CAPABILITY structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_capability(TW_UINT16 _MSG,
pTW_CAPABILITY _pCap);
/**
* handles DAT_USERINTERFACE requests.
* @param[in] _MSG the message to handle.
* @param[in,out] _pData a pointer to a TW_USERINTERFACE structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_userinterface(TW_UINT16 _MSG,
pTW_USERINTERFACE _pData);
/**
* handles DAT_SETUPFILEXFER requests.
* @param[in] _MSG the message to handle.
* @param[in] _pData a pointer to a TW_SETUPFILEXFER structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_setupfilexfer(TW_UINT16 _MSG,
pTW_SETUPFILEXFER _pData);
/**
* handles DAT_SETUPMEMXFER requests.
* @param[in] _MSG the message to handle.
* @param[in] _pData a pointer to a TW_SETUPMEMXFER structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_setupmemxfer(TW_UINT16 _MSG,
pTW_SETUPMEMXFER _pData);
/**
* handles DAT_IMAGENATIVEXFER requests.
* @param[in] _MSG the message to handle.
* @param[in] _pData a handle to the memory.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_imagenativexfer(TW_UINT16 _MSG,
TW_HANDLE& _pData);
/**
* handles DAT_IMAGEFILEXFER requests.
* @param[in] _MSG the message to handle.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_imagefilexfer(TW_UINT16 _MSG);
/**
* handles DAT_IMAGEMEMXFER requests.
* @param[in] _MSG the message to handle.
* @param[in] _pData a pointer to a TW_IMAGEMEMXFER structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_imagememxfer(TW_UINT16 _MSG,
pTW_IMAGEMEMXFER _pData);
/**
* handles DAT_IMAGELAYOUT requests.
* @param[in] _MSG the message to handle.
* @param[in] _pData a pointer to a TW_IMAGELAYOUT structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_imagelayout(TW_UINT16 _MSG,
pTW_IMAGELAYOUT _pData);
/**
* Figures out what to do with the DAT_IMAGEINFO request.
* @param[in] _MSG the message to handle.
* @param[in] _pImageInfo a pointer to a TW_IMAGEINFO structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_imageinfo(TW_UINT16 _MSG,
pTW_IMAGEINFO _pImageInfo);
/**
* Figures out what to do with the DAT_EXTIMAGEINFO request.
* @param[in] _MSG the message to handle.
* @param[in] _pData a pointer to a TW_EXTIMAGEINFO structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_extimageinfo(TW_UINT16 _MSG,
pTW_EXTIMAGEINFO _pData);
/**
* Figures out what to do with the DAT_ENTRYPOINT request.
* @param[in] _MSG the message to handle.
* @param[in] _pEntryPoints a pointer to a TW_ENTRYPOINT structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_entrypoint(TW_UINT16 _MSG,
pTW_ENTRYPOINT _pEntryPoints);
/**
* Figures out what to do with the DAT_XFERGROUP request.
* @param[in] _MSG the message to handle.
* @param[in] _pXferGroup a pointer to a TW_UINT32 value.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_xfergroup(TW_UINT16 _MSG,
pTW_UINT32 _pXferGroup);
/**
* Figures out what to do with the DAT_CUSTOMDSDATA request.
* @param[in] _MSG the message to handle.
* @param[in] _pDSData a pointer to a TW_CUSTOMDSDATA structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 dat_customdsdata(TW_UINT16 _MSG,
pTW_CUSTOMDSDATA _pDSData);
//////////////////////////////////////////////////////////////////////////////
/**
* @name Pure Virtuals
* @{
*/
/**
* Fills the identity structure with our information.
* Overload this function in derived classes to uniquely identify them selves.
* @param[out] _idStruct our TW_IDENTITY information.
*/
virtual void fillIdentityStructure(TW_IDENTITY& _idStruct) = 0;
/**
* Initialize the Datasource. Allocate memory for Capabilities.
* Sets condition code if had problem.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 Initialize() = 0;
/**
* Enable the Data Source.
* Called when a DG_CONTROL / DAT_USERINTERFACE / MSG_ENABLEDS op is sent.
* @param[in] _pData a pointer to a TW_USERINTERFACE structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 enableDS(pTW_USERINTERFACE _pData) = 0;
/**
* Enable the Data Source in setup mode.
* Called when a DG_CONTROL / DAT_USERINTERFACE / MSG_ENABLEDS op is sent.
* @param[in] _pData a pointer to a TW_USERINTERFACE structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 enableDSOnly(pTW_USERINTERFACE _pData) = 0;
/**
* Disable the Data Source.
* Called when a DG_CONTROL / DAT_USERINTERFACE / MSG_DISABLEDS op is sent.
* @param[in] _pData a pointer to a TW_USERINTERFACE structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 disableDS(pTW_USERINTERFACE _pData) = 0;
/**
* Get image information.
* Called when a DG_IMAGE / DAT_IMAGEINFO / MSG_GET op is sent.
* -If in state 6, general info is provided about the image about to be transferred.
* -If in state 7, specific info is provided about the current image just transferred.
* @param[out] _pImageInfo a pointer to TW_IMAGEINFO structure to return image information.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 getImageInfo(pTW_IMAGEINFO _pImageInfo) = 0;
/**
* Open the Data Source.
* Called when a DG_CONTROL / DAT_IDENTITY / MSG_OPENDS op is sent.
* @param[in] _pOrigin a pointer to TW_IDENTITY structure of the Application identity.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 openDS(pTW_IDENTITY _pOrigin) = 0;
/**
* Close the Data Source.
* Called when a DG_CONTROL / DAT_IDENTITY / MSG_CLOSEDS op is sent.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 closeDS() = 0;
/**
* get data for memory transfer.
* Called when a DG_CONTROL / DAT_SETUPMEMXFER / MSG_GET op is sent.
* @param[in] _pData a pointer to TW_SETUPMEMXFER structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 getMemoryXfer(pTW_SETUPMEMXFER _pData) = 0;
/**
* Process events.
* Called when a DG_CONTROL / DAT_EVENT / MSG_PROCESSEVENT op is sent.
* @param[in] _pEvent a pointer to TW_EVENT structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 processEvent(pTW_EVENT _pEvent) = 0;
/**
* Stop currect transfer if not done. Single from application that application is
* done with all data with current image.
* Check to see if there is still documents or data remaining to transfer.
* Called when a DG_CONTROL / DAT_PENDINGXFERS / MSG_ENDXFER op is sent.
* @param[out] _pXfers a pointer to TW_PENDINGXFERS structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 endXfer(pTW_PENDINGXFERS _pXfers) = 0;
/**
* Check to see if there is still documents or data remaining to transfer.
* Called when a DG_CONTROL / DAT_PENDINGXFERS / MSG_GET op is sent.
* @param[out] _pXfers a pointer to TW_PENDINGXFERS structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 getXfer(pTW_PENDINGXFERS _pXfers) = 0;
/**
* Flush all pending transfers from the Source..
* Called when a DG_CONTROL / DAT_PENDINGXFERS / MSG_RESET op is sent.
* @param[out] _pXfers a pointer to TW_PENDINGXFERS structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 resetXfer(pTW_PENDINGXFERS _pXfers) = 0;
/**
* Transfer image data from scanner to memory.
* Called during one of the transfer methods.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 transfer() = 0;
// END Pure Virtuals
/**
* @}
*/
//////////////////////////////////////////////////////////////////////////////
/**
* @name Capabilities
* @{
*/
/**
* Start the transfer of image data natively.
* Called when a DG_IMAGE / DAT_IMAGENATIVEXFER / MSG_GET op is sent.
* @param[out] _hData a handle to store the image locaton.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 transferNativeImage(TW_HANDLE &_hData);
/**
* Return info about the file that the Source will write the acquired data into
* Called when a DG_CONTROL / DAT_SETUPFILEXFER / MSG_GET op is sent.
* @param[in] _pData a pointer to TW_SETUPFILEXFER structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 getFileXfer(pTW_SETUPFILEXFER _pData);
/**
* Return the default file transfer information
* Called when a DG_CONTROL / DAT_SETUPFILEXFER / MSG_GETDEFAULT op is sent.
* @param[in] _pData a pointer to TW_SETUPFILEXFER structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 getDefaultFileXfer(pTW_SETUPFILEXFER _pData);
/**
* Reset current file information to default values
* Called when a DG_CONTROL / DAT_SETUPFILEXFER / MSG_RESET op is sent.
* @param[in] _pData a pointer to TW_SETUPFILEXFER structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 resetFileXfer(pTW_SETUPFILEXFER _pData);
/**
* Set file transfer information for next file transfer
* Called when a DG_CONTROL / DAT_SETUPFILEXFER / MSG_SET op is sent.
* @param[in] _pData a pointer to TW_SETUPFILEXFER structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 setFileXfer(pTW_SETUPFILEXFER _pData);
/**
* Save image data to file.
* Called when a DG_IMAGE / DAT_IMAGEFILEXFER / MSG_GET op is sent.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 saveImageFile();
/**
* Transfer memory buffers.
* Called when a DG_IMAGE / DAT_IMAGEMEMXFER / MSG_GET op is sent.
* @param[out] _pData a pointer to TW_IMAGEMEMXFER structure.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 transferMemoryBuffers(pTW_IMAGEMEMXFER _pData);
/**
* get the Internal Image format.
* Called when a DG_IMAGE / DAT_IMAGENATIVEXFER / MSG_GET op is sent.
* also used when creating a BMP for saving when DG_IMAGE / DAT_IMAGEFILEXFER / MSG_GET op is sent.
* @param[out] _hImage a handle to store the image locaton.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 getDIBImage(TW_HANDLE &_hImage);
#ifdef TWNDS_OS_APPLE
/**
* MAC only
* get the Internal Image format.
* Called when a DG_IMAGE / DAT_IMAGENATIVEXFER / MSG_GET op is sent.
* also used when creating a BMP for saving when DG_IMAGE / DAT_IMAGEFILEXFER / MSG_GET op is sent.
* @param[out] _hImage a handle to store the image locaton.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 getPICTImage(TW_HANDLE &_hPICTImage);
#endif
/**
* Save the current image data as a BMP file
* @return a valid TWRC_xxxx return code, TWRC_XFERDONE on success.
*/
TW_INT16 saveImageFileAsBMP();
/**
* Save the current image data as a TIFF file
* @return a valid TWRC_xxxx return code, TWRC_XFERDONE on success.
*/
TW_INT16 saveImageFileAsTIFF();
/**
* Request the DSM that we are ready to send images.
* @return true if successful.
*/
virtual bool DoXferReadyEvent();
/**
* Request the DSM the most likly user clicks on the OK?button on GUI.
* @return true if successful.
*/
virtual bool DoCloseDSOkEvent();
/**
* Request the DSM that the Sources user interface be disabled.
* @return true if successful.
*/
virtual bool DoCloseDSRequestEvent();
/**
* Report to the DSM that a device event has occurred.
* @return true if successful.
*/
virtual bool DoDeviceEvent();
/**
* get the Internal Image format. For Linux Only
* Called when a DG_IMAGE / DAT_IMAGENATIVEXFER / MSG_GET op is sent.
* also used when creating a BMP for saving when DG_IMAGE / DAT_IMAGEFILEXFER / MSG_GET op is sent.
* @param[out] _hImage a handle to store the image locaton.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 getTIFFImage(TW_HANDLE &_hImage);
// END Capabilities
/**
* @}
*/
//////////////////////////////////////////////////////////////////////////////
/**
* @name Accessors
* @{
*/
/**
* Returns the current condition code.
* @return a valid TWCC_xxxxxx condition code.
*/
virtual TW_INT16 getConditionCode() const;
/**
* Sets the current condition code.
* @param[in] _cc a valid TWCC_xxxxxx condition code.
*/
virtual void setConditionCode(TW_INT16 _cc);
/**
* Returns a pointer to our identity structure.
* @return pointer to out TW_IDENTITY identity structure.
*/
pTW_IDENTITY getIdentity();
/**
* Returns a pointer to the source application controlling us.
* @return pointer to TW_IDENTITY identity structure.
*/
pTW_IDENTITY getApp();
/**
* Returns the current state of the Data Source.
* @return a DS_State of the current state.
*/
DS_State getState() { return m_CurrentState; }
/**
* This is a template class that will actually operate on the capability.
* It supports all valid CTWAINContainer types which are currently INTS, FIX32 and FRAME's.
* @param[in] _MSG the message
* @param[in] _pContainer the container type
* @param[in] _pCap the capability
* @return a valid TWRC_xxxx return code.
*/
template<class TWAINContainerType>
TW_INT16 handleCap(TW_UINT16 _MSG, TWAINContainerType* _pContainer, pTW_CAPABILITY _pCap);
/**
* Return a CTWAINContainer class of the capability.
* @param[in] _unCap the capability looking for
* @return the capability if found
*/
virtual CTWAINContainer* findCapability(const TW_UINT16 _unCap);
/**
* if the CTWAINContainer is dependend on another Capabiltiy or settings.
* This function is used to get the data it needs.
* @param[in] _pContainer the container
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 updatePreDependencies(CTWAINContainer* _pContainer);
/**
* Validate the value being used to set a capability. Ranges and enums can be tested
* by the capability but OneValues might have only some values that are acceptable.
* Override this function in base class to support more capabilities
* @param[in] Cap the Capability ID
* @param[in] ConType the container type
* @param[in] _pCap a pointer to BYTE. Pointer to Cap container
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 validateCapabilitySet(TW_UINT16 _Cap, TW_UINT16 _ConType, BYTE* _pContainer);
/**
* Update Capability Container after the operation
* Override this function in base class to support more capabilities
* @param[in] _pCap the capability
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 updatePostContainer(pTW_CAPABILITY _pCap);
/**
* Update Capability Container before the operation
* Override this function in base class to support more capabilities
* @param[in] _pCap the capability
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 updatePreContainer(pTW_CAPABILITY _pCap);
/**
* if the CTWAINContainer is dependend on another Capabiltiy.
* This function is used to get the data it needs.
* @param[in] MSG the message that was sent
* @param[in] Cap the Capability that it was sent to
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 updatePostDependencies(TW_UINT16 MSG, TW_UINT16 Cap);
/**
* Update the frame to bewithin the constrains of the scanners Phyisical
* dimentions and minimum allowed sizes.
* @param[in out] _frame the frame to update.
* @return true if the frame is not change, false if changed.
*/
virtual bool ConstrainFrameToScanner(InternalFrame& _frame,bool &bConstrained);
/**
* get the current unit and resolution. A helper function used by Unit dependent cap
* @param[out] Unit the current unit value.
* @param[out] Xres the current X resolution value.
* @param[out] Yres the current Y resolution value.
* @return a CTWAINContainer for the capability.
*/
TW_INT16 getCurrentUnits(int &Unit, float &Xres, float &Yres);
/**
* Get Gustom DS data
* @param[out] _pDSData a pointer to a TW_CUSTOMDSDATA structure.
* @return a valid TWRC_xxxx return code, TWRC_SUCCESS on success.
*/
virtual TW_INT16 GetGustomDSData(pTW_CUSTOMDSDATA _pDSData);
/**
* Set Gustom DS data
* @param[in] _pDSData a pointer to a TW_CUSTOMDSDATA structure.
* @return a valid TWRC_xxxx return code, TWRC_SUCCESS on success.
*/
virtual TW_INT16 SetGustomDSData(pTW_CUSTOMDSDATA _pDSData);
// END Accessors
/**
* @}
*/
static TW_IDENTITY m_TheIdentity; /**< default Identity */
protected:
TWAINCapabilitiesMap m_IndependantCapMap; /**< Stores a list of all capacitites that each instance support. */
TW_INT16 m_DSConditionCode; /**< Current global condition. */
TW_IDENTITY m_MyIdentity; /**< Detail information of our information.*/
TW_IDENTITY m_App; /**< Detail information of the application source. */
DS_State m_CurrentState; /**< Current state of the Data Source. */
TW_STR255 m_CurFileExferName; /**< Current File Transfer Name. */
TW_STR255 m_DefFileExferName; /**< Default File Transfer Name. */
TW_IMAGEINFO m_ImageInfo; /**< Current Image Info data. */
TW_UINT32 m_DocumentNumber; /**< Current Document Number */
TW_UINT32 m_PageNumber; /**< Current Page Number */
TW_PENDINGXFERS m_Xfers; /**< Number of Transfers remianing in this batch */
DWORD m_nDestScanLine; /**< Current Scanline used for memory transfer */
TW_HANDLE m_hImageData; /**< Handle to Current Image Data */
};
#endif // __CTWAINBASE_H__

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,269 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CTWAINDS_FreeImage.h
* The main Data Source class.
* This class is derived from the Base class describing a TWAIN DS.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINDS_FREEIMAGE_H__
#define __CTWAINDS_FREEIMAGE_H__
#include "CTWAINDS_Base.h"
#include "CScanner_FreeImage.h"
#include "JsonConfig.h"
//#include "IndicatorDlg.h"
#define CUSTCAP_LONGDOCUMENT CAP_CUSTOMBASE+1
#define CUSTCAP_DOCS_IN_ADF CAP_CUSTOMBASE+2
#define kCUSTOMDSGUI "{A4FAF845-1383-4036-AEDC-17C3968188B4}"
const TW_GUID CustomDSGUI =
{ 0xa4faf845, 0x1383, 0x4036, { 0xae, 0xdc, 0x17, 0xc3, 0x96, 0x81, 0x88, 0xb4 } };
typedef struct _CUST_DS_DATA_ELEMENT
{
DWORD dwSize;
TW_UINT16 unCapID;
TW_UINT16 unCapIdx;
TW_UINT16 unItemType;
TW_UINT16 unContType;
DWORD dwVal[1];
}CUST_DS_DATA_ELEMENT;
/**
* This is the main DS class. It inherits the TWAIN base class, implements all
* the pure virtual functions and manages all of the required capabilities
*/
class CTWAINDS_FreeImage : public CTWAINDS_Base
{
public:
CTWAINDS_FreeImage(TW_IDENTITY AppID);
~CTWAINDS_FreeImage();
/**
* Fills the passed in identity structure with our information.
* @param[in] _idStruct the TW_IDENTITY structure to fill
*/
void fillIdentityStructure(TW_IDENTITY& _idStruct);
/**
* Initialize the Datasource. Allocate memory for Capabilities.
* Sets condition code if had problem.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 Initialize();
/**
* Get image information.
* Implementation of base class pure virtual function.
* Called when a DG_IMAGE / DAT_IMAGEINFO / MSG_GET op is sent.
* -If in state 6, general info is provided about the image about to be transferred.
* -If in state 7, specific info is provided about the current image just transferred.
* @param[out] _pImageInfo a TW_IMAGEINFO structure to return image information.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 getImageInfo(pTW_IMAGEINFO _pImageInfo);
/**
* Open the Data Source.
* Implementation of base class pure virtual function.
* Called when a DG_CONTROL / DAT_IDENTITY / MSG_OPENDS op is sent.
* @param[in] _pOrigin a pointer to TW_IDENTITY structure of the Application identity.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 openDS(pTW_IDENTITY _pOrigin);
/**
* Close the Data Source.
* Implementation of base class pure virtual function.
* Called when a DG_CONTROL / DAT_IDENTITY / MSG_CLOSEDS op is sent.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 closeDS();
/**
* Process events.
* Implementation of base class pure virtual function.
* Called when a DG_CONTROL / DAT_EVENT / MSG_PROCESSEVENT op is sent.
* @param[in] _pEvent a pointer to TW_EVENT structure.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 processEvent(pTW_EVENT _pEvent);
/**
* Stop currect transfer if not done. Single from application that application is
* done with all data with current image.
* Check to see if there is still documents or data remaining to transfer.
* Implementation of base class pure virtual function.
* Called when a DG_CONTROL / DAT_PENDINGXFERS / MSG_ENDXFER op is sent.
* @param[out] _pXfers a pointer to TW_PENDINGXFERS structure.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 endXfer(pTW_PENDINGXFERS _pXfers);
/**
* Check to see if there is still documents or data remaining to transfer.
* Called when a DG_CONTROL / DAT_PENDINGXFERS / MSG_GET op is sent.
* @param[out] _pXfers a pointer to TW_PENDINGXFERS structure.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 getXfer(pTW_PENDINGXFERS _pXfers);
/**
* Flush all pending transfers from the Source..
* Called when a DG_CONTROL / DAT_PENDINGXFERS / MSG_RESET op is sent.
* @param[out] _pXfers a pointer to TW_PENDINGXFERS structure.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 resetXfer(pTW_PENDINGXFERS _pXfers);
/**
* Called by the base class when the data source is enabled.
* @param[in] _pData contains info about if the UI should be shown etc.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 enableDS(pTW_USERINTERFACE _pData);
/**
* Enable the Data Source in setup mode.
* Called when a DG_CONTROL / DAT_USERINTERFACE / MSG_ENABLEDS op is sent.
* @param[in] _pData a pointer to a TW_USERINTERFACE structure.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 enableDSOnly(pTW_USERINTERFACE _pData);
/**
* Called by the base class when the data source is disabled.
* @param[in] _pData a pointer to a TW_USERINTERFACE struct.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 disableDS(pTW_USERINTERFACE _pData);
/**
* handles DAT_IMAGELAYOUT requests
* @param[in] _MSG the message to handle.
* @param[in] _pData a pointer to TW_IMAGELAYOUT structure.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 dat_imagelayout(TW_UINT16 _MSG, pTW_IMAGELAYOUT _pData);
/**
* Called by the base class to when the application wants to get memory transfer data.
* @param[in] _pData filled with buffer size data
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 getMemoryXfer(pTW_SETUPMEMXFER _pData);
/**
* Transfer image data from scanner to memory.
* Called during one of the transfer methods.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 transfer();
/**
* Return a CTWAINContainer for requested capability.
* @param[in] _unCap the ICAP_xxxx that is requested.
* @return a CTWAINContainer for the capability.
*/
CTWAINContainer* findCapability(const TW_UINT16 _unCap);
/**
* Request the DSM the most likly user clicks on the OK?button on GUI.
* @return true if successful.
*/
virtual bool DoCloseDSOkEvent();
/**
* Updates the scanner from the current caps.
* @return true if successful.
*/
bool updateScannerFromCaps();
/**
* Convenience function that will get the proper ICAP_BITDEPTH container
* @return CTWAINContainer BitDepth for current PixelType.
*/
CTWAINContainer* getICAP_BITDEPTH();
bool StartScanning(bool showUI=true);
bool StopScanning();
bool ReadCustomDSdata(stringstream &DsData);
bool StoreCustomDSdata(stringstream &DsData);
bool StoreCapInStream(stringstream &_DsData, TW_UINT16 _unCapID, TW_UINT16 _unCapIdx, TW_UINT16 unContType);
bool ReadCapFromStream(stringstream &_DsData, TW_UINT16 _unCapID, TW_UINT16 _unCapIdx);
/**
* Get Gustom DS data
* @param[out] _pDSData a pointer to a TW_CUSTOMDSDATA structure.
* @return a valid TWRC_xxxx return code, TWRC_SUCCESS on success.
*/
TW_INT16 GetGustomDSData(pTW_CUSTOMDSDATA _pDSData);
/**
* Set Gustom DS data
* @param[in] _pDSData a pointer to a TW_CUSTOMDSDATA structure.
* @return a valid TWRC_xxxx return code, TWRC_SUCCESS on success.
*/
TW_INT16 SetGustomDSData(pTW_CUSTOMDSDATA _pDSData);
/**
* Validate the value being used to set a capability. Ranges and enums can be tested
* by the capability but OneValues might have only some values that are acceptable.
* Override this function in base class to support more capabilities
* @param[in] Cap the Capability ID
* @param[in] ConType the container type
* @param[in] _pCap a pointer to BYTE. Pointer to Cap container
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 validateCapabilitySet(TW_UINT16 _Cap, TW_UINT16 _ConType, BYTE* _pContainer);
bool UpdateCapsFromConfig(CONFIGPARAMS pConfig);
std::string GetSerialNum();
std::string GetFWVerison();
bool IsImageQueueEmpty();
protected:
CScanner_FreeImage m_Scanner; /**< The main scanner. */
TWAINCapabilitiesMap_int m_BitDepthMap; /**< Capability for various Bit Depths */
CTWAINContainerFrame *m_pICAP_FRAMES; /**< Capabiltiy for a FRAMES based container */
TW_IDENTITY m_AppID;
bool m_bCanceled;
CTWAIN_UI *m_pGUI; /**< This is the main MFC UI dialog */
bool bIndicators;
BOOL b_created;
};
#endif // __CTWAINDS_FREEIMAGE_H__

View File

@ -0,0 +1,195 @@
/***************************************************************************
* Copyright © 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CTWAINDS_Sample1.cpp
* Reveals the main entry point for the DSM
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CTWAINDS_Sample1.h"
#include <list>
#include "twain.h"
//////////////////////////////////////////////////////////////////////////////
// Globals
/**
* gloabal pointer of the Data Source, for access to the main DS_Entry.
*/
typedef struct _DS_inst
{
TW_IDENTITY AppId;
CTWAINDS_Base *pDS;
}DS_inst;
typedef list<DS_inst> lstDS;
lstDS g_lstDS;
#ifdef TWH_CMP_MSC
/**
* gloadbal Windows Instance handle for the DSM DLL...
*/
HINSTANCE g_hinstance = 0;
#endif
//////////////////////////////////////////////////////////////////////////////
// This is the main entry point. This function is dlsym'd by the DSM.
#ifdef TWH_CMP_MSC
TW_UINT16 FAR PASCAL
#else
FAR PASCAL TW_UINT16
#endif
DS_Entry( pTW_IDENTITY _pOrigin,
TW_UINT32 _DG,
TW_UINT16 _DAT,
TW_UINT16 _MSG,
TW_MEMREF _pData)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
CTWAINDS_Base* pTWAINLayer = 0;
if(_pOrigin)
{
lstDS::iterator llIter=g_lstDS.begin();
for(;llIter!=g_lstDS.end();llIter++)
{
if((*llIter).AppId.Id==_pOrigin->Id)
{
pTWAINLayer=(*llIter).pDS;
}
}
}
// Curently we are not open
if( 0 == pTWAINLayer )
{
// Special case DSM can request to get identity information about
// DS before it is open. In this special case, where the DS is not
// open, we return this static Idenity.
if( DG_CONTROL == _DG && DAT_IDENTITY == _DAT && MSG_GET == _MSG )
{
// Copy the ID assigned by the DSM eventhough the spec states
// that the id will not be assigned until MSG_OPENDS
CTWAINDS_Base::m_TheIdentity.Id = ((pTW_IDENTITY)_pData)->Id;
memcpy( _pData, &CTWAINDS_Base::m_TheIdentity, sizeof(CTWAINDS_Base::m_TheIdentity) );
return TWRC_SUCCESS;
}
// The DS is not open. If we get a request to close DS do not open
// just to close, instead return that it is success closed.
if( DG_CONTROL == _DG && DAT_IDENTITY == _DAT && MSG_CLOSEDS == _MSG )
{
return TWRC_SUCCESS;
}
// Open the DS
pTWAINLayer = new CTWAINDS_FreeImage(*_pOrigin);
if( NULL == pTWAINLayer
|| TWRC_SUCCESS != pTWAINLayer->Initialize())
{
// Failed to create the DS
//setConditionCode(TWCC_LOWMEMORY);
if(pTWAINLayer)
{
// Created but could not Initialize
delete pTWAINLayer;
}
return TWRC_FAILURE;
}
DS_inst _DS;
_DS.pDS = pTWAINLayer;
_DS.AppId = *_pOrigin;
g_lstDS.push_back(_DS);
}
// If we were not open before, we are now, so continue with the TWAIN call
TW_INT16 result = pTWAINLayer->DS_Entry(_pOrigin, _DG, _DAT, _MSG, _pData);
/**
* Special case - free memory if closing DS
* @todo keep track of what apps are connecting to the ds and only
* delete when count goes down to 0
*/
if( TWRC_SUCCESS == result &&
DG_CONTROL == _DG && DAT_IDENTITY == _DAT && MSG_CLOSEDS == _MSG &&
NULL != pTWAINLayer )
{
lstDS::iterator llIter=g_lstDS.begin();
for(;llIter!=g_lstDS.end();)
{
if((*llIter).AppId.Id==_pOrigin->Id)
{
delete (*llIter).pDS;
llIter = g_lstDS.erase(llIter);
continue;
}
llIter++;
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
//#ifdef TWH_CMP_MSC
///**
//* DllMain is only needed for Windows, and it's only needed to collect
//* our instance handle, which is also our module handle. Don't ever
//* put anything else in here, not even logging messages. It just isn't
//* safe...
//*/
//BOOL WINAPI DllMain(HINSTANCE _hmodule,
// DWORD _dwReasonCalled,
// LPVOID)
//{
// switch (_dwReasonCalled)
// {
// case DLL_THREAD_ATTACH:
// case DLL_THREAD_DETACH:
// break;
// case DLL_PROCESS_ATTACH:
// g_hinstance = _hmodule;
// break;
// case DLL_PROCESS_DETACH:
// unLoadDSMLib();
// g_hinstance = 0;
// break;
// }
// return(TRUE);
//}
//#elif (TWNDS_CMP == TWNDS_CMP_GNUGPP)
// // Nothing for us to do...
//#else
// #error Sorry, we do not recognize this system...
//#endif

View File

@ -0,0 +1,53 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CTWAINDS_Sample1.h
* Reveals the main entry point for the DSM
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINDS_SAMPLE1_H__
#define __CTWAINDS_SAMPLE1_H__
#include "CTWAINDS_FreeImage.h"
/**
* The main entry point - defined in twain.h
FAR PASCAL TW_UINT16 DS_Entry( pTW_IDENTITY _pOrigin,
TW_UINT32 _DG,
TW_UINT16 _DAT,
TW_UINT16 _MSG,
TW_MEMREF _pData);
*/
#endif //__CTWAINDS_SAMPLE1_H__

View File

@ -0,0 +1,288 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CTiffWriter.cpp
* Write an image to disk as a tiff file.
* @author JFL Peripheral Solutions Inc.
* @date October 2007
*/
#include "stdafx.h"
#include "CTiffWriter.h"
#include <sstream>
CTiffWriter::CTiffWriter(const string& _filename,
const long int _width,
const long int _height,
const int _bitsPerPixel,
const unsigned long int _bytesPerRow)
{
m_pImageStream = 0;
m_nOffset = 0;
m_filename = _filename;
m_ImageWidth.TagID = kTIFF_TAG_IMGWIDTH;
m_ImageWidth.DataType = kTIFF_TY_LONG;
m_ImageWidth.DataCount = 1;
m_ImageWidth.DataOffset = _width;
m_ImageLength.TagID = kTIFF_TAG_IMGLENGTH;
m_ImageLength.DataType = kTIFF_TY_LONG;
m_ImageLength.DataCount = 1;
m_ImageLength.DataOffset = _height;
m_BitsPerSample.TagID = kTIFF_TAG_BITSPERSAMPLE;
m_BitsPerSample.DataType = kTIFF_TY_SHORT;
m_BitsPerSample.DataCount = 1;
if(24 == _bitsPerPixel)
{
m_BitsPerSample.DataOffset = 8;
}
else
{
m_BitsPerSample.DataOffset = _bitsPerPixel;
}
m_Compression.TagID = kTIFF_TAG_COMPRESSION;
m_Compression.DataType = kTIFF_TY_SHORT;
m_Compression.DataCount = 1;
m_Compression.DataOffset = 1;
m_PhotometricInterp.TagID = kTIFF_TAG_PHOTOMETRICINT;
m_PhotometricInterp.DataType = kTIFF_TY_SHORT;
m_PhotometricInterp.DataCount = 1;
if(24 == _bitsPerPixel)
{
m_PhotometricInterp.DataOffset = 2;
}
else
{
m_PhotometricInterp.DataOffset = 1;
}
// -there is only one strip that contains all the row data, and it starts right after the header.
// -There are always 12 tags being written for each tiff.
m_StripOffsets.TagID = kTIFF_TAG_STRIPOFFSETS;
m_StripOffsets.DataType = kTIFF_TY_SHORT;
m_StripOffsets.DataCount = 1;
m_StripOffsets.DataOffset = getSizeofHeader();
m_SamplesPerPixel.TagID = kTIFF_TAG_SAMPLESPERPIXEL;
m_SamplesPerPixel.DataType = kTIFF_TY_SHORT;
if(24 == _bitsPerPixel)
{
m_SamplesPerPixel.DataCount = 1;
m_SamplesPerPixel.DataOffset = 3;
}
else
{
m_SamplesPerPixel.DataCount = 1;
m_SamplesPerPixel.DataOffset = 1;
}
m_RowsPerStrip.TagID = kTIFF_TAG_ROWSPERSTRIP;
m_RowsPerStrip.DataType = kTIFF_TY_LONG;
m_RowsPerStrip.DataCount = 1;
m_RowsPerStrip.DataOffset = _height;
m_StripByteCounts.TagID = kTIFF_TAG_STRIPBYTECOUNTS;
m_StripByteCounts.DataType = kTIFF_TY_LONG;
m_StripByteCounts.DataCount = 1;
m_StripByteCounts.DataOffset = _bytesPerRow * _height;
m_XResolution.TagID = kTIFF_TAG_XRESOLUTION;
m_XResolution.DataType = kTIFF_TY_RATIONAL;
m_XResolution.DataCount = 1;
m_XResolution.DataOffset = m_StripOffsets.DataOffset - sizeof(DWORD)*4; // fixed offset from the end of the header
setXResolution(100, 1);
m_YResolution.TagID = kTIFF_TAG_YRESOLUTION;
m_YResolution.DataType = kTIFF_TY_RATIONAL;
m_YResolution.DataCount = 1;
m_YResolution.DataOffset = m_StripOffsets.DataOffset - sizeof(DWORD)*2; // fixed offset from the end of the header
setYResolution(100, 1);
m_ResolutionUnit.TagID = kTIFF_TAG_RESOLUTIONUNIT;
m_ResolutionUnit.DataType = kTIFF_TY_SHORT;
m_ResolutionUnit.DataCount = 1;
m_ResolutionUnit.DataOffset = 2;
}
CTiffWriter::~CTiffWriter()
{
if(0 != m_pImageStream)
{
if(m_pImageStream->is_open())
{
m_pImageStream->close();
}
delete m_pImageStream;
}
}
void CTiffWriter::setImageWidth(const long int _v)
{
m_ImageWidth.DataOffset = _v;
}
void CTiffWriter::setImageHeight(const long int _v)
{
m_ImageLength.DataOffset = _v;
}
void CTiffWriter::setBitsPerSample(const int _v)
{
m_BitsPerSample.DataOffset = _v;
}
void CTiffWriter::setCompression(const int _v)
{
m_Compression.DataOffset = _v;
}
void CTiffWriter::setPhotometricInterp(const int _v)
{
m_PhotometricInterp.DataOffset = _v;
}
void CTiffWriter::setSamplesPerPixel(const int _v)
{
m_SamplesPerPixel.DataOffset = _v;
}
void CTiffWriter::setXResolution(const int _numerator, const int _denominator)
{
m_xres[0] = _numerator;
m_xres[1] = _denominator;
}
void CTiffWriter::setYResolution(const int _numerator, const int _denominator)
{
m_yres[0] = _numerator;
m_yres[1] = _denominator;
}
void CTiffWriter::setBytesPerRow(const int _v)
{
m_StripByteCounts.DataOffset = _v * m_ImageLength.DataOffset;
}
void CTiffWriter::GetImageHeader(stringstream &Header)
{
// write the header
TIFFIFH hdr = {0x4949, 0x002a, sizeof(TIFFIFH)};
Header.write(reinterpret_cast<char*>(&hdr), sizeof(TIFFIFH));
// write the Tags immediately after the header
WORD numTags = 12;
Header.write(reinterpret_cast<char*>(&numTags), sizeof(numTags));
const int nsize = sizeof(TIFFTag);
Header.write(reinterpret_cast<char*>(&m_ImageWidth), nsize);
Header.write(reinterpret_cast<char*>(&m_ImageLength), nsize);
Header.write(reinterpret_cast<char*>(&m_BitsPerSample), nsize);
Header.write(reinterpret_cast<char*>(&m_Compression), nsize);
Header.write(reinterpret_cast<char*>(&m_PhotometricInterp), nsize);
Header.write(reinterpret_cast<char*>(&m_StripOffsets), nsize);
Header.write(reinterpret_cast<char*>(&m_SamplesPerPixel), nsize);
Header.write(reinterpret_cast<char*>(&m_RowsPerStrip), nsize);
Header.write(reinterpret_cast<char*>(&m_StripByteCounts), nsize);
Header.write(reinterpret_cast<char*>(&m_XResolution), nsize);
Header.write(reinterpret_cast<char*>(&m_YResolution), nsize);
Header.write(reinterpret_cast<char*>(&m_ResolutionUnit), nsize);
// end the header by setting the next image offset to null
DWORD end = 0;
Header.write(reinterpret_cast<char*>(&end), sizeof(end));
// write the X and Y resolutions
Header.write(reinterpret_cast<char*>(&m_xres), sizeof(DWORD)*2);
Header.write(reinterpret_cast<char*>(&m_yres), sizeof(DWORD)*2);
}
bool CTiffWriter::writeImageHeader()
{
// create the out stream if not done so already
if(0 == m_pImageStream)
{
m_pImageStream = new ofstream();
}
// open the stream. If already open, reset it
if(m_pImageStream->is_open())
{
m_pImageStream->seekp(0);
}
else
{
m_pImageStream->open(m_filename.c_str(), ios_base::out|ios_base::binary|ios_base::trunc);
}
stringstream Header;
GetImageHeader(Header);
Header.seekp(0, ios_base::end);
m_nOffset =(int) Header.tellp();
Header.seekg(0, ios_base::beg);
char *pData = new char[m_nOffset];
Header.read(pData,m_nOffset);
m_pImageStream->write(pData,m_nOffset);
delete []pData;
return true;
}
bool CTiffWriter::WriteTIFFData(char *_pData, DWORD _nCount)
{
bool bret = false;
if(0 != m_pImageStream &&
m_pImageStream->good())
{
m_pImageStream->seekp(m_nOffset);
m_pImageStream->write(_pData, _nCount);
m_nOffset += _nCount;
bret = true;
}
return bret;
}
unsigned int CTiffWriter::getSizeofHeader()
{
// Header is as follows:
// TIFFIFH + Num. of Tags + each tag + Xres Data (2 dwords) + Yres Data (2 dwords) + Next Image offset (1 dword)
return sizeof(TIFFIFH)+sizeof(WORD)+sizeof(TIFFTag)*12+sizeof(DWORD)*5;
}

240
hugaotwainds/CTiffWriter.h Normal file
View File

@ -0,0 +1,240 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CTiffWriter.h
* Write an image to disk as a tiff file.
* @author TWAIN Working Group
* @date October 2007
*/
#ifndef __TIFFWRITER_H__
#define __TIFFWRITER_H__
#include <string>
#include <fstream>
using namespace std;
#ifdef _MSC_VER
#include <windows.h>
#else
typedef uint16_t WORD;
typedef uint32_t DWORD;
#endif // _MSC_VER
#define TIFF_UNCOMPRESSED 1 /**< TIFF compression types */
#define TIFF_CCITTGROUP3 3
#define TIFF_CCITTGROUP4 4
// TIFF types
#define kTIFF_TY_BYTE 1 /**< 8-bit unsigned int */
#define kTIFF_TY_ASCII 2 /**< 8-bit byte that contains a 7-bit ASCII code; last byte must be binary 0 (NULL) */
#define kTIFF_TY_SHORT 3 /**< 16-bit (2-byte) unsigned int */
#define kTIFF_TY_LONG 4 /**< 32-bit (4-byte) unsigned int */
#define kTIFF_TY_RATIONAL 5 /**< two LONGs; the first is the numerator of a fraction; the second, the denominator */
// these field types where introduced in TIFF 6.0
#define kTIFF_TY_SBYTE 6 /**< 8-bit signed int */
#define kTIFF_TY_UNDEFINED 7 /**< 8-bit byte that may contain anything, depending on the definition of the field */
#define kTIFF_TY_SSHORT 8 /**< 16-bit (2-byte) signed int */
#define kTIFF_TY_SLONG 9 /**< 32-bit (4-byte) signed int */
#define kTIFF_TY_SRATIONAL 10 /**< two SLONG's; first is numerator of fraction, second is denominator */
#define kTIFF_TY_FLOAT 11 /**< single precision (4-byte) IEEE format */
#define kTIFF_TY_DOUBLE 12 /**< double precision (8-byte) IEEE format */
// TIFF Tags
#define kTIFF_TAG_IMGWIDTH 0x0100 /**< Image width, short or long */
#define kTIFF_TAG_IMGLENGTH 0x0101 /**< Image length, short or long */
#define kTIFF_TAG_BITSPERSAMPLE 0x0102 /**< BitsPerSample, short */
#define kTIFF_TAG_COMPRESSION 0x0103 /**< Compression, short */
#define kTIFF_TAG_PHOTOMETRICINT 0x0106 /**< PhotometricInterpretation, short */
#define kTIFF_TAG_STRIPOFFSETS 0x0111 /**< StripOffsets, short or long */
#define kTIFF_TAG_SAMPLESPERPIXEL 0x0115 /**< Samples per pixel, short */
#define kTIFF_TAG_ROWSPERSTRIP 0x0116 /**< RowsPerStrip, short or long */
#define kTIFF_TAG_STRIPBYTECOUNTS 0x0117 /**< StripByteCounts, short or long */
#define kTIFF_TAG_XRESOLUTION 0x011A /**< X Resolution, rational */
#define kTIFF_TAG_YRESOLUTION 0x011B /**< Y Resolution, rational */
#define kTIFF_TAG_RESOLUTIONUNIT 0x0128 /**< Resolution unit, short */
#define kTIFF_TAG_COLORMAP 0x0140 /**< ColorMap, short, RGB order, black = 0,0,0, TWAIN supports max 256 entry pallette */
/**
* TIFF Image File Header
*/
struct TIFFIFH
{
WORD Identifier;
WORD Version;
DWORD IFDOffset;
};
/**
* A TIFF Tag
* If the actual value of the tag is less then a DWORD, then offset will contain
* it, else offset is truly an offset to the value.
*/
struct TIFFTag
{
WORD TagID;
WORD DataType;
DWORD DataCount;
DWORD DataOffset;
};
/**
* This is a class that will progressively write a TIFF image to a file.
*/
class CTiffWriter
{
public:
/**
* Constructor for CTiffWriter. This is a class that will progressively
* write a TIFF image to a file.
* @param[in] _filename name of file to write to.
* @param[in] _width image width.
* @param[in] _height image height.
* @param[in] _bitsPerPixel number of bits per each pixel.
* @param[in] _bytesPerRow number of bytes per row of data.
*/
CTiffWriter(const string& _filename,
const long int _width,
const long int _height,
const int _bitsPerPixel,
const unsigned long int _bytesPerRow);
/**
* Deconstructor for CTiffWriter.
*/
virtual ~CTiffWriter();
/**
* Set the width of the image.
* @param[in] _v the new image width
*/
void setImageWidth(const long int _v);
/**
* Set the height of the image.
* @param[in] _v the new image height
*/
void setImageHeight(const long int _v);
/**
* Set the bits per sample of the image.
* @param[in] _v the new bits per sample
*/
void setBitsPerSample(const int _v);
/**
* Set the compression method to use.
* @param[in] _v the new compression method
*/
void setCompression(const int _v);
/**
* Set the Photometric Interpretation.
* @param[in] _v the new Photometric Interpretation
*/
void setPhotometricInterp(const int _v);
/**
* Set the number of samples per pixel of the image.
* @param[in] _v the new samples per pixel
*/
void setSamplesPerPixel(const int _v);
/**
* Set the x resolution of the image. Using type kTIFF_TY_RATIONAL (fraction)
* @param[in] _numerator the numerator part of the fraction
* @param[in] _denominator the denominator part of the fraction
*/
void setXResolution(const int _numerator, const int _denominator);
/**
* Set the y resolution of the image. Using type kTIFF_TY_RATIONAL (fraction)
* @param[in] _numerator the numerator part of the fraction
* @param[in] _denominator the denominator part of the fraction
*/
void setYResolution(const int _numerator, const int _denominator);
/**
* Set the Bytes per row of the image.
* @param[in] _v the new bytes per row
*/
void setBytesPerRow(const int _v);
/**
* Write the prepaired image header to the file.
* @return true for succes
*/
bool writeImageHeader();
/**
* Write the data for the image to the file.
* @param[in] _pData pointer to the image data
* @param[in] _nCount number of bytes to write
* @return true for success
*/
bool WriteTIFFData(char *_pData, DWORD _nCount);
/**
* Return the size of the TIFF header for the image file.
* @return the size of the header
*/
unsigned int getSizeofHeader();
void GetImageHeader(stringstream &Header);
protected:
string m_filename; /**< Name and or path of file */
int m_nOffset; /**< Current offset into file */
DWORD m_xres[2]; /**< The X resolution of the image */
DWORD m_yres[2]; /**< The Y resolution of the image */
TIFFTag m_ImageWidth; /**< The image width in pixels */
TIFFTag m_ImageLength; /**< The image height in pixels */
TIFFTag m_BitsPerSample; /**< The number of Bits per sample */
TIFFTag m_Compression; /**< The compression method to use */
TIFFTag m_PhotometricInterp; /**< The Photometric Interpretation to use */
TIFFTag m_StripOffsets; /**< The strip offset, where image data starts */
TIFFTag m_SamplesPerPixel; /**< The number of channels (RGB, G, )*/
TIFFTag m_RowsPerStrip; /**< The number of rows that make up each strip */
TIFFTag m_StripByteCounts; /**< The size of each strip of image data */
TIFFTag m_XResolution; /**< The offset to the X resolution */
TIFFTag m_YResolution; /**< The offset to the Y resolution */
TIFFTag m_ResolutionUnit; /**< The units of the Resolution */
ofstream* m_pImageStream; /**< The output stream to write the file to */
};
#endif // __TIFFWRITER_H__

View File

@ -0,0 +1,126 @@
#include "stdafx.h"
#include "CTwainMutex.h"
CTwainMutex::CTwainMutex(void)
{
m_hTwainMutex=NULL;
m_bInited=FALSE;
memset(m_sTwainMutex,0,sizeof(m_sTwainMutex));
}
CTwainMutex::~CTwainMutex(void)
{
if (m_hTwainMutex!=NULL)
{
CloseHandle(m_hTwainMutex);
m_hTwainMutex=NULL;
}
}
BOOL CTwainMutex::CreatTwainMutex(TCHAR *str_Mutex)
{
TCHAR mutexName[MAX_PATH]={0};
DWORD error_code=0;
HANDLE hMutex=NULL;
BOOL b_ret=FALSE;
if (m_hTwainMutex!=NULL)
{
return b_ret;
}
_tcscpy(mutexName,str_Mutex);
hMutex=CreateMutex(NULL,FALSE,mutexName);
if (hMutex!=NULL)
{
error_code=GetLastError();
if (error_code==ERROR_ALREADY_EXISTS||error_code==ERROR_ACCESS_DENIED)
{
MessageBox(NULL,"设备已被其他程序占用,请关闭占用程序之后再重试!","提示",MB_OK|MB_ICONWARNING);
b_ret=CloseHandle(hMutex);
if (!b_ret)
{
MessageBox(NULL, TEXT("资源释放异常"), 0, MB_ICONWARNING);
}
hMutex=NULL;
return FALSE;
}
else
{
if (m_hTwainMutex!=NULL)
{
b_ret=CloseHandle(m_hTwainMutex);
if (!b_ret)
{
return FALSE;
}
m_hTwainMutex=NULL;
}
m_hTwainMutex=hMutex;
b_ret=TRUE;
}
return b_ret;
}
else
{
MessageBox(NULL, TEXT("程序初始化错误"), 0, MB_ICONWARNING);
}
return b_ret;
}
BOOL CTwainMutex::CheckExistTwainMutex(TCHAR* str_Mutex)
{
TCHAR szMutexName[MAX_PATH] = {0};
DWORD error_code = 0;
BOOL b_ret = FALSE;
HANDLE hMutex = NULL;
if (m_hTwainMutex!=NULL)
{
return TRUE;
}
_tcscpy(szMutexName,str_Mutex);
hMutex=CreateMutex(NULL,FALSE,szMutexName);
if (hMutex!=NULL)
{
error_code=GetLastError();
if (error_code==ERROR_ALREADY_EXISTS||error_code==ERROR_ACCESS_DENIED)
{
b_ret=CloseHandle(hMutex);
hMutex=NULL;
b_ret=TRUE;
return b_ret;
}
else
{
CloseHandle(hMutex);
b_ret=FALSE;
return b_ret;
}
}
else
{
return TRUE;
}
return b_ret;
}
BOOL CTwainMutex::CloseTwainMutex()
{
BOOL b_ret=FALSE;
if (m_hTwainMutex!=NULL)
{
b_ret=CloseHandle(m_hTwainMutex);
if (!b_ret)
{
MessageBox(NULL, TEXT("释放资源失败"), 0, MB_ICONWARNING);
}
m_hTwainMutex=NULL;
return b_ret;
}
return TRUE;
}

View File

@ -0,0 +1,16 @@
#include "stdafx.h"
class CTwainMutex
{
public:
CTwainMutex(void);
~CTwainMutex(void);
public:
BOOL CreatTwainMutex(TCHAR *str_Mutex);
BOOL CheckExistTwainMutex(TCHAR *str_Mutex);
BOOL CloseTwainMutex();
private:
HANDLE m_hTwainMutex;
TCHAR m_sTwainMutex[MAX_PATH];
BOOL m_bInited;
};

View File

@ -0,0 +1,193 @@
#include "stdafx.h"
#include "CUSBHotPlugged.h"
CUSBHotPlugged::CUSBHotPlugged()
{
//usbHotPlugged=this;
isconnected=true;
tHandle=NULL;
hWnd=NULL;
initThread();
}
CUSBHotPlugged::~CUSBHotPlugged()
{
if (tHandle!=NULL)
{
PostThreadMessage(iThread,THRD_MESSAGE_EXIT,0,0);
WaitForSingleObject(tHandle,1000);
CloseHandle(tHandle);
}
if (hWnd!=NULL&&IsWindow(hWnd))
{
//PostQuitMessage(0);
//SendMessage(hWnd,WM_CLOSE,);
BOOL ret= UnregisterClass(CLASS_NAME,GetModuleHandle(NULL));
BOOL ret1=DestroyWindow(hWnd);
hWnd=NULL;
int aa=-1;
}
}
bool CUSBHotPlugged::getIsConnected()
{
return isconnected;
}
void CUSBHotPlugged::UpdateDevice(PDEV_BROADCAST_DEVICEINTERFACE pDevInf, WPARAM wParam)
{
CString szDevId = pDevInf->dbcc_name + 4;
int idx = szDevId.ReverseFind(_T('#'));
szDevId.Truncate(idx);
szDevId.Replace(_T('#'), _T('\\'));
szDevId.MakeUpper();
CString szClass;
idx = szDevId.Find(_T('\\'));
szClass = szDevId.Left(idx);
CString szTmp;
if (DBT_DEVICEARRIVAL == wParam) \
szTmp.Format(_T("Adding %s\r\n"), szDevId.GetBuffer());
else
szTmp.Format(_T("Removing %s\r\n"), szDevId.GetBuffer());
_tprintf(szTmp);
}
LRESULT CUSBHotPlugged::DeviceChange(UINT message, WPARAM wParam, LPARAM lParam)
{
if (DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam)
{
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
PDEV_BROADCAST_DEVICEINTERFACE pDevInf;
PDEV_BROADCAST_HANDLE pDevHnd;
PDEV_BROADCAST_OEM pDevOem;
PDEV_BROADCAST_PORT pDevPort;
PDEV_BROADCAST_VOLUME pDevVolume;
switch (pHdr->dbch_devicetype)
{
case DBT_DEVTYP_DEVICEINTERFACE:
pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
CUSBHotPlugged::UpdateDevice(pDevInf, wParam);
break;
case DBT_DEVTYP_HANDLE:
pDevHnd = (PDEV_BROADCAST_HANDLE)pHdr;
break;
case DBT_DEVTYP_OEM:
pDevOem = (PDEV_BROADCAST_OEM)pHdr;
break;
case DBT_DEVTYP_PORT:
pDevPort = (PDEV_BROADCAST_PORT)pHdr;
break;
case DBT_DEVTYP_VOLUME:
pDevVolume = (PDEV_BROADCAST_VOLUME)pHdr;
break;
}
}
return 0;
}
LRESULT CALLBACK CUSBHotPlugged::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_PAINT:
break;
case WM_SIZE:
break;
case WM_DEVICECHANGE:
return DeviceChange(message, wParam, lParam);
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
bool CUSBHotPlugged::CreateMessageOnlyWindow()
{
hWnd = CreateWindowEx(0, CLASS_NAME, _T(""), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
GetModuleHandle(NULL), // Instance handle
NULL // Additional application data
);
return hWnd != NULL;
}
void CUSBHotPlugged::RegisterDeviceNotify()
{
HDEVNOTIFY hDevNotify;
for (int i = 0; i < sizeof(GUID_DEVINTERFACE_LIST) / sizeof(GUID); i++)
{
DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;
ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
NotificationFilter.dbcc_classguid = GUID_DEVINTERFACE_LIST[i];
hDevNotify = RegisterDeviceNotification(hWnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
}
}
DWORD CUSBHotPlugged::ThrdFunc(LPVOID lpParam)
{
if (0 ==MyRegisterClass())
return -1;
if (!CreateMessageOnlyWindow())
return -1;
RegisterDeviceNotify();
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
if (msg.message == THRD_MESSAGE_EXIT)
{
//cout << "worker receive the exiting Message..." << endl;
return 0;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
int CUSBHotPlugged::initThread()
{
int ret=-1;
if (tHandle==NULL)
{
tHandle=CreateThread(NULL, sizeof(CUSBHotPlugged),_usbhotPlugDetect, (LPVOID)this, 0L, &iThread);
if (tHandle==NULL)
{
return ret;
}
ret=0;
}
return ret;
}
DWORD WINAPI CUSBHotPlugged::_usbhotPlugDetect(LPVOID lp_param)
{
CUSBHotPlugged* This=(CUSBHotPlugged*) lp_param;
return This->ThrdFunc(lp_param);
}
ATOM CUSBHotPlugged::MyRegisterClass()
{
//CUSBHotPlugged* This=(CUSBHotPlugged*) lp_param;
WNDCLASS wc = { 0 };
wc.lpfnWndProc =WndProc;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = CLASS_NAME;
return RegisterClass(&wc);
}

View File

@ -0,0 +1,57 @@
#include "stdafx.h"
#include <Windows.h>
#include <tchar.h>
#include <Dbt.h>
#include <setupapi.h>
#include <iostream>
#include <atlstr.h>
#pragma comment (lib, "Kernel32.lib")
#pragma comment (lib, "User32.lib")
#define THRD_MESSAGE_EXIT WM_USER + 1
const _TCHAR CLASS_NAME[] = _T("Sample Window Class");
static const GUID GUID_DEVINTERFACE_LIST[] =
{
// GUID_DEVINTERFACE_USB_DEVICE
{ 0xA5DCBF10, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } },
// GUID_DEVINTERFACE_DISK
{ 0x53f56307, 0xb6bf, 0x11d0, { 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b } },
// GUID_DEVINTERFACE_HID,
{ 0x4D1E55B2, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } },
// GUID_NDIS_LAN_CLASS
{ 0xad498944, 0x762f, 0x11d0, { 0x8d, 0xcb, 0x00, 0xc0, 0x4f, 0xc3, 0x35, 0x8c } },
// GUID_DEVINTERFACE_COMPORT
{ 0x86e0d1e0, 0x8089, 0x11d0, { 0x9c, 0xe4, 0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73 } },
// GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR
{ 0x4D36E978, 0xE325, 0x11CE, { 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18 } },
// GUID_DEVINTERFACE_PARALLEL
{ 0x97F76EF0, 0xF883, 0x11D0, { 0xAF, 0x1F, 0x00, 0x00, 0xF8, 0x00, 0x84, 0x5C } },
// GUID_DEVINTERFACE_PARCLASS
{ 0x811FC6A5, 0xF728, 0x11D0, { 0xA5, 0x37, 0x00, 0x00, 0xF8, 0x75, 0x3E, 0xD1 } }
};
class CUSBHotPlugged
{
public:
CUSBHotPlugged();
~CUSBHotPlugged();
bool getIsConnected();
protected:
static void UpdateDevice(PDEV_BROADCAST_DEVICEINTERFACE pDevInf, WPARAM wParam);
static LRESULT DeviceChange(UINT message, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
bool CreateMessageOnlyWindow();
void RegisterDeviceNotify();
DWORD ThrdFunc(LPVOID lpParam);
int initThread();
static DWORD WINAPI _usbhotPlugDetect(LPVOID lp_param);
ATOM MyRegisterClass();
private:
bool isconnected;
HANDLE tHandle;
DWORD iThread;
HWND hWnd;
//CUSBHotPlugged* usbHotPlugged;
};

272
hugaotwainds/Common.h Normal file
View File

@ -0,0 +1,272 @@
/***************************************************************************
* Copyright © 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file Common.h
* Common defines and typedefs used by the DS, App, and scanner
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __COMMON_H__
#define __COMMON_H__
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#define TWNDS_OS_WIN
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#endif
#include <windows.h>
#endif
#if defined(__APPLE__)
#define TWNDS_OS_APPLE
#endif
#include "twain.h"
#ifdef TWH_CMP_GNU
#if !(defined(TWNDS_OS_WIN) || defined(TWNDS_OS_APPLE))
#define TWNDS_OS_LINUX
#endif
#include <wchar.h>
#include <stdarg.h>
#endif
/**
* These headers are available on all platforms...
*/
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <assert.h>
/**
* First off, figure out what compiler we're running and on which
* platform we think we're running it. We assume that you're building
* on the same platform you intend to run, so if you are cross compiling
* you will likely have a bit of work to do here...
*/
/**
* Compilers we support...
*/
#define TWNDS_CMP_VISUALCPP 0x1001 // Preferably 2005+
#define TWNDS_CMP_GNUGPP 0x1002 // Preferably v4.x+
#define TWNDS_CMP_XCODE 0x1003 // Xcode
/**
* If the user defines TWNDS_CMP in their make file or project,
* then we'll assume they want to take responsibility for picking
* how we'll build the system. At this point it seems like the
* compiler definition is used to select which native library calls
* we're dealing with, while the os definition is more about
* where we'll expect to find stuff on the running system, like
* directories...
*/
#ifndef TWNDS_CMP
// GNU g++
#if defined(TWH_CMP_GNU) || defined(TWH_CMP_XCODE)
#define TWNDS_CMP TWNDS_CMP_GNUGPP
#define TWNDS_CMP_VERSION __GNUC__
#define kTWAIN_DSM_DIR "/usr/local/lib/"
// Visual Studio C++
#elif defined(TWH_CMP_MSC)
#define TWNDS_CMP TWNDS_CMP_VISUALCPP
#define TWNDS_CMP_VERSION _MSC_VER
// Not neccessary it is in Windows path
#define kTWAIN_DSM_DIR ""
// Xcode
#elif defined (TWH_CMP_XCODE)
#define TWNDS_CMP TWNDS_CMP_XCODE
#define TWNDS_CMP_VERSION
// ruh-roh...
#else
#error Sorry, we don't recognize this system...
#endif
#endif
/**
* @def LOADLIBRARY(lib)
* Call system loadibrary function. OS abstraction macro that tries to load a library.
* @param lib path and name of library
*
* @def LOADFUNCTION(lib, func)
* Call system GetProcAddress function. OS abstraction macro that tries to locate the addess of a funtion name.
* @param lib path and name of library
* @param func name of the funtion
*
* @def UNLOADLIBRARY(lib)
* Call system FreeLibrary function. OS abstraction macro that tries to release the library.
* @param lib library modual to unload
*
* @def UNLINK
* OS abstraction macro that calls system _unlink function.
*
* @def READ
* OS abstraction macro that calls system _read function.
*
* @def CLOSE
* OS abstraction macro that calls system _close function.
*
* @def SNPRINTF
* OS abstraction macro that calls system _snprintf function.
*
*/
#if (TWNDS_CMP == TWNDS_CMP_VISUALCPP)
//#include "stdafx.h"
#define DllExport __declspec( dllexport )
#define LOADLIBRARY(lib) LoadLibraryA(lib)
#define LOADFUNCTION(lib, func) GetProcAddress(lib, func)
#define UNLOADLIBRARY(lib) FreeLibrary(lib)
#define UNLINK _unlink
#define READ _read
#define CLOSE _close
#define FILE_EXISTS(FILE_NAME) ((0xFFFFFFFF==GetFileAttributes(FILE_NAME))?FALSE:TRUE)
#define PATH_SEPERATOR '\\'
#ifndef PATH_MAX
#define PATH_MAX _MAX_PATH
#endif
#if (TWNDS_CMP_VERSION >= 1400)
#define SNPRINTF _snprintf_s
#define SSCANF sscanf_s
#define FOPEN(pf,name,mode) (void)fopen_s(&pf,name,mode)
#define _OPEN(pf,name,mode,share,perm) (void)_sopen_s(&pf,name,mode,share,perm)
#else
#define SSCANF sscanf
#define SNPRINTF _snprintf
#define FOPEN(pf,name,mode) pf=fopen(name,mode)
#define _OPEN(pf,name,mode,share,perm) pf = _open(name,mode,share)
#endif
#define MAX(a, b) max(a,b)
#define MIN(a, b) min(a,b)
#elif (TWNDS_CMP == TWNDS_CMP_GNUGPP)
#define DllExport
#define LOADLIBRARY(lib) dlopen(lib, RTLD_NOW)
#define LOADFUNCTION(lib, func) dlsym(lib, func)
#define UNLOADLIBRARY(lib) dlclose(lib)
#define UNLINK unlink
#define kTWAIN_DSM_DLL_NAME "libtwaindsm.so"
#define READ read
#define CLOSE close
#define PATH_SEPERATOR '/'
#define SNPRINTF snprintf
#define SSCANF sscanf
typedef void * HMODULE;
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define FILE_EXISTS(FILE_NAME) ((0 == access(FILE_NAME, R_OK))?TRUE:FALSE)
#define FOPEN(pf,name,mode) (pf=fopen(name,mode))
#if !defined(TRUE)
#define FALSE 0
#define TRUE 1
#endif
#include <inttypes.h>
typedef uint16_t WORD;
typedef uint32_t DWORD;
#else
#error Sorry, we don't recognize this system...
#endif
/**
* We want to use secure string functions whenever possible, if g++
* every includes a set I think it would be excellent to switch over
* to it, but at least with Windows using them we stand a better
* chance of finding boo-boos...
*/
#if (TWNDS_CMP == TWNDS_CMP_VISUALCPP) && (TWNDS_CMP_VERSION >= 1400)
#define SSTRCPY(d,z,s) strncpy_s(d,z,s,_TRUNCATE)
#define SSTRCAT(d,z,s) strncat_s(d,z,s,_TRUNCATE)
#define SSTRNCPY(d,z,s,m) strncpy_s(d,z,s,m)
#define SGETENV(d,z,n) ::GetEnvironmentVariable(n,d,z)
inline int SSNPRINTF(char *d, size_t z, size_t c, const char *f,...)
{
int result;
va_list valist;
va_start(valist,f);
result = _vsnprintf_s(d,z,c,f,valist);
va_end(valist);
return result;
}
/**
* These functions are insecure, but everybody has them, so we
* don't need an else/error section like we use everywhere else...
*/
#else
#define SSTRCPY(d,z,s) strcpy(d,s)
#define SSTRCAT(d,z,s) strcat(d,s)
#define SSTRNCPY(d,z,s,m) strncpy(d,s,m)
#define SGETENV(d,z,n) strcpy(d,getenv(n)?getenv(n):"")
inline int SSNPRINTF(char *d, size_t, size_t c, const char *f,...)
{
int result;
va_list valist;
va_start(valist,f);
#if (TWNDS_CMP == TWNDS_CMP_VISUALCPP)
result = _vsnprintf(d,c,f,valist);
#elif (TWNDS_CMP == TWNDS_CMP_GNUGPP)
result = vsnprintf(d,c,f,valist);
#else
#error Sorry, we don't recognize this system...
#endif
va_end(valist);
return result;
}
#endif
/**
* Determine the number of bytes needed for one line.
*/
#define BYTES_PERLINE(width, bpp) ((((int)(width)*(bpp))+7)/8)
/**
* Determine the number of bytes needed rouned up to 4 byte alignment.
*/
#define BYTES_PERLINE_ALIGN4(width, bpp) (((((int)(width)*(bpp))+31)/32)*4)
#endif // __COMMON_H__

155
hugaotwainds/CommonDS.cpp Normal file
View File

@ -0,0 +1,155 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CommonDS.cpp
* Utilities functions used by TWAIN Data Sources
*
* @author TWAIN Working Group
* @date October 2007
*/
#include "stdafx.h"
#include "CommonDS.h"
//////////////////////////////////////////////////////////////////////////////
float ConvertUnits(float val, int fromUnits, int toUnits, float resolution)
{
double result = val; //assume we don't have to convert
if( fromUnits != toUnits ) //if we do have to convert
{
//see what we're converting from, and convert to inches
switch(fromUnits)
{
case TWUN_INCHES:
// nothing to do
break;
case TWUN_CENTIMETERS:
result = val / 2.54;
break;
case TWUN_PICAS:
result = val / 6.0;
break;
case TWUN_POINTS:
result = val / 72.0;
break;
case TWUN_TWIPS:
result = val / 1440.0;
break;
case TWUN_PIXELS:
if(resolution != 0)
{
result = val / resolution;
}
break;
case TWUN_1000INCHES:
result = val / 1000.0;
break;
default:
// problem
break;
}
// We are now in inches
// see what we're converting to, and convert the result to those units
switch(toUnits)
{
case TWUN_INCHES:
// nothing to do
break;
case TWUN_CENTIMETERS:
result *= 2.54;
break;
case TWUN_PICAS:
result *= 6.0;
break;
case TWUN_POINTS:
result *= 72.0;
break;
case TWUN_TWIPS:
result *= 1440.0;
break;
case TWUN_PIXELS:
result *= resolution;
break;
case TWUN_1000INCHES:
result *= 1000;
break;
default:
// problem
break;
}
}
return (float)result; //return the result
}
TW_FIX32 ConvertUnits(TW_FIX32 val, int fromUnits, int toUnits, float resolution)
{
TW_FIX32 result = val;
if( fromUnits != toUnits ) //if we do have to convert
{
result = FloatToFIX32(ConvertUnits( FIX32ToFloat(val), fromUnits, toUnits, resolution));
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
TW_FRAME ConvertUnits(TW_FRAME val, int fromUnits, int toUnits, float Xresolution, float Yresolution)
{
TW_FRAME result = val;
if( fromUnits != toUnits ) //if we do have to convert
{
result.Left = ConvertUnits( val.Left, fromUnits, toUnits, Xresolution);
result.Top = ConvertUnits( val.Top, fromUnits, toUnits, Yresolution);
result.Right = ConvertUnits( val.Right, fromUnits, toUnits, Xresolution);
result.Bottom = ConvertUnits( val.Bottom, fromUnits, toUnits, Yresolution);
}
return result;
}
//////////////////////////////////////////////////////////////////////////////

121
hugaotwainds/CommonDS.h Normal file
View File

@ -0,0 +1,121 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CommonDS.h
* Common defines and typedefs used by the DS
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __COMMONDS_H__
#define __COMMONDS_H__
#include "Common.h"
#include "FreeImage.h"
#include "CommonTWAIN.h"
#ifdef TWH_CMP_MSC
#include "resource.h"
#endif
#include "DSMInterface.h"
#include "TWAINContainer.h"
#include "TWAINContainerInt.h"
#include "TWAINContainerFix32.h"
#include "TWAINContainerFix32Range.h"
#include "TWAINContainerBool.h"
#include "TWAINContainerFrame.h"
#include "TWAINContainerString.h"
#include "CTiffWriter.h"
#include <map>
using namespace std;
/**
* Base TWAIN Container
*/
typedef map<int, CTWAINContainer*> TWAINCapabilitiesMap;
/**
* Int TWAIN Container
*/
typedef map<int, CTWAINContainerInt*> TWAINCapabilitiesMap_int;
/**
* Fix32 TWAIN Container
*/
typedef map<int, CTWAINContainerFix32*> TWAINCapabilitiesMap_FIX32;
/**
* Our internal dimention we use to store data
*/
#define TWUN_1000INCHES 0x8000
/**
* A commonly used conversion function for converting a dimention of one unit to a dimention of another unit.
* converts the given value from fromUnits to toUnits; resolution is optional if pixels are not involved, and should be in dots-per-inch
* @param[in] val the value in float to convert.
* @param[in] fromUnits the original unit of the value.
* @param[in] toUnits the result unit ot convert to
* @param[in] resolution the resolution in dots per inch, used to express the unit. Required if one of the units is pixels.
* @return the converted value as float
*/
float ConvertUnits(float val, int fromUnits, int toUnits, float resolution);
/**
* A commonly used conversion function for converting a dimention of one unit to a dimention of another unit.
* converts the given value from fromUnits to toUnits; resolution is optional if pixels are not involved, and should be in dots-per-inch
* @param[in] val the value in TW_FIX32 to convert.
* @param[in] fromUnits the original unit of the value.
* @param[in] toUnits the result unit ot convert to
* @param[in] resolution the resolution in dots per inch, used to express the unit. Required if one of the units is pixels.
* @return the converted value as TW_FIX32
*/
TW_FIX32 ConvertUnits(TW_FIX32 val, int fromUnits, int toUnits, float resolution);
/**
* A commonly used conversion function for converting a frame of one unit to a frame of another unit.
* converts the given frame from fromUnits to toUnits; resolution is optional if pixels are not involved, and should be in dots-per-inch
* @param[in] val the value as TW_FRAME to convert.
* @param[in] fromUnits the original unit of the value.
* @param[in] toUnits the result unit ot convert to
* @param[in] Xresolution the X resolution in dots per inch, used to express the unit. Required if one of the units is pixels.
* @param[in] Yresolution the Y resolution in dots per inch, used to express the unit. Required if one of the units is pixels.
* @return the converted frame as TW_FRAME
*/
TW_FRAME ConvertUnits(TW_FRAME val, int fromUnits, int toUnits, float Xresolution, float Yresolution);
#endif // __COMMONDS_H__

View File

@ -0,0 +1,634 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CommonTWAIN.cpp
* Utilities functions used by TWAIN Data Sources
*
* @author TWAIN Working Group
* @date October 2007
*/
#include "stdafx.h"
#include "CommonTWAIN.h"
extern TW_HANDLE _DSM_Alloc(TW_UINT32 _size);
extern TW_MEMREF _DSM_LockMemory(TW_HANDLE _hMemory);
extern void _DSM_UnlockMemory(TW_HANDLE _hMemory);
extern void _DSM_Free(TW_HANDLE _hMemory);
//////////////////////////////////////////////////////////////////////////////
TW_FIX32 FloatToFIX32 (float floater)
{
TW_FIX32 Fix32_value;
TW_BOOL sign = (floater < 0)?TRUE:FALSE;
TW_INT32 value = (TW_INT32) (floater * 65536.0 + (sign?(-0.5):0.5));
Fix32_value.Whole = (TW_UINT16)(value >> 16);
Fix32_value.Frac = (TW_UINT16)(value & 0x0000ffffL);
return (Fix32_value);
}
//////////////////////////////////////////////////////////////////////////////
float FIX32ToFloat(const TW_FIX32& _fix32)
{
return float(_fix32.Whole) + float(_fix32.Frac / 65536.0);
}
//////////////////////////////////////////////////////////////////////////////
bool getCurrent(TW_CAPABILITY *pCap, TW_UINT32& val)
{
bool bret = false;
if(0 != pCap->hContainer)
{
if(TWON_ENUMERATION == pCap->ConType)
{
pTW_ENUMERATION pCapPT = (pTW_ENUMERATION)_DSM_LockMemory(pCap->hContainer);
switch(pCapPT->ItemType)
{
case TWTY_INT32:
val = (TW_INT32)((pTW_INT32)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
bret = true;
break;
case TWTY_UINT32:
val = (TW_INT32)((pTW_UINT32)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
bret = true;
break;
case TWTY_INT16:
val = (TW_INT32)((pTW_INT16)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
bret = true;
break;
case TWTY_UINT16:
val = (TW_INT32)((pTW_UINT16)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
bret = true;
break;
case TWTY_INT8:
val = (TW_INT32)((pTW_INT8)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
bret = true;
break;
case TWTY_UINT8:
val = (TW_INT32)((pTW_UINT8)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
bret = true;
break;
case TWTY_BOOL:
val = (TW_INT32)((pTW_BOOL)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
bret = true;
break;
}
_DSM_UnlockMemory(pCap->hContainer);
}
else if(TWON_ONEVALUE == pCap->ConType)
{
pTW_ONEVALUE pCapPT = (pTW_ONEVALUE)_DSM_LockMemory(pCap->hContainer);
if(pCapPT->ItemType < TWTY_FIX32)
{
val = pCapPT->Item;
bret = true;
}
_DSM_UnlockMemory(pCap->hContainer);
}
else if(TWON_RANGE == pCap->ConType)
{
pTW_RANGE pCapPT = (pTW_RANGE)_DSM_LockMemory(pCap->hContainer);
if(pCapPT->ItemType < TWTY_FIX32)
{
val = pCapPT->CurrentValue;
bret = true;
}
_DSM_UnlockMemory(pCap->hContainer);
}
}
return bret;
}
//////////////////////////////////////////////////////////////////////////////
bool getCurrent(TW_CAPABILITY *pCap, string& val)
{
bool bret = false;
if(0 != pCap->hContainer)
{
if(TWON_ENUMERATION == pCap->ConType)
{
pTW_ENUMERATION pCapPT = (pTW_ENUMERATION)_DSM_LockMemory(pCap->hContainer);
switch(pCapPT->ItemType)
{
case TWTY_STR32:
{
pTW_STR32 pStr = &((pTW_STR32)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
// In case the Capability is not null terminated
pStr[32] = 0;
val = pStr;
bret = true;
}
break;
case TWTY_STR64:
{
pTW_STR64 pStr = &((pTW_STR64)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
// In case the Capability is not null terminated
pStr[64] = 0;
val = pStr;
bret = true;
}
break;
case TWTY_STR128:
{
pTW_STR128 pStr = &((pTW_STR128)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
// In case the Capability is not null terminated
pStr[128] = 0;
val = pStr;
bret = true;
}
break;
case TWTY_STR255:
{
pTW_STR255 pStr = &((pTW_STR255)(&pCapPT->ItemList))[pCapPT->CurrentIndex];
// In case the Capability is not null terminated
pStr[255] = 0;
val = pStr;
bret = true;
}
break;
}
_DSM_UnlockMemory(pCap->hContainer);
}
else if(TWON_ONEVALUE == pCap->ConType)
{
pTW_ONEVALUE pCapPT = (pTW_ONEVALUE)_DSM_LockMemory(pCap->hContainer);
switch(pCapPT->ItemType)
{
case TWTY_STR32:
{
pTW_STR32 pStr = ((pTW_STR32)(&pCapPT->Item));
// In case the Capability is not null terminated
pStr[32] = 0;
val = pStr;
bret = true;
}
break;
case TWTY_STR64:
{
pTW_STR64 pStr = ((pTW_STR64)(&pCapPT->Item));
// In case the Capability is not null terminated
pStr[64] = 0;
val = pStr;
bret = true;
}
break;
case TWTY_STR128:
{
pTW_STR128 pStr = ((pTW_STR128)(&pCapPT->Item));
// In case the Capability is not null terminated
pStr[128] = 0;
val = pStr;
bret = true;
}
break;
case TWTY_STR255:
{
pTW_STR255 pStr = ((pTW_STR255)(&pCapPT->Item));
// In case the Capability is not null terminated
pStr[255] = 0;
val = pStr;
bret = true;
}
break;
}
_DSM_UnlockMemory(pCap->hContainer);
}
}
return bret;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
bool getCurrent(TW_CAPABILITY *pCap, TW_FIX32& val)
{
bool bret = false;
if(0 != pCap->hContainer)
{
if(TWON_ENUMERATION == pCap->ConType)
{
pTW_ENUMERATION_FIX32 pCapPT = (pTW_ENUMERATION_FIX32)_DSM_LockMemory(pCap->hContainer);
if(TWTY_FIX32 == pCapPT->ItemType)
{
val = pCapPT->ItemList[pCapPT->CurrentIndex];
bret = true;
}
_DSM_UnlockMemory(pCap->hContainer);
}
else if(TWON_ONEVALUE == pCap->ConType)
{
pTW_ONEVALUE_FIX32 pCapPT = (pTW_ONEVALUE_FIX32)_DSM_LockMemory(pCap->hContainer);
if(TWTY_FIX32 == pCapPT->ItemType)
{
val = pCapPT->Item;
bret = true;
}
_DSM_UnlockMemory(pCap->hContainer);
}
else if(TWON_RANGE == pCap->ConType)
{
pTW_RANGE pCapPT = (pTW_RANGE)_DSM_LockMemory(pCap->hContainer);
if(TWTY_FIX32 == pCapPT->ItemType)
{
val = *(TW_FIX32*)&pCapPT->CurrentValue;
bret = true;
}
_DSM_UnlockMemory(pCap->hContainer);
}
}
return bret;
}
//////////////////////////////////////////////////////////////////////////////
bool getCurrent(TW_CAPABILITY *pCap, TW_FRAME& frame)
{
bool bret = false;
if(0 != pCap->hContainer)
{
if(TWON_ENUMERATION == pCap->ConType)
{
pTW_ENUMERATION_FRAME pCapPT = (pTW_ENUMERATION_FRAME)_DSM_LockMemory(pCap->hContainer);
if(TWTY_FRAME == pCapPT->ItemType)
{
frame = pCapPT->ItemList[pCapPT->CurrentIndex];
bret = true;
}
_DSM_UnlockMemory(pCap->hContainer);
}
else if(TWON_ONEVALUE == pCap->ConType)
{
pTW_ONEVALUE_FRAME pCapPT = (pTW_ONEVALUE_FRAME)_DSM_LockMemory(pCap->hContainer);
if(TWTY_FRAME == pCapPT->ItemType)
{
frame = pCapPT->Item;
bret = true;
}
_DSM_UnlockMemory(pCap->hContainer);
}
}
return bret;
}
//////////////////////////////////////////////////////////////////////////////
bool GetItem(TW_CAPABILITY *pCap, TW_UINT32 item, TW_UINT32& val)
{
bool bret = false;
if(0 != pCap && 0 != pCap->hContainer)
{
if( TWON_ARRAY == pCap->ConType
|| TWON_ENUMERATION == pCap->ConType )
{
TW_UINT8 *pData = NULL;
unsigned int Count = 0;
TW_UINT16 Type = 0;
if( TWON_ARRAY == pCap->ConType )
{
pTW_ARRAY pArray = (pTW_ARRAY)_DSM_LockMemory(pCap->hContainer);
Count = pArray->NumItems;
Type = pArray->ItemType;
pData = &pArray->ItemList[0];
}
if( TWON_ENUMERATION == pCap->ConType )
{
pTW_ENUMERATION pEnumeration = (pTW_ENUMERATION)_DSM_LockMemory(pCap->hContainer);
Count = pEnumeration->NumItems;
Type = pEnumeration->ItemType;
pData = &pEnumeration->ItemList[0];
}
if(item < Count)
{
switch(Type)
{
case TWTY_INT32:
val = (int)((pTW_INT32)(pData))[item];
bret = true;
break;
case TWTY_UINT32:
val = (int)((pTW_UINT32)(pData))[item];
bret = true;
break;
case TWTY_INT16:
val = (int)((pTW_INT16)(pData))[item];
bret = true;
break;
case TWTY_UINT16:
val = (int)((pTW_UINT16)(pData))[item];
bret = true;
break;
case TWTY_INT8:
val = (int)((pTW_INT8)(pData))[item];
bret = true;
break;
case TWTY_UINT8:
val = (int)((pTW_UINT8)(pData))[item];
bret = true;
break;
case TWTY_BOOL:
val = (int)((pTW_BOOL)(pData))[item];
bret = true;
break;
}
}
_DSM_UnlockMemory(pCap->hContainer);
}
}
return bret;
}
//////////////////////////////////////////////////////////////////////////////
bool GetItem(TW_CAPABILITY *pCap, TW_UINT32 item, string& val)
{
bool bret = false;
if(0 != pCap && 0 != pCap->hContainer)
{
if( TWON_ARRAY == pCap->ConType
|| TWON_ENUMERATION == pCap->ConType )
{
TW_UINT8 *pData = NULL;
unsigned int Count = 0;
TW_UINT16 Type = 0;
if( TWON_ARRAY == pCap->ConType )
{
pTW_ARRAY pArray = (pTW_ARRAY)_DSM_LockMemory(pCap->hContainer);
Count = pArray->NumItems;
Type = pArray->ItemType;
pData = &pArray->ItemList[0];
}
if( TWON_ENUMERATION == pCap->ConType )
{
pTW_ENUMERATION pEnumeration = (pTW_ENUMERATION)_DSM_LockMemory(pCap->hContainer);
Count = pEnumeration->NumItems;
Type = pEnumeration->ItemType;
pData = &pEnumeration->ItemList[0];
}
if(item < Count)
{
switch(Type)
{
case TWTY_STR32:
{
pTW_STR32 pStr = &((pTW_STR32)(pData))[item];
// In case the Capability is not null terminated
pStr[32] = 0;
val = pStr;
bret = true;
}
break;
case TWTY_STR64:
{
pTW_STR64 pStr = &((pTW_STR64)(pData))[item];
// In case the Capability is not null terminated
pStr[64] = 0;
val = pStr;
bret = true;
}
break;
case TWTY_STR128:
{
pTW_STR128 pStr = &((pTW_STR128)(pData))[item];
// In case the Capability is not null terminated
pStr[128] = 0;
val = pStr;
bret = true;
}
break;
case TWTY_STR255:
{
pTW_STR255 pStr = &((pTW_STR255)(pData))[item];
// In case the Capability is not null terminated
pStr[255] = 0;
val = pStr;
bret = true;
}
break;
}
}
_DSM_UnlockMemory(pCap->hContainer);
}
}
return bret;
}
//////////////////////////////////////////////////////////////////////////////
bool GetItem(TW_CAPABILITY *pCap, TW_UINT32 item, TW_FIX32& val)
{
bool bret = false;
if(0 != pCap && 0 != pCap->hContainer)
{
if( TWON_ARRAY == pCap->ConType
|| TWON_ENUMERATION == pCap->ConType )
{
TW_FIX32 *pData = NULL;
unsigned int Count = 0;
TW_UINT16 Type = 0;
if( TWON_ARRAY == pCap->ConType )
{
pTW_ARRAY_FIX32 pArray = (pTW_ARRAY_FIX32)_DSM_LockMemory(pCap->hContainer);
Count = pArray->NumItems;
Type = pArray->ItemType;
pData = &pArray->ItemList[0];
}
if( TWON_ENUMERATION == pCap->ConType )
{
pTW_ENUMERATION_FIX32 pEnumeration = (pTW_ENUMERATION_FIX32)_DSM_LockMemory(pCap->hContainer);
Count = pEnumeration->NumItems;
Type = pEnumeration->ItemType;
pData = &pEnumeration->ItemList[0];
}
if(item < Count && Type == TWTY_FIX32)
{
val = pData[item];
bret = true;
}
_DSM_UnlockMemory(pCap->hContainer);
}
}
return bret;
}
//////////////////////////////////////////////////////////////////////////////
bool GetItem(TW_CAPABILITY *pCap, TW_UINT32 item, TW_FRAME& val)
{
bool bret = false;
if(0 != pCap && 0 != pCap->hContainer)
{
if( TWON_ARRAY == pCap->ConType
|| TWON_ENUMERATION == pCap->ConType )
{
TW_FRAME *pData = NULL;
unsigned int Count = 0;
TW_UINT16 Type = 0;
if( TWON_ARRAY == pCap->ConType )
{
pTW_ARRAY_FRAME pArray = (pTW_ARRAY_FRAME)_DSM_LockMemory(pCap->hContainer);
Count = pArray->NumItems;
Type = pArray->ItemType;
pData = &pArray->ItemList[0];
}
if( TWON_ENUMERATION == pCap->ConType )
{
pTW_ENUMERATION_FRAME pEnumeration = (pTW_ENUMERATION_FRAME)_DSM_LockMemory(pCap->hContainer);
Count = pEnumeration->NumItems;
Type = pEnumeration->ItemType;
pData = &pEnumeration->ItemList[0];
}
if(item < Count && Type == TWTY_FRAME)
{
val = pData[item];
bret = true;
}
_DSM_UnlockMemory(pCap->hContainer);
}
}
return bret;
}
//////////////////////////////////////////////////////////////////////////////
int getTWTYsize(TW_UINT16 ItemType)
{
int TypeSize = 0;
switch(ItemType)
{
case TWTY_INT8:
TypeSize = sizeof(TW_INT8);
break;
case TWTY_INT16:
TypeSize = sizeof(TW_INT16);
break;
case TWTY_INT32:
TypeSize = sizeof(TW_INT32);
break;
case TWTY_UINT8:
TypeSize = sizeof(TW_UINT8);
break;
case TWTY_UINT16:
TypeSize = sizeof(TW_UINT16);
break;
case TWTY_UINT32:
TypeSize = sizeof(TW_UINT32);
break;
case TWTY_BOOL:
TypeSize = sizeof(TW_BOOL);
break;
case TWTY_FIX32:
TypeSize = sizeof(TW_FIX32);
break;
case TWTY_FRAME:
TypeSize = sizeof(TW_FRAME);
break;
case TWTY_STR32:
TypeSize = sizeof(TW_STR32);
break;
case TWTY_STR64:
TypeSize = sizeof(TW_STR64);
break;
case TWTY_STR128:
TypeSize = sizeof(TW_STR128);
break;
case TWTY_STR255:
TypeSize = sizeof(TW_STR255);
break;
case TWTY_STR1024:
TypeSize = sizeof(TW_STR1024);
break;
case TWTY_UNI512:
TypeSize = sizeof(TW_UNI512);
break;
case TWTY_HANDLE:
TypeSize = sizeof(TW_HANDLE);
break;
default:
break;
}
return TypeSize;
}

475
hugaotwainds/CommonTWAIN.h Normal file
View File

@ -0,0 +1,475 @@
/***************************************************************************
* Copyright © 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CommonTWAIN.h
* Common defines and typedefs used by the DS
* @author TWAIN Working Group
* @date April 2007
*/
#include "Common.h"
#include <string>
#ifndef __COMMONTWAIN_H__
#define __COMMONTWAIN_H__
using namespace std;
typedef struct _TW_GUID {
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[ 8 ];
} TW_GUID;
/**
* @def kTWAIN_DSM_DLL_NAME
* File name of the DSM library.
*/
#ifdef TWH_CMP_MSC
#ifdef TWH_64BIT
#define kTWAIN_DSM_DLL_NAME "TWAINDSM.dll"
#else
#define kTWAIN_DSM_DLL_NAME "TWAINDSM.dll"
#endif // #ifdef TWH_64BIT
#elif defined(TWH_CMP_GNU)
#define kTWAIN_DSM_DLL_NAME "libtwaindsm.so"
#else
#error Sorry, we don't recognize this system...
#endif
/**
* A commonly used conversion function for converting float to TW_FIX32.
* @param[in] floater the float value to change to TW_FIX32
* @return the value as TW_FIX32
*/
TW_FIX32 FloatToFIX32 (float floater);
/**
* A commonly used conversion function for converting TW_FIX32 to float.
* @param[in] _fix32 the TW_FIX32 value to change to float
* @return the value as float
*/
float FIX32ToFloat(const TW_FIX32& _fix32);
/* Set the packing: this occurs before any structures are defined */
#ifdef TWH_CMP_MSC
#pragma pack (push, before_twain)
#pragma pack (2)
#elif defined(TWH_CMP_GNU)
#pragma pack (push, before_twain)
#ifdef __APPLE__
//#pragma pack (4)
#else
#pragma pack (2)
#endif
#elif defined(TWH_CMP_BORLAND)
#pragma option -a2
#endif
// The following structures combinations are implimented and found in the TWAIN specifications
// BOOL INT8 INT16 INT32 UINT8 UINT16 UINT32 STR32 STR64 STR128 STR255 STR1024 UNI512 FIX32 FRAME
// OneValue x x x x x x x x x x
// Array x x x x x x
// Enumeration x x x x x x x x
// Range x x x x x
/**
* TW_ONEVALUE that holds a TW_FIX32 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_FIX32 */
#ifdef __APPLE__
TW_UINT16 Dummy;
#endif
TW_FIX32 Item; /**< TW_FIX32 value being passed */
} TW_ONEVALUE_FIX32, FAR * pTW_ONEVALUE_FIX32; /**< Pointer to TW_ONEVALUE that holds a TW_FIX32 item */
/**
* TW_ONEVALUE that holds a TW_STR32 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_STR32 */
TW_STR32 Item; /**< TW_STR32 value being passed */
} TW_ONEVALUE_STR32, FAR * pTW_ONEVALUE_STR32; /**< Pointer to TW_ONEVALUE that holds a TW_STR32 item */
/**
* TW_ONEVALUE that holds a TW_STR64 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_STR64 */
TW_STR64 Item; /**< TW_STR32 value being passed */
} TW_ONEVALUE_STR64, FAR * pTW_ONEVALUE_STR64; /**< Pointer to TW_ONEVALUE that holds a TW_STR32 item */
/**
* TW_ONEVALUE that holds a TW_STR128 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_STR128 */
TW_STR128 Item; /**< TW_STR128 value being passed */
} TW_ONEVALUE_STR128, FAR * pTW_ONEVALUE_STR128; /**< Pointer to TW_ONEVALUE that holds a TW_STR128 item */
/**
* TW_ONEVALUE that holds a TW_STR255 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_STR255 */
TW_STR255 Item; /**< TW_STR255 value being passed */
} TW_ONEVALUE_STR255, FAR * pTW_ONEVALUE_STR255; /**< Pointer to TW_ONEVALUE that holds a TW_STR255 item */
/**
* TW_ONEVALUE that holds a TW_FRAME item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_FRAME */
#ifdef __APPLE__
TW_UINT16 Dummy;
#endif
TW_FRAME Item; /**< TW_FRAME structure being passed */
} TW_ONEVALUE_FRAME, FAR * pTW_ONEVALUE_FRAME; /**< Pointer to TW_ONEVALUE that holds a TW_FRAME item */
/**
* TW_ARRAY that holds a TW_UINT8 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_UINT8 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT8 ItemList[1]; /**< Array of TW_UINT8 structures starts here */
} TW_ARRAY_UINT8, FAR * pTW_ARRAY_UINT8; /**< Pointer to TW_ARRAY that holds a TW_UINT8 item */
/**
* TW_ARRAY that holds a TW_UINT16 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_UINT16 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT16 ItemList[1]; /**< Array of TW_UINT16 structures starts here */
} TW_ARRAY_UINT16, FAR * pTW_ARRAY_UINT16; /**< Pointer to TW_ARRAY that holds a TW_UINT16 item */
/**
* TW_ARRAY that holds a TW_UINT32 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_UINT32 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 ItemList[1]; /**< Array of TW_UINT32 structures starts here */
} TW_ARRAY_UINT32, FAR * pTW_ARRAY_UINT32; /**< Pointer to TW_ARRAY that holds a TW_UINT32 item */
/**
* TW_ARRAY that holds a TW_STR32 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_STR32 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_STR32 ItemList[1]; /**< Array of TW_STR32 structures starts here */
} TW_ARRAY_STR32, FAR * pTW_ARRAY_STR32; /**< Pointer to TW_ARRAY that holds a TW_STR32 item */
/**
* TW_ARRAY that holds a TW_FIX32 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_FIX32 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_FIX32 ItemList[1]; /**< Array of TW_FIX32 structures starts here */
} TW_ARRAY_FIX32, FAR * pTW_ARRAY_FIX32; /**< Pointer to TW_ARRAY that holds a TW_FIX32 item */
/**
* TW_ARRAY that holds a TW_FRAME item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_FRAME */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_FRAME ItemList[1]; /**< Array of TW_FRAME structures starts here */
} TW_ARRAY_FRAME, FAR * pTW_ARRAY_FRAME; /**< Pointer to TW_ARRAY that holds a TW_FRAME item */
/**
* TW_ENUMERATION that holds a TW_BOOL item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_BOOL */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_BOOL ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_BOOL, FAR * pTW_ENUMERATION_BOOL; /**< Pointer to TW_ENUMERATION that holds an array TW_BOOL items */
/**
* TW_ENUMERATION that holds a TW_INT16 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_INT16 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_INT16 ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_INT16, FAR * pTW_ENUMERATION_INT16;/**< Pointer to TW_ENUMERATION that holds an array TW_INT16 items */
/**
* TW_ENUMERATION that holds a TW_INT32 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_INT32 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_INT32 ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_INT32, FAR * pTW_ENUMERATION_INT32;/**< Pointer to TW_ENUMERATION that holds an array TW_UINT32 items */
/**
* TW_ENUMERATION that holds a TW_UINT16 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_UINT16 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_UINT16 ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_UINT16, FAR * pTW_ENUMERATION_UINT16;/**< Pointer to TW_ENUMERATION that holds an array TW_UINT16 items */
/**
* TW_ENUMERATION that holds a TW_UINT32 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_UINT32 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_UINT32 ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_UINT32, FAR * pTW_ENUMERATION_UINT32;/**< Pointer to TW_ENUMERATION that holds an array TW_UINT32 items */
/**
* TW_ENUMERATION that holds a TW_STR32 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_STR32 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_STR32 ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_STR32, FAR * pTW_ENUMERATION_STR32;/**< Pointer to TW_ENUMERATION that holds an array TW_STR32 items */
/**
* TW_ENUMERATION that holds a TW_STR64 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_STR64 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_STR64 ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_STR64, FAR * pTW_ENUMERATION_STR64;/**< Pointer to TW_ENUMERATION that holds an array TW_STR32 items */
/**
* TW_ENUMERATION that holds a TW_STR128 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_STR128 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_STR128 ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_STR128, FAR * pTW_ENUMERATION_STR128;/**< Pointer to TW_ENUMERATION that holds an array TW_STR32 items */
/**
* TW_ENUMERATION that holds a TW_STR255 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_STR255 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_STR255 ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_STR255, FAR * pTW_ENUMERATION_STR255;/**< Pointer to TW_ENUMERATION that holds an array TW_STR255 items */
/**
* TW_ENUMERATION that holds a TW_FIX32 item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_FIX32 */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_FIX32 ItemList[1]; /**< Array of ItemType values starts here */
} TW_ENUMERATION_FIX32, FAR * pTW_ENUMERATION_FIX32;/**< Pointer to TW_ENUMERATION that holds an array TW_FIX32 items */
/**
* TW_ENUMERATION that holds a TW_FRAME item
*/
typedef struct {
TW_UINT16 ItemType; /**< Assigned TWAIN Type TWTY_FRAME */
TW_UINT32 NumItems; /**< How many items in ItemList */
TW_UINT32 CurrentIndex; /**< Current value is in ItemList[CurrentIndex] */
TW_UINT32 DefaultIndex; /**< Powerup value is in ItemList[DefaultIndex] */
TW_FRAME ItemList[1]; /**< Array of TW_FRAME structures starts here */
} TW_ENUMERATION_FRAME, FAR * pTW_ENUMERATION_FRAME;/**< Pointer to TW_ENUMERATION that holds a TW_FRAME item */
/**
* TW_RANGE that holds a TW_FIX32 item
*/
typedef struct {
TW_UINT16 ItemType;
#ifdef __APPLE__
TW_UINT16 Dummy;
#endif
TW_FIX32 MinValue; /* Starting value in the range. */
TW_FIX32 MaxValue; /* Final value in the range. */
TW_FIX32 StepSize; /* Increment from MinValue to MaxValue. */
TW_FIX32 DefaultValue; /* Power-up value. */
TW_FIX32 CurrentValue; /* The value that is currently in effect. */
} TW_RANGE_FIX32, FAR * pTW_RANGE_FIX32; /**< Pointer to TW_RANGE that holds an array TW_FIX32 items */
/* Restore the previous packing alignment: this occurs after all structures are defined */
#ifdef TWH_CMP_MSC
#pragma pack (pop, before_twain)
#elif defined(TWH_CMP_GNU)
#pragma pack (pop, before_twain)
#elif defined(TWH_CMP_BORLAND)
#pragma option ña.
//#elif defined(TWH_CMP_XCODE)
// #if PRAGMA_STRUCT_ALIGN
// #pragma options align=reset
// #elif PRAGMA_STRUCT_PACKPUSH
// #pragma pack (pop)
// #elif PRAGMA_STRUCT_PACK
// #pragma pack()
// #endif
#endif
#ifdef TWH_CMP_GNU
#pragma pack(1)
/**
* Structure contains information about the type, size, and layout of a file
* that contains a DIB.
*/
typedef struct tagBITMAPFILEHEADER
{
WORD bfType; /**< Specifies the file type, must be BM. */
DWORD bfSize; /**< Specifies the size, in bytes, of the bitmap file. */
WORD bfReserved1; /**< Reserved; must be zero. */
WORD bfReserved2; /**< Reserved; must be zero. */
DWORD bfOffBits; /**< Specifies the offset, in bytes, from the beginning of
the BITMAPFILEHEADER structure to the bitmap bits. */
} BITMAPFILEHEADER;
#pragma pack() // reset
#endif // TWH_CMP_GNU
/**
* Get the current value from a Capability as a TW_UINT32.
* @param[in] pCap a pointer to the capability to retrieve the current value
* @param[out] val the value retrieved from the capability
* @return true if successful
*/
bool getCurrent(TW_CAPABILITY *pCap, TW_UINT32& val);
/**
* Get the current value from a Capability as a string for capabilities of
* types TWTY_STR32, TWTY_STR64, TWTY_STR128, and TWTY_STR256
* @param[in] pCap a pointer to the capability to retrieve the current value
* @param[out] val the value retrieved from the capability
* @return true if successful
*/
bool getCurrent(TW_CAPABILITY *pCap, string& val);
/**
* Get the current value from a Capability as a TW_FIX32.
* @param[in] pCap a pointer to the capability to retrieve the current value
* @param[out] val the value retrieved from the capability
* @return true if successful
*/
bool getCurrent(TW_CAPABILITY *pCap, TW_FIX32& val);
/**
* Get the current value from a Capability as a TW_FRAME.
* @param[in] pCap a pointer to the capability to retrieve the current value
* @param[out] val the value retrieved from the capability
* @return true if successful
*/
bool getCurrent(TW_CAPABILITY *pCap, TW_FRAME& val);
/**
* Get an item value from an array of values from a TW_ENUMERATION or TW_ARRAY
* type Capability as a TW_UINT32.
* @param[in] pCap a pointer to the capability to retrieve the value
* @pCount[in] item the 0 based location in the array to retrieve the item.
* @param[out] val the value retrieved from the capability
* @return true if successful. false if no value returned
*/
bool GetItem(TW_CAPABILITY *pCap, TW_UINT32 item, TW_UINT32& val);
/**
* Get an item value from an array of values from a TW_ENUMERATION or TW_ARRAY
* containing types TWTY_STR32, TWTY_STR64, TWTY_STR128, and TWTY_STR256
* @param[in] pCap a pointer to the capability to retrieve the value
* @pCount[in] item the 0 based location in the array to retrieve the item.
* @param[out] val the value retrieved from the capability
* @return true if successful. false if no value returned
*/
bool GetItem(TW_CAPABILITY *pCap, TW_UINT32 item, string& val);
/**
* Get an item value from an array of values from a TW_ENUMERATION or TW_ARRAY
* containing type TWTY_FIX32
* @param[in] pCap a pointer to the capability to retrieve the value
* @pCount[in] item the 0 based location in the array to retrieve the item.
* @param[out] val the value retrieved from the capability
* @return true if successful. false if no value returned
*/
bool GetItem(TW_CAPABILITY *pCap, TW_UINT32 item, TW_FIX32& val);
/**
* Get an item value from an array of values from a TW_ENUMERATION or TW_ARRAY
* containing type TWTY_FRAME
* @param[in] pCap a pointer to the capability to retrieve the value
* @pCount[in] item the 0 based location in the array to retrieve the item.
* @param[out] val the value retrieved from the capability
* @return true if successful. false if no value returned
*/
bool GetItem(TW_CAPABILITY *pCap, TW_UINT32 item, TW_FRAME& val);
/**
* Get the size of TWAIN type
* @param[in] ItemType the TWAIN type to return the size for
* @return the size of the type returned
*/
int getTWTYsize(TW_UINT16 ItemType);
#endif // __COMMONTWAIN_H__

View File

@ -0,0 +1,297 @@
/***************************************************************************
* Copyright <EFBFBD> 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file DSMInterface.cpp
* Common defines and typedefs used for accessing DSM for Twain Data Sources.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "DSMInterface.h"
#include <iostream>
using namespace std;
/**
* gloabal pointer to the Data Source Manager
*/
HMODULE gpDSM = 0;
/**
* gloabal pointer to the Data Source Manager's Entry point
* - cleared & init'd in @see LoadDSMLib
*/
TW_ENTRYPOINT g_DSM_Entry =
{
0,// TW_UINT32 Size;
0,// DSMENTRYPROC DSM_Entry;
0,// DSM_MEMALLOCATE DSM_MemAllocate;
0,// DSM_MEMFREE DSM_MemFree;
0,// DSM_MEMLOCK DSM_MemLock;
0 // DSM_MEMUNLOCK DSM_MemUnlock;
};
#ifdef TWH_CMP_GNU
#include <dlfcn.h>
#endif
#ifdef TWNDS_OS_APPLE
// #include "CarbonCore/MacMemory.h"
#include <Carbon/Carbon.h>
#endif
/**
* This is the same as the main DS_Entry function. Routes traffic
* to the proper location.
* @param[in] _pOrigin Identifies the source DS for the message.
* @param[in] _pDest Identifies the destination application for the message.
* @param[in] _DG The Data Group.
* @param[in] _DAT The Data Attribute Type.
* @param[in] _MSG The message with respect to the Data Group and the Data Attribute Type.
* @param[in,out] _pData A pointer to the data structure or variable identified
* by the Data Attribute Type.
* @return a valid TWRC_xxxx return code.
*/
TW_UINT16 _DSM_Entry( pTW_IDENTITY _pOrigin,
pTW_IDENTITY _pDest,
TW_UINT32 _DG,
TW_UINT16 _DAT,
TW_UINT16 _MSG,
TW_MEMREF _pData)
{
TW_UINT16 ret = TWRC_FAILURE;
// With DSM2 we do not need to load the DSM. We should have recieved
// Message with the entry points that we use.
// On windows with DSM1(twain_32.dll) we will need to first laod the dll
// then find the entry point First check to see if you have an entry point.
// On Mac we will use the dynamicaly linked at build time dll.
if(0 == g_DSM_Entry.DSM_Entry)
{
// We do not already have the entry point for regisry callback
#ifdef TWNDS_OS_APPLE
// This should only happen if not being called by the DSM2
// Other words only on Mac with an older DSM
// So we use the old dll
g_DSM_Entry.DSM_Entry = DSM_Entry;
// ret = DSM_Entry(_pOrigin, _pDest, _DG, _DAT, _MSG, _pData);
#elif defined (TWH_CMP_MSC)
// This should only happen if not being called by the DSM2
// Other words only on Windows with an older DSM
// So we load the old dll
char DSMName[MAX_PATH];
memset(DSMName, 0, MAX_PATH*sizeof(char));
if(GetWindowsDirectory (DSMName, MAX_PATH)==0)
{
DSMName[0]=0;
}
#if (TWNDS_CMP_VERSION >= 1400)
if (DSMName[strlen(DSMName)-1] != '\\')
{
strcat_s(DSMName,MAX_PATH, "\\");
}
strcat_s (DSMName,MAX_PATH, "TWAIN_32.dll");
#else
if (DSMName[strlen(DSMName)-1] != '\\')
{
strcat(DSMName, "\\");
}
strcat(DSMName, "TWAIN_32.dll");
#endif
if((0 == gpDSM) && !LoadDSMLib(DSMName))
{
cerr << "Could not load the DSM" << endl;
return TWRC_FAILURE;
}
#endif // TWNDS_OS_APPLE & TWH_CMP_MSC
}
if(0 == g_DSM_Entry.DSM_Entry)
{
cerr << "No Entry Point for DSM_Entry" << endl;
return TWRC_FAILURE;
}
// If we did not have an enty point before we do now.
ret = g_DSM_Entry.DSM_Entry(_pOrigin, _pDest, _DG, _DAT, _MSG, _pData);
return ret;
}
/////////////////////////////////////////////////////////////////////////////
bool LoadDSMLib(char* _pszLibName)
{
// check if already opened
if(0 != gpDSM)
{
return true;
}
memset(&g_DSM_Entry, 0, sizeof(TW_ENTRYPOINT));
#ifdef TWH_CMP_GNU
char *error;
#endif //TWH_CMP_GNU
if((gpDSM=LOADLIBRARY(_pszLibName)) != 0)
{
if((g_DSM_Entry.DSM_Entry=(DSMENTRYPROC)LOADFUNCTION(gpDSM, "DSM_Entry")) == 0)
{
#ifdef TWH_CMP_MSC // dlsym returning NULL is not an error on Unix
cerr << "Error - Could not find DSM_Entry function in DSM: " << _pszLibName << endl;
return false;
#endif //TWH_CMP_MSC
}
#ifdef TWH_CMP_GNU
if ((error = dlerror()) != 0)
{
cerr << "App - dlsym: " << error << endl;
return false;
}
#endif //TWH_CMP_GNU
}
else
{
cerr << "Error - Could not load DSM: " << _pszLibName << endl;
#ifdef TWH_CMP_GNU
cerr << "App - dlopen: " << dlerror() << endl;
#endif //TWH_CMP_GNU
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
void unLoadDSMLib()
{
if(gpDSM)
{
memset(&g_DSM_Entry, 0, sizeof(TW_ENTRYPOINT));
UNLOADLIBRARY(gpDSM);
gpDSM = 0;
}
}
/////////////////////////////////////////////////////////////////////////////
void setEntryPoints(pTW_ENTRYPOINT _pEntryPoints)
{
if(_pEntryPoints)
{
g_DSM_Entry = *_pEntryPoints;
}
else
{
memset(&g_DSM_Entry, 0, sizeof(TW_ENTRYPOINT));
}
}
//////////////////////////////////////////////////////////////////////////////
// The following functions are defined in the DSM2,
// For backwards compatibiltiy on windows call the default function
TW_HANDLE _DSM_Alloc(TW_UINT32 _size)
{
if(g_DSM_Entry.DSM_MemAllocate)
{
return g_DSM_Entry.DSM_MemAllocate(_size);
}
#ifdef TWH_CMP_MSC
return ::GlobalAlloc(GPTR, _size);
#elif defined (TWNDS_OS_APPLE)
return NewHandle(_size);
#endif
return 0;
}
//////////////////////////////////////////////////////////////////////////////
void _DSM_Free(TW_HANDLE _hMemory)
{
if(g_DSM_Entry.DSM_MemFree)
{
return g_DSM_Entry.DSM_MemFree(_hMemory);
}
#ifdef TWH_CMP_MSC
::GlobalFree(_hMemory);
#elif defined (TWNDS_OS_APPLE)
DisposeHandle(_hMemory);
#endif
return;
}
//////////////////////////////////////////////////////////////////////////////
TW_MEMREF _DSM_LockMemory(TW_HANDLE _hMemory)
{
if(g_DSM_Entry.DSM_MemLock)
{
return g_DSM_Entry.DSM_MemLock(_hMemory);
}
#ifdef TWH_CMP_MSC
return (TW_MEMREF)::GlobalLock(_hMemory);
#elif defined (TWNDS_OS_APPLE)
return (TW_MEMREF)(*_hMemory);
#endif
return 0;
}
//////////////////////////////////////////////////////////////////////////////
void _DSM_UnlockMemory(TW_HANDLE _hMemory)
{
if(g_DSM_Entry.DSM_MemUnlock)
{
return g_DSM_Entry.DSM_MemUnlock(_hMemory);
}
#ifdef TWH_CMP_MSC
::GlobalUnlock(_hMemory);
#elif defined (TWNDS_OS_APPLE)
// do nothing
#endif
return;
}
//////////////////////////////////////////////////////////////////////////////

125
hugaotwainds/DSMInterface.h Normal file
View File

@ -0,0 +1,125 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file DSMInterface.h
* Common defines and typedefs used for accessing DSM for TWAIN Data Sources.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __DSMINTERFACE_H__
#define __DSMINTERFACE_H__
#include "CommonDS.h"
/**
* Load the DSM library.
* @param[in] the name of the DSM library to open
* @return true if success.
*/
bool LoadDSMLib(char* _pszLibName);
/**
* Unload the DSM library.
*/
void unLoadDSMLib();
/**
* Initialize and register the entry point into the DSM.
* @param[in] _pOrigin Identifies the source module of the message. This could
* identify an Application, a Source, or the Source Manager.
*
* @param[in] _pDest Identifies the destination module for the message.
* This could identify an application or a data source.
* If this is NULL, the message goes to the Source Manager.
*
* @param[in] _DG The Data Group.
* Example: DG_IMAGE.
*
* @param[in] _DAT The Data Attribute Type.
* Example: DAT_IMAGEMEMXFER.
*
* @param[in] _MSG The message. Messages are interpreted by the destination module
* with respect to the Data Group and the Data Attribute Type.
* Example: MSG_GET.
*
* @param[in,out] _pData A pointer to the data structure or variable identified
* by the Data Attribute Type.
* Example: (TW_MEMREF)&ImageMemXfer
* where ImageMemXfer is a TW_IMAGEMEMXFER structure.
*
* @return a valid TWRC_xxxx return code.
* Example: TWRC_SUCCESS.
*/
TW_UINT16 _DSM_Entry( pTW_IDENTITY _pOrigin,
pTW_IDENTITY _pDest,
TW_UINT32 _DG,
TW_UINT16 _DAT,
TW_UINT16 _MSG,
TW_MEMREF _pData);
/**
* Set up the EntryPoints for memory and callback
* @param[in] _pEntryPoints the structure for the entrypoints.
*/
void setEntryPoints(pTW_ENTRYPOINT _pEntryPoints);
/**
* Allocate global memory
* @param[in] _size of memory to allocate.
* @return TW_HANDLE to the memory allocated.
*/
TW_HANDLE _DSM_Alloc(TW_UINT32 _size);
/**
* Free previously allocated global memory
* @param[in] _hMemory TW_HANDLE to the memory needing free.
*/
void _DSM_Free(TW_HANDLE _hMemory);
/**
* Lock global memory from being updated by others. return a pointer to the
* memory so we can update it.
* @param[in] _hMemory TW_HANDLE to the memory to update.
* @return TW_MEMREF pointer to the memory.
*/
TW_MEMREF _DSM_LockMemory(TW_HANDLE _hMemory);
/**
* Unlock global memory after locking. to allow updating by others.
* @param[in] _hMemory TW_HANDLE to memory returned by _DSM_Alloc
*/
void _DSM_UnlockMemory(TW_HANDLE _hMemory);
#endif // __DSMINTERFACE_H__

Binary file not shown.

BIN
hugaotwainds/FeederPaper.h Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

View File

@ -0,0 +1,186 @@
#include "StdAfx.h"
#include "ImageAdjustColors.h"
CImageAdjustColors::CImageAdjustColors(void)
{
lut.create(1, 256, CV_8UC1);
setAdjustColors(0, 0, 1.0);
}
CImageAdjustColors::CImageAdjustColors(float fBrightness, float fContrast, float fGamma)
{
lut.create(1, 256, CV_8UC1);
setAdjustColors(fBrightness, fContrast, fGamma);
}
CImageAdjustColors::~CImageAdjustColors(void)
{
}
void CImageAdjustColors::apply(cv::Mat& pDib,int side)
{
if (m_fBrightness != 0|| m_fContrast != 0|| m_fGamma != 1.0)
{
//MessageBox(NULL,"Inter","Error",MB_OK);
cv::LUT(pDib, lut, pDib);
}
}
void CImageAdjustColors::setAdjustColors(float fBrightness, float fContrast, float fGamma)
{
m_fBrightness = fBrightness;
m_fContrast = getRealContrast(fContrast);
m_fGamma = fGamma;
updata();
}
void CImageAdjustColors::MapToMap(byte* mapsIn, byte* mapsOut)
{
for (int i = 0; i < 256; i++)
{
mapsOut[i] = mapsIn[mapsOut[i]];
}
}
float CImageAdjustColors::getRealContrast(float twContrast)
{
float ret=0.0;
if (twContrast<=-1000.0)
{
ret=-36.0;
}
else if(twContrast>-1000.0&&twContrast<=-666.0)
{
ret=-24.0;
}
else if(twContrast>-666.0&&twContrast<=-333.0)
{
ret=-12.0;
}
else if (twContrast>= 333 && twContrast < 666)
{
ret=12.0;
}
else if (twContrast >= 666 && twContrast < 1000)
{
ret=24.0;
}
else if (twContrast >= 1000)
{
ret=36.0;
}
return ret;
}
void CImageAdjustColors::CalculateMap(Range in, Range out, unsigned char* map)
{
double k = 0, b = 0;
if (in.getMax() != in.getMin())
{
k = (double)(out.getMax() - out.getMin()) / (double)(in.getMax() - in.getMin());
b = (double)(out.getMin()) - k * in.getMin();
}
for (int i = 0; i < 256; i++)
{
byte v = (byte)i;
if (v >= in.getMax())
v = (byte)out.getMax();
else if (v <= in.getMin())
v = (byte)out.getMin();
else
v = (byte)(k * v + b);
map[i] = v;
}
}
void CImageAdjustColors::updata()
{
Range inIR;
Range OutIR;
byte maps[256];
byte _maps[256];
for (int i = 0; i < 256; i++)
{
_maps[i] = maps[i] = (byte)i;
}
//if (m_fBrightness > 0)
//{
// inIR = Range(0, (int)(255 - m_fBrightness));
// OutIR = Range((int)m_fBrightness, 255);
//}
//else
//{
// inIR = Range((int)-m_fBrightness, 255);
// OutIR = Range(0, (int)(255 + m_fBrightness));
//}
//CalculateMap(inIR, OutIR, maps);
//MapToMap(maps, _maps);
//if (m_fContrast > 0)
//{
// inIR = Range(0, (int)(255 - m_fContrast));
// OutIR = Range((int)m_fContrast, 255);
//}
//else
//{
// inIR = Range((int)-m_fContrast, 255);
// OutIR = Range(0, (int)(255 + m_fContrast));
//}
//CalculateMap(inIR, OutIR, maps);
//MapToMap(maps, _maps);
double g = 1 / m_fGamma;
if (g != 1.0)
{
for (int i = 0; i < 256; i++)
{
maps[i] = (byte)MIN(255, (int)(pow(i / 255.0, g) * 255 + 0.5));
}
}
else
{
for (int i = 0; i < 128; i++)
{
int color = GetRangeValue(0, 127, i - (int)m_fContrast);
color = GetRangeValue(0, 255, color + (int)m_fBrightness);
maps[i] = (byte)color;
}
for (int i = 128; i < 256; i++)
{
int color = GetRangeValue(128, 255, i + (int)m_fContrast);
color = GetRangeValue(0, 255, color + (int)m_fBrightness);
maps[i] = (byte)color;
}
}
MapToMap(maps, _maps);
memcpy(lut.data, _maps, sizeof(_maps));
}
int CImageAdjustColors::GetRangeValue(int low, int up, int value)
{
if (low > up)
{
return value;
}
if (value<low)
{
return low;
}
if (value>up)
{
return up;
}
return value;
}

View File

@ -0,0 +1,52 @@
#pragma once
#include "ImageApply.h"
class CImageAdjustColors : public CImageApply
{
public:
CImageAdjustColors(void);
CImageAdjustColors(float fBrightness, float fContrast, float fGamma);
virtual ~CImageAdjustColors(void);
virtual void apply(cv::Mat& pDib,int side);
void setAdjustColors(float fBrightness, float fContrast, float fGamma);
private:
class Range
{
public:
Range()
{
}
Range(int nMin, int nMax)
{
m_min = MIN(nMin, nMax);
m_max = MAX(nMin, nMax);
}
int getMin()
{
return m_min;
}
int getMax()
{
return m_max;
}
private:
int m_min;
int m_max;
};
void updata();
int GetRangeValue(int low, int up, int value);
void CalculateMap(Range in, Range out, unsigned char* map);
void MapToMap(byte* mapsIn, byte* mapsOut);
float m_fBrightness;
float m_fContrast;
float m_fGamma;
float getRealContrast(float twContrast);
cv::Mat lut;
};

View File

@ -0,0 +1,12 @@
#include "StdAfx.h"
#include "ImageApply.h"
CImageApply::CImageApply(void)
{
}
CImageApply::~CImageApply(void)
{
}

20
hugaotwainds/ImageApply.h Normal file
View File

@ -0,0 +1,20 @@
#pragma once
#include <vector>
#include <memory>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
//class twainImage;
class CImageApply
{
public:
CImageApply(void);
virtual ~CImageApply(void);
virtual void apply(cv::Mat& pDib,int side) = 0;
//virtual void apply(twainImage& pDib) = 0;
};
typedef std::shared_ptr<CImageApply> ImageApplyPtr;

View File

@ -0,0 +1,32 @@
#include "StdAfx.h"
#include "ImageApplyCrop.h"
CImageApplyCrop::CImageApplyCrop(void)
{
}
CImageApplyCrop::~CImageApplyCrop(void)
{
}
void CImageApplyCrop::apply(cv::Mat& pDib,int side)
{
pDib = pDib(cv::Rect(m_org, m_size));
}
cv::Size CImageApplyCrop::getSize()
{
return m_size;
}
void CImageApplyCrop::setSize(cv::Size size)
{
m_size=size;
}
void CImageApplyCrop::setOrg(cv::Point point)
{
m_org=point;
}

View File

@ -0,0 +1,20 @@
#pragma once
#include "imageapply.h"
class CImageApplyCrop :
public CImageApply
{
public:
CImageApplyCrop(void);
virtual ~CImageApplyCrop(void);
void apply(cv::Mat& pDib,int side);
cv::Size getSize();
cv::Point getOrg();
void setSize(cv::Size size);
void setOrg(cv::Point point);
private:
cv::Size m_size;
cv::Point m_org;
};

View File

@ -0,0 +1,51 @@
#include "StdAfx.h"
#include "ImageApplyResize.h"
#include "PublicFunc.h"
CImageApplyResize::CImageApplyResize(float orgResulution,float setResulution,bool autocut,SIZE dstsize)
:m_orgDpi(orgResulution),m_dpi(setResulution),autoCut(autocut),dstSize(dstsize)
{
}
CImageApplyResize::~CImageApplyResize(void)
{
}
void CImageApplyResize::apply(cv::Mat& pDib,int side)
{
if(autoCut)
{
if (m_dpi != m_orgDpi)
{
float ratio = m_dpi / m_orgDpi;
cv::resize(pDib, pDib, cv::Size(0, 0), ratio, ratio);
XdPrint("1");
}
}
else
{
cv::Size dst(dstSize.cx,dstSize.cy);
cv::resize(pDib,pDib,dst,0,0);
}
}
float CImageApplyResize::getDpi()
{
return m_dpi;
}
void CImageApplyResize::setDpi(float dpi)
{
m_dpi = dpi;
}
float CImageApplyResize::getOrgDpi()
{
return m_orgDpi;
}
void CImageApplyResize::setOrgDpi(float dpi)
{
m_orgDpi = dpi;
}

View File

@ -0,0 +1,24 @@
#pragma once
#include "imageapply.h"
class CImageApplyResize :
public CImageApply
{
public:
CImageApplyResize(float orgResulution=0.0,float setResulution=0.0,bool autocut=false,SIZE dstsize=CSize(0,0));
virtual ~CImageApplyResize(void);
virtual void apply(cv::Mat& pDib,int side);
float getDpi();
void setDpi(float dpi);
float getOrgDpi();
void setOrgDpi(float dpi);
private:
float m_dpi;
float m_orgDpi;
SIZE dstSize;
bool autoCut;
};

View File

@ -0,0 +1,48 @@
#include "StdAfx.h"
#include "ImageBWBinaray.h"
CImageBWBinaray::CImageBWBinaray(bool needtoBW):needToBW(needtoBW)
{
}
CImageBWBinaray::~CImageBWBinaray(void)
{
}
void CImageBWBinaray::apply(cv::Mat& dib,int side)
{
if (needToBW)
{
if (dib.channels()!=1)
{
return;
}
threshold(dib,dib,128.0,255.0,CV_THRESH_BINARY);
}
}
void CImageBWBinaray::gray2binary(cv::Mat gray, unsigned char* binary){
if(gray.channels() != 1)
return;
int width = gray.cols;
int height = gray.rows;
int n_lineByte = (width + 7)/8;
int lineByte = (n_lineByte * 8 + 31)/32*4;
unsigned char * imageData = gray.data;
unsigned char temp;
for(int row = height -1 ; row >= 0 ; row--){
for(int col =0; col < width; col++ ){
int pos = col % 8;
int pix = *(imageData+ row * width + col);
temp = 1 << (7 - pos );
if( pix == 255 ){
*(binary + col /8) |= temp;
}else{
*(binary + col / 8 ) &= (~temp);
}
}
binary = binary + lineByte;
}
}

View File

@ -0,0 +1,15 @@
#pragma once
#include "ImageApply.h"
class CImageBWBinaray:public CImageApply
{
public:
CImageBWBinaray(bool needtoBW=false);
~CImageBWBinaray(void);
void apply(cv::Mat& dib,int side);
private:
void gray2binary(cv::Mat gray, unsigned char* binary);
bool needToBW;
};

View File

@ -0,0 +1,185 @@
#include "StdAfx.h"
#include "ImageChannel.h"
using namespace cv;
CImageChannel::CImageChannel(int index)
: m_cmIndex(index)
{
colorTable=NULL;
if (index>3)
{
short channal=m_cmIndex==4?2:(m_cmIndex==5?1:0);
InitColorTable(channal);
}
}
CImageChannel::~CImageChannel(void)
{
if (colorTable!=NULL)
{
free(colorTable);
}
}
void CImageChannel::apply(cv::Mat& pDib,int side)
{
if (m_cmIndex>0&&m_cmIndex<4)
{
if (m_cmIndex <= pDib.channels())
{
//0通道为B分量1通道为G分量2通道为R分量
//m_cmIndex 1 除红 2 除绿 3 除蓝
//2除红1除绿0除蓝
//std::vector<cv::Mat> mats;
//cv::split(pDib, mats);
//int rmIndex=m_cmIndex==1?2:(m_cmIndex==2?1:0);
//pDib = mats[rmIndex];
pDib=FilterColor(pDib,m_cmIndex==1?2:(m_cmIndex==2?1:0));
}
}
else if(m_cmIndex>=4&&m_cmIndex<=6)
{
short channal=m_cmIndex==4?2:(m_cmIndex==5?1:0);
pDib=colorEnhancement(pDib,channal);
}
}
void CImageChannel::setCH(int channel)
{
m_cmIndex = channel;
}
int CImageChannel::getCH()
{
return m_cmIndex;
}
void CImageChannel::RGBtoHSV(double r, double g, double b, double &h, double &s, double &v)
{
double min, max, delta;
min = ( (r<g ? r:g) < b ) ?(r<g ? r:g):b;
max = ( (r>g ? r:g) > b ) ? (r>g ? r:g): b ;
v = max; // v
delta = max - min;
if (max != 0)
{
s = delta / max; // s
}
else
{
// r = g = b = 0
// s = 0, v is undefined
s = 0;
h = -1;
return;
}
if (r == max)
{
h = (g - b) / delta; // between yellow & magenta
}
else if (g == max)
{
h = 2 + (b - r) / delta; // between cyan & yellow
}
else
{
h = 4 + (r - g) / delta; // between magenta & cyan
}
h *= 60; // degrees
if (h < 0)
{
h += 360;
}
}
void CImageChannel::InitColorTable(short channel)
{
//colorTable=new unsigned char();
colorTable=(unsigned char *)malloc(sizeof(unsigned char)*256*256*256);
for (int i = 0; i < 256; i++)
{
for (int j = 0; j < 256; j++)
{
for (int k = 0; k < 256; k++)
{
if (channel == 2) //红色增强
{
*(colorTable + i * 256 * 256 + j * 256 + k )= (unsigned char)(0 + 0.833 * j + 0.167 * k);
}
else if (channel == 1) //绿色增强
{
*(colorTable + i * 256 * 256 + j * 256 + k ) = (unsigned char)(0.731 * i + 0 + 0.268 * k);
}
else if (channel == 0) //蓝色增强
{
*(colorTable + i * 256 * 256 + j * 256 + k ) = (unsigned char)(0.337 * i + 0.663 * j + 0);
}
}
}
}
}
cv::Mat CImageChannel::colorEnhancement(cv::Mat image,short channel)
{
Mat grayImage(image.rows,image.cols,CV_8UC1);
if (channel>3)
{
return grayImage;
}
unsigned char * dstData = grayImage.data;
unsigned char * srcData = image.data;
for(int r = 0; r < image.rows; r++)
{
for (int c = 0; c < image.cols; c++)
{
*(dstData + r * grayImage.step + c ) = colorTable[*(srcData + r * image.step + c * 3 + 2 ) * 256 * 256 + *(srcData + r * image.step + c * 3 + 1 ) * 256+ *(srcData + r * image.step + c * 3 )];
}
}
return grayImage;
}
cv::Mat CImageChannel::FilterColor(cv::Mat image,short channel)
{
Mat dstImage(image.rows,image.cols,CV_8UC1);
//int pixelSize = image.depth();
int channels = image.channels();
if(channel > channels -1){
return dstImage;
}
if ( ( channel == 3 ) && ( channels != 4 ) && ( channels != 8 ))
{
return dstImage;
}
if ( channels <= 4 )
{
int srcOffset = image.step - image.cols* channels ;
int dstOffset = dstImage.step - dstImage.cols;
unsigned char* src = image.data;
unsigned char* dst = dstImage.data;
src += channel;
for ( int y = 0; y < image.rows; y++ )
{
for ( int x = 0; x < image.cols; x++, src += channels , dst++ )
{
unsigned short pix = *src;
if(pix >=100){
pix = 255;
}
*dst = pix;
}
src += srcOffset;
dst += dstOffset;
}
}
return dstImage;
}

View File

@ -0,0 +1,22 @@
#pragma once
#include "imageapply.h"
class CImageChannel :
public CImageApply
{
public:
CImageChannel(int index);
virtual ~CImageChannel(void);
virtual void apply(cv::Mat& pDib,int side);
void setCH(int channel);
int getCH();
private:
void RGBtoHSV(double r, double g, double b, double &h, double &s, double &v);
void InitColorTable(short channel);
cv::Mat colorEnhancement(cv::Mat image,short channel);
cv::Mat FilterColor(cv::Mat image,short channel);
int m_cmIndex;
unsigned char * colorTable;
};

View File

@ -0,0 +1,108 @@
#include "StdAfx.h"
#include "ImageMatQueue.h"
#include "PublicFunc.h"
ImageMatQueue::ImageMatQueue(void)
{
pixType=-1;
/*if(!bRun)
{
m_threadProc = boost::thread(&ImageMatQueue::proc, this);
bRun = true;
}*/
}
void ImageMatQueue::run()
{
if(!bRun)
{
m_threadProc = boost::thread(&ImageMatQueue::proc, this);
bRun = true;
}
}
ImageMatQueue::~ImageMatQueue(void)
{
bRun = false;
Sleep(100);
}
void ImageMatQueue::pushMat(JpegBuffer& data)
{
boost::lock_guard<boost::mutex> lck(m_mtxJB);
m_pImages.push(data);
}
cv::Mat ImageMatQueue::popMat()
{
boost::lock_guard<boost::mutex> lck(m_Locker);
return _popMat();
}
bool ImageMatQueue::valid()
{
boost::lock_guard<boost::mutex> lck(m_mtxJB);
return !m_images.empty();
}
void ImageMatQueue::clear()
{
boost::lock_guard<boost::mutex> lck(m_mtxJB);
//for (int i=0;i<m_images.size();i++)
// m_images.pop();
//for (int i=0;i<m_images.size();i++)
// m_pImages.pop();
m_images = std::queue<cv::Mat>();
m_pImages = std::queue<JpegBuffer>();
}
void ImageMatQueue::setlist(std::vector<std::shared_ptr<CImageApply>> list)
{
//m_iaList.clear();
m_iaList=list;
}
cv::Mat ImageMatQueue::_popMat()
{
cv::Mat image = m_images.front();
m_images.pop();
return image;
}
bool ImageMatQueue::empty()
{
boost::lock_guard<boost::mutex> lck(m_mtxJB);
return m_images.empty() && m_pImages.empty();
}
void ImageMatQueue::proc()
{
while(bRun)
{
Sleep(5);
{
boost::lock_guard<boost::mutex> lck(m_mtxJB);
if(m_images.empty() && !m_pImages.empty())
{
if (pixType!=-1)
{
cv::Mat image = m_pImages.front().getMat(pixType);
int side=m_pImages.front().getSide();
for (int i=0;i<m_iaList.size();i++)
{
if (image.empty())
break;
m_iaList[i]->apply(image,side);
}
m_pImages.pop();
if (!image.empty())
{
m_images.push(image);
}
}
}
}
}
}

View File

@ -0,0 +1,38 @@
#pragma once
#include <boost\thread\win32\mfc_thread_init.hpp>
#include <boost\thread\thread.hpp>
#include <boost\thread\mutex.hpp>
#include <opencv2\opencv.hpp>
#include "JpegBuffer.h"
#include <queue>
#include "ImageApply.h"
class ImageMatQueue
{
public:
ImageMatQueue(void);
virtual ~ImageMatQueue(void);
void pushMat(JpegBuffer& data);
cv::Mat popMat();
bool empty();
bool valid();
void clear();
void setlist(std::vector<std::shared_ptr<CImageApply>> list);
void run();
public:
int pixType;
private:
void proc();
cv::Mat _popMat();
std::queue<cv::Mat> m_images; //!< ÒÑ´¦ÀíͼÏñ¶ÓÁÐ
std::queue<JpegBuffer> m_pImages;
boost::mutex m_Locker;
boost::mutex m_mtxJB;
boost::thread m_threadProc;
volatile bool bRun;
std::vector<std::shared_ptr<CImageApply>> m_iaList;
};

View File

@ -0,0 +1,169 @@
#include "StdAfx.h"
#include "ImageProcDiscardBlank.h"
using namespace cv;
static int ProcessRectR(Mat & image, RotatedRect & rotatedRect, vector<Point>& maxContour, double scale, double thresh, int blobAreaSize)
{
Mat gray;
int blockCount = 0;
if (image.channels() == 3)
{
if (scale != 1.0f)
{
Size ResImgSiz = Size(image.cols*scale, image.rows*scale);
resize(image, gray, cv::Size(), scale, scale, 0);
cvtColor(gray, gray, CV_BGR2GRAY);
}
else
{
cvtColor(image, gray, CV_BGR2GRAY);
}
}
else
{
if (scale != 1.0f)
{
resize(image, gray, cv::Size(), scale, scale, 0);
}
else
{
gray = image;
}
}
Mat threshold_img;
threshold(gray, threshold_img, thresh, 255.0, CV_THRESH_BINARY);
vector<vector<Point>> contours;
findContours(threshold_img, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
threshold_img.release();
if (contours.size() == 0)
{
return blockCount;
}
vector<Point2f> list_com;
for (int i = 0; i < contours.size(); i++)
{
double area = contourArea(contours[i]);
if (area > blobAreaSize)
{
blockCount++;
for (int j = 0; j < contours[i].size(); j++)
{
list_com.push_back(contours[i][j]);
}
}
}
if (list_com.size() == 0)
{
return blockCount;
}
rotatedRect = minAreaRect(list_com);
rotatedRect.center.x /= (float)scale;
rotatedRect.center.y /= (float)scale;
rotatedRect.size.width /= (float)scale;
rotatedRect.size.height /= (float)scale;
if (rotatedRect.angle < -45.0f)
{
rotatedRect.angle += 90.0f;
float l_temp = rotatedRect.size.width;
rotatedRect.size.width = rotatedRect.size.height;
rotatedRect.size.height = l_temp;
}
vector<int> hull;
convexHull(list_com, hull);
for (int i = 0; i < hull.size(); i++)
{
Point temp = list_com[hull[i]];
int x = (int)(temp.x / scale);
int y = (int)(temp.y / scale);
maxContour.push_back(Point(x, y));
}
return blockCount;
}
static bool Scalar_LE(cv::Scalar& val1, cv::Scalar& val2)
{
for(int i = 0; i < 3; i++)
{
if(val1[i] > val2[i])
return false;
}
return true;
}
CImageProcDiscardBlank::CImageProcDiscardBlank(bool isnormal)
: devTh (10, 10, 10, 10), dSize(200),isNormalDiscard(isnormal)
{
}
CImageProcDiscardBlank::~CImageProcDiscardBlank(void)
{
}
void CImageProcDiscardBlank::setIntensity(int val)
{
val = max(min(20, val), 2);
devTh = cv::Scalar(val, val, val, val);
}
void CImageProcDiscardBlank::setMinArea(int val)
{
dSize = max(min(500, val), 100);
}
cv::Mat CImageProcDiscardBlank::getRoiMat(cv::Mat& image)
{
int gap = 100;
RotatedRect rect;
vector<Point> contour;
double scale = 0.25;
double thresh = 50;
int blobSize = 200;
int edgeWidth = 10;
ProcessRectR(image, rect, contour, scale, thresh, blobSize);
cv::Rect rect2 = rect.boundingRect();
cv::Rect inRect = rect2 & Rect(0, 0, image.cols, image.rows);
gap = max(inRect.width - rect.size.width, inRect.height -rect.size.height)+100;
inRect = cv::Rect(inRect.x+ gap, inRect.y + gap, inRect.width -gap*2, inRect.height-gap*2);
return image(inRect);
}
void CImageProcDiscardBlank::apply(cv::Mat& pDib,int side)
{
setIntensity(isNormalDiscard?8:20);
setMinArea(isNormalDiscard?200:300);
cv::Scalar mean;
cv::Scalar dev;
cv::Mat image = getRoiMat(pDib);
cv::Rect rect;
cv::Rect imRect(0, 0, image.cols, image.rows);
for(int i = 0; i < image.cols; i+= dSize)
{
for(int j = 0; j < image.rows; j+= dSize)
{
rect = cv::Rect(i, j,dSize, dSize) & imRect;
if(rect != cv::Rect())
{
cv::meanStdDev (image(rect) , mean, dev);
if(!Scalar_LE(dev, devTh))
{
m_res = false;
return;
}
}
}
}
m_res = true;
if (m_res)
pDib.release();
}

View File

@ -0,0 +1,27 @@
#pragma once
#include "ImageApply.h"
#include <math.h>
class CImageProcDiscardBlank :
public CImageApply
{
public:
CImageProcDiscardBlank(bool isnormal=true);
virtual ~CImageProcDiscardBlank(void);
virtual void apply(cv::Mat& pDib,int side);
private:
void setIntensity(int val);
void setMinArea(int val);
private:
int dSize;
bool m_res;
cv::Scalar devTh;
bool isNormalDiscard;
cv::Mat getRoiMat(cv::Mat& pDib);
};

Binary file not shown.

BIN
hugaotwainds/ImageProcess.h Normal file

Binary file not shown.

View File

@ -0,0 +1,49 @@
#include "StdAfx.h"
#include "ImageRotation.h"
using namespace cv;
using namespace std;
CImageRotation::CImageRotation(int index_of_orentation,bool m_bBackRotate):m_nRotation(index_of_orentation),m_BackRotate(m_bBackRotate)
{
}
CImageRotation::~CImageRotation()
{
}
void CImageRotation::apply(cv::Mat & pDib,int side)
{
if (m_nRotation==4)//自动文本方向识别
{
}
else if (m_BackRotate&&side==1)//背面旋转180
{
if (m_nRotation!=2)//旋转180度
{
if (m_nRotation==1||m_nRotation==3)//90° -90°
{
transpose(pDib,pDib);
flip(pDib,pDib,m_nRotation==1?0:1);
}
else
{
flip(pDib,pDib,0);
flip(pDib,pDib,1);
}
}
}
else //zh
{
if (m_nRotation==1||m_nRotation==3)//90° -90°
{
transpose(pDib,pDib);
flip(pDib,pDib,m_nRotation==1?1:0);
}
else if(m_nRotation==2)
{
flip(pDib,pDib,0);
flip(pDib,pDib,1);
}
}
}

View File

@ -0,0 +1,19 @@
#pragma once
#include "ImageApply.h"
class CImageRotation :
public CImageApply
{
public:
CImageRotation(int index_of_orentation,bool m_bBackRotate=false);
virtual ~CImageRotation();
// 通过 CImageApply 继承
virtual void apply(cv::Mat & pDib,int side) override;
private:
int m_nRotation;
bool m_BackRotate;
int side;
};

Binary file not shown.

BIN
hugaotwainds/IndicatorDlg.h Normal file

Binary file not shown.

View File

@ -0,0 +1,73 @@
#include "StdAfx.h"
#include "JpegBuffer.h"
#include "jpeglib.h"
#include "twain.h"
//#include "filetools.h"
using namespace std;
JpegBuffer::JpegBuffer(cv::Mat buffer, int color_type,int side,int mFilter)
{
this->m_buffer = buffer;
this->m_color_type=color_type;
this->m_side=side;
this->m_mFilter=mFilter;
}
JpegBuffer::~JpegBuffer(void)
{
}
unsigned char* JpegBuffer::getBuffer()
{
return m_buffer.data;
}
cv::Mat JpegBuffer::buffer()
{
return m_buffer;
}
int JpegBuffer::getSize()
{
return m_buffer.cols;
}
cv::Mat JpegBuffer::getMat( int pixType)
{
JpegLib jl;
cv::Mat image = jl.decode(m_buffer, pixType);
//FileTools::write_log("D:/1.txt",)
//StopWatch sw;
//sw.start();
//cv::InputArray arr(m_buffer);
//
//cv::Mat image=imdecode(arr,m_color_type==TWPT_RGB?CV_LOAD_IMAGE_COLOR:CV_LOAD_IMAGE_GRAYSCALE);
//cv::imwrite("0.bmp",image);
//sw.stop();
//sw.time_run();
//char str[256];
//sprintf(str, "%lf", sw.time_run());
//string res=str;
//FileTools::write_log("D:/1.txt",res);
//0 ÕýÃæ 1·´Ãæ
//if (!backRotate&&(m_side==0||m_side==1))
//{
// cv::Rect rect(0, m_side == 0 ? 0 : gap, image.cols,(image.rows-gap));
// image = image(rect);
//}
return image.clone();
}
int JpegBuffer::getMFilter()
{
return m_mFilter;
}
int JpegBuffer::getSide()
{
return m_side;
}

22
hugaotwainds/JpegBuffer.h Normal file
View File

@ -0,0 +1,22 @@
#pragma once
#include <opencv2\opencv.hpp>
//#include "jpeglib.h"
class JpegBuffer
{
public:
JpegBuffer(cv::Mat buffer,int color_type=2,int side=0,int mFilter=0);
virtual ~JpegBuffer(void);
unsigned char* getBuffer();
cv::Mat buffer();
int getSize();
cv::Mat getMat( int pixType);
int getMFilter();
int getSide();
private:
cv::Mat m_buffer;
int m_color_type;
int m_side;
int m_mFilter;
};

390
hugaotwainds/JsonConfig.cpp Normal file
View File

@ -0,0 +1,390 @@
#include "StdAfx.h"
#include "JsonConfig.h"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <sstream>
#include "CJsonObject.hpp"
JsonConfig::JsonConfig(void)
{
}
JsonConfig::~JsonConfig(void)
{
}
/************************************************************************/
/* 保存配置参数 */
/************************************************************************/
void JsonConfig::WriteToJson(PCONFIGPARAMS pConfigItem,const std::string fileNames,bool isConfigItem)
{
neb::CJsonObject outJson;
outJson.AddEmptySubObject("Config");//header
outJson["Config"].Add(PIXTYPE,(int)(pConfigItem->Pixtype));
outJson["Config"].Add(PAPARSIZE,(int)(pConfigItem->PaperSize));
outJson["Config"].Add(AUTOCROP,(bool)(pConfigItem->EnAutoCrop),false);
outJson["Config"].Add(RESOLUTION,(int)(pConfigItem->Resolution));
outJson["Config"].Add(DUPLEX,(int)(pConfigItem->Duplex));
outJson["Config"].Add(DISCARBLANK,(bool)(pConfigItem->EnDiscardBlank),false);
outJson["Config"].Add(BRIGHTNESS,(int)(pConfigItem->Brightness));
outJson["Config"].Add(AUTOCONTRAST,(bool)(pConfigItem->EnAutoContrast),false);
outJson["Config"].Add(CONTRAST,(int)(pConfigItem->Contrast));
outJson["Config"].Add(GAMMA,(int)(pConfigItem->Gamma));
outJson["Config"].Add(FILTERTYPE,(int)(pConfigItem->Filter));
outJson["Config"].Add(AUTODESCREW,(bool)(pConfigItem->EnAutoDescrew),false);
outJson["Config"].Add(FILLBLACK,(bool)(pConfigItem->EnFillBlack),false);
outJson["Config"].Add(ULTRADETECT,(bool)(pConfigItem->EnUltrasonicDetect),false);
outJson["Config"].Add(BINDINGDETECT,(bool)(pConfigItem->EnBindingDetect),false);
outJson["Config"].Add(SCANCOUNT,(int)(pConfigItem->ScanCount));
outJson["Config"].Add(DOCORIENTATION,(int)(pConfigItem->Orentation));
outJson["Config"].Add(BACKROTATE180,(bool)(pConfigItem->EnBackRotate180),false);
outJson["Config"].Add(SCREWDETECT,(bool)(pConfigItem->EnScrewDetect),false);
outJson["Config"].Add(SCREWLEVEL,(int)(pConfigItem->ScrewDetectLevel));
if (isConfigItem)
{
outJson["Config"].Add(ITEMCAPTION,(string)(pConfigItem->Caption));
outJson["Config"].Add(SAVEPATH,(string)(pConfigItem->SavePath));
}
std::ofstream os;
os.open(fileNames.c_str());
os<<outJson.ToFormattedString();
os.close();
}
void JsonConfig::WriteJsonData(const std::string fileName)
{
//Json::Reader reader;
//Json::Value root;
//std::ifstream is;
//is.open(fileName.c_str(),std::ios::binary);
//if (reader.parse(is,root))
//{
//
//}
}
//PCONFIGPARAMS JsonConfig::ReadJsonFromFile(const char* fileNames)
//{
//}
void JsonConfig::WriteJsonArrayToFile(std::vector<CONFIGPARAMS> cfgArray,const std::string filename)
{
//Json::StyledWriter sw;
neb::CJsonObject root;
root.AddEmptySubObject("Config");
root["Config"].AddEmptySubArray(PIXTYPE);
root["Config"].AddEmptySubArray(PAPARSIZE);
root["Config"].AddEmptySubArray(AUTOCROP);
root["Config"].AddEmptySubArray(RESOLUTION);
root["Config"].AddEmptySubArray(DUPLEX);
root["Config"].AddEmptySubArray(DISCARBLANK);
root["Config"].AddEmptySubArray(BRIGHTNESS);
root["Config"].AddEmptySubArray(AUTOCONTRAST);
root["Config"].AddEmptySubArray(CONTRAST);
root["Config"].AddEmptySubArray(GAMMA);
root["Config"].AddEmptySubArray(FILTERTYPE);
root["Config"].AddEmptySubArray(AUTODESCREW);
root["Config"].AddEmptySubArray(FILLBLACK);
root["Config"].AddEmptySubArray(ULTRADETECT);
root["Config"].AddEmptySubArray(BINDINGDETECT);
root["Config"].AddEmptySubArray(SCANCOUNT);
root["Config"].AddEmptySubArray(DOCORIENTATION);
root["Config"].AddEmptySubArray(BACKROTATE180);
root["Config"].AddEmptySubArray(SCREWDETECT);
root["Config"].AddEmptySubArray(SCREWLEVEL);
root["Config"].AddEmptySubArray(ITEMCAPTION);
root["Config"].AddEmptySubArray(SAVEPATH);
for (int i=0;i<cfgArray.size();i++)
{
root["Config"][PIXTYPE].Add(cfgArray[i].Pixtype);
root["Config"][PAPARSIZE].Add(cfgArray[i].PaperSize);
root["Config"][AUTOCROP].Add(i,cfgArray[i].EnAutoCrop);
root["Config"][RESOLUTION].Add(cfgArray[i].Resolution);
root["Config"][DUPLEX].Add(cfgArray[i].Duplex);
root["Config"][DISCARBLANK].Add(i,cfgArray[i].EnDiscardBlank);
root["Config"][BRIGHTNESS].Add(cfgArray[i].Brightness);
root["Config"][AUTOCONTRAST].Add(i,cfgArray[i].EnAutoContrast);
root["Config"][CONTRAST].Add(cfgArray[i].Contrast);
root["Config"][GAMMA].Add(cfgArray[i].Gamma);
root["Config"][FILTERTYPE].Add(cfgArray[i].Filter);
root["Config"][AUTODESCREW].Add(i,cfgArray[i].EnAutoDescrew);
root["Config"][FILLBLACK].Add(i,cfgArray[i].EnFillBlack);
root["Config"][ULTRADETECT].Add(i,cfgArray[i].EnUltrasonicDetect);
root["Config"][BINDINGDETECT].Add(i,cfgArray[i].EnBindingDetect);
root["Config"][SCANCOUNT].Add(cfgArray[i].ScanCount);
root["Config"][DOCORIENTATION].Add(cfgArray[i].Orentation);
root["Config"][BACKROTATE180].Add(i,cfgArray[i].EnBackRotate180);
root["Config"][SCREWDETECT].Add(i,cfgArray[i].EnScrewDetect);
root["Config"][SCREWLEVEL].Add(cfgArray[i].ScrewDetectLevel);
if (cfgArray[i].Caption.c_str()!=NULL)
{
root["Config"][ITEMCAPTION].Add(cfgArray[i].Caption);
}
if (cfgArray[i].SavePath.c_str()!=NULL)
{
root["Config"][SAVEPATH].Add(cfgArray[i].SavePath);
}
}
std::ofstream os;
os.open(filename.c_str());
os<<root.ToFormattedString();
os.close();
}
CONFIGPARAMS JsonConfig::ReadDefaultConfig()
{
TCHAR szIniFile[MAX_PATH] = { 0 };
SHGetSpecialFolderPath(NULL, szIniFile, CSIDL_COMMON_DOCUMENTS, TRUE);
_tcscat(szIniFile, HUAGAO_SCAN);
_tcscat(szIniFile,TWAIN_INIPATH);
_tcscat(szIniFile, TEXT("\\"));
_tcscat(szIniFile, TWAIN_JSON_NAME);
std::string s_default(szIniFile);
vector<CONFIGPARAMS> vc;
vc=ReadJsonArrayFromFile(s_default.c_str());
if (vc.size()!=0)
{
return vc[0];
}
return GetDefaultConfigParams();
}
bool JsonConfig::DeleteJsonFile(std::string path)
{
return (remove(path.c_str()));
}
std::vector<CONFIGPARAMS> JsonConfig::ReadJsonArrayFromFile(const std::string filename)
{
std::vector<CONFIGPARAMS> re;
FILE* file=fopen(filename.c_str(),"rb");
if (!file)
{
return re;
}
fseek(file,0,SEEK_END);
long size=ftell(file);
fseek(file,0,SEEK_SET);
std::string text;
char* buffer=new char[size+1];
buffer[size]=0;
if (!fread(buffer,1,size,file)==(unsigned long)size)
{
return re;
}
text=buffer;
fclose(file);
delete []buffer;
re=parseJsonFromString(text);
return re;
}
CONFIGPARAMS JsonConfig::GetDefaultConfigParams()
{
CONFIGPARAMS params;
params.Pixtype=1;//灰度
params.PaperSize=11;//A3
params.EnAutoCrop=FALSE;//自动裁切
params.Resolution=200;//200dpi
params.Duplex=1;//双面
params.EnDiscardBlank=FALSE;//自动丢弃空白页
params.Brightness=0;//亮度
params.EnAutoContrast=FALSE;//自动对比度
params.Contrast=0;//对比度
params.Gamma=10;//伽玛值
params.Filter=0;//除色 无
params.EnFillBlack=FALSE;//不填黑框
params.EnAutoDescrew=TRUE;//不自动纠偏
params.EnUltrasonicDetect=TRUE;//超声检测开关 开
params.EnBindingDetect=FALSE;//装订检测开关 开
params.ScanCount=-1;//扫描张数
params.Orentation=0;//旋转方向0度
params.EnBackRotate180=FALSE;//背面旋转180度 不旋转
params.EnScrewDetect=TRUE;//歪斜检测 开
params.ScrewDetectLevel=3;//歪斜检测等级 3级
return params;
}
std::vector<CONFIGPARAMS> JsonConfig::parseJsonFromString(const std::string str)
{
neb::CJsonObject root(str);
vector<CONFIGPARAMS> vcConfig;
int size=0;
neb::CJsonObject itmPaparSize;
root["Config"].Get(PAPARSIZE,itmPaparSize);
size=itmPaparSize.GetArraySize();
if (size>0)
{
neb::CJsonObject itmPixType;
root["Config"].Get(PIXTYPE,itmPixType);
neb::CJsonObject itmAutoCrop;
root["Config"].Get(AUTOCROP,itmAutoCrop);
neb::CJsonObject itmRes;
root["Config"].Get(RESOLUTION,itmRes);
neb::CJsonObject itmDulpex;
root["Config"].Get(DUPLEX,itmDulpex);
neb::CJsonObject itmDiscardBlk;
root["Config"].Get(DISCARBLANK,itmDiscardBlk);
neb::CJsonObject itmBrtnes;
root["Config"].Get(BRIGHTNESS,itmBrtnes);
neb::CJsonObject itmAutoCrnt;
root["Config"].Get(AUTOCONTRAST,itmAutoCrnt);
neb::CJsonObject itmContrast;
root["Config"].Get(CONTRAST,itmContrast);
neb::CJsonObject itmGamma;
root["Config"].Get(GAMMA,itmGamma);
neb::CJsonObject itmFilter;
root["Config"].Get(FILTERTYPE,itmFilter);
neb::CJsonObject itmAutoDescrew;
root["Config"].Get(AUTODESCREW,itmAutoDescrew);
neb::CJsonObject itmFillBlack;
root["Config"].Get(FILLBLACK,itmFillBlack);
neb::CJsonObject itmUltDetect;
root["Config"].Get(ULTRADETECT,itmUltDetect);
neb::CJsonObject itmBingdingDetect;
root["Config"].Get(BINDINGDETECT,itmBingdingDetect);
neb::CJsonObject itmScanCount;
root["Config"].Get(SCANCOUNT,itmScanCount);
neb::CJsonObject itmDocOrientation;
root["Config"].Get(DOCORIENTATION,itmDocOrientation);
neb::CJsonObject itmBackRotate;
root["Config"].Get(BACKROTATE180,itmBackRotate);
neb::CJsonObject itmScrewDetct;
root["Config"].Get(SCREWDETECT,itmScrewDetct);
neb::CJsonObject itmScrewLevel;
root["Config"].Get(SCREWLEVEL,itmScrewLevel);
neb::CJsonObject itmCaption;
if (!root["Config"][ITEMCAPTION].IsEmpty())
{
root["Config"].Get(ITEMCAPTION,itmCaption);
}
neb::CJsonObject itmSavePtah;
if (!root["Config"][SAVEPATH].IsEmpty())
{
root["Config"].Get(SAVEPATH,itmSavePtah);
}
for (int i=0;i<size;i++)
{
CONFIGPARAMS cfp;
int i_value;
bool b_value;
std::string s_value;
itmPixType.Get(i,i_value);
cfp.Pixtype=i_value;
itmPaparSize.Get(i,i_value);
cfp.PaperSize=i_value;
itmAutoCrop.Get(i,b_value);
cfp.EnAutoCrop=b_value;
itmRes.Get(i,i_value);
cfp.Resolution=i_value;
itmDulpex.Get(i,i_value);
cfp.Duplex=i_value;
itmDiscardBlk.Get(i,b_value);
cfp.EnDiscardBlank=b_value;
itmBrtnes.Get(i,i_value);
cfp.Brightness=i_value;
itmAutoCrnt.Get(i,b_value);
cfp.EnAutoContrast=b_value;
itmContrast.Get(i,i_value);
cfp.Contrast=i_value;
itmGamma.Get(i,i_value);
cfp.Gamma=i_value;
itmFilter.Get(i,i_value);
cfp.Filter=i_value;
itmAutoDescrew.Get(i,b_value);
cfp.EnAutoDescrew=b_value;
itmFillBlack.Get(i,b_value);
cfp.EnFillBlack=b_value;
itmUltDetect.Get(i,b_value);
cfp.EnUltrasonicDetect=b_value;
itmBingdingDetect.Get(i,b_value);
cfp.EnBindingDetect=b_value;
itmScanCount.Get(i,i_value);
cfp.ScanCount=i_value;
itmDocOrientation.Get(i,i_value);
cfp.Orentation=i_value;
itmBackRotate.Get(i,b_value);
cfp.EnBackRotate180=b_value;
itmScrewDetct.Get(i,b_value);
cfp.EnScrewDetect=b_value;
itmScrewLevel.Get(i,i_value);
cfp.ScrewDetectLevel=i_value;
if (!root["Config"][ITEMCAPTION].IsEmpty())
{
itmCaption.Get(i,s_value);
cfp.Caption=s_value;
}
if (!root["Config"][SAVEPATH].IsEmpty())
{
itmSavePtah.Get(i,s_value);
cfp.SavePath=s_value;
}
vcConfig.push_back(cfp);
}
}
else
{
CONFIGPARAMS cfp;
int index;
bool bvalue;
std::string svalue;
root["Config"].Get(PIXTYPE,index);
cfp.Pixtype=index;
root["Config"].Get(PAPARSIZE,index);
cfp.PaperSize=index;
root["Config"].Get(AUTOCROP,bvalue);
cfp.EnAutoCrop=bvalue;
root["Config"].Get(RESOLUTION,index);
cfp.Resolution=index;
root["Config"].Get(DUPLEX,index);
cfp.Duplex=index;
root["Config"].Get(DISCARBLANK,bvalue);
cfp.EnDiscardBlank=bvalue;
root["Config"].Get(BRIGHTNESS,index);
cfp.Brightness=index;
root["Config"].Get(AUTOCONTRAST,bvalue);
cfp.EnAutoContrast=bvalue;
root["Config"].Get(CONTRAST,index);
cfp.Contrast=index;
root["Config"].Get(GAMMA,index);
cfp.Gamma=index;
root["Config"].Get(FILTERTYPE,index);
cfp.Filter=index;
root["Config"].Get(AUTODESCREW,bvalue);
cfp.EnAutoCrop=bvalue;
root["Config"].Get(FILLBLACK,bvalue);
cfp.EnFillBlack=bvalue;
root["Config"].Get(ULTRADETECT,bvalue);
cfp.EnUltrasonicDetect=bvalue;
root["Config"].Get(BINDINGDETECT,bvalue);
cfp.EnBindingDetect=bvalue;
root["Config"].Get(SCANCOUNT,index);
cfp.ScanCount=index;
root["Config"].Get(DOCORIENTATION,index);
cfp.Orentation=index;
root["Config"].Get(BACKROTATE180,bvalue);
cfp.EnBackRotate180=bvalue;
root["Config"].Get(SCREWDETECT,bvalue);
cfp.EnScrewDetect=bvalue;
root["Config"].Get(SCREWLEVEL,index);
cfp.ScrewDetectLevel=index;
if (!root["Config"][ITEMCAPTION].IsEmpty())
{
root["Config"].Get(ITEMCAPTION,svalue);
cfp.Caption=svalue;
}
if (!root["Config"][SAVEPATH].IsEmpty())
{
root["Config"].Get(SAVEPATH,svalue);
cfp.SavePath=svalue;
}
vcConfig.push_back(cfp);
}
return vcConfig;
}

25
hugaotwainds/JsonConfig.h Normal file
View File

@ -0,0 +1,25 @@
#pragma once
#include "PublicFunc.h"
#include <vector>
#include <json.h>
using namespace std;
class JsonConfig
{
public:
JsonConfig(void);
~JsonConfig(void);
public:
void WriteToJson(PCONFIGPARAMS pConfigItem,const std::string fileName,bool isConfigItem=true);
//PCONFIGPARAMS ReadJsonFromFile(const char* fileNames);
void WriteJsonData(const std::string fileName);
void WriteJsonArrayToFile(std::vector<CONFIGPARAMS> cfgArray,const std::string filename);
CONFIGPARAMS ReadDefaultConfig();
bool DeleteJsonFile(std::string path);
std::vector<CONFIGPARAMS> ReadJsonArrayFromFile(const std::string filename);
CONFIGPARAMS GetDefaultConfigParams();
private:
std::vector<CONFIGPARAMS> parseJsonFromString(const std::string str) ;
};

145
hugaotwainds/MFC_UI.cpp Normal file
View File

@ -0,0 +1,145 @@
#include "stdafx.h"
#include "MFC_UI.h"
#include "TwainUIDlg.h"
#include "IndicatorDlg.h"
#include "hugaotwainds.h"
#include "Resource.h"
#include "hugaotwainds.h"
extern ChugaotwaindsApp theApp;
MFC_UI::MFC_UI(CTWAINDS_FreeImage *pDS)
: CTWAIN_UI(pDS)
{
m_pDlg = NULL;
m_pChildWnd = NULL;
indicator=NULL;
indicatorCreated=false;
}
MFC_UI::~MFC_UI()
{
}
TW_INT16 MFC_UI::DisplayTWAINGUI(TW_USERINTERFACE Data, bool bSetup, bool bIndicators)
{
TW_INT16 nRes = CTWAIN_UI::DisplayTWAINGUI(Data, bSetup, bIndicators);
if (nRes)
{
return nRes;
}
if (bSetup)
{
Data.ShowUI = 1;
}
if (Data.ShowUI == 0 && !bIndicators)
{
return TWRC_SUCCESS;
}
if (Data.hParent)
{
CDialog* dlg = new CDialog();
dlg->Create(IDD_DIALOG_TWAINUI);
m_pChildWnd = dlg;
theApp.m_pMainWnd = m_pChildWnd;
long ll = GetWindowLong(m_pChildWnd->GetSafeHwnd(), GWL_STYLE);
SetWindowLong(m_pChildWnd->GetSafeHwnd(), GWL_STYLE, WS_CHILD | ll);
SetParent(m_pChildWnd->GetSafeHwnd(), (HWND)Data.hParent);
}
if (bIndicators)
{
indicator=new IndicatorDlg(this,Data.ShowUI?m_pDlg:m_pChildWnd);
showUI=Data.ShowUI;
}
if (Data.ShowUI)
{
m_pDlg = new TwainUIDlg(this, m_pChildWnd);
m_pDlg->Create(IDD_DIALOG_TWAINUI, m_pChildWnd);
if (!bSetup)
{
m_pDlg->SetDlgItemTextA(IDC_CONFIRM, _T("ɨÃè"));
}
else
{
m_pDlg->SetDlgItemTextA(IDC_CONFIRM, _T("È·¶¨"));
}
if (m_pDlg)
{
m_pDlg->ShowWindow(SW_SHOWNORMAL);
}
else
{
return TWRC_FAILURE;
}
}
return TWRC_SUCCESS;
}
void MFC_UI::DestroyTWAINGUI()
{
CTWAIN_UI::DestroyTWAINGUI();
if (indicator!=NULL)
{
indicator->DestroyWindow();
delete indicator;
indicator=NULL;
indicatorCreated=false;
}
if (m_pDlg!=NULL)
{
m_pDlg->DestroyWindow();
delete m_pDlg;
m_pDlg = NULL;
}
if (m_pChildWnd!=NULL)
{
m_pChildWnd->DestroyWindow();
delete m_pChildWnd;
m_pChildWnd = NULL;
}
}
void MFC_UI::UpdateProgress(bool bShow, unsigned char ucProgress, unsigned int unPageNo, string strProgressTitle)
{
if (indicator==NULL) return;
if (!indicatorCreated)
{
//indicator->Create(IDD_DIALOG_INDICATOR,showUI?m_pDlg:m_pChildWnd);
indicator->Create(IDD_DIALOG_INDICATOR,m_pChildWnd);
indicatorCreated=true;
}
indicator->ShowWindow(bShow?SW_SHOWNORMAL:SW_HIDE);
if (m_pDlg)
{
m_pDlg->EnableWindow(bShow?FALSE:TRUE);
}
}
unsigned int MFC_UI::MessageBox(string strMessage, string strTitle, unsigned int unIconID)
{
//QMessageBox msgBox(QMessageBox::NoIcon, strTitle.c_str(), strMessage.c_str());
return ::MessageBox(NULL, strMessage.c_str(), strTitle.c_str(), unIconID);
}
bool MFC_UI::processEvent(pTW_EVENT _pEvent)
{
if(m_pChildWnd)
{
if (IsDialogMessage(m_pChildWnd->m_hWnd, (LPMSG)(((pTW_EVENT)_pEvent)->pEvent)))
{
return TRUE;
}
}
return FALSE;
}

42
hugaotwainds/MFC_UI.h Normal file
View File

@ -0,0 +1,42 @@
#pragma once
#include "CTWAINDS_FreeImage.h"
#include "TWAIN_UI.h"
class TwainUIDlg;
class CWnd;
class IndicatorDlg;
class ChugaotwaindsApp;
class MFC_UI :
public CTWAIN_UI
{
public:
MFC_UI(CTWAINDS_FreeImage *pDS);
~MFC_UI();
/**
* Will show the TWAIN GUI
* @param[in] _pData contains info about if the UI should be shown etc.
* @return a valid TWRC_xxxx return code.
*/
TW_INT16 DisplayTWAINGUI(TW_USERINTERFACE Data, bool bSetup, bool bIndicators);
/**
* Close the user interface for TWAIN
*/
void DestroyTWAINGUI();
void UpdateProgress(bool bShow, unsigned char ucProgress, unsigned int unPageNo, string strProgressTitle);
unsigned int MessageBox(string strMessage, string strTitle, unsigned int unIconID);
bool processEvent(pTW_EVENT _pEvent);
public:
//CUI_INI *m_pCUI_INI;
private:
TwainUIDlg* m_pDlg;
CWnd* m_pChildWnd;
IndicatorDlg* indicator;
bool indicatorCreated;
bool showUI;
ChugaotwaindsApp* m_app;
};

52
hugaotwainds/MutexEx.h Normal file
View File

@ -0,0 +1,52 @@
#pragma once
#include <windows.h>
//对临界区同样进行封装
class CMyCriticalSection
{
public:
CMyCriticalSection()
{
InitializeCriticalSection(&m_cSection);
}
void Lock()
{
EnterCriticalSection(&m_cSection);
}
void UnLock()
{
LeaveCriticalSection(&m_cSection);
}
//利用析构函数删除临界区对象
virtual ~CMyCriticalSection()
{
DeleteCriticalSection(&m_cSection);
}
private:
CRITICAL_SECTION m_cSection;
};
class CCriticalSectionAutoLock
{
public:
//利用构造函数上锁,即进去临界区
CCriticalSectionAutoLock(CMyCriticalSection *mySection)
:pCMySection(mySection)
{
pCMySection->Lock();
}
//利用析构函数解锁,即离开临界区
virtual ~CCriticalSectionAutoLock()
{
pCMySection->UnLock();
}
private:
CMyCriticalSection *pCMySection;
};

617
hugaotwainds/PublicFunc.cpp Normal file
View File

@ -0,0 +1,617 @@
#include "stdafx.h"
#include "PublicFunc.h"
//#include "UI_INI.h"
//#include "DirectshowCaptureVideo.h"
//#include "DirectshowCaptureVideoUvc.h"
//#include "WatermarkDataType.h"
//#include "SupperDevType.h"
#include "CTwainMutex.h"
#include <io.h>
BOOL g_b_show_ui_flg = FALSE;
//WATER_PRO g_st_water_pro = {0};
BOOL g_add_water_flg = FALSE;
DWORD g_dw_white_bright_count = 40000;
//CDirectshowCaptureVideoUvc g_dc_uvc_video;
BOOL g_b_use_uvc_dev = FALSE;
TWAIN_IMAGE_DATA_INFO g_st_twain_bmp_info = {0};
BOOL g_b_brigth_show_flg = TRUE;
HWND g_hwnd_dlg = NULL;
//CDirectshowCaptureVideo g_dc_video;
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 = _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 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(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 = _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=磁盘空间不足
MyMessageBox( TEXT("磁盘分区可用空间不足"), 0, MB_ICONWARNING);
return FALSE;
}
}
else
{
MyMessageBox( TEXT("磁盘分区可用空间不足"), 0, MB_ICONWARNING);
//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 FreeTwainFileListMem()
{
if ( g_st_twain_bmp_info.p_wifl != NULL )
{
free(g_st_twain_bmp_info.p_wifl);
g_st_twain_bmp_info.p_wifl = NULL;
}
//if ( g_st_twain_bmp_info.st_bmp_info.p_image_data != NULL )
//{
// free(g_st_twain_bmp_info.st_bmp_info.p_image_data);
// g_st_twain_bmp_info.st_bmp_info.p_image_data = NULL;
//}
//memset(&g_st_twain_bmp_info, 0, sizeof(TWAIN_IMAGE_DATA_INFO));
}
BOOL MallocTwainFileListMem()
{
if ( g_st_twain_bmp_info.p_wifl == NULL )
{
memset(&g_st_twain_bmp_info, 0, sizeof(TWAIN_IMAGE_DATA_INFO));
}
else if ( g_st_twain_bmp_info.n_wifl_count != 0 && g_st_twain_bmp_info.p_wifl == NULL )
{
memset(&g_st_twain_bmp_info, 0, sizeof(TWAIN_IMAGE_DATA_INFO));
}
if ( g_st_twain_bmp_info.n_wifl_cur_count +3 > g_st_twain_bmp_info.n_wifl_count)
{
if ( SHGetSpecialFolderPath(NULL, g_st_twain_bmp_info.sz_path_dir, CSIDL_COMMON_DOCUMENTS, TRUE) )
{
INT len = _tcslen(g_st_twain_bmp_info.sz_path_dir);
if ( len > 0 )
{
//if ( g_st_twain_bmp_info.sz_path_dir[len -1] != '\\' )
// _tcscat(g_st_twain_bmp_info.sz_path_dir, TEXT("\\"));
//_tcscat(g_st_twain_bmp_info.sz_path_dir, TWAIN_DATA_PATH);
//CheckAndCreateFileDir(g_st_twain_bmp_info.sz_path_dir, TRUE);
}
}
else
return FALSE;
if ( g_st_twain_bmp_info.p_wifl == NULL )
{
g_st_twain_bmp_info.p_wifl = (PTWAIN_IMAGE_FILE_LIST)malloc(sizeof(TWAIN_IMAGE_FILE_LIST)* (g_st_twain_bmp_info.n_wifl_count + 20));
if ( g_st_twain_bmp_info.p_wifl != NULL )
{
memset(g_st_twain_bmp_info.p_wifl, 0, sizeof(TWAIN_IMAGE_FILE_LIST)* (g_st_twain_bmp_info.n_wifl_count + 20));
g_st_twain_bmp_info.n_wifl_count += 20;
}
else
return FALSE;
}
else
{
PTWAIN_IMAGE_FILE_LIST p_wifl = (PTWAIN_IMAGE_FILE_LIST)malloc(sizeof(TWAIN_IMAGE_FILE_LIST)* (g_st_twain_bmp_info.n_wifl_count + 20));
if ( g_st_twain_bmp_info.p_wifl != NULL )
{
memset(p_wifl, 0, sizeof(TWAIN_IMAGE_FILE_LIST)* (g_st_twain_bmp_info.n_wifl_count + 20));
memcpy(p_wifl, g_st_twain_bmp_info.p_wifl, sizeof(TWAIN_IMAGE_FILE_LIST)* g_st_twain_bmp_info.n_wifl_cur_count );
g_st_twain_bmp_info.n_wifl_count += 20;
free(g_st_twain_bmp_info.p_wifl);
g_st_twain_bmp_info.p_wifl = p_wifl;
p_wifl = NULL;
}
else
return FALSE;
}
}
return TRUE;
}
BOOL WriteTwianImageData(TCHAR *p_file_path, PBYTE p_data, DWORD dw_size)
{
DWORD dw_write_size = 0;
if ( p_file_path == NULL || p_data == NULL )
return FALSE;
if ( _msize(p_data) < dw_size )
return FALSE;
DeleteFile(p_file_path);
HANDLE h_file = CreateFile(p_file_path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, NULL, NULL);
if ( h_file == INVALID_HANDLE_VALUE )
{
return FALSE;
}
BOOL b_flg = WriteFile(h_file, p_data, dw_size, &dw_write_size,0);
if ( !b_flg || dw_size != dw_write_size )
{
b_flg = FALSE;
}
CloseHandle(h_file);
h_file = INVALID_HANDLE_VALUE;
if ( !b_flg )
{
DeleteFile(p_file_path);
}
return TRUE;
}
DWORD ReadTwianImageData(TCHAR *p_file_path)
{
if ( p_file_path == NULL )
return 0;
DWORD dw_size = 0;
HANDLE h_file = CreateFile(p_file_path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if ( h_file == INVALID_HANDLE_VALUE )
{
return 0;
}
dw_size = GetFileSize(h_file, 0);
if ( dw_size == 0 )
{
CloseHandle(h_file);
return 0;
}
//if ( g_st_twain_bmp_info.st_bmp_info.p_image_data != NULL )
//{
// free(g_st_twain_bmp_info.st_bmp_info.p_image_data);
// g_st_twain_bmp_info.st_bmp_info.p_image_data = NULL;
//}
//DWORD dw_read_size = 0;
//g_st_twain_bmp_info.st_bmp_info.p_image_data = (PBYTE)malloc(dw_size);
//if ( g_st_twain_bmp_info.st_bmp_info.p_image_data == NULL )
//{
// CloseHandle(h_file);
// return 0;
//}
//BOOL b_flg = ReadFile(h_file, ////g_st_twain_bmp_info.st_bmp_info.p_image_data, dw_size, /&dw_read_size,/ 0);
////CloseHandle(h_file);
//h_file = INVALID_HANDLE_VALUE;
//if ( !b_flg || dw_size != dw_read_size)
//{
// //free(g_st_twain_bmp_info.st_bmp_info.p_image_data);
// dw_size = 0;
//}
//else
// DeleteFile(p_file_path);
return dw_size;
}
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;
}
DWORD MyMessageBox(TCHAR *p_str, TCHAR *p_str2, DWORD dw_id)
{
if ( p_str2 == NULL )
{
return MessageBox(g_hwnd_dlg, p_str, TEXT("test")/*g_p_cur_supper_sdti->sz_type_str*/, dw_id);
}
else
{
return MessageBox(g_hwnd_dlg, p_str, p_str2, dw_id);
}
}
CTwainMutex g_sys_mutex;
BOOL g_not_user_sineng_dev = true;
BOOL g_InitSysMutexRun()
{
//return g_sys_mutex.InitRunMutexId(COMPANY_NAME PRODUCT_NAME);
return true;
//return g_sys_mutex.CreatTwainMutex(SCANNERNAME);
}
BOOL g_InitSysMutexScanRun(DWORD dwPid, DWORD dwUid)
{
//return g_sys_mutex.InitScanRunMutexId(COMPANY_NAME PRODUCT_NAME, dwPid, dwUid);
return true;
}
BOOL g_CloseSysMutexRun()
{
//return g_sys_mutex.CloseAllScnDocA3Mutex();
return g_sys_mutex.CloseTwainMutex();
}
BOOL g_CloseOneSysMutexRun()
{
//return g_sys_mutex.CloseScnDocA3Mutex((SCN_MUTEX_TYPE)smt);
return true;
//return g_sys_mutex.CloseTwainMutex();
}
BOOL g_CheckSysMutex()
{
//return g_sys_mutex.CheckScnDocA3Mutex((SCN_MUTEX_TYPE)smt);
return true;
return g_sys_mutex.CheckExistTwainMutex(SCANNERNAME);
}
BOOL g_CreateSysMutex()
{
//return g_sys_mutex.CreateScnDocA3Mutex((SCN_MUTEX_TYPE)smt);
//return true;
return g_sys_mutex.CreatTwainMutex(SCANNERNAME);
}
RGBQUAD g_default_map[256] = {0};
BOOL ReadDefaultMap()
{
int i = 0;
for ( i = 0; i < 256; i++ )
{
g_default_map[i].rgbBlue = g_default_map[i].rgbGreen = g_default_map[i].rgbRed = i;
}
TCHAR sz_path[MAX_PATH] = {0};
bool nRet = GetModuleFileName(AfxGetApp()->m_hInstance, sz_path, sizeof(sz_path));
if (nRet > 0)
{
TCHAR *p = _tcsrchr(sz_path, TEXT('\\'));
if ( p != NULL )
{
*(p+1) = TEXT('\0');
}
else
{
return TRUE;
}
}
_tcscat(sz_path, TEXT("default.map"));
HANDLE hfile = CreateFile(sz_path, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL);
if ( hfile != INVALID_HANDLE_VALUE )
{
DWORD dw_write = 0;
ReadFile(hfile, g_default_map, sizeof(g_default_map), &dw_write, NULL);
if ( dw_write != sizeof(g_default_map) )
{
nRet = false;
}
CloseHandle(hfile);
}
return nRet;
}
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;
}
VOID XdPrint(_TCHAR* format, ...)
{
va_list args;
va_start(args, format);
_TCHAR buf[256];
_vstprintf(buf, format, args);
OutputDebugString(buf);
va_end(args);
}

174
hugaotwainds/PublicFunc.h Normal file
View File

@ -0,0 +1,174 @@
#ifndef PUBLICFUNC_H_
#define PUBLICFUNC_H_
#include "stdafx.h"
#include <string>
//#include "UI_INI.h"
//#include "DirectshowCaptureVideo.h"
//#include "DirectshowCaptureVideoUvc.h"
using namespace std;
/************************************
**json格式保存参数名称**
*************************************/
#define PIXTYPE "iPixType"
#define PAPARSIZE "iPaparSize"
#define AUTOCROP "bAuotCrop"
#define RESOLUTION "iResolution"
#define DUPLEX "iDuplex"
#define DISCARBLANK "bDiscardBlank"
#define FLOD "bFlod"
#define BRIGHTNESS "iBrightness"
#define AUTOCONTRAST "bAutoContrast"
#define CONTRAST "iContrast"
#define GAMMA "dGamma"
#define FILTERTYPE "iFilter"
#define FILLBLACK "bFillBlcak"
#define AUTODESCREW "bAutoDescrew"
#define ULTRADETECT "bUltrasonicDetect"
#define BINDINGDETECT "bBindingDetect"
#define SCANCOUNT "ScanCount"
#define DOCORIENTATION "bOrientation"
#define BACKROTATE180 "iBackRotate180"
#define SCREWDETECT "bScrewDetect"
#define SCREWLEVEL "iScrewLevel"
#define ITEMCAPTION "Caption"
#define SAVEPATH "SavePath"
/******************
****
*******************/
struct tagCONFIGPARAMS
{
INT Pixtype;
INT PaperSize;
BOOL EnAutoCrop;
INT Resolution;
INT Duplex;
BOOL EnDiscardBlank;
BOOL EnFlod;
INT Brightness;
BOOL EnAutoContrast;
INT Contrast;
INT Gamma;
INT Filter;
BOOL EnFillBlack;
BOOL EnAutoDescrew;
BOOL EnUltrasonicDetect;
BOOL EnBindingDetect;
INT ScanCount;
INT Orentation;
BOOL EnBackRotate180;
BOOL EnScrewDetect;
INT ScrewDetectLevel;
std::string Caption;
std::string SavePath;
};
typedef tagCONFIGPARAMS CONFIGPARAMS,*PCONFIGPARAMS;
struct tagCONFIGINFO
{
std::string Caption;
std::string SavePath;
};
typedef struct tagCONFIGINFO CONFIGINFO,*PCONFIGINFO;
#define CAPTION_LEN 256
#define TWAIN_IMAGE_FILE_LIST_NAME TEXT(".dat")
#ifndef malloc_my
#define malloc_my malloc
#endif
typedef struct tagTWAIN_IMAGE_FILE_LIST
{
INT n_item;//
TCHAR sz_path[MAX_PATH];
DWORD dw_color_bit;
DWORD dw_width;
DWORD dw_height;
DWORD dw_dpi;
DWORD dw_image_size;
BOOL b_del_flg;//文件时是否删除, 传送一个删除一个
}TWAIN_IMAGE_FILE_LIST,FAR*PTWAIN_IMAGE_FILE_LIST;
typedef struct tagTWAIN_IMAGE_DATA_INFO
{
BOOL b_lock_flg;//是否在使用中
//BOOL b_flg;
TCHAR sz_path_dir[MAX_PATH];//文件目录
//IMAGE_BMP_INFO st_bmp_info;//图像信息
PTWAIN_IMAGE_FILE_LIST p_wifl;
INT n_wifl_count;//内存大小
INT n_wifl_cur_count;//当前使用内存个数
INT n_wifl_cur_pos;//当前传送内存位置
}TWAIN_IMAGE_DATA_INFO, FAR*PTWAIN_IMAGE_DATA_INFO;
DWORD ReadTwianImageData(TCHAR *p_file_path);
BOOL WriteTwianImageData(TCHAR *p_file_path, PBYTE p_data, DWORD dw_size);
BOOL MallocTwainFileListMem();
VOID FreeTwainFileListMem();
//取得用户自定义目录,参数 窗口句柄,当前目录, 显示在浏览对话框上的字符串
TCHAR* GetUserCustomFilePath(HWND hWin, LPSTR lpFilePath, TCHAR *lp_head_text = NULL);
//取得当前模块的文件路径, 参数,模块实列举并, 文件路径, 字符串的长度
TCHAR* GetCurExeFilePath(HINSTANCE hInstance, TCHAR* lpPath, DWORD dwSize);
//取得路径中已经存在的路径,并返回
TCHAR* GetExistFileDir(TCHAR* p_file_path);
//回调函数,取得用户自定义的文件路径
DWORD CALLBACK BrowserCallbackProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) ;
std::string UtfToString(std::string strValue);
std::string StringToUtf(std::string strValue);
//检查,创建文件夹, 参数 文件路径, = 真,创建p_file_path不寻在文件路径
BOOL CheckAndCreateFileDir(TCHAR* p_file_path, BOOL flg);
BOOL CheckDiskFreeBitM(HWND hWin, TCHAR *p_disk_name, DWORD dw_min_bit_m);
HBITMAP SetButtonStaticBkBmp(HINSTANCE hInst, HWND hWin, UINT id, UINT iamge_id);
DWORD MyMessageBox(TCHAR *p_str, TCHAR *p_str2, DWORD dw_id);
extern TWAIN_IMAGE_DATA_INFO g_st_twain_bmp_info;
//extern CDirectshowCaptureVideo g_dc_video;
extern BOOL g_b_show_ui_flg;
//extern WATER_PRO g_st_water_pro;
extern BOOL g_add_water_flg;
extern DWORD g_dw_white_bright_count;
//extern CDirectshowCaptureVideoUvc g_dc_uvc_video;
extern BOOL g_b_use_uvc_dev ;
extern BOOL g_b_brigth_show_flg;
extern HWND g_hwnd_dlg;
//extern CSysMutex g_sys_mutex;
typedef enum tagSYS_MUTEX_TYPE
{
SYSMUTEX_APP_RUN_TYPE,// ok
SYSMUTEX_TWAIN_RUN_TYPE,
SYSMUTEX_APP_SCANNER_RUN_TYPE,
SYSMUTEX_TWAIN_SCANNER_RUN_TYPE
}SYS_MUTEX_TYPE, FAR* PSYS_MUTEX_TYPE;
BOOL g_InitSysMutexRun();
BOOL g_InitSysMutexScanRun(DWORD dwPid, DWORD dwUid);
BOOL g_CloseSysMutexRun();
BOOL g_CloseOneSysMutexRun();
BOOL g_CreateSysMutex();
BOOL g_CheckSysMutex();
float GetContrast(int level);
VOID XdPrint(_TCHAR* format, ...);
extern BOOL g_not_user_sineng_dev;
extern RGBQUAD g_default_map[256];
BOOL ReadDefaultMap();
#endif

BIN
hugaotwainds/Resource.h Normal file

Binary file not shown.

View File

@ -0,0 +1,91 @@
// SaveConfigDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "hugaotwainds.h"
#include "SaveConfigDlg.h"
#include "afxdialogex.h"
//#include "UI_INI.h"
#include "TwainUIDlg.h"
//#include "JsonConfig.h"
#include <io.h>
// SaveConfigDlg 对话框
IMPLEMENT_DYNAMIC(SaveConfigDlg, CDialog)
//extern CUI_INI* m_pUI_INI;
SaveConfigDlg::SaveConfigDlg(CWnd* pParent /*=NULL*/)
: CDialog(IDD_DIALOGSAVECONFIG, pParent)
{
}
SaveConfigDlg::~SaveConfigDlg()
{
}
void SaveConfigDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(SaveConfigDlg, CDialog)
ON_BN_CLICKED(IDOK, &SaveConfigDlg::OnBnClickedOk)
END_MESSAGE_MAP()
// SaveConfigDlg 消息处理程序
void SaveConfigDlg::OnBnClickedOk()
{
TwainUIDlg* m_Parent=(TwainUIDlg*)GetParent();
CONFIGPARAMS citem={0};
m_Parent->UpDateScanParam(&citem,false);
CString m_sName;
GetDlgItemTextA(IDC_EDITSAVENAME,m_sName);
TCHAR szIniFile[MAX_PATH] = { 0 };
INT length=m_sName.GetLength();
//INT length=10;
if (length>0&&length<50)
{
char invalid_FileChars[8]={'/','\\',':','*',' ?','<', '>','|'};
for(short j=0;j<8;j++)
{
m_sName.Remove(invalid_FileChars[j]);
}
if (m_sName.IsEmpty())
{
MessageBox(_TEXT("请避免输入非法字符('/','\\',':','*',' ?','<', '>','|')!"),_TEXT("提示"),MB_OK|MB_ICONWARNING
);
return;
}
SHGetSpecialFolderPath(NULL, szIniFile, CSIDL_COMMON_DOCUMENTS, TRUE);
_tcscat(szIniFile,HUAGAO_SCAN);
_tcscat(szIniFile, TWAIN_DATA_PATH);
citem.Caption=m_sName;
_tcscat(szIniFile,(_TEXT("/")+m_sName+_TEXT(".json")));
std::string s_savePath(szIniFile);
citem.SavePath=s_savePath;
//((CListBox*)(m_Parent->GetDlgItem(IDC_LSTCONFIG)))->AddString(m_sName);
m_sName.ReleaseBuffer();
JsonConfig cfg;
cfg.WriteToJson(&citem,s_savePath,true);
m_Parent->UpdateListConfig();
CDialog::OnOK();
}
else
{
if (length==0)
{
MessageBox(_TEXT("请输入保存项名称"),_TEXT("提示"));
}
else
{
MessageBox(_TEXT("最多只允许输入50个字符,请重新输入"),_TEXT("提示"));
}
}
}

View File

@ -0,0 +1,27 @@
#pragma once
//#include "UI_INI.h"
// SaveConfigDlg 对话框
class SaveConfigDlg : public CDialog
{
DECLARE_DYNAMIC(SaveConfigDlg)
public:
SaveConfigDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~SaveConfigDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOGSAVECONFIG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedOk();
private:
CWnd* m_Parent;
};

View File

@ -0,0 +1,247 @@
#include "stdafx.h"
#include "SupperScanImageMTF.h"
#include "math.h"
CSupperScanImageMTF::CSupperScanImageMTF(void)
{
memset(&st_im, 0, sizeof(IMAGE_MTF));
blank_bk = NULL;
cur_image = NULL;
}
CSupperScanImageMTF::~CSupperScanImageMTF(void)
{
memset(&st_im, 0, sizeof(IMAGE_MTF));
delete[]blank_bk[0];
delete[]blank_bk;
delete[]cur_image[0];
delete[]cur_image;
}
/// <summary>
/// return the state of the image whether it is blank.
/// </summary>
bool CSupperScanImageMTF::GetImageBlankFlag()
{
return is_blank;
}
/// <summary>
/// Initialize the information needed to estimate an image.
/// set the size of the image, the starting coordinate.
/// set the parameters related to the dafault values(10,10,1.0,76).
/// If the initialization finished,return true and the b_init_image_info_flg will be set to true;
/// otherwise return false.
/// </summary>
/// <param name="n_image_width","n_image_height"> the width ,height of the input image.</param>
/// <param name=" n_start_x"," n_start_y">the starting position on the width and the height direction.</param>
bool CSupperScanImageMTF::InitMTFImageInfo(INT n_image_width, INT n_image_height, INT n_start_x, INT n_start_y)
{
if (st_im.b_init_image_info_flg)
return TRUE;
if (n_image_width < 0 || n_image_height < 0 || n_start_x < 0 || n_start_y < 0)
{
return FALSE;
}
if ((n_image_width - n_start_x) < width_half_count * 2 || (n_image_height - n_start_y) < height_half_count * 2)
{
return FALSE;
}
memset(&st_im, 0, sizeof(IMAGE_MTF));
st_im.st_image_size.n_image_height = n_image_height;
st_im.st_image_size.n_image_width = n_image_width;
st_im.st_image_size.n_image_start_x = n_start_x;
st_im.st_image_size.n_image_start_y = n_start_y;
FLOAT f_x = (n_image_width - n_start_x)*1.0F / (width_half_count * 2);
FLOAT f_y = (n_image_height - n_start_y)*1.0F / (height_half_count * 2);
st_im.n_mtf_image_width = (INT)f_x;
st_im.n_mtf_image_height = (INT)f_y;
//SetSkipBlankPara(10, 10, 1, 76);
st_im.b_init_image_info_flg = TRUE;
return TRUE;
}
/// <summary>
/// estimate the input image whehter it is blank or not
/// set the size of the image, the starting coordinate;
/// set the parameters(INT w_half_count, INT h_half_count, INT f_range, INT thres) needed to estimate
/// an image blank to the dafault values(10,10,1.0,76).
/// allocate space for the two-dimensional array which will contain the computed variances of each region of the input image.
/// allocate space for the two-dimensional array which will contain the computed variances of each region of a blank image.
/// initialize both of the two arrays to 0.0.
/// </summary>
/// <param name="n_image_width"> the width of the input image.</param>
/// <param name="n_image_height">the height of the input image.</param>
/// <param name=" n_start_x">the starting position on the width direction .</param>
/// <param name=" n_start_y">the start position on the height direction.</param>
bool CSupperScanImageMTF::IsImageBlank(PBYTE p_image_data, INT n_image_width, INT n_image_height, DWORD dw_bit_color)
{
bool blank = false;
if (p_image_data == NULL && n_image_width != st_im.st_image_size.n_image_height && n_image_height != st_im.st_image_size.n_image_width)
return blank;
if (!st_im.b_init_image_info_flg) {
return blank;
}
INT n_w = 0;
INT n_h = 0;
INT n_x = 0;
INT n_y = 0;
DWORD dw_all_r = 0;
DWORD dw_all_g = 0;
DWORD dw_all_b = 0;
INT f_r_average = 0.0F;
INT f_g_average = 0.0F;
INT f_b_average = 0.0F;
DWORD dw_src_image_line_bytes = (n_image_width * dw_bit_color + 31) / 32 * 4;
if (dw_bit_color >= 8 && dw_bit_color % 8 == 0 && dw_bit_color != 16)
{
DWORD dw_bit_pixel = dw_bit_color >> 3;
DWORD dwMTF_RECT_HEIGHT = n_image_height / (height_half_count * 2);
DWORD dwMTF_RECT_WIDTH = n_image_width / (width_half_count * 2);
PBYTE p_data_ls = NULL;
DWORD dw_data_pos_h_ls = 0;
DWORD dw_data_pos_w_ls = 0;
for (n_h = 0; n_h < height_half_count * 2; n_h++)
{
for (n_w = 0; n_w < width_half_count * 2; n_w++)
{
dw_all_r = 0;
dw_all_g = 0;
dw_all_b = 0;
p_data_ls = p_image_data + n_h * dwMTF_RECT_HEIGHT * dw_src_image_line_bytes + n_w * dwMTF_RECT_WIDTH * dw_bit_pixel;
dw_data_pos_h_ls = 0;
for (n_y = 0; n_y < dwMTF_RECT_HEIGHT; n_y++)
{
dw_data_pos_w_ls = 0;
for (n_x = 0; n_x < dwMTF_RECT_WIDTH; n_x++)
{
if (dw_bit_pixel == 1) {
dw_all_g += *(p_data_ls + dw_data_pos_h_ls + dw_data_pos_w_ls);
}
else {
dw_all_b += *(p_data_ls + dw_data_pos_h_ls + dw_data_pos_w_ls + 0);
dw_all_g += *(p_data_ls + dw_data_pos_h_ls + dw_data_pos_w_ls + 1);
dw_all_r += *(p_data_ls + dw_data_pos_h_ls + dw_data_pos_w_ls + 2);
}
dw_data_pos_w_ls += dw_bit_pixel;
}
dw_data_pos_h_ls += dw_src_image_line_bytes;
}
if (dw_bit_pixel == 1) {
f_r_average = f_g_average = f_b_average = dw_all_g / (dwMTF_RECT_HEIGHT * dwMTF_RECT_WIDTH);
}
else {
f_b_average = dw_all_b / (dwMTF_RECT_HEIGHT * dwMTF_RECT_WIDTH);
f_g_average = dw_all_g / (dwMTF_RECT_HEIGHT * dwMTF_RECT_WIDTH);
f_r_average = dw_all_r / (dwMTF_RECT_HEIGHT * dwMTF_RECT_WIDTH);
}
dw_all_r = 0;
dw_all_g = 0;
dw_all_b = 0;
p_data_ls = p_image_data + n_h * dwMTF_RECT_HEIGHT * dw_src_image_line_bytes + n_w * dwMTF_RECT_WIDTH * dw_bit_pixel;
dw_data_pos_h_ls = 0;
DWORD dw_tmp = 0x0L;
for (n_y = 0; n_y < dwMTF_RECT_HEIGHT; n_y++)
{
dw_data_pos_w_ls = 0;
for (n_x = 0; n_x < dwMTF_RECT_WIDTH; n_x++)
{
if (dw_bit_pixel == 1) {
dw_tmp = *(p_data_ls + dw_data_pos_h_ls + dw_data_pos_w_ls) - f_g_average;
dw_all_g += (DWORD)dw_tmp * dw_tmp;
}
else {
dw_tmp = *(p_data_ls + dw_data_pos_h_ls + dw_data_pos_w_ls + 0) - f_b_average;
dw_all_b += dw_tmp * dw_tmp;
dw_tmp = *(p_data_ls + dw_data_pos_h_ls + dw_data_pos_w_ls + 1) - f_g_average;
dw_all_g += dw_tmp * dw_tmp;
dw_tmp = *(p_data_ls + dw_data_pos_h_ls + dw_data_pos_w_ls + 2) - f_r_average;
dw_all_r += dw_tmp * dw_tmp;
}
dw_data_pos_w_ls += dw_bit_pixel;
}
dw_data_pos_h_ls += dw_src_image_line_bytes;
}
if (dw_bit_pixel == 1) {
cur_image[n_w][n_h].f_r_mtf = cur_image[n_w][n_h].f_g_mtf = cur_image[n_w][n_h].f_b_mtf = (INT)sqrt((dw_all_g*1.0F) / (dwMTF_RECT_HEIGHT * dwMTF_RECT_WIDTH - 1));
}
else {
cur_image[n_w][n_h].f_r_mtf = (INT)sqrt((dw_all_r*1.0F) / (dwMTF_RECT_HEIGHT * dwMTF_RECT_WIDTH - 1));
cur_image[n_w][n_h].f_g_mtf = (INT)sqrt((dw_all_g*1.0F) / (dwMTF_RECT_HEIGHT * dwMTF_RECT_WIDTH - 1));
cur_image[n_w][n_h].f_b_mtf = (INT)sqrt((dw_all_b*1.0F) / (dwMTF_RECT_HEIGHT * dwMTF_RECT_WIDTH - 1));
}
}
}
}
else
{
return blank;
}
st_im.n_cur_precent_rect_count = 0;
for (n_w = 0; n_w < width_half_count * 2; n_w++)
{
for (n_h = 0; n_h < height_half_count * 2; n_h++)
{
if (CMP_FLOAT_RANGLE(blank_bk[n_w][n_h].f_r_mtf, float_range, cur_image[n_w][n_h].f_r_mtf) && \
CMP_FLOAT_RANGLE(blank_bk[n_w][n_h].f_g_mtf, float_range, cur_image[n_w][n_h].f_g_mtf) && \
CMP_FLOAT_RANGLE(blank_bk[n_w][n_h].f_b_mtf, float_range, cur_image[n_w][n_h].f_b_mtf))
{
st_im.n_cur_precent_rect_count++;
}
}
}
st_im.n_cur_precent_rect_count = (INT)((st_im.n_cur_precent_rect_count)*1.0F / (height_half_count * width_half_count * 4) * 100);
if (st_im.n_cur_precent_rect_count >= threshold)//±³¾°
{
blank = true;
is_blank = blank;
}
return blank;
}
/// <summary>
/// Set the parameters needed to estimate whether an image is blank or not.
/// allocate space for the two two-dimensional array which will contain the computed variances of each region of the input image and a blank image respectively.
/// initialize both of the two arrays to 0.0.
/// If the setting finished,return true; otherwise return false.
/// </summary>
/// <param name=" w_half_count","h_half_count"> half of the number of blocks divided on the width and height of the input image.</param>
/// <param name="f_range">the float range of variance compared with 0,because the variances of regions of an blank image are all 0.</param>
/// <param name="thres">the percent of regions whose variance is in the floating range.</param>
bool CSupperScanImageMTF::SetSkipBlankPara(INT w_half_count, INT h_half_count, INT f_range, INT thres) {
if (w_half_count <= 0 || w_half_count >= (st_im.st_image_size.n_image_width >> 1) || h_half_count <= 0 || h_half_count >= st_im.st_image_size.n_image_height >> 1) {
return FALSE;
}
if (f_range < 0 || thres < 0 || thres >100) {
return FALSE;
}
this->width_half_count = w_half_count;
this->height_half_count = h_half_count;
this->float_range = f_range;
this->threshold = thres;
if (blank_bk != NULL) {
delete[]blank_bk[0];
delete[]blank_bk;
}
if (cur_image != NULL) {
delete[]cur_image[0];
delete[]cur_image;
}
blank_bk = new IMAGE_RECT_MTF *[width_half_count * 2];//±³¾°mtf
cur_image = new IMAGE_RECT_MTF *[width_half_count * 2];//µ±Ç°Ö¡µÄMTF
blank_bk[0] = new IMAGE_RECT_MTF[width_half_count *height_half_count * 4];
cur_image[0] = new IMAGE_RECT_MTF[width_half_count *height_half_count * 4];
for (int i = 1; i < width_half_count * 2; ++i) {
blank_bk[i] = blank_bk[i - 1] + height_half_count * 2;
cur_image[i] = cur_image[i - 1] + height_half_count * 2;
}
IMAGE_RECT_MTF bk = { 0.0f, 0.0f, 0.0f };
for (int i = 0; i < width_half_count * 2; ++i) {
for (int j = 0; j < height_half_count * 2; ++j) {
blank_bk[i][j] = bk;
cur_image[i][j] = bk;
}
}
return TRUE;
}

View File

@ -0,0 +1,57 @@
#pragma once
#include <windows.h>
#define CMP_FLOAT_RANGLE(F_SRC,F_ERR,F_CUR) (F_CUR<=(F_SRC+F_ERR))&&(F_CUR>=(F_SRC-F_ERR))
typedef struct tagIMAGE_SIZE_MTF
{
INT n_image_width;
INT n_image_height;
INT n_image_start_x;
INT n_image_start_y;
}IMAGE_SIZE_MTF,*PIMAGE_SIZE_MTF;
typedef struct tagIMAGE_RECT_MTF
{
FLOAT f_r_mtf;
FLOAT f_g_mtf;
FLOAT f_b_mtf;
}IMAGE_RECT_MTF,*PIMAGE_RECT_MTF;
typedef struct tagIMAGE_MTF
{
INT width_half_count;
INT height_half_count;
INT n_mtf_image_width;
INT n_mtf_image_height;
INT n_cur_precent_rect_count;
IMAGE_SIZE_MTF st_image_size;
bool b_init_image_info_flg;
}IMAGE_MTF,*PIMAGE_MTF;
class CSupperScanImageMTF
{
public:
CSupperScanImageMTF(void);
~CSupperScanImageMTF(void);
IMAGE_MTF st_im;
private :
bool is_blank;
INT width_half_count;
INT height_half_count;
INT float_range;
INT threshold;
bool b_init_image_info_flg;
IMAGE_RECT_MTF(**blank_bk);
IMAGE_RECT_MTF(**cur_image);
public:
bool SetSkipBlankPara(INT width_half_count,INT height_half_count,INT float_range,INT threshold);
bool GetImageBlankFlag();
bool InitMTFImageInfo(INT n_image_width, INT n_image_height, INT n_start_x, INT n_start_y);
bool IsImageBlank(PBYTE p_image_data, INT n_image_width, INT n_image_height, DWORD dw_bit_color);
};

View File

@ -0,0 +1,206 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainer.cpp
* Base Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CommonDS.h"
CTWAINContainer::CTWAINContainer(const TW_UINT16 _unCapID,
const TW_UINT16 _unItemType,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries, /*=TWQC_ALL*/
const TW_UINT16 _unGetCurrentType, /*=TWON_ONEVALUE*/
const TW_UINT16 _unGetDefaultType) /*=TWON_ONEVALUE*/
{
m_unCapID = _unCapID;
m_unItemType = _unItemType;
m_unGetType = _unGetType;
m_nMSG_QUERYSUPPORT = _nSupportedQueries;
m_unGetCurrentType = _unGetCurrentType;
m_unGetDefaultType = _unGetDefaultType;
m_nCurrent = -1;
m_nDefault = -1;
}
CTWAINContainer::~CTWAINContainer()
{
}
TW_UINT16 CTWAINContainer::GetCapID()
{
return m_unCapID;
}
TW_UINT16 CTWAINContainer::GetItemType()
{
return m_unItemType;
}
TW_UINT16 CTWAINContainer::GetGetType(const TW_UINT16 _unMsg)
{
switch(_unMsg)
{
case MSG_GET:
return m_unGetType;
break;
case MSG_GETCURRENT:
return m_unGetCurrentType;
break;
case MSG_GETDEFAULT:
return m_unGetDefaultType;
break;
default:
break;
}
return TWON_ONEVALUE;
}
unsigned int CTWAINContainer::getTWTYSize(TW_UINT16 _TWType)
{
unsigned int unSize = 0;
switch(_TWType)
{
case TWTY_INT8:
unSize = sizeof(TW_INT8);
break;
case TWTY_INT16:
unSize = sizeof(TW_INT16);
break;
case TWTY_INT32:
unSize = sizeof(TW_INT32);
break;
case TWTY_UINT8:
unSize = sizeof(TW_UINT8);
break;
case TWTY_UINT16:
unSize = sizeof(TW_UINT16);
break;
case TWTY_BOOL:
unSize = sizeof(TW_BOOL);
break;
case TWTY_UINT32:
unSize = sizeof(TW_UINT32);
break;
case TWTY_FIX32:
unSize = sizeof(TW_FIX32);
break;
case TWTY_FRAME:
unSize = sizeof(TW_FRAME);
break;
case TWTY_STR32:
unSize = sizeof(TW_STR32);
break;
case TWTY_STR64:
unSize = sizeof(TW_STR64);
break;
case TWTY_STR128:
unSize = sizeof(TW_STR128);
break;
case TWTY_STR255:
unSize = sizeof(TW_STR255);
break;
case TWTY_STR1024:
unSize = sizeof(TW_STR1024);
break;
case TWTY_UNI512:
unSize = sizeof(TW_UNI512);
break;
}
return unSize;
}
bool CTWAINContainer::isOperationAllowed(const TW_UINT16 _unMsg)
{
bool bret = false;
switch(_unMsg)
{
case MSG_RESET:
if(m_nMSG_QUERYSUPPORT & TWQC_RESET)
{
bret = true;
}
break;
case MSG_SET:
if(m_nMSG_QUERYSUPPORT & TWQC_SET)
{
bret = true;
}
break;
case MSG_GETCURRENT:
if(m_nMSG_QUERYSUPPORT & TWQC_GETCURRENT)
{
bret = true;
}
break;
case MSG_GETDEFAULT:
if(m_nMSG_QUERYSUPPORT & TWQC_GETDEFAULT)
{
bret = true;
}
break;
case MSG_GET:
if(m_nMSG_QUERYSUPPORT & TWQC_GET)
{
bret = true;
}
break;
}
return bret;
}

View File

@ -0,0 +1,209 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainer.h
* Base Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINCONTAINER_H__
#define __CTWAINCONTAINER_H__
/**
@TODO TW_RANGE not implimented. Need to be able to Set with one type and return with another.
@TODO TWTY_STRnnn not implimented for any containers
*/
#ifdef TWH_CMP_GNU
#include <stdlib.h>
#endif // TWH_CMP_GNU
#include "twain.h"
#include <string>
#include <vector>
using namespace std;
/**
* String Vector
*/
typedef vector<string> StringVector;
/**
* Float Vector
*/
typedef vector<float> FloatVector;
/**
* Int Vector
*/
typedef vector<int> IntVector;
/**
* All possible TWQC_xxxxx messages
*/
#define TWQC_ALL (TWQC_GET | TWQC_SET | TWQC_GETDEFAULT | TWQC_GETCURRENT | TWQC_RESET)
/**
* All get TWQC_xxxxx messages
*/
#define TWQC_GETS (TWQC_GET | TWQC_GETDEFAULT | TWQC_GETCURRENT)
/**
* TWAIN Container Base class.
* All values are stored internally as 1/1000th of an inch. They are converted
* as necessary when TWAIN containers are created. Any direct access will require
* the caller to do their own conversion.
*/
class CTWAINContainer
{
friend class CTWAIN_UI;
public:
/**
* Constructor.
* @param[in] _unCapID Capability ID
* @param[in] _unItemType TWAIN Type TWTY_xxxx being stored.
* @param[in] _unGetType TWON_xxxx container
* @param[in] _nSupportedQueries the supported querie types TWQC_xxxx
*/
CTWAINContainer(const TW_UINT16 _unCapID,
const TW_UINT16 _unItemType,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries = TWQC_ALL,
const TW_UINT16 _unGetCurrentType = TWON_ONEVALUE,
const TW_UINT16 _unGetDefaultType = TWON_ONEVALUE);
virtual ~CTWAINContainer();
/**
* Return the capability ID.
* @return the capability ID
*/
TW_UINT16 GetCapID();
/**
* Return the TWTY_xxxx item type.
* @return the item type
*/
TW_UINT16 GetItemType();
/**
* Return the TWON_xxxx containor type.
* @param[in] _MSG the MSG_GETxxxx get message.
* @return the containor type
*/
virtual TW_UINT16 GetGetType(const TW_UINT16 _unMsg);
//////////////////////////////////////////////////////////////////////////////
/**
* @name Pure Virtuals
* @{
*/
// TWAIN operations
/**
* Return the container.
* @param[in] _unMsg the MSG_GETxxxx get message.
* @return a handle to containor
*/
virtual TW_HANDLE GetContainer(const TW_UINT16 _unMsg) = 0;
/**
* Set a container.
* @param[in] _pCap a pointer to TW_CAPABILITY structure.
* @param[out] Condition the TWCC_xxx code if failed
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition) = 0;
/**
* Reset container back to default,
* @return true if success.
*/
virtual bool Reset() = 0;
protected:
/**
* Check to see if type is valid.
* @param[in] _unTWType type to check
* @return true if valid
*/
virtual bool isValidType(const TW_UINT16 _unTWType) = 0;
// END Pure Virtuals
////////////////////////////////////////////////////////////
/**
* @}
*/
public:
/**
* Return the size in bytes of the TWAIN type.
* @param[in] _TWType the type to retrieve the size of.
* @return the number of bytes of type.
*/
unsigned int getTWTYSize(TW_UINT16 _TWType);
/**
* checks m_nMSG_QUERYSUPPORT to see if the operation in _unMsg is allowed
* @param[in] _unMsg message to check.
* @return true if allowed.
*/
bool isOperationAllowed(const TW_UINT16 _unMsg);
/**
* Return a OR compasition of what messages are supported.
* @return messages supported.
*/
TW_INT32 getMSG_QUERYSUPPORT()
{
return m_nMSG_QUERYSUPPORT;
}
protected:
TW_UINT16 m_unCapID; /**< Capability ID */
TW_UINT16 m_unItemType; /**< Item TWTY_xxxx Type */
TW_UINT16 m_unGetType; /**< Prefered Containor TWON_xxxx Type. Used with MSG_GET */
TW_UINT16 m_unGetCurrentType; /**< Prefered Containor TWON_xxxx Type. Used with MSG_GETCURRENT */
TW_UINT16 m_unGetDefaultType; /**< Prefered Containor TWON_xxxx Type. Used with MSG_GETCURRENT */
int m_nCurrent; /**< Holds an index of the currently set value. An Index into the appropriate Vector array. */
int m_nDefault; /**< Holds an index of the default value. An Index into the appropriate Vector array. */
TW_INT32 m_nMSG_QUERYSUPPORT; /**< Holds the supported operations for this capability, all OR together. */
};
#endif // __CTWAINCONTAINER_H__

View File

@ -0,0 +1,340 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerBool.cpp
* bool Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CommonDS.h"
#include <algorithm>
CTWAINContainerBool::CTWAINContainerBool(const TW_UINT16 _unCapID,
const bool _bAPP2,
const TW_INT32 _nSupportedQueries /*=TWQC_ALL*/)
: CTWAINContainer(_unCapID, TWTY_BOOL, TWON_ENUMERATION, _nSupportedQueries)
{
m_bApp2 = _bAPP2;
}
CTWAINContainerBool::~CTWAINContainerBool()
{
}
TW_UINT16 CTWAINContainerBool::GetGetType(const TW_UINT16 _unMsg)
{
switch(_unMsg)
{
case MSG_GET:
return m_bApp2?m_unGetType:TWON_ONEVALUE;
break;
case MSG_GETCURRENT:
return m_unGetCurrentType;
break;
case MSG_GETDEFAULT:
return m_unGetDefaultType;
break;
default:
break;
}
return TWON_ONEVALUE;
}
TW_HANDLE CTWAINContainerBool::GetContainer(const TW_UINT16 _unMsg)
{
TW_HANDLE hContainer = 0;
if((MSG_GETCURRENT == _unMsg) ||
(MSG_GET == _unMsg && !m_bApp2) ||
(MSG_GETDEFAULT == _unMsg))
{
hContainer = _DSM_Alloc(sizeof(TW_ONEVALUE));
if(0 != hContainer)
{
TW_ONEVALUE* pCap = (TW_ONEVALUE*)_DSM_LockMemory(hContainer);
pCap->ItemType = TWTY_BOOL;
// If the Cap has been constrained the default may only be in the m_listBoolsDefault.
const bool bVal = ((MSG_GETDEFAULT == _unMsg)?m_listBoolsDefault[m_nDefault]:m_listBools[m_nCurrent])!=0;
pCap->Item = bVal?1:0;
_DSM_UnlockMemory(hContainer);
}
}
else if(MSG_GET == _unMsg)
{
hContainer = _DSM_Alloc((TW_UINT32)(sizeof(TW_ENUMERATION)-1 + (sizeof(TW_BOOL) * (m_listBools.size())))); // -1 because already contains 1 byte
if(0 != hContainer)
{
TW_ENUMERATION* pCap = (TW_ENUMERATION*)_DSM_LockMemory(hContainer);
pCap->ItemType = TWTY_BOOL;
pCap->NumItems = (TW_UINT32)m_listBools.size();
pCap->CurrentIndex = m_nCurrent;
//If the CAP has been constrained m_nDefault index might not point
// to the correct index and the index may not be valid. We need to
// find the value in the default list and see if we can find a match
// in the current list. If no match found then set to first index.
// see spec on twain.org Chap4 p73 Advanced Application Implementation |
// Capabilities | Constrained Capabilities and Message Responses | MSG_SET
const bool bVal = m_listBoolsDefault[m_nDefault]!=0;
int nIndex = getIndexForValue(bVal);
if(nIndex != -1)
{
pCap->DefaultIndex = nIndex;
}
else
{
// We use the first index. We could try transversing through the
// list and finding the closest match in value. But either way
// the application should not be using this value.
pCap->DefaultIndex = 0;
}
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
((TW_BOOL*)pCap->ItemList)[x] = m_listBools[x]?1:0;
}
_DSM_UnlockMemory(hContainer);
}
}
return hContainer;
}
bool CTWAINContainerBool::isValidType(const TW_UINT16 _unTWType)
{
return (TWTY_BOOL == _unTWType);
}
TW_INT16 CTWAINContainerBool::Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition)
{
TW_INT16 twrc = TWRC_SUCCESS;
Condition = TWCC_SUCCESS;
if(TWON_ONEVALUE == _pCap->ConType)
{
TW_ONEVALUE* pCap = (TW_ONEVALUE*)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
if(!SetCurrent((pCap->Item&0xFFFF)!=0))
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else if(TWON_ENUMERATION == _pCap->ConType)
{
TW_ENUMERATION* pCap = (TW_ENUMERATION*)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
int nNewCurrentIndex = pCap->CurrentIndex;
IntVector::iterator iter;
bool bListCleared = false; // We only want to crear the current list if we are passed
// valid data, and only clear it once through the loop of testing
bool bVal;
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
bVal = ((TW_BOOL*)pCap->ItemList)[x]!=0;
// only set the value if it exists in m_listBoolsDefault
iter = find(m_listBoolsDefault.begin(), m_listBoolsDefault.end(), (bVal?1:0));
if(iter != m_listBoolsDefault.end())
{
// We have valid data
if(!bListCleared)
{
// only clear the list if we have not done so already
m_listBools.clear();
bListCleared = true;
}
// only add it if it was not added already
iter = find(m_listBools.begin(), m_listBools.end(), (bVal?1:0));
if(iter == m_listBools.end())
{
m_listBools.push_back(bVal);
}
else
{
if(x < pCap->CurrentIndex)
{
nNewCurrentIndex--;
}
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
else
{
// if the index is below the current then we need to adjust what is going to be current
if(x < pCap->CurrentIndex)
{
nNewCurrentIndex--;
}
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
// If the list has been cleared then there was at at least some valid data
if(bListCleared)
{
if(nNewCurrentIndex >= 0 && nNewCurrentIndex < (int)(m_listBools.size()))
{
m_nCurrent = nNewCurrentIndex;
}
else
{
// the new current index is not in range
m_nCurrent = 0;
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
else
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
}
else // NOT isValidType(pCap->ItemType))
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else //bad container type
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
return twrc;
}
bool CTWAINContainerBool::Reset()
{
m_listBools.clear();
const int nSize = (int)(m_listBoolsDefault.size());
for(int x = 0; x < nSize; ++x)
{
m_listBools.push_back(m_listBoolsDefault[x]);
}
m_nCurrent = m_nDefault;
return true;
}
bool CTWAINContainerBool::GetCurrent(bool &_bVal)
{
if((m_nCurrent >= 0) && ((int)(m_listBools.size()) > m_nCurrent))
{
_bVal = m_listBools[m_nCurrent]!=0;
return true;
}
return false;
}
bool CTWAINContainerBool::GetDefault(bool &_bVal)
{
if((m_nDefault >= 0) && ((int)(m_listBoolsDefault.size()) > m_nDefault))
{
_bVal = m_listBoolsDefault[m_nDefault]!=0;
return true;
}
return false;
}
const IntVector &CTWAINContainerBool::GetSupported()
{
return m_listBools;
}
bool CTWAINContainerBool::Add(const bool _bAdd, bool _bDefault /*= false*/)
{
m_listBools.push_back(_bAdd);
m_listBoolsDefault.push_back(_bAdd);
if(m_nDefault == -1 || _bDefault)
{
m_nCurrent = (int)m_listBools.size()-1;
m_nDefault = (int)m_listBoolsDefault.size()-1;
}
return true;
}
bool CTWAINContainerBool::SetCurrent(bool _bCurr)
{
int nIdx = getIndexForValue(_bCurr);
if(nIdx < 0)
{
return false;
}
m_nCurrent = nIdx;
return true;
}
int CTWAINContainerBool::getIndexForValue(const bool _bVal)
{
const int nSize = (int)(m_listBools.size());
for(int x = 0; x < nSize; ++x)
{
if(_bVal == (m_listBools[x]!=0))
{
return x;
}
}
return -1;
}

View File

@ -0,0 +1,138 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerBool.h
* Fix32 Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINCONTAINERBOOL_H__
#define __CTWAINCONTAINERBOOL_H__
#include "TWAINContainer.h"
/**
* This class can be used for any Bool based TWAIN container.
*/
class CTWAINContainerBool : public CTWAINContainer
{
friend class CTWAIN_UI;
public:
/**
* Constructor.
* @param[in] _unCapID Capability ID
* @param[in] _unItemType TWAIN Type TWTY_xxxx being stored.
* @param[in] _unGetType TWON_xxxx container
* @param[in] _nSupportedQueries the supported querie types TWQC_xxxx
*/
CTWAINContainerBool(const TW_UINT16 _unCapID,
const bool _bAPP2,
const TW_INT32 _nSupportedQueries = TWQC_ALL);
virtual ~CTWAINContainerBool();
/**
* Return the TWON_xxxx containor type.
* @param[in] _MSG the MSG_GETxxxx get message.
* @return the containor type
*/
virtual TW_UINT16 GetGetType(const TW_UINT16 _unMsg);
virtual TW_HANDLE GetContainer(const TW_UINT16 _unMsg);
virtual TW_INT16 Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition);
virtual bool Reset();
// For float vals
/**
* Try to add a value for container. The first value added to a capabiltiy is set as the default and current value.
* @param[in] _flAdd the value to be added.
* @param[in] _bDefault if true explisitly sets this value to be the default and current.
* @return true if success.
*/
bool Add(const bool _blAdd, bool _bDefault = false);
/**
* Try to set the current value for container.
* The value must already be part of the container.
* @param[in] _flAdd the value to be set as current.
* @return true if success.
*/
bool SetCurrent(bool _blCurr);
/**
* Return the default value through _flVal if set.
* @param[out] _flVal set the default value on return.
* @return true if success.
*/
bool GetDefault(bool &_blVal);
/**
* Return the current value through _flVal if set.
* @param[out] _flVal set the current value on return.
* @return true if success.
*/
bool GetCurrent(bool &_bVal);
/**
* Return a vector of supported values.
* @return supported values.
*/
const IntVector &GetSupported();
/**
* Return the weather or not the value is supported by this capability.
* @param[in] _flVal the value to check to see if it is supported
* @return true is the _flVal is supported.
*/
bool isValueSupported(const bool _bVal) {return -1 != getIndexForValue(_bVal);}
/**
* Return the index in vector list for value.
* @param[in] _flVal value to search for.
* @return the index of value, or -1 if does not exist.
*/
int getIndexForValue(const bool _bVal);
protected:
/**
* Check to see if type is valid.
* @param[in] _unTWType type to check
* @return true if valid
*/
bool isValidType(const TW_UINT16 _unTWType);
IntVector m_listBools; /**< vector of valid container values. */
IntVector m_listBoolsDefault; /**< vector of valid container default values. */
bool m_bApp2;
};
#endif // __CTWAINCONTAINERBOOL_H__

View File

@ -0,0 +1,411 @@
/***************************************************************************
* Copyright <EFBFBD> 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerFix32.cpp
* Fix32 Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CommonDS.h"
#include <algorithm>
#include <float.h>
CTWAINContainerFix32::CTWAINContainerFix32(const TW_UINT16 _unCapID,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries/* = TWQC_ALL*/,
const TW_UINT16 _unGetCurrentType/* = TWON_ONEVALUE*/,
const TW_UINT16 _unGetDefaultType/* = TWON_ONEVALUE*/)
: CTWAINContainer(_unCapID, TWTY_FIX32, _unGetType, _nSupportedQueries,_unGetCurrentType,_unGetDefaultType)
{
}
CTWAINContainerFix32::~CTWAINContainerFix32()
{
}
TW_HANDLE CTWAINContainerFix32::GetContainer(const TW_UINT16 _unMsg)
{
TW_HANDLE hContainer = 0;
TW_UINT16 unGetType=TWON_ONEVALUE;
switch(_unMsg)
{
case MSG_GET:
unGetType = m_unGetType;
break;
case MSG_GETCURRENT:
unGetType = m_unGetCurrentType;
break;
case MSG_GETDEFAULT:
unGetType = m_unGetDefaultType;
break;
}
switch(unGetType)
{
default:
case TWON_ONEVALUE:
{
hContainer = _DSM_Alloc(sizeof(TW_ONEVALUE_FIX32));
if(0 != hContainer)
{
pTW_ONEVALUE_FIX32 pCap = (pTW_ONEVALUE_FIX32)_DSM_LockMemory(hContainer);
pCap->ItemType = TWTY_FIX32;
// If the Cap has been constrained the default may only be in the m_listFloatsDefault.
const float flVal = (MSG_GETDEFAULT == _unMsg)?m_listFloatsDefault[m_nDefault]:m_listFloats[m_nCurrent];
pCap->Item = FloatToFIX32(flVal);
_DSM_UnlockMemory(hContainer);
}
}
break;
case TWON_ENUMERATION:
{
hContainer = _DSM_Alloc(sizeof(TW_ENUMERATION_FIX32) + (sizeof(TW_FIX32) * (m_listFloats.size()-1))); // -1 because already contains 1 element
if(0 != hContainer)
{
pTW_ENUMERATION_FIX32 pCap = (pTW_ENUMERATION_FIX32)_DSM_LockMemory(hContainer);
pCap->ItemType = TWTY_FIX32;
pCap->NumItems = (TW_UINT32)m_listFloats.size();
pCap->CurrentIndex = m_nCurrent;
//If the CAP has been constrained m_nDefault index might not point
// to the correct index and the index may not be valid. We need to
// find the value in the default list and see if we can find a match
// in the current list. If no match found then set to first index.
// see spec on twain.org Chap4 p73 Advanced Application Implementation |
// Capabilities | Constrained Capabilities and Message Responses | MSG_SET
const float flVal = m_listFloatsDefault[m_nDefault];
int nIndex = getIndexForValue(flVal);
if(nIndex != -1)
{
pCap->DefaultIndex = nIndex;
}
else
{
// We use the first index. We could try transversing through the
// list and finding the closest match in value. But either way
// the application should not be using this value.
pCap->DefaultIndex = 0;
}
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
pCap->ItemList[x] = FloatToFIX32(m_listFloats[x]);
}
_DSM_UnlockMemory(hContainer);
}
}
break;
case TWON_ARRAY:
{
hContainer = _DSM_Alloc(sizeof(TW_ARRAY_FIX32) + (sizeof(TW_FIX32) * (m_listFloats.size()-1))); // -1 because a TW_ARRAY_FIX32 already includes 1 element
if(0 != hContainer)
{
pTW_ARRAY_FIX32 pCap = (pTW_ARRAY_FIX32)_DSM_LockMemory(hContainer);
pCap->ItemType = m_unItemType;
pCap->NumItems = (TW_UINT32)m_listFloats.size();
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
pCap->ItemList[x] = FloatToFIX32(m_listFloats[x]);
}
_DSM_UnlockMemory(hContainer);
}
}
}
return hContainer;
}
bool CTWAINContainerFix32::isValidType(const TW_UINT16 _unTWType)
{
bool bret = false;
if(TWTY_FIX32 == _unTWType)
{
bret = true;
}
return bret;
}
TW_INT16 CTWAINContainerFix32::Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition)
{
TW_INT16 twrc = TWRC_SUCCESS;
Condition = TWCC_SUCCESS;
if(TWON_ONEVALUE == _pCap->ConType)
{
pTW_ONEVALUE_FIX32 pCap = (pTW_ONEVALUE_FIX32)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
float flVal = FIX32ToFloat(pCap->Item);
switch(m_unGetType)
{
case TWON_ONEVALUE:
{
m_listFloats.clear();
m_listFloats.push_back(flVal);
m_nCurrent = 0;
}
break;
case TWON_ENUMERATION:
{
int nVal = -1;
if((nVal = getIndexForValue(flVal)) >= 0)
{
m_nCurrent = nVal;
}
else
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
}
break;
//case TWON_ARRAY:
//break;
//case TWON_RANGE:
//break;
default:
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
break;
}
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else if(TWON_ENUMERATION == _pCap->ConType)
{
pTW_ENUMERATION_FIX32 pCap = (pTW_ENUMERATION_FIX32)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
int nNewCurrentIndex = pCap->CurrentIndex;
FloatVector::iterator iter;
bool bListCleared = false; // We only want to crear the current list if we are passed
// valid data, and only clear it once through the loop of testing
float flVal;
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
flVal = FIX32ToFloat(pCap->ItemList[x]);
// only set the value if it exists in m_listFloatsDefault
iter = find(m_listFloatsDefault.begin(), m_listFloatsDefault.end(), flVal);
if(iter != m_listFloatsDefault.end())
{
// We have valid data
if(!bListCleared)
{
// only clear the list if we have not done so already
m_listFloats.clear();
bListCleared = true;
}
// only add it if it was not added already
iter = find(m_listFloats.begin(), m_listFloats.end(), flVal);
if(iter == m_listFloats.end())
{
m_listFloats.push_back(flVal);
}
else
{
if(x < pCap->CurrentIndex)
{
nNewCurrentIndex--;
}
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
else
{
// if the index is below the current then we need to adjust what is going to be current
if(x < pCap->CurrentIndex)
{
nNewCurrentIndex--;
}
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
// If the list has been cleared then there was at at least some valid data
if(bListCleared)
{
if(nNewCurrentIndex >= 0 && nNewCurrentIndex < (int)(m_listFloats.size()))
{
m_nCurrent = nNewCurrentIndex;
}
else
{
// the new current index is not in range
m_nCurrent = 0;
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
else
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
}
else // NOT isValidType(pCap->ItemType))
{
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else //bad container type
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
return twrc;
}
bool CTWAINContainerFix32::Reset()
{
m_nCurrent = m_nDefault;
m_listFloats.clear();
const int nSize = (int)(m_listFloatsDefault.size());
for(int x = 0; x < nSize; ++x)
{
m_listFloats.push_back(m_listFloatsDefault[x]);
}
return true;
}
bool CTWAINContainerFix32::GetCurrent(float &_flVal)
{
bool bret = false;
if((m_nCurrent >= 0) && ((int)(m_listFloats.size()) > m_nCurrent))
{
_flVal = m_listFloats[m_nCurrent];
bret = true;
}
return bret;
}
bool CTWAINContainerFix32::GetDefault(float &_flVal)
{
bool bret = false;
if((m_nDefault >= 0) && ((int)(m_listFloatsDefault.size()) > m_nDefault))
{
_flVal = m_listFloatsDefault[m_nDefault];
bret = true;
}
return bret;
}
const FloatVector &CTWAINContainerFix32::GetSupported()
{
return m_listFloats;
}
bool CTWAINContainerFix32::Add(const float _flAdd, bool _bDefault /*= false*/)
{
m_listFloats.push_back(_flAdd);
m_listFloatsDefault.push_back(_flAdd);
if(m_nDefault == -1 || _bDefault)
{
m_nCurrent = m_nDefault = getIndexForValue(_flAdd);
}
return true;
}
bool CTWAINContainerFix32::SetCurrent(float _flCurr)
{
if(TWON_ONEVALUE == m_unGetType)//check before call
{
m_listFloats.clear();
m_listFloats.push_back(_flCurr);
m_nCurrent = 0;
}
else
{
int nIdx = getIndexForValue(_flCurr);
if(nIdx < 0)
{
return false;
}
m_nCurrent = nIdx;
}
return true;
}
int CTWAINContainerFix32::getIndexForValue(const float _flVal)
{
int ret = -1;
const int nSize = (int)(m_listFloats.size());
for(int x = 0; x < nSize; ++x)
{
if(_flVal >= m_listFloats[x]-1.0/65536.0 && _flVal <= m_listFloats[x]+1.0/65536.0) //@TODO remove float comparison
{
ret = x;
break;
}
}
return ret;
}

View File

@ -0,0 +1,137 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerFix32.h
* Fix32 Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINCONTAINERFIX32_H__
#define __CTWAINCONTAINERFIX32_H__
#include "TWAINContainer.h"
/**
* This class can be used for any Fix32 based TWAIN container.
* All values are stored internally as 1/1000th of an inch. They are converted
* as necessary when TWAIN containers are created. Any direct access will require
* the caller to do their own conversion.
*/
class CTWAINContainerFix32 : public CTWAINContainer
{
friend class CTWAIN_UI;
public:
/**
* Constructor.
* @param[in] _unCapID Capability ID
* @param[in] _unItemType TWAIN Type TWTY_xxxx being stored.
* @param[in] _unGetType TWON_xxxx container
* @param[in] _nSupportedQueries the supported querie types TWQC_xxxx
*/
CTWAINContainerFix32(const TW_UINT16 _unCapID,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries = TWQC_ALL,
const TW_UINT16 _unGetCurrentType = TWON_ONEVALUE,
const TW_UINT16 _unGetDefaultType = TWON_ONEVALUE);
virtual ~CTWAINContainerFix32();
virtual TW_HANDLE GetContainer(const TW_UINT16 _unMsg);
virtual TW_INT16 Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition);
virtual bool Reset();
// For float vals
/**
* Try to add a value for container. The first value added to a capabiltiy is set as the default and current value.
* @param[in] _flAdd the value to be added.
* @param[in] _bDefault if true explisitly sets this value to be the default and current.
* @return true if success.
*/
bool Add(const float _flAdd, bool _bDefault = false);
/**
* Try to set the current value for container.
* The value must already be part of the container.
* @param[in] _flAdd the value to be set as current.
* @return true if success.
*/
bool SetCurrent(float _flCurr);
/**
* Return the default value through _flVal if set.
* @param[out] _flVal set the default value on return.
* @return true if success.
*/
bool GetDefault(float &_flVal);
/**
* Return the current value through _flVal if set.
* @param[out] _flVal set the current value on return.
* @return true if success.
*/
bool GetCurrent(float &_flVal);
/**
* Return a vector of supported values.
* @return supported values.
*/
const FloatVector &GetSupported();
/**
* Return the weather or not the value is supported by this capability.
* @param[in] _flVal the value to check to see if it is supported
* @return true is the _flVal is supported.
*/
bool isValueSupported(const float _flVal) {return -1 != getIndexForValue(_flVal);}
/**
* Return the index in vector list for value.
* @param[in] _flVal value to search for.
* @return the index of value, or -1 if does not exist.
*/
int getIndexForValue(const float _flVal);
protected:
/**
* Check to see if type is valid.
* @param[in] _unTWType type to check
* @return true if valid
*/
bool isValidType(const TW_UINT16 _unTWType);
FloatVector m_listFloats; /**< vector of valid container values. */
FloatVector m_listFloatsDefault; /**< vector of valid container default values. */
};
#endif // __CTWAINCONTAINERFIX32_H__

View File

@ -0,0 +1,342 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerFix32.cpp
* Fix32 Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CommonDS.h"
#include <algorithm>
CTWAINContainerFix32Range::CTWAINContainerFix32Range(const TW_UINT16 _unCapID,
const FLOAT_RANGE _InitRange,
const TW_INT32 _nSupportedQueries /*=TWQC_ALL*/)
: CTWAINContainer(_unCapID, TWTY_FIX32, TWON_RANGE, _nSupportedQueries)
{
m_Cur = m_Def = _InitRange;
}
CTWAINContainerFix32Range::~CTWAINContainerFix32Range()
{
}
TW_HANDLE CTWAINContainerFix32Range::GetContainer(const TW_UINT16 _unMsg)
{
TW_HANDLE hContainer = 0;
if((MSG_GETCURRENT == _unMsg) ||
(MSG_GETDEFAULT == _unMsg))
{
hContainer = _DSM_Alloc(sizeof(TW_ONEVALUE_FIX32));
if(0 != hContainer)
{
pTW_ONEVALUE_FIX32 pCap = (pTW_ONEVALUE_FIX32)_DSM_LockMemory(hContainer);
pCap->ItemType = TWTY_FIX32;
const float flVal = (MSG_GETDEFAULT == _unMsg)?m_Def.fCurrentValue:m_Cur.fCurrentValue;
pCap->Item = FloatToFIX32(flVal);
_DSM_UnlockMemory(hContainer);
}
}
else if(MSG_GET == _unMsg)
{
hContainer = _DSM_Alloc(sizeof(TW_RANGE_FIX32));
if(0 != hContainer)
{
pTW_RANGE_FIX32 pCap = (pTW_RANGE_FIX32)_DSM_LockMemory(hContainer);
pCap->ItemType = TWTY_FIX32;
pCap->CurrentValue = FloatToFIX32(m_Cur.fCurrentValue);
pCap->DefaultValue = FloatToFIX32(m_Def.fCurrentValue);
pCap->MaxValue = FloatToFIX32(m_Cur.fMaxValue);
pCap->MinValue = FloatToFIX32(m_Cur.fMinValue);
pCap->StepSize = FloatToFIX32(m_Cur.fStepSize);
_DSM_UnlockMemory(hContainer);
}
}
return hContainer;
}
bool CTWAINContainerFix32Range::isValidType(const TW_UINT16 _unTWType)
{
return TWTY_FIX32 == _unTWType;
}
TW_INT16 CTWAINContainerFix32Range::Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition)
{
TW_INT16 twrc = TWRC_SUCCESS;
Condition = TWCC_SUCCESS;
if(TWON_ONEVALUE == _pCap->ConType)
{
pTW_ONEVALUE_FIX32 pCap = (pTW_ONEVALUE_FIX32)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
float flVal = FIX32ToFloat(pCap->Item);
int nRes = IsInRange(m_Cur,flVal);
if(nRes!=0)
{
float flTemp = flVal;
nRes = IsInRange(m_Def,flTemp);
if(nRes<0)
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
else if(nRes==0)
{
m_Cur = m_Def;
m_Cur.fCurrentValue = flTemp;
}
else if(nRes>0)
{
if(flTemp != flVal)
{
m_Cur = m_Def;
}
m_Cur.fCurrentValue = flTemp;
}
twrc = TWRC_CHECKSTATUS;
}
else
{
m_Cur.fCurrentValue = flVal;
}
}
else
{
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else if(TWON_RANGE == _pCap->ConType)
{
pTW_RANGE_FIX32 pCap = (pTW_RANGE_FIX32)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
FLOAT_RANGE fNewRange;
fNewRange.fCurrentValue = FIX32ToFloat(pCap->CurrentValue);
fNewRange.fMaxValue = FIX32ToFloat(pCap->MaxValue);
fNewRange.fMinValue = FIX32ToFloat(pCap->MinValue);
fNewRange.fStepSize = FIX32ToFloat(pCap->StepSize);
int nRes = 0;
if(fNewRange.fMinValue>fNewRange.fMaxValue ||
fNewRange.fCurrentValue<fNewRange.fMinValue || fNewRange.fCurrentValue>fNewRange.fMaxValue ||
fNewRange.fStepSize <=0 ||
(fNewRange.fMinValue!=fNewRange.fMaxValue &&
(((int)((fNewRange.fMaxValue-fNewRange.fMinValue)/fNewRange.fStepSize))*fNewRange.fStepSize+fNewRange.fMinValue)!=fNewRange.fMaxValue) ||
m_Def.fStepSize>fNewRange.fStepSize ||
(fNewRange.fMinValue!=fNewRange.fMaxValue && fNewRange.fMinValue+fNewRange.fStepSize>fNewRange.fMaxValue))
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
if(twrc != TWRC_FAILURE)
{
nRes = IsInRange(m_Def,fNewRange.fCurrentValue);
if(nRes<0)
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
else if(nRes>0)
{
twrc = TWRC_CHECKSTATUS;
}
}
if(twrc != TWRC_FAILURE)
{
nRes = IsInRange(m_Def,fNewRange.fMinValue);
if(nRes<0)
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
else if(nRes>0)
{
twrc = TWRC_CHECKSTATUS;
}
}
if(twrc != TWRC_FAILURE)
{
nRes = IsInRange(m_Def,fNewRange.fMaxValue);
if(nRes<0)
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
else if(nRes>0)
{
twrc = TWRC_CHECKSTATUS;
}
}
if(twrc != TWRC_FAILURE)
{
int nIdx = (int)(fNewRange.fStepSize/m_Def.fStepSize);
if(nIdx*m_Def.fStepSize != fNewRange.fStepSize)
{
twrc = TWRC_CHECKSTATUS;
}
if(((nIdx+0.5)*m_Def.fStepSize)>fNewRange.fStepSize)
{
fNewRange.fStepSize = nIdx*m_Def.fStepSize;
}
else
{
fNewRange.fStepSize = (nIdx+1)*m_Def.fStepSize;
}
}
if(twrc != TWRC_FAILURE)
{
if(IsInRange(fNewRange,fNewRange.fCurrentValue)<0)
{
twrc = TWRC_FAILURE;
}
}
if(twrc != TWRC_FAILURE)
{
fNewRange.fMaxValue = ((int)((fNewRange.fMaxValue - fNewRange.fMinValue)/fNewRange.fStepSize))*fNewRange.fStepSize + fNewRange.fMinValue;
m_Cur = fNewRange;
}
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else //bad container type
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
return twrc;
}
bool CTWAINContainerFix32Range::Reset()
{
m_Cur = m_Def;
return true;
}
bool CTWAINContainerFix32Range::GetCurrent(float &_flVal)
{
_flVal = m_Cur.fCurrentValue;
return true;
}
bool CTWAINContainerFix32Range::SetCurrent(float _flVal)
{
int nRes = IsInRange(m_Cur,_flVal);
if(nRes!=0)
{
float flTemp = _flVal;
nRes = IsInRange(m_Def,flTemp);
if(nRes<0)
{
return false;
}
else if(nRes==0)
{
m_Cur = m_Def;
m_Cur.fCurrentValue = _flVal;
}
else if(nRes>0)
{
if(flTemp != _flVal)
{
m_Cur = m_Def;
}
m_Cur.fCurrentValue = flTemp;
}
}
else
{
m_Cur.fCurrentValue = _flVal;
}
return true;
}
bool CTWAINContainerFix32Range::GetDefault(float &_flVal)
{
_flVal = m_Def.fCurrentValue;
return true;
}
void CTWAINContainerFix32Range::GetMinMaxStep(float &_flMinVal,float &_flMaxVal,float &_flStepVal)
{
_flMinVal=m_Cur.fMinValue;
_flMaxVal=m_Cur.fMaxValue;
_flStepVal=m_Cur.fStepSize;
}
int CTWAINContainerFix32Range::IsInRange(FLOAT_RANGE _Range, float &_flVal)
{
if(_flVal<_Range.fMinValue || _flVal>_Range.fMaxValue)
{
return -1;
}
if(_Range.fMinValue == _Range.fMaxValue && _flVal!=_Range.fMinValue)//@TODO remove flaot comparision
{
return -1;
}
int nIdx = (int)((_flVal-_Range.fMinValue)/_Range.fStepSize);
float fTemp = nIdx*_Range.fStepSize+_Range.fMinValue;
if(fTemp==_flVal)//@TODO remove float comparision
{
return 0;
}
if((_flVal+_Range.fStepSize/2)>fTemp)
{
_flVal = fTemp;
}
else
{
_flVal = fTemp-_Range.fStepSize;
}
return 1;
}

View File

@ -0,0 +1,109 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerFix32.h
* Fix32 Range Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINContainerFix32RangeRANGE_H__
#define __CTWAINContainerFix32RangeRANGE_H__
#include "TWAINContainer.h"
typedef struct {
float fMinValue; /* Starting value in the range. */
float fMaxValue; /* Final value in the range. */
float fStepSize; /* Increment from MinValue to MaxValue. */
float fCurrentValue; /* The value that is currently in effect. */
} FLOAT_RANGE;
/**
* This class can be used for any Fix32 based TWAIN container.
*/
class CTWAINContainerFix32Range : public CTWAINContainer
{
friend class CTWAIN_UI;
public:
/**
* Constructor.
* @param[in] _unCapID Capability ID
* @param[in] _unItemType TWAIN Type TWTY_xxxx being stored.
* @param[in] _unGetType TWON_xxxx container
* @param[in] _nSupportedQueries the supported querie types TWQC_xxxx
*/
CTWAINContainerFix32Range(const TW_UINT16 _unCapID,
const FLOAT_RANGE _InitRange,
const TW_INT32 _nSupportedQueries = TWQC_ALL);
virtual ~CTWAINContainerFix32Range();
virtual TW_HANDLE GetContainer(const TW_UINT16 _unMsg);
virtual TW_INT16 Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition);
virtual bool Reset();
/**
* Return the default value through _flVal if set.
* @param[out] _flVal set the default value on return.
* @return true if success.
*/
bool GetDefault(float &_flVal);
/**
* Return the current value through _flVal if set.
* @param[out] _flVal set the current value on return.
* @return true if success.
*/
bool GetCurrent(float &_flVal);
/**
* Set the current value through _flVal.
* @param[in] _flVal the current value.
* @return true if success.
*/
bool SetCurrent(float _flVal);
void GetMinMaxStep(float &_flMinVal,float &_flMaxVal,float &_flStepVal);
int IsInRange(FLOAT_RANGE _Range, float &_flVal);
protected:
/**
* Check to see if type is valid.
* @param[in] _unTWType type to check
* @return true if valid
*/
bool isValidType(const TW_UINT16 _unTWType);
FLOAT_RANGE m_Cur;
FLOAT_RANGE m_Def;
};
#endif // __CTWAINContainerFix32RangeRANGE_H__

View File

@ -0,0 +1,643 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerFrame.cpp
* Frame Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CommonDS.h"
#include <algorithm>
InternalFrame::InternalFrame()
{
nLeft = 0;
nTop = 0;
nRight = 0;
nBottom = 0;
}
InternalFrame::InternalFrame(int left, int top, int right, int bottom)
{
nLeft = left;
nTop = top;
nRight = right;
nBottom = bottom;
}
InternalFrame::InternalFrame(const TW_FRAME twFrame, int fromUnits, float Xresolution, float Yresolution)
{
nLeft = int(ConvertUnits(FIX32ToFloat(twFrame.Left), fromUnits, TWUN_PIXELS, Xresolution));
nTop = int(ConvertUnits(FIX32ToFloat(twFrame.Top), fromUnits, TWUN_PIXELS, Yresolution));
nRight = int(ConvertUnits(FIX32ToFloat(twFrame.Right), fromUnits, TWUN_PIXELS, Xresolution));
nBottom = int(ConvertUnits(FIX32ToFloat(twFrame.Bottom), fromUnits, TWUN_PIXELS, Yresolution));
}
InternalFrame::InternalFrame(const TW_UINT16 ss)
{
//see which supported size they want the dimensions of
switch(ss)
{
case TWSS_USLEDGER:
SetFrame( 0, 0, 11.0f, 17.0f, TWUN_INCHES, 100, 100);
break;
case TWSS_USLEGAL:
SetFrame( 0, 0, 8.5f, 14.0f, TWUN_INCHES, 100, 100);
break;
case TWSS_USLETTER:
SetFrame( 0, 0, 8.5f, 11.0f, TWUN_INCHES, 100, 100);
break;
case TWSS_USEXECUTIVE:
SetFrame( 0, 0, 7.25f, 10.5f, TWUN_INCHES, 100, 100);
break;
case TWSS_USSTATEMENT:
SetFrame( 0, 0, 5.5f, 8.5f, TWUN_INCHES, 100, 100);
break;
case TWSS_BUSINESSCARD:
SetFrame( 0, 0, 3.5f, 2.0f, TWUN_INCHES, 100, 100);
break;
case TWSS_4A0:
SetFrame( 0, 0,168.2f, 237.8f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_2A0:
SetFrame( 0, 0,118.9f, 168.2f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A0:
SetFrame( 0, 0, 84.1f, 118.9f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A1:
SetFrame( 0, 0, 59.4f, 84.1f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A2:
SetFrame( 0, 0, 42.0f, 59.4f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A3:
SetFrame( 0, 0, 29.7f, 42.0f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A4: // case TWSS_A4LETTER:
SetFrame( 0, 0, 21.0f, 29.7f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A5:
SetFrame( 0, 0, 14.8f, 21.0f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A6:
SetFrame( 0, 0, 10.5f, 14.8f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A7:
SetFrame( 0, 0, 7.4f, 10.5f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A8:
SetFrame( 0, 0, 5.2f, 7.4f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A9:
SetFrame( 0, 0, 3.7f, 5.2f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_A10:
SetFrame( 0, 0, 2.6f, 3.7f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB0:
SetFrame( 0, 0,100.0f, 141.4f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB1:
SetFrame( 0, 0, 70.7f, 100.0f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB2:
SetFrame( 0, 0, 50.0f, 70.7f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB3: // case TWSS_B3:
SetFrame( 0, 0, 35.3f, 50.0f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB4: // case TWSS_B4:
SetFrame( 0, 0, 25.0f, 35.4f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB5:
SetFrame( 0, 0, 17.6f, 25.0f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB6: // case TWSS_B6:
SetFrame( 0, 0, 12.5f, 17.6f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB7:
SetFrame( 0, 0, 8.8f, 12.5f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB8:
SetFrame( 0, 0, 6.2f, 8.8f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB9:
SetFrame( 0, 0, 4.4f, 6.2f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_ISOB10:
SetFrame( 0, 0, 3.1f, 4.4f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB0:
SetFrame( 0, 0,103.0f, 145.6f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB1:
SetFrame( 0, 0, 72.8f, 103.0f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB2:
SetFrame( 0, 0, 51.5f, 72.8f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB3:
SetFrame( 0, 0, 36.4f, 51.5f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB4:
SetFrame( 0, 0, 25.7f, 36.4f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB5: // case TWSS_B5LETTER:
SetFrame( 0, 0, 18.2f, 25.7f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB6:
SetFrame( 0, 0, 12.8f, 18.2f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB7:
SetFrame( 0, 0, 9.1f, 12.8f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB8:
SetFrame( 0, 0, 6.4f, 9.1f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB9:
SetFrame( 0, 0, 4.5f, 6.4f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_JISB10:
SetFrame( 0, 0, 3.2f, 4.5f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C0:
SetFrame( 0, 0, 91.7f, 129.7f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C1:
SetFrame( 0, 0, 64.8f, 91.7f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C2:
SetFrame( 0, 0, 45.8f, 64.8f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C3:
SetFrame( 0, 0, 32.4f, 45.8f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C4:
SetFrame( 0, 0, 22.9f, 32.4f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C5:
SetFrame( 0, 0, 16.2f, 22.9f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C6:
SetFrame( 0, 0, 11.4f, 16.2f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C7:
SetFrame( 0, 0, 8.1f, 11.4f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C8:
SetFrame( 0, 0, 5.7f, 8.1f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C9:
SetFrame( 0, 0, 4.0f, 5.7f, TWUN_CENTIMETERS, 100, 100);
break;
case TWSS_C10:
SetFrame( 0, 0, 2.8f, 4.0f, TWUN_CENTIMETERS, 100, 100);
break;
default:
nLeft = nTop = nRight = nBottom = 0;
break;
}
}
InternalFrame* InternalFrame::SetFrame(float left, float top, float right, float bottom, int fromUnits, float Xresolution, float Yresolution)
{
nLeft = int(ConvertUnits(left, fromUnits, TWUN_PIXELS, Xresolution));
nTop = int(ConvertUnits(top, fromUnits, TWUN_PIXELS, Yresolution));
nRight = int(ConvertUnits(right, fromUnits, TWUN_PIXELS, Xresolution));
nBottom = int(ConvertUnits(bottom, fromUnits, TWUN_PIXELS, Yresolution));
return this;
}
TW_FRAME InternalFrame::AsTW_FRAME(int toUnits, float Xresolution, float Yresolution)
{
TW_FRAME frame;
frame.Left = FloatToFIX32(ConvertUnits(float(nLeft), TWUN_PIXELS, toUnits, Xresolution));
frame.Top = FloatToFIX32(ConvertUnits(float(nTop), TWUN_PIXELS, toUnits, Yresolution));
frame.Right = FloatToFIX32(ConvertUnits(float(nRight), TWUN_PIXELS, toUnits, Xresolution));
frame.Bottom = FloatToFIX32(ConvertUnits(float(nBottom), TWUN_PIXELS, toUnits, Yresolution));
return frame;
}
bool operator== (const InternalFrame& _frame1, const InternalFrame& _frame2)
{
if((2> abs((int)_frame1.nLeft - (int)_frame2.nLeft) ) &&
(2> abs((int)_frame1.nTop - (int)_frame2.nTop) ) &&
(2> abs((int)_frame1.nRight - (int)_frame2.nRight) ) &&
(2> abs((int)_frame1.nBottom - (int)_frame2.nBottom)) )
{
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
CTWAINContainerFrame::CTWAINContainerFrame(const TW_UINT16 _unCapID,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries/* = TWQC_ALL*/,
const TW_UINT16 _unGetCurrentType/* = TWON_ONEVALUE*/,
const TW_UINT16 _unGetDefaultType/* = TWON_ONEVALUE*/)
: CTWAINContainer(_unCapID, TWTY_FRAME, _unGetType, _nSupportedQueries,_unGetCurrentType,_unGetDefaultType)
{
m_Unit = TWUN_PIXELS;
m_Xres = 100;
m_Yres = 100;
}
CTWAINContainerFrame::~CTWAINContainerFrame()
{
}
TW_HANDLE CTWAINContainerFrame::GetContainer(const TW_UINT16 _unMsg)
{
TW_HANDLE hContainer = 0;
TW_UINT16 unGetType=TWON_ONEVALUE;
switch(_unMsg)
{
case MSG_GET:
unGetType = m_unGetType;
break;
case MSG_GETCURRENT:
unGetType = m_unGetCurrentType;
break;
case MSG_GETDEFAULT:
unGetType = m_unGetDefaultType;
break;
}
switch(unGetType)
{
default:
case TWON_ONEVALUE:
{
hContainer = _DSM_Alloc(sizeof(TW_ONEVALUE_FRAME));
if(0 != hContainer)
{
pTW_ONEVALUE_FRAME pCap = (pTW_ONEVALUE_FRAME)_DSM_LockMemory(hContainer);
// If the Cap has been constrained the default may only be in the defaultlist.
InternalFrame frame = (MSG_GETDEFAULT == _unMsg)?m_listFramesDefault[m_nDefault]:m_listFrames[m_nCurrent];
pCap->Item = frame.AsTW_FRAME(m_Unit, m_Xres, m_Yres);
pCap->ItemType = m_unItemType;
_DSM_UnlockMemory(hContainer);
}
}
break;
case TWON_ENUMERATION:
{
hContainer = _DSM_Alloc(sizeof(TW_ENUMERATION_FRAME) + (sizeof(TW_FRAME) * (m_listFrames.size()-1))); // -1 because already contains 1 element
if(0 != hContainer)
{
pTW_ENUMERATION_FRAME pCap = (pTW_ENUMERATION_FRAME)_DSM_LockMemory(hContainer);
pCap->ItemType = m_unItemType;
pCap->NumItems = (TW_UINT32)m_listFrames.size();
pCap->CurrentIndex = m_nCurrent;
//If the CAP has been constrained m_nDefault index might not point
// to the correct index and the index may not be valid. We need to
// find the value in the default list and see if we can find a match
// in the current list. If no match found then set to first index.
// see spec on twain.org Chap4 p73 Advanced Application Implementation |
// Capabilities | Constrained Capabilities and Message Responses | MSG_SET
const InternalFrame frame = m_listFramesDefault[m_nDefault];
int nIndex = getIndexForValue(frame);
if(nIndex != -1)
{
pCap->DefaultIndex = nIndex;
}
else
{
// We use the first index. We could try transversing through the
// list and finding the closest match in value. But either way
// the application should not be using this value.
pCap->DefaultIndex = 0;
}
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
pCap->ItemList[x] = m_listFrames[x].AsTW_FRAME(m_Unit, m_Xres, m_Yres);
}
_DSM_UnlockMemory(hContainer);
}
}
break;
case TWON_ARRAY:
{
hContainer = _DSM_Alloc(sizeof(TW_ARRAY_FRAME) + (sizeof(TW_FRAME) * (m_listFrames.size()-1))); // -1 because a TW_ARRAY_FIX32 already includes 1 element
if(0 != hContainer)
{
pTW_ARRAY_FRAME pCap = (pTW_ARRAY_FRAME)_DSM_LockMemory(hContainer);
pCap->ItemType = m_unItemType;
pCap->NumItems = (TW_UINT32)m_listFrames.size();
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
pCap->ItemList[x] = m_listFrames[x].AsTW_FRAME(m_Unit, m_Xres, m_Yres);
}
_DSM_UnlockMemory(hContainer);
}
}
}// switch(unGetType)
return hContainer;
}
bool CTWAINContainerFrame::isValidType(const TW_UINT16 _unTWType)
{
bool bret = false;
if(TWTY_FRAME == _unTWType)
{
bret = true;
}
return bret;
}
TW_INT16 CTWAINContainerFrame::Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition)
{
// TW_FRAME can override the current and available list regardless if they
// are available in the default list.
TW_INT16 twrc = TWRC_SUCCESS;
Condition = TWCC_SUCCESS;
if(TWON_ONEVALUE == _pCap->ConType)
{
pTW_ONEVALUE_FRAME pCap = (pTW_ONEVALUE_FRAME)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
InternalFrame frame(pCap->Item, m_Unit, m_Xres, m_Yres);
switch(m_unGetType)
{
case TWON_ONEVALUE:
case TWON_ENUMERATION:
{
/// @todo check to see if frame is in range
Set(frame);
}
break;
/*
case TWON_ENUMERATION:
{
int nVal = -1;
if((nVal = getIndexForValue(frame)) >= 0)
{
m_nCurrent = nVal;
}
else
{
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
break;
*/
//case TWON_ARRAY:
//break;
//case TWON_RANGE:
//break;
default:
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
break;
}
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else if(TWON_ENUMERATION == _pCap->ConType)
{
pTW_ENUMERATION_FRAME pCap = (pTW_ENUMERATION_FRAME)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
m_nCurrent = pCap->CurrentIndex;
// We ignor trying to set the default. The default can not be changed from outside
FrameVector::iterator iter;
m_listFrames.clear();
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
InternalFrame frame(pCap->ItemList[x], m_Unit, m_Xres, m_Yres);
// Only add items that are within the range of the frame regardless what is in our m_listFramesDefault
// iter = find(m_listFramesDefault.begin(), m_listFramesDefault.end(), frame);
/// @todo check if value is within range
if(1)
{
m_listFrames.push_back(frame);
m_nCurrent = 0;
}
else
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
}
}
else // NOT isValidType(pCap->ItemType))
{
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else //bad container type
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
return twrc;
}
bool CTWAINContainerFrame::Set(const InternalFrame& _frame)
{
// Set is only called after the Frame has been initilized by calling Add
if(m_nDefault == -1)
{
assert(m_nDefault != -1);
return false;
}
m_listFrames.clear();
m_listFrames.push_back(_frame);
m_nCurrent = 0;
return true;
}
bool CTWAINContainerFrame::Reset()
{
m_nCurrent = m_nDefault;
m_listFrames.clear();
const int nSize = (int)(m_listFramesDefault.size());
for(int x = 0; x < nSize; ++x)
{
m_listFrames.push_back(m_listFramesDefault[x]);
}
return true;
}
bool CTWAINContainerFrame::GetCurrent(InternalFrame& _frame)
{
bool bret = false;
if(!(m_nMSG_QUERYSUPPORT & TWQC_GETCURRENT))
{
return false;
}
if((m_nCurrent >= 0) && ((int)(m_listFrames.size()) > m_nCurrent))
{
_frame = m_listFrames[m_nCurrent];
bret = true;
}
return bret;
}
bool CTWAINContainerFrame::GetDefault(InternalFrame& _frame)
{
bool bret = false;
if(!(m_nMSG_QUERYSUPPORT & TWQC_GETDEFAULT))
{
return false;
}
if((m_nDefault >= 0) && ((int)(m_listFramesDefault.size()) > m_nDefault))
{
_frame = m_listFramesDefault[m_nDefault];
bret = true;
}
return bret;
}
const FrameVector &CTWAINContainerFrame::GetSupported()
{
return m_listFrames;
}
bool CTWAINContainerFrame::Add(const int _nLeft, const int _nTop, const int _nRight, const int _nBottom, bool _bDefault /*= false*/)
{
InternalFrame frame(_nLeft, _nTop, _nRight, _nBottom);
return Add(frame, _bDefault);
}
bool CTWAINContainerFrame::Add(const InternalFrame& _frame, bool _bDefault /*= false*/)
{
m_listFrames.push_back(_frame);
m_listFramesDefault.push_back(_frame);
if(m_nDefault == -1 || _bDefault)
{
m_nCurrent = m_nDefault = getIndexForValue(_frame);
}
return true;
}
bool CTWAINContainerFrame::SetCurrent(const int _nLeft, const int _nTop, const int _nRight, const int _nBottom)
{
InternalFrame frame(_nLeft, _nTop, _nRight, _nBottom);
return SetCurrent(frame);
}
bool CTWAINContainerFrame::SetCurrent(const InternalFrame& _frame)
{
int nIdx = getIndexForValue(_frame);
if(nIdx < 0)
{
return false;
}
m_nCurrent = nIdx;
return true;
}
int CTWAINContainerFrame::getIndexForValue(const InternalFrame& _frame)
{
int ret = -1;
const int nSize = (int)(m_listFrames.size());
for(int x = 0; x < nSize; ++x)
{
if(_frame == m_listFrames[x])
{
ret = x;
break;
}
}
return ret;
}
void CTWAINContainerFrame::setCurrentUnits(int Unit, float Xres, float Yres)
{
m_Unit = Unit;
m_Xres = Xres;
m_Yres = Yres;
}

View File

@ -0,0 +1,255 @@
/***************************************************************************
* Copyright 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerFrame.h
* Frame Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINCONTAINERFRAME_H__
#define __CTWAINCONTAINERFRAME_H__
#include "TWAINContainer.h"
/**
* This structure is used to hold the values for a frame.
* All values are stored using internal units of 1/1000th of an inch
*/
struct InternalFrame
{
int nLeft; /**< left */
int nTop; /**< top */
int nRight; /**< right */
int nBottom; /**< bottom */
/**
* Constructor
*/
InternalFrame();
/**
* Constructor
* @param[in] left Left
* @param[in] lop Top
* @param[in] right Right
* @param[in] bottom Bottom
*/
InternalFrame(int left, int top, int right, int bottom);
/**
* Constructor Convert to interanal from TW_FRAME
* @param[in] twFrame external value to convert.
* @param[in] fromUnits the units to convert to
* @param[in] Xresolution the X resolution
* @param[in] Yresolution the Y resolution
* @return true if success.
*/
InternalFrame(const TW_FRAME twFrame, int fromUnits, float Xresolution, float Yresolution);
/**
* create interanal frame from a SupportedSize
* @param[in] ss the CSupportedSize to create internal frame from
* @return the InternalFrame
*/
InternalFrame(const TW_UINT16 ss);
/**
* Convert interanal frame value to external TW_FRAME value converting the units
* @param[in] toUnits the units to convert to
* @param[in] Xresolution the X resolution
* @param[in] Yresolution the Y resolution
* @return the frame as a TW_FRAME
*/
TW_FRAME AsTW_FRAME(int toUnits, float Xresolution, float Yresolution);
protected:
/**
* Set the frame to interanal from external units
* @param[in] left Left
* @param[in] lop Top
* @param[in] right Right
* @param[in] bottom Bottom
* @param[in] fromUnits the units to convert to
* @param[in] Xresolution the X resolution
* @param[in] Yresolution the Y resolution
* @return true if success.
*/
InternalFrame * SetFrame(float left, float top, float right, float bottom, int fromUnits, float Xresolution, float Yresolution);
};
/**
* test if two frames are equal.
* @return true if equal.
*/
bool operator== (const InternalFrame& _frame1, const InternalFrame& _frame2);
/**
* Frame Vector
*/
typedef vector<InternalFrame> FrameVector;
/**
* This class can be used for any TW_FRAME based TWAIN container.
*
* All values are stored internally as 1/1000th of an inch. They are converted
* as necessary when TWAIN containers are created. Any direct access will require
* the caller to do their own conversion.
*/
class CTWAINContainerFrame : public CTWAINContainer
{
friend class CTWAIN_UI;
public:
/**
* Constructor.
* @param[in] _unCapID Capability ID
* @param[in] _unItemType TWAIN Type TWTY_xxxx being stored.
* @param[in] _unGetType TWON_xxxx container
* @param[in] _nSupportedQueries the supported querie types TWQC_xxxx
*/
CTWAINContainerFrame(const TW_UINT16 _unCapID,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries = TWQC_ALL,
const TW_UINT16 _unGetCurrentType = TWON_ONEVALUE,
const TW_UINT16 _unGetDefaultType = TWON_ONEVALUE);
virtual ~CTWAINContainerFrame();
virtual TW_HANDLE GetContainer(const TW_UINT16 _unMsg);
virtual TW_INT16 Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition);
virtual bool Reset();
/**
* Try to add a value for container. The first value added to a capabiltiy is set as the default and current value.
* @param[in] _frame the value to be added.
* @param[in] _bDefault if true explisitly sets this value to be the default and current.
* @return true if success.
*/
bool Add(const InternalFrame& _frame, bool _bDefault = false);
/**
* Try to add a value for container. The first value added to a capabiltiy is set as the default and current value.
* @param[in] _nLeft left
* @param[in] _nTop top
* @param[in] _nRight right
* @param[in] _nBottom bottom
* @param[in] _bDefault if true explisitly sets this value to be the default and current.
* @return true if success.
*/
bool Add(const int _nLeft, const int _nTop, const int _nRight, const int _nBottom, bool _bDefault = false);
/**
* Set the current Frame. Only used after the default has been set using Add
* @param[in] _frame the value to be added.
* @return true if success.
*/
bool Set(const InternalFrame& _frame);
/**
* Try to set the current value for container.
* The value must already be part of the container.
* @param[in] _frame the value to be set as current.
* @return true if success.
*/
bool SetCurrent(const InternalFrame& _frame);
/**
* Try to set the current value for container.
* The value must already be part of the container.
* @param[in] _nLeft left
* @param[in] _nTop top
* @param[in] _nRight right
* @param[in] _nBottom bottom
* @return true if success.
*/
bool SetCurrent(const int _nLeft, const int _nTop, const int _nRight, const int _nBottom);
/**
* Return the default value through _frame if set.
* @param[out] _frame set the default value on return.
* @return true if success.
*/
bool GetDefault(InternalFrame& _frame);
/**
* Return the current value through _frame if set.
* @param[out] _frame set the current value on return.
* @return true if success.
*/
bool GetCurrent(InternalFrame& _frame);
/**
* Return a vector of supported values.
* @return supported values.
*/
const FrameVector &GetSupported();
/**
* Return the weather or not the value is supported by this capability.
* @param[in] _frame the value to check to see if it is supported
* @return true is the _frame is supported.
*/
bool isValueSupported(const InternalFrame& _frame) {return -1 != getIndexForValue(_frame);}
/**
* Return the index in vector list for value.
* @param[in] _frame value to search for.
* @return the index of value, or -1 if does not exist.
*/
int getIndexForValue(const InternalFrame& _frame);
/**
* set the current unit and resolution. Used to translate the Frames coming and going
* @param[in] Unit the current unit value.
* @param[in] Xres the current X resolution value.
* @param[in] Yres the current Y resolution value.
*/
void setCurrentUnits(int Unit, float Xres, float Yres);
protected:
/**
* Check to see if type is valid.
* @param[in] _unTWType type to check
* @return true if valid
*/
bool isValidType(const TW_UINT16 _unTWType);
FrameVector m_listFrames; /**< vector of valid container values. */
FrameVector m_listFramesDefault; /**< vector of valid container default values. */
int m_Unit; /**< used to translate the units coming and going */
float m_Xres; /**< used to translate the units coming and going */
float m_Yres; /**< used to translate the units coming and going */
};
#endif // __CTWAINCONTAINERFRAME_H__

View File

@ -0,0 +1,542 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerInt.cpp
* Int Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CommonDS.h"
#include <algorithm>
CTWAINContainerInt::CTWAINContainerInt(const TW_UINT16 _unCapID,
const TW_UINT16 _unItemType,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries/* = TWQC_ALL*/,
const TW_UINT16 _unGetCurrentType/* = TWON_ONEVALUE*/,
const TW_UINT16 _unGetDefaultType/* = TWON_ONEVALUE*/)
: CTWAINContainer(_unCapID, _unItemType, _unGetType, _nSupportedQueries,_unGetCurrentType,_unGetDefaultType)
{
}
CTWAINContainerInt::~CTWAINContainerInt()
{
}
TW_HANDLE CTWAINContainerInt::GetContainer(const TW_UINT16 _unMsg)
{
TW_HANDLE hContainer = 0;
TW_UINT16 unGetType=TWON_ONEVALUE;
switch(_unMsg)
{
case MSG_GET:
unGetType = m_unGetType;
break;
case MSG_GETCURRENT:
unGetType = m_unGetCurrentType;
break;
case MSG_GETDEFAULT:
unGetType = m_unGetDefaultType;
break;
}
switch(unGetType)
{
default:
case TWON_ONEVALUE:
{
hContainer = _DSM_Alloc(sizeof(TW_ONEVALUE));
if(0 != hContainer)
{
pTW_ONEVALUE pCap = (pTW_ONEVALUE)_DSM_LockMemory(hContainer);
pCap->ItemType = m_unItemType;
// If the Cap has been constrained the default may only be in the defaultlist.
pCap->Item = (MSG_GETDEFAULT == _unMsg)?m_listIntsDefault[m_nDefault]:m_listInts[m_nCurrent];
_DSM_UnlockMemory(hContainer);
}
}
break;
case TWON_ENUMERATION:
{
unsigned int unSize = getTWTYSize(m_unItemType);
hContainer = _DSM_Alloc(sizeof(TW_ENUMERATION) -1 + (unSize * m_listInts.size()));
if(0 != hContainer)
{
pTW_ENUMERATION pCap = (pTW_ENUMERATION)_DSM_LockMemory(hContainer);
pCap->ItemType = m_unItemType;
pCap->NumItems = (TW_UINT32)m_listInts.size();
pCap->CurrentIndex = m_nCurrent;
//If the CAP has been constrained m_nDefault index might not point
// to the correct index and the index may not be valid. We need to
// find the value in the default list and see if we can find a match
// in the current list. If no match found then set to first index.
// see spec on twain.org Chap4 p73 Advanced Application Implementation |
// Capabilities | Constrained Capabilities and Message Responses | MSG_SET
const int nVal = m_listIntsDefault[m_nDefault];
int nIndex = getIndexForValue(nVal);
if(nIndex != -1)
{
pCap->DefaultIndex = nIndex;
}
else
{
// We use the first index. We could try transversing through the
// list and finding the closest match in value. But either way
// the application should not be using this value.
pCap->DefaultIndex = 0;
}
fillValues(&pCap->ItemList, pCap->NumItems, m_unItemType);
_DSM_UnlockMemory(hContainer);
}
}
break;
case TWON_ARRAY:
{
unsigned int unSize = getTWTYSize(m_unItemType);
hContainer = _DSM_Alloc(sizeof(TW_ARRAY)-1 + (unSize * m_listInts.size()));
if(0 != hContainer)
{
pTW_ARRAY pCap = (pTW_ARRAY)_DSM_LockMemory(hContainer);
pCap->ItemType = m_unItemType;
pCap->NumItems = (TW_UINT32)m_listInts.size();
fillValues(&pCap->ItemList, pCap->NumItems, m_unItemType);
_DSM_UnlockMemory(hContainer);
}
}
} // switch(unGetType)
return hContainer;
}
void CTWAINContainerInt::fillValues(void* _pItemList, const TW_UINT32 _unNumItems, const TW_UINT16 _unItemType)
{
for(TW_UINT32 x = 0; x < _unNumItems; ++x)
{
switch(_unItemType)
{
case TWTY_INT8:
((TW_INT8*)_pItemList)[x] = (TW_INT8)m_listInts[x];
break;
case TWTY_INT16:
((TW_INT16*)_pItemList)[x] = (TW_INT16)m_listInts[x];
break;
case TWTY_INT32:
((TW_INT32*)_pItemList)[x] = (TW_INT32)m_listInts[x];
break;
case TWTY_UINT8:
((TW_UINT8*)_pItemList)[x] = (TW_UINT8)m_listInts[x];
break;
case TWTY_UINT16:
((TW_UINT16*)_pItemList)[x] = (TW_UINT16)m_listInts[x];
break;
case TWTY_UINT32:
((TW_UINT32*)_pItemList)[x] = (TW_UINT32)m_listInts[x];
break;
case TWTY_BOOL:
((TW_BOOL*)_pItemList)[x] = (TW_BOOL)m_listInts[x];
break;
}
}
}
bool CTWAINContainerInt::isValidType(const TW_UINT16 _unTWType)
{
bool bret = false;
switch(_unTWType)
{
case TWTY_INT8:
case TWTY_INT16:
case TWTY_INT32:
case TWTY_UINT8:
case TWTY_UINT16:
case TWTY_UINT32:
case TWTY_BOOL:
bret = true;
break;
}
return bret;
}
int CTWAINContainerInt::getValue(const pTW_ONEVALUE _pVal)
{
int nRet = 0;
switch(_pVal->ItemType)
{
case TWTY_INT8:
nRet = *((TW_INT8*)&(_pVal->Item));
break;
case TWTY_INT16:
nRet = *((TW_INT16*)&(_pVal->Item));
break;
case TWTY_INT32:
nRet = *((TW_INT32*)&(_pVal->Item));
break;
case TWTY_UINT8:
nRet = *((TW_UINT8*)&(_pVal->Item));
break;
case TWTY_UINT16:
nRet = *((TW_UINT16*)&(_pVal->Item));
break;
case TWTY_UINT32:
nRet = *((TW_UINT32*)&(_pVal->Item));
break;
case TWTY_BOOL:
nRet = *((TW_BOOL*)&(_pVal->Item));
break;
}
return nRet;
}
TW_INT16 CTWAINContainerInt::Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition)
{
TW_INT16 twrc = TWRC_SUCCESS;
Condition = TWCC_SUCCESS;
if(TWON_ONEVALUE == _pCap->ConType)
{
pTW_ONEVALUE pCap = (pTW_ONEVALUE)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
switch(m_unGetType)
{
case TWON_ONEVALUE:
{
m_listInts.clear();
m_listInts.push_back(getValue(pCap));
m_nCurrent = 0;
}
break;
case TWON_ENUMERATION:
{
int nVal = -1;
if( (nVal = getIndexForValue(getValue(pCap))) >= 0 )
{
m_nCurrent = nVal;
}
else
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
}
break;
//case TWON_ARRAY:
//break;
//case TWON_RANGE:
//break;
default:
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
break;
}
}
else // NOT isValidType(pCap->ItemType))
{
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else if(TWON_ENUMERATION == _pCap->ConType)
{
pTW_ENUMERATION pCap = (pTW_ENUMERATION)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
int nNewCurrentIndex = pCap->CurrentIndex;
IntVector::iterator iter;
bool bListCleared = false; // We only want to crear the current list if we are passed
// valid data, and only clear it once through the loop of testing
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
// only set the value if it exists in m_listIntsDefault
int nValue = GetIndexIntValue(pCap, x);
iter = find(m_listIntsDefault.begin(), m_listIntsDefault.end(), nValue);
if(iter != m_listIntsDefault.end())
{
// We have valid data
if(!bListCleared)
{
// only clear the list if we have not done so already
m_listInts.clear();
bListCleared = true;
}
// only add it if it was not added already
iter = find(m_listInts.begin(), m_listInts.end(), nValue);
if(iter == m_listInts.end())
{
m_listInts.push_back(nValue);
}
else
{
// if the index is below the current then we need to adjust what is going to be current
if(x < pCap->CurrentIndex)
{
nNewCurrentIndex--;
}
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
else
{
// if the index is below the current then we need to adjust what is going to be current
if(x < pCap->CurrentIndex)
{
nNewCurrentIndex--;
}
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
// If the list has been cleared then there was at at least some valid data
if(bListCleared)
{
if(nNewCurrentIndex >= 0 && nNewCurrentIndex < (int)(m_listInts.size()))
{
m_nCurrent = nNewCurrentIndex;
}
else
{
// the new current index is not in range
m_nCurrent = 0;
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
else
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
}
else // NOT isValidType(pCap->ItemType))
{
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else //bad container type
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
return twrc;
}
bool CTWAINContainerInt::Reset()
{
m_nCurrent = m_nDefault;
m_listInts.clear();
const int nSize = (int)(m_listIntsDefault.size());
for(int x = 0; x < nSize; ++x)
{
m_listInts.push_back(m_listIntsDefault[x]);
}
return true;
}
// For int vals
bool CTWAINContainerInt::GetCurrent(int &_nVal)
{
bool bret = false;
if(!(m_nMSG_QUERYSUPPORT & TWQC_GETCURRENT))
{
return false;
}
if((m_nCurrent >= 0) && ((int)(m_listInts.size()) > m_nCurrent))
{
_nVal = m_listInts[m_nCurrent];
bret = true;
}
return bret;
}
bool CTWAINContainerInt::GetDefault(int &_nVal)
{
bool bret = false;
if(!(m_nMSG_QUERYSUPPORT & TWQC_GETDEFAULT))
{
return TWRC_FAILURE;
}
if((m_nDefault >= 0) && ((int)(m_listIntsDefault.size()) > m_nDefault))
{
_nVal = m_listIntsDefault[m_nDefault];
bret = true;
}
return bret;
}
const IntVector &CTWAINContainerInt::GetSupported()
{
return m_listInts;
}
bool CTWAINContainerInt::Add(int _nAdd, bool _bDefault /*= false*/)
{
m_listInts.push_back(_nAdd);
m_listIntsDefault.push_back(_nAdd);
if(m_nDefault == -1 || _bDefault)
{
m_nCurrent = m_nDefault = getIndexForValue(_nAdd);
}
return true;
}
bool CTWAINContainerInt::SetCurrent(int _nCurr)
{
if(TWON_ONEVALUE == m_unGetType)//check before call
{
m_listInts.clear();
m_listInts.push_back(_nCurr);
m_nCurrent = 0;
}
else
{
int nIdx = getIndexForValue(_nCurr);
if(nIdx < 0)
{
return false;
}
m_nCurrent = nIdx;
}
return true;
}
int CTWAINContainerInt::getIndexForValue(const int _nVal)
{
int ret = -1;
const int nSize = (int)(m_listInts.size());
for(int x = 0; x < nSize; ++x)
{
if(_nVal == m_listInts[x])
{
ret = x;
break;
}
}
return ret;
}
int GetIndexIntValue(pTW_ENUMERATION pCap, TW_UINT32 index)
{
int rtn = 0;
if(pCap && pCap->NumItems > index)
{
switch(pCap->ItemType)
{
case TWTY_INT8:
rtn = ((TW_INT8*)&pCap->ItemList)[index];
break;
case TWTY_INT16:
rtn = ((TW_INT16*)&pCap->ItemList)[index];
break;
case TWTY_INT32:
rtn = ((TW_INT32*)&pCap->ItemList)[index];
break;
case TWTY_UINT8:
rtn = ((TW_UINT8*)&pCap->ItemList)[index];
break;
case TWTY_UINT16:
rtn = ((TW_UINT16*)&pCap->ItemList)[index];
break;
case TWTY_UINT32:
rtn = ((TW_UINT32*)&pCap->ItemList)[index];
break;
case TWTY_BOOL:
rtn = ((TW_BOOL*)&pCap->ItemList)[index];
break;
}
}
return rtn;
}

View File

@ -0,0 +1,159 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerInt.h
* Int Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINCONTAINERINT_H__
#define __CTWAINCONTAINERINT_H__
#include "TWAINContainer.h"
/**
* Return the Int Value of the index into an enumeration of Ints
* @param[in] pCap The enumeration to retreive the value
* @param[in] index the index into the enumeration to retrieve the value.
* @return the Int value at index into pCap
*/
int GetIndexIntValue(pTW_ENUMERATION pCap, TW_UINT32 index);
/**
* This class can be used for any Integer based TWAIN container.
* All values are stored internally as 1/1000th of an inch. They are converted
* as necessary when TWAIN containers are created. Any direct access will require
* the caller to do their own conversion.
*/
class CTWAINContainerInt : public CTWAINContainer
{
friend class CTWAIN_UI;
public:
/**
* Constructor.
* @param[in] _unCapID Capability ID
* @param[in] _unItemType TWAIN Type TWTY_xxxx being stored.
* @param[in] _unGetType TWON_xxxx container
* @param[in] _nSupportedQueries the supported querie types TWQC_xxxx
*/
CTWAINContainerInt(const TW_UINT16 _unCapID,
const TW_UINT16 _unItemType,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries = TWQC_ALL,
const TW_UINT16 _unGetCurrentType = TWON_ONEVALUE,
const TW_UINT16 _unGetDefaultType = TWON_ONEVALUE);
virtual ~CTWAINContainerInt();
virtual TW_HANDLE GetContainer(const TW_UINT16 _unMsg);
virtual TW_INT16 Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition);
virtual bool Reset();
/**
* Try to add a value for container. The first value added to a capabiltiy is set as the default and current value.
* @param[in] _nAdd the value to be added.
* @param[in] _bDefault if true explisitly sets this value to be the default and current.
* @return true if success.
*/
bool Add(int _nAdd, bool _bDefault = false);
/**
* Try to set the current value for container.
* The value must already be part of the container.
* @param[in] _nCurr the value to be set as current.
* @return true if success.
*/
bool SetCurrent(int _nCurr);
/**
* Return the default value through _nVal if set.
* @param[out] _nVal set the default value on return.
* @return true if success.
*/
bool GetDefault(int &_nVal);
/**
* Return the current value through _nVal if set.
* @param[out] _nVal set the current value on return.
* @return true if success.
*/
bool GetCurrent(int &_nVal);
/**
* Return a vector of supported values.
* @return supported values.
*/
const IntVector &GetSupported();
/**
* Return the current value from the container.
* @param[in] _pVal pointer to TW_ONEVALUE container of
* @return the value converted to int.
*/
int getValue(const pTW_ONEVALUE _pVal);
/**
* Return the weather or not the value is supported by this capability.
* @param[in] _nVal the value to check to see if it is supported
* @return true is the _nVal is supported.
*/
bool isValueSupported(const int _nVal) {return -1 != getIndexForValue(_nVal);}
/**
* Return the index in vector list for value.
* @param[in] _flVal value to search for.
* @return the index of value, or -1 if does not exist.
*/
int getIndexForValue(const int _nVal);
protected:
/**
* Check to see if type is valid.
* @param[in] _unTWType type to check
* @return true if valid
*/
bool isValidType(const TW_UINT16 _unTWType);
/**
* This is a utility function used to help create the TWAIN container.
* @param[in] _pItemList container to fill up.
* @param[in] _unNumItems number of fields to fill in.
* @param[in] _unItemType type of item in container.
*/
void fillValues(void* _pItemList, const TW_UINT32 _unNumItems, const TW_UINT16 _unItemType);
IntVector m_listInts; /**< vector of valid container values. */
IntVector m_listIntsDefault; /**< vector of valid container default values. */
};
#endif // __CTWAINCONTAINERINT_H__

View File

@ -0,0 +1,444 @@
/***************************************************************************
* Copyright <EFBFBD> 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerInt.cpp
* Int Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CommonDS.h"
#include <algorithm>
CTWAINContainerString::CTWAINContainerString(const TW_UINT16 _unCapID,
const TW_UINT16 _unItemType,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries/* = TWQC_ALL*/,
const TW_UINT16 _unGetCurrentType/* = TWON_ONEVALUE*/,
const TW_UINT16 _unGetDefaultType/* = TWON_ONEVALUE*/)
: CTWAINContainer(_unCapID, _unItemType, _unGetType, _nSupportedQueries,_unGetCurrentType,_unGetDefaultType)
{
m_unItemSize = getTWTYSize(_unItemType);
}
CTWAINContainerString::~CTWAINContainerString()
{
}
TW_HANDLE CTWAINContainerString::GetContainer(const TW_UINT16 _unMsg)
{
TW_HANDLE hContainer = 0;
TW_UINT16 unGetType=TWON_ONEVALUE;
switch(_unMsg)
{
case MSG_GET:
unGetType = m_unGetType;
break;
case MSG_GETCURRENT:
unGetType = m_unGetCurrentType;
break;
case MSG_GETDEFAULT:
unGetType = m_unGetDefaultType;
break;
}
switch(unGetType)
{
default:
case TWON_ONEVALUE:
{
hContainer = _DSM_Alloc(sizeof(TW_ONEVALUE)+m_unItemSize-sizeof(TW_UINT32));
if(0 != hContainer)
{
pTW_ONEVALUE pCap = (pTW_ONEVALUE)_DSM_LockMemory(hContainer);
pCap->ItemType = m_unItemType;
// If the Cap has been constrained the default may only be in the defaultlist.
string strTemp = ((MSG_GETDEFAULT == _unMsg)?m_listStrsDefault[m_nDefault]:m_listStrs[m_nCurrent]);
memset((char*)&pCap->Item,0,m_unItemSize);
#ifdef __APPLE__
memcpy(((char*)&pCap->Item)+1, strTemp.c_str(),MIN(m_unItemSize, strTemp.length()));
((char*)&pCap->Item)[0]=strTemp.length();
#else
memcpy((char*)&pCap->Item, strTemp.c_str(),MIN(m_unItemSize, strTemp.length()));
#endif
_DSM_UnlockMemory(hContainer);
}
}
break;
case TWON_ENUMERATION:
{
hContainer = _DSM_Alloc(sizeof(TW_ENUMERATION) -1 + (m_unItemSize * m_listStrs.size()));
if(0 != hContainer)
{
pTW_ENUMERATION pCap = (pTW_ENUMERATION)_DSM_LockMemory(hContainer);
pCap->ItemType = m_unItemType;
pCap->NumItems = (TW_UINT32)m_listStrs.size();
pCap->CurrentIndex = m_nCurrent;
//If the CAP has been constrained m_nDefault index might not point
// to the correct index and the index may not be valid. We need to
// find the value in the default list and see if we can find a match
// in the current list. If no match found then set to first index.
// see spec on twain.org Chap4 p73 Advanced Application Implementation |
// Capabilities | Constrained Capabilities and Message Responses | MSG_SET
const string strVal = m_listStrsDefault[m_nDefault];
int nIndex = getIndexForValue(strVal);
if(nIndex != -1)
{
pCap->DefaultIndex = nIndex;
}
else
{
// We use the first index. We could try transversing through the
// list and finding the closest match in value. But either way
// the application should not be using this value.
pCap->DefaultIndex = 0;
}
fillValues(&pCap->ItemList, pCap->NumItems);
_DSM_UnlockMemory(hContainer);
}
}
break;
case TWON_ARRAY:
{
hContainer = _DSM_Alloc(sizeof(TW_ARRAY)-1 + (m_unItemSize * m_listStrs.size()));
if(0 != hContainer)
{
pTW_ARRAY pCap = (pTW_ARRAY)_DSM_LockMemory(hContainer);
pCap->ItemType = m_unItemType;
pCap->NumItems = (TW_UINT32)m_listStrs.size();
fillValues(&pCap->ItemList, pCap->NumItems);
_DSM_UnlockMemory(hContainer);
}
}
} // switch(unGetType)
return hContainer;
}
void CTWAINContainerString::fillValues(void* _pItemList, const TW_UINT32 _unNumItems)
{
for(TW_UINT32 x = 0; x < _unNumItems; ++x)
{
string strTemp = m_listStrs[x];
char *pItem = (char*)_pItemList + m_unItemSize*x;
memset(pItem,0,m_unItemSize);
#ifdef __APPLE__
memcpy(((char*)pItem)+1, strTemp.c_str(),MIN(m_unItemSize, strTemp.length()));
((char*)pItem)[0]=strTemp.length();
#else
memcpy(pItem, strTemp.c_str(),MIN(m_unItemSize, strTemp.length()));
#endif
}
}
bool CTWAINContainerString::isValidType(const TW_UINT16 _unTWType)
{
return m_unItemType == _unTWType;
}
string CTWAINContainerString::getValue(const char* _pchVal)
{
string strRet;
char *pstrTemp = new char[m_unItemSize+1];
memcpy(pstrTemp,_pchVal,m_unItemSize);
pstrTemp[m_unItemSize]=0;
strRet = pstrTemp;
delete [] pstrTemp;
return strRet;
}
TW_INT16 CTWAINContainerString::Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition)
{
TW_INT16 twrc = TWRC_SUCCESS;
Condition = TWCC_SUCCESS;
if(TWON_ONEVALUE == _pCap->ConType)
{
pTW_ONEVALUE pCap = (pTW_ONEVALUE)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
switch(m_unGetType)
{
case TWON_ONEVALUE:
{
m_listStrs.clear();
m_listStrs.push_back(getValue((char*)&(pCap->Item)));
m_nCurrent = 0;
}
break;
case TWON_ENUMERATION:
{
int nVal = -1;
if( (nVal = getIndexForValue(getValue((char*)&(pCap->Item)))) >= 0 )
{
m_nCurrent = nVal;
}
else
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
}
break;
//case TWON_ARRAY:
//break;
//case TWON_RANGE:
//break;
default:
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
break;
}
}
else // NOT isValidType(pCap->ItemType))
{
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else if(TWON_ENUMERATION == _pCap->ConType)
{
pTW_ENUMERATION pCap = (pTW_ENUMERATION)_DSM_LockMemory(_pCap->hContainer);
if(isValidType(pCap->ItemType))
{
int nNewCurrentIndex = pCap->CurrentIndex;
StringVector::iterator iter;
bool bListCleared = false; // We only want to crear the current list if we are passed
// valid data, and only clear it once through the loop of testing
for(TW_UINT32 x = 0; x < pCap->NumItems; ++x)
{
// only set the value if it exists in m_listStrsDefault
string strValue = getValue((char*)&(pCap->ItemList)+x*m_unItemSize);
iter = find(m_listStrsDefault.begin(), m_listStrsDefault.end(), strValue);
if(iter != m_listStrsDefault.end())
{
// We have valid data
if(!bListCleared)
{
// only clear the list if we have not done so already
m_listStrs.clear();
bListCleared = true;
}
// only add it if it was not added already
iter = find(m_listStrs.begin(), m_listStrs.end(), strValue);
if(iter == m_listStrs.end())
{
m_listStrs.push_back(strValue);
}
else
{
// if the index is below the current then we need to adjust what is going to be current
if(x < pCap->CurrentIndex)
{
nNewCurrentIndex--;
}
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
else
{
// if the index is below the current then we need to adjust what is going to be current
if(x < pCap->CurrentIndex)
{
nNewCurrentIndex--;
}
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
// If the list has been cleared then there was at at least some valid data
if(bListCleared)
{
if(nNewCurrentIndex >= 0 && nNewCurrentIndex < (int)(m_listStrs.size()))
{
m_nCurrent = nNewCurrentIndex;
}
else
{
// the new current index is not in range
m_nCurrent = 0;
twrc = TWRC_CHECKSTATUS;
Condition = TWCC_BADVALUE;
}
}
else
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
}
else // NOT isValidType(pCap->ItemType))
{
twrc = TWRC_FAILURE;
Condition = TWCC_CAPBADOPERATION;
}
_DSM_UnlockMemory(_pCap->hContainer);
}
else //bad container type
{
twrc = TWRC_FAILURE;
Condition = TWCC_BADVALUE;
}
return twrc;
}
bool CTWAINContainerString::Reset()
{
m_nCurrent = m_nDefault;
m_listStrs.clear();
const int nSize = (int)(m_listStrsDefault.size());
for(int x = 0; x < nSize; ++x)
{
m_listStrs.push_back(m_listStrsDefault[x]);
}
return true;
}
// For int vals
bool CTWAINContainerString::GetCurrent(string &_strVal)
{
bool bret = false;
if(!(m_nMSG_QUERYSUPPORT & TWQC_GETCURRENT))
{
return false;
}
if((m_nCurrent >= 0) && ((int)(m_listStrs.size()) > m_nCurrent))
{
_strVal = m_listStrs[m_nCurrent];
bret = true;
}
return bret;
}
bool CTWAINContainerString::GetDefault(string &_strVal)
{
bool bret = false;
if(!(m_nMSG_QUERYSUPPORT & TWQC_GETDEFAULT))
{
return TWRC_FAILURE;
}
if((m_nDefault >= 0) && ((int)(m_listStrsDefault.size()) > m_nDefault))
{
_strVal = m_listStrsDefault[m_nDefault];
bret = true;
}
return bret;
}
const StringVector &CTWAINContainerString::GetSupported()
{
return m_listStrs;
}
bool CTWAINContainerString::Add(string _strAdd, bool _bDefault /*= false*/)
{
m_listStrs.push_back(_strAdd);
m_listStrsDefault.push_back(_strAdd);
if(m_nDefault == -1 || _bDefault)
{
m_nCurrent = m_nDefault = m_listStrsDefault.size()-1;
}
return true;
}
bool CTWAINContainerString::SetCurrent(string _strCurr)
{
if(TWON_ONEVALUE == m_unGetType)//check before call
{
m_listStrs.clear();
m_listStrs.push_back(_strCurr);
m_nCurrent = 0;
}
else
{
int nIdx = getIndexForValue(_strCurr);
if(nIdx < 0)
{
return false;
}
m_nCurrent = nIdx;
}
return true;
}
int CTWAINContainerString::getIndexForValue(const string _strVal)
{
int ret = -1;
const int nSize = (int)(m_listStrs.size());
for(int x = 0; x < nSize; ++x)
{
if(_strVal == m_listStrs[x])
{
ret = x;
break;
}
}
return ret;
}

View File

@ -0,0 +1,152 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAINContainerString.h
* String Container class for negotiating capabilities.
* @author TWAIN Working Group
* @date April 2007
*/
#ifndef __CTWAINContainerString_H__
#define __CTWAINContainerString_H__
#include "TWAINContainer.h"
/**
* This class can be used for any Integer based TWAIN container.
* All values are stored internally as 1/1000th of an inch. They are converted
* as necessary when TWAIN containers are created. Any direct access will require
* the caller to do their own conversion.
*/
class CTWAINContainerString : public CTWAINContainer
{
friend class CTWAIN_UI;
public:
/**
* Constructor.
* @param[in] _unCapID Capability ID
* @param[in] _unItemType TWAIN Type TWTY_xxxx being stored.
* @param[in] _unGetType TWON_xxxx container
* @param[in] _nSupportedQueries the supported querie types TWQC_xxxx
*/
CTWAINContainerString(const TW_UINT16 _unCapID,
const TW_UINT16 _unItemType,
const TW_UINT16 _unGetType,
const TW_INT32 _nSupportedQueries = TWQC_ALL,
const TW_UINT16 _unGetCurrentType = TWON_ONEVALUE,
const TW_UINT16 _unGetDefaultType = TWON_ONEVALUE);
virtual ~CTWAINContainerString();
virtual TW_HANDLE GetContainer(const TW_UINT16 _unMsg);
virtual TW_INT16 Set(pTW_CAPABILITY _pCap, TW_INT16 &Condition);
virtual bool Reset();
/**
* Try to add a value for container. The first value added to a capabiltiy is set as the default and current value.
* @param[in] _nAdd the value to be added.
* @param[in] _bDefault if true explisitly sets this value to be the default and current.
* @return true if success.
*/
bool Add(string _strAdd, bool _bDefault = false);
/**
* Try to set the current value for container.
* The value must already be part of the container.
* @param[in] _nCurr the value to be set as current.
* @return true if success.
*/
bool SetCurrent(string _strCurr);
/**
* Return the default value through _nVal if set.
* @param[out] _nVal set the default value on return.
* @return true if success.
*/
bool GetDefault(string &_strVal);
/**
* Return the current value through _nVal if set.
* @param[out] _nVal set the current value on return.
* @return true if success.
*/
bool GetCurrent(string &_strVal);
/**
* Return a vector of supported values.
* @return supported values.
*/
const StringVector &GetSupported();
/**
* Return the current value from the container.
* @param[in] _pVal pointer to TW_ONEVALUE container of
* @return the value converted to int.
*/
string getValue(const char* _pchVal);
/**
* Return the weather or not the value is supported by this capability.
* @param[in] _nVal the value to check to see if it is supported
* @return true is the _nVal is supported.
*/
bool isValueSupported(const string _strVal) {return -1 != getIndexForValue(_strVal);}
/**
* Return the index in vector list for value.
* @param[in] _flVal value to search for.
* @return the index of value, or -1 if does not exist.
*/
int getIndexForValue(const string _strVal);
protected:
/**
* Check to see if type is valid.
* @param[in] _unTWType type to check
* @return true if valid
*/
bool isValidType(const TW_UINT16 _unTWType);
/**
* This is a utility function used to help create the TWAIN container.
* @param[in] _pItemList container to fill up.
* @param[in] _unNumItems number of fields to fill in.
*/
void fillValues(void* _pItemList, const TW_UINT32 _unNumItems);
StringVector m_listStrs; /**< vector of valid container values. */
StringVector m_listStrsDefault; /**< vector of valid container default values. */
unsigned int m_unItemSize; /**< Size of single item */
};
#endif // __CTWAINContainerString_H__

679
hugaotwainds/TWAIN_UI.cpp Normal file
View File

@ -0,0 +1,679 @@
/***************************************************************************
* Copyright <EFBFBD> 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file CTWAINDS_FreeImage.cpp
* The main Data Source class.
* This class is derived from the Base class describing a TWAIN DS.
* @author TWAIN Working Group
* @date April 2007
*/
#include "stdafx.h"
#include "CommonDS.h"
#include "CTWAINDS_FreeImage.h"
#include "TWAIN_UI.h"
#include <typeinfo>
#ifdef TWH_CMP_GNU
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <pwd.h>
#define MAX_PATH 1024
#elif defined(TWNDS_OS_WIN)
#include <shlobj.h>
#else
#endif
#include "MFC_UI.h"
/*++ nick
*/
CTWAIN_UI* CreateUI(CTWAINDS_FreeImage *pDS)
{
return new MFC_UI(pDS);
}
void DestroyUI(CTWAIN_UI* pUI)
{
if (pUI)
{
delete pUI;
}
}
CTWAIN_UI::CTWAIN_UI(CTWAINDS_FreeImage *pDS)
{
m_pDS = pDS;
m_bScanning=false;
memset(&m_EnableDSdata,0,sizeof(TW_USERINTERFACE));
m_strProfilesDirectory=="";
char strProfilesPath[MAX_PATH];
char strOldPath[MAX_PATH];
#ifdef TWH_CMP_GNU
getcwd(strOldPath,MAX_PATH);
strcpy(strProfilesPath , getenv ("HOME"));
#elif defined(TWNDS_OS_WIN)
GetCurrentDirectory(MAX_PATH, strOldPath);
// get temp Application data directory for all users
if(!SHGetSpecialFolderPath(NULL, strProfilesPath, CSIDL_COMMON_APPDATA|CSIDL_FLAG_CREATE, TRUE))
{
return;
}
#else
#endif
if(strProfilesPath[strlen(strProfilesPath)-1] != '/')
{
//SSTRCAT(strProfilesPath, MAX_PATH, "\\");
strcat(strProfilesPath, "/");
}
SSTRCAT(strProfilesPath, MAX_PATH, PROFILELOCATION);
if(strProfilesPath[strlen(strProfilesPath)-1] != '/')
{
SSTRCAT(strProfilesPath, MAX_PATH, "/");
}
SSTRCAT(strProfilesPath, MAX_PATH, kCUSTOMDSGUI);
if(strProfilesPath[strlen(strProfilesPath)-1] != '/')
{
SSTRCAT(strProfilesPath, MAX_PATH, "/");
}
// Set current directory to profiles directory
#ifdef TWH_CMP_GNU
if(chdir(strProfilesPath))
#elif defined(TWNDS_OS_WIN)
if(!SetCurrentDirectory(strProfilesPath))
#else
#endif
{
char szPath[MAX_PATH];
char szTempPath[MAX_PATH];
char *pPath;
char *pSeparator;
SSTRCPY(szPath, MAX_PATH, strProfilesPath);
pPath = szPath;
// creates profiles path if it is needed
while( pSeparator = strchr(pPath, '/') )
{
*pSeparator = '\0';
SSTRCPY(szTempPath, MAX_PATH, pPath);
SSTRCAT(szTempPath, MAX_PATH, "/");
#ifdef TWH_CMP_GNU
if(chdir(szTempPath))
#elif defined(TWNDS_OS_WIN)
if(!SetCurrentDirectory(szTempPath))
#else
#endif
{
#ifdef TWH_CMP_GNU
if(mkdir(szTempPath,S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH))
#elif defined(TWNDS_OS_WIN)
if( !CreateDirectory(szTempPath, NULL) )
#else
#endif
{
return;
}
#ifdef TWH_CMP_GNU
chmod(szTempPath,S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH);
if(chdir(szTempPath))
#elif defined(TWNDS_OS_WIN)
if(!SetCurrentDirectory(szTempPath))
#else
#endif
{
return;
}
}
pPath = pSeparator+1;
}
}
m_strProfilesDirectory = strProfilesPath;
#ifdef TWH_CMP_GNU
chdir(strOldPath);
#elif defined(TWNDS_OS_WIN)
SetCurrentDirectory(strOldPath);
#else
#endif
}
TW_INT16 CTWAIN_UI::DisplayTWAINGUI(TW_USERINTERFACE Data, bool bSetup, bool bIndicators)
{
m_bIndicators = bIndicators;
m_bSetup = bSetup;
m_EnableDSdata = Data;
m_bScanning =(Data.ShowUI==0);
return 0;
}
void CTWAIN_UI::DestroyTWAINGUI()
{
m_bScanning=false;
memset(&m_EnableDSdata,0,sizeof(TW_USERINTERFACE));
}
void CTWAIN_UI::UpdateProgress(bool bShow, unsigned char ucProgress, unsigned int unPageNo, string strProgressTitle)
{
;
}
void CTWAIN_UI::Scan()
{
if(m_pDS->StartScanning())
{
m_bScanning = m_pDS->DoXferReadyEvent();
}
}
void CTWAIN_UI::Cancel()
{
m_pDS->StopScanning();
m_pDS->DoCloseDSRequestEvent();
}
void CTWAIN_UI::Save()
{
m_pDS->DoCloseDSOkEvent();
}
unsigned int CTWAIN_UI::MessageBox(string strMessage,string strTitle, unsigned int unIconID)
{
return 0;
}
bool CTWAIN_UI::processEvent(pTW_EVENT _pEvent)
{
return false;
}
int CTWAIN_UI::GetCurrentCapIndex(const TW_UINT16 _unCap)
{
CTWAINContainer *pfCap = m_pDS->findCapability(_unCap);
if(pfCap==NULL)
{
assert(0);
return 0;//@TODO
}
return pfCap->m_nCurrent;
}
TW_FRAME CTWAIN_UI::GetCurrentFrame()
{
CTWAINContainerFrame *pfCap = (CTWAINContainerFrame *)m_pDS->findCapability(ICAP_FRAMES);
if(pfCap==NULL)
{
assert(0);
return TW_FRAME();//@TODO
}
InternalFrame frame = pfCap->m_listFrames.at(pfCap->m_nCurrent);
int unit = TWUN_PIXELS;
float Xres = 100;
float Yres = 100;
m_pDS->getCurrentUnits(unit, Xres, Yres);
return frame.AsTW_FRAME(unit, Xres, Yres);
}
const IntVector* CTWAIN_UI::GetValidCap(const TW_UINT16 _unCap)
{
CTWAINContainer *pfCap = m_pDS->findCapability(_unCap);
if(pfCap==NULL)
{
assert(0);
return 0;//@TODO
}
if(typeid(*pfCap) == typeid(CTWAINContainerBool))
{
CTWAINContainerBool *pfBoolCap = (CTWAINContainerBool*)pfCap;
return &pfBoolCap->m_listBools;
}
else if(typeid(*pfCap) == typeid(CTWAINContainerInt))
{
CTWAINContainerInt *pfIntCap = (CTWAINContainerInt*)pfCap;
return &pfIntCap->m_listInts;
}
assert(0);
return 0;
}
const FloatVector* CTWAIN_UI::GetValidCapFloat(const TW_UINT16 _unCap)
{
CTWAINContainer *pfCap = m_pDS->findCapability(_unCap);
if(pfCap==NULL)
{
assert(0);
return 0;//@TODO
}
if(typeid(*pfCap) == typeid(CTWAINContainerFix32))
{
CTWAINContainerFix32 *pfFix32Cap = (CTWAINContainerFix32*)pfCap;
return &pfFix32Cap->m_listFloats;
}
assert(0);
return 0;
}
float CTWAIN_UI::GetCapValueFloat(const TW_UINT16 _unCap)
{
CTWAINContainer *pfCap = m_pDS->findCapability(_unCap);
if(pfCap==NULL)
{
assert(0);
return 0;//@TODO
}
float fVal;
if(typeid(*pfCap) == typeid(CTWAINContainerFix32))
{
CTWAINContainerFix32 *pfFix32Cap = (CTWAINContainerFix32*)pfCap;
if(pfFix32Cap->GetCurrent(fVal))
{
return fVal;
}
}
else if(typeid(*pfCap) == typeid(CTWAINContainerFix32Range))
{
CTWAINContainerFix32Range *pfFix32Cap = (CTWAINContainerFix32Range*)pfCap;
if(pfFix32Cap->GetCurrent(fVal))
{
return fVal;
}
}
assert(0);
return 0;
}
bool CTWAIN_UI::SetCurrentFrame(float fTop, float fLeft, float fBottom, float fRight)
{
TW_CAPABILITY cap;
cap.Cap = ICAP_FRAMES;
cap.ConType = TWON_ONEVALUE;
cap.hContainer = _DSM_Alloc(sizeof(TW_ONEVALUE_FRAME));
TW_INT16 twRC;
if(0 != cap.hContainer)
{
TW_ONEVALUE_FRAME* pCap = (TW_ONEVALUE_FRAME*)_DSM_LockMemory(cap.hContainer);
pCap->ItemType = TWTY_FRAME;
pCap->Item.Top = FloatToFIX32(fTop);
pCap->Item.Left = FloatToFIX32(fLeft);
pCap->Item.Bottom = FloatToFIX32(fBottom);
pCap->Item.Right = FloatToFIX32(fRight);
_DSM_UnlockMemory(cap.hContainer);
twRC = m_pDS->dat_capability(MSG_SET,&cap);
_DSM_Free(cap.hContainer);
}
else
{
return false;
}
m_pDS->setConditionCode(TWCC_SUCCESS); // clear condition code
if(twRC==TWRC_SUCCESS || (twRC==TWRC_CHECKSTATUS))
{
return true;
}
return false;
}
bool CTWAIN_UI::GetCapRangeFloat(const TW_UINT16 _unCap, float &fMin, float &fMax, float &fStep)
{
CTWAINContainer *pfCap = m_pDS->findCapability(_unCap);
if(pfCap==NULL)
{
return false;
}
if(typeid(*pfCap) == typeid(CTWAINContainerFix32Range))
{
CTWAINContainerFix32Range *pfFloatCap = (CTWAINContainerFix32Range*)pfCap;
pfFloatCap->GetMinMaxStep(fMin, fMax, fStep);
return true;
}
return false;
}
bool CTWAIN_UI::SetCapValueFloat(const TW_UINT16 _unCap, float fVal)
{
TW_CAPABILITY cap;
cap.Cap = _unCap;
cap.ConType = TWON_ONEVALUE;
cap.hContainer = _DSM_Alloc(sizeof(TW_FRAME));
TW_INT16 twRC;
if(0 != cap.hContainer)
{
TW_ONEVALUE_FIX32* pCap = (TW_ONEVALUE_FIX32*)_DSM_LockMemory(cap.hContainer);
pCap->ItemType = TWTY_FIX32;
pCap->Item = FloatToFIX32(fVal);
_DSM_UnlockMemory(cap.hContainer);
twRC = m_pDS->dat_capability(MSG_SET,&cap);
_DSM_Free(cap.hContainer);
}
else
{
return false;
}
m_pDS->setConditionCode(TWCC_SUCCESS); // clear condition code
if(twRC==TWRC_SUCCESS || (twRC==TWRC_CHECKSTATUS))
{
return true;
}
return false;
}
bool CTWAIN_UI::SetCapValueInt(const TW_UINT16 _unCap, int nVal)
{
CTWAINContainer *pCapCont = m_pDS->findCapability(_unCap);
if(pCapCont ==0)
{
return false;
}
TW_CAPABILITY cap;
cap.Cap = _unCap;
cap.ConType = TWON_ONEVALUE;
cap.hContainer = _DSM_Alloc(sizeof(TW_ONEVALUE));
TW_INT16 twRC;
if(0 != cap.hContainer)
{
TW_ONEVALUE* pCap = (TW_ONEVALUE*)_DSM_LockMemory(cap.hContainer);
pCap->ItemType = pCapCont->GetItemType();
pCap->Item = nVal;
_DSM_UnlockMemory(cap.hContainer);
twRC = m_pDS->dat_capability(MSG_SET,&cap);
_DSM_Free(cap.hContainer);
}
else
{
return false;
}
m_pDS->setConditionCode(TWCC_SUCCESS); // clear condition code
if(twRC==TWRC_SUCCESS || (twRC==TWRC_CHECKSTATUS))
{
return true;
}
return false;
}
bool CTWAIN_UI::ResetAllCaps()
{
TW_CAPABILITY cap;
cap.Cap = CAP_SUPPORTEDCAPS;
cap.ConType = TWON_DONTCARE16;
cap.hContainer = 0;
TW_INT16 twRC;
twRC = m_pDS->dat_capability(MSG_RESETALL,&cap);
m_pDS->setConditionCode(TWCC_SUCCESS); // clear condition code
if(twRC==TWRC_SUCCESS || (twRC==TWRC_CHECKSTATUS))
{
return true;
}
return false;
}
#ifdef TWH_CMP_GNU
void CTWAIN_UI::TW_GetAllProfiles(lstString& strFileNames)
{
strFileNames.clear();
// Set current directory to profiles directory
DIR *dir;
dirent *dirInfo;
if((dir = opendir(m_strProfilesDirectory.c_str())) == NULL)
{
return;
}
TW_CUSTOMDSDATA DSDataBackUp;
if(m_pDS->GetGustomDSData(&DSDataBackUp)!=TWRC_SUCCESS)
{
return ;
}
while(dirInfo=readdir(dir))
{
string strName = dirInfo->d_name;
if(strName.size()>strlen(FILEEXTENTION) && strName.substr(strName.size()-strlen(FILEEXTENTION),strlen(FILEEXTENTION))==FILEEXTENTION)
{
strName = strName.substr(0,strName.size()-strlen(FILEEXTENTION));
try
{
// check if profile is valid
if(TW_LoadProfileFromFile(strName))
{
strFileNames.push_back(strName);
}
}
catch(...)
{
}
}
}
m_pDS->SetGustomDSData(&DSDataBackUp);
closedir(dir);
}
#elif defined(TWNDS_OS_WIN)
void CTWAIN_UI::TW_GetAllProfiles(lstString& strFileNames)
{
char strOldPath[MAX_PATH];
GetCurrentDirectory(MAX_PATH, strOldPath);
strFileNames.clear();
// Set current directory to profiles directory
if(!SetCurrentDirectory(m_strProfilesDirectory.c_str()))
{
return;
}
TW_CUSTOMDSDATA DSDataBackUp;
if(m_pDS->GetGustomDSData(&DSDataBackUp)!=TWRC_SUCCESS)
{
return ;
}
WIN32_FIND_DATA FindFileData;
HANDLE hFind = NULL;
char szFileName[MAX_PATH];
char *pDot;
hFind = FindFirstFile("*"/*FILEEXTENTION*/, &FindFileData);
while(hFind != INVALID_HANDLE_VALUE)
{
SSTRCPY(szFileName, MAX_PATH, FindFileData.cFileName);
pDot = strchr(szFileName, '.');
if(pDot)
{
*pDot = '\0';
}
try
{
// check if profile is valid
if(TW_LoadProfileFromFile(szFileName))
{
strFileNames.push_back(szFileName);
}
}
catch(...)
{
}
if(!FindNextFile(hFind, &FindFileData))
{
FindClose(hFind);
break;
}
}
m_pDS->SetGustomDSData(&DSDataBackUp);
SetCurrentDirectory(strOldPath);
}
#else
#endif
bool CTWAIN_UI::TW_LoadProfileFromFile(string strFileName)
{
TW_HANDLE hData;
strFileName = m_strProfilesDirectory+strFileName+FILEEXTENTION;
FILE *pFile = NULL;
//open file
FOPEN(pFile, strFileName.c_str(), "rb");
if(pFile==0)
{
return false;
}
// get file size
fseek(pFile, 0, SEEK_END);
DWORD dwDataSize = (DWORD)ftell(pFile);
rewind(pFile);
bool bRes = true;
// it has to contains at least DS identity
if(dwDataSize==0)
{
fclose(pFile);
return false;
}
// allocate storage and read CustomDSdata
void * pData = NULL;
if(hData = _DSM_Alloc(dwDataSize))
{
pData = _DSM_LockMemory(hData);
if(pData)
{
if(fread(pData, dwDataSize, 1, pFile)!=1)
{
bRes = false;
}
}
else
{
bRes = false;
}
}
else
{
bRes = false;
}
fclose(pFile);
if(hData)
{
_DSM_UnlockMemory(hData);
if(bRes)
{
TW_CUSTOMDSDATA DSData;
DSData.hData = hData;
DSData.InfoLength = dwDataSize;
bRes = m_pDS->SetGustomDSData(&DSData)==TWRC_SUCCESS;
}
// free resource on error
_DSM_Free(hData);
}
return bRes;
}
bool CTWAIN_UI::TW_SaveProfileToFile(string strFileName)
{
strFileName = m_strProfilesDirectory+strFileName+FILEEXTENTION;
TW_CUSTOMDSDATA DSData;
if(m_pDS->GetGustomDSData(&DSData)!=TWRC_SUCCESS)
{
return false;
}
void* pData = _DSM_LockMemory(DSData.hData);
if(!pData)
{
_DSM_Free(DSData.hData);
return false;
}
FILE *pFile = NULL;
bool bError = false;
//opens file
FOPEN(pFile, strFileName.c_str(), "wb");
if(pFile)
{
bError = true;
//store CustomDSdata
if(fwrite(pData, DSData.InfoLength, 1, pFile)!=1)
{
bError = false;
}
fclose(pFile);
//remove file on error
if(!bError)
{
int i = remove(strFileName.c_str());
}
}
_DSM_UnlockMemory(DSData.hData);
_DSM_Free(DSData.hData);
return bError;
}
bool CTWAIN_UI::TW_DeleteProfile(string strFileName)
{
if(!strFileName.empty())// if profile is selected
{
strFileName = m_strProfilesDirectory+strFileName+FILEEXTENTION;
//delete file from the disk
return remove(strFileName.c_str())==0;
}
else
{
return false;
}
}

131
hugaotwainds/TWAIN_UI.h Normal file
View File

@ -0,0 +1,131 @@
/***************************************************************************
* Copyright <EFBFBD> 2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TWAIN_UI.h
* UI base class - framework independent
* @author TWAIN Working Group
* @date Nov 2009
*/
#ifndef __TWAIN_UI_H__
#define __TWAIN_UI_H__
#include <list>
//#include "UI_INI.h"
#define FILEEXTENTION ".DSP"
#ifdef TWNDS_OS_LINUX
#define PROFILELOCATION ".TWAIN Working Group/Sample2/"
#elif defined(TWNDS_OS_WIN)
#define PROFILELOCATION "TWAIN Working Group/Sample2/"
#elif defined(TWNDS_OS_APPLE)
#define PROFILELOCATION "TWAIN Working Group/Sample2/"
#else
#endif
CTWAIN_UI* CreateUI(CTWAINDS_FreeImage *pDS);
void DestroyUI(CTWAIN_UI* pUI);
typedef list<string> lstString;
class CTWAIN_UI
{
public:
CTWAIN_UI(CTWAINDS_FreeImage *pDS);
~CTWAIN_UI(){};
/**
* Will show the TWAIN GUI
* @param[in] _pData contains info about if the UI should be shown etc.
* @return a valid TWRC_xxxx return code.
*/
virtual TW_INT16 DisplayTWAINGUI(TW_USERINTERFACE Data, bool bSetup, bool bIndicators);
/**
* Close the user interface for TWAIN
*/
virtual void DestroyTWAINGUI();
virtual void UpdateProgress(bool bShow, unsigned char ucProgress, unsigned int unPageNo, string strProgressTitle);
virtual void Scan();
virtual void Cancel();
virtual void Save();
virtual unsigned int MessageBox(string strMessage,string strTitle, unsigned int unIconID);
virtual bool processEvent(pTW_EVENT _pEvent);
int GetCurrentCapIndex(const TW_UINT16 _unCap);
const IntVector* GetValidCap(const TW_UINT16 _unCap);
const FloatVector* GetValidCapFloat(const TW_UINT16 _unCap);
TW_FRAME GetCurrentFrame();
bool SetCurrentFrame(float fTop, float fLeft, float fBottom, float fRight);
bool GetCapRangeFloat(const TW_UINT16 _unCap, float &fMin, float &fMax, float &fStep);
float GetCapValueFloat(const TW_UINT16 _unCap);
bool SetCapValueFloat(const TW_UINT16 _unCap, float fVal);
bool SetCapValueInt(const TW_UINT16 _unCap, int nVal);
/**
* Initialize combobox with profile names
* @param[in] pcbxProfiles a pointer to CComboBox.
* @return true on success
*/
void TW_GetAllProfiles(lstString& strFileNames);
/**
* Save CustomDSdata to file
* @param[in] strFileName a CString. Name of the file
* @param[in] hData a HGLOBAL. Handle to CustomDSdata
* @param[in] dwDataSize a hData. Size of CustomDSdata
* @return true on success
*/
bool TW_SaveProfileToFile(string strFileName);
/**
* Load CustomDSdata from file
* @param[in] strFileName a CString. Name of the file
* @param[out] hData a pointer to HGLOBAL. Handle to CustomDSdata
* @param[out] dwDataSize a pointer to hData. Size of CustomDSdata
* @return true on success
*/
bool TW_LoadProfileFromFile(string strFileName);
/**
* Delete selected profile from the disk
* @param[in] pcbxProfiles a pointer to CComboBox.
* @return true on success
*/
bool TW_DeleteProfile(string strFileName);
bool ResetAllCaps();
CTWAINDS_FreeImage *m_pDS;
TW_USERINTERFACE m_EnableDSdata;
bool m_bScanning;
bool m_bSetup;
bool m_bIndicators;
string m_strProfilesDirectory;
};
#endif // __TWAIN_UI_H__

BIN
hugaotwainds/TWG-Logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@ -0,0 +1,24 @@
#include "StdAfx.h"
#include "TextDirection.h"
CTextDirection::CTextDirection(void)
{
}
CTextDirection::~CTextDirection(void)
{
}
void CTextDirection::applyInPlace(cv::Mat& pDib)
{
}
bool CTextDirection::getResult()
{
return m_res;
}

View File

@ -0,0 +1,17 @@
#pragma once
#include "ImageApply.h"
class CTextDirection :
public CImageApply
{
public:
CTextDirection(void);
virtual ~CTextDirection(void);
virtual void applyInPlace(cv::Mat& pDib);
bool getResult();
private:
bool m_res;
};

6979
hugaotwainds/TwainString.cpp Normal file

File diff suppressed because it is too large Load Diff

499
hugaotwainds/TwainString.h Normal file
View File

@ -0,0 +1,499 @@
/***************************************************************************
* Copyright ?2007 TWAIN Working Group:
* Adobe Systems Incorporated, AnyDoc Software Inc., Eastman Kodak Company,
* Fujitsu Computer Products of America, JFL Peripheral Solutions Inc.,
* Ricoh Corporation, and Xerox Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TWAIN Working Group nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY TWAIN Working Group ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWAIN Working Group BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
***************************************************************************/
/**
* @file TwainString.h
* Convert TWAIN Constants to Strings
* @author JFL Peripheral Solutions Inc.
* @date Dec 2008
*/
#ifndef __TWAINSTRING_H__
#define __TWAINSTRING_H__
#pragma once
#include "CommonTWAIN.h"
typedef const char*(*pfnStringCvrtFuncType)(const TW_UINT16 _unItem);
/**
* converts the integer CAP value into string form
* @param[in] _unCap the cap
* @return the equivalent cap string
*/
const char* convertCAP_toString(const TW_UINT16 _unCap);
/**
* converts the integer CAP transfer method into string form
* @param[in] _unCap the cap
* @param[in] _unItem the value
* @param[in] _unType the TWAIN Type of the item
* @return the equivalent string
*/
const char* convertCAP_Item_toString(const TW_UINT16 _unCap, const TW_UINT32 _unItem, const TW_UINT16 _unType);
/**
* converts the integer CAP transfer method into string form
* @param[in] _unEI the ExtendedImageInfo
* @param[in] _unItem the value
* @return the equivalent string, or NULL if not found
*/
const char* convertEI_Item_toString(const TW_UINT16 _unEI, const TW_UINT32 _unItem);
/**
* converts the integer CAP transfer method into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_XFERMECH_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP unit into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_UNITS_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Pixel type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_PIXELTYPE_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Pixel flavor value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_PIXELFLAVOR_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Image File format type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_IMAGEFILEFORMAT_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Image File format type value into .xxx extention string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_IMAGEFILEFORMAT_toExt(const TW_UINT16 _unItem);
/**
* converts the integer CAP Compression type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_COMPRESSION_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Alarms type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_ALARMS_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP AutoSize type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_AUTOSIZE_toString(const TW_UINT16 _unItem);
/**
* converts the integer ICAP BarCode Search Mode type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_BARCODESEARCHMODE_toString(const TW_UINT16 _unItem);
/**
* converts the integer ICAP Bit Order type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_BITORDER_toString(const TW_UINT16 _unItem);
/**
* converts the integer ICAP Auto discard blank pages type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_AUTODISCARDBLANKPAGES_toString(const TW_UINT16 _unItem);
/**
* converts the integer ICAP Bitdepth Reduction type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_BITDEPTHREDUCTION_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Supported Barcode Types type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_SUPPORTEDBARCODETYPES_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Cameraside type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_CAMERASIDE_toString(const TW_UINT16 _unItem);
/**
* converts the integer TWEI Pageside type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertTWEI_PAGESIDE_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP ClearBuffers type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_CLEARBUFFERS_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Device Event type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_DEVICEEVENT_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Duplex type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_DUPLEX_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Feeder Alignment type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_FEEDERALIGNMENT_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Feeder Type type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_FEEDERTYPE_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Flash used2 type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_FLASHUSED2_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Feeder Order type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_FEEDERORDER_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Feeder Pocket type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_FEEDERPOCKET_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Flip Rotation type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_FLIPROTATION_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Filter type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_FILTER_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP ICC Profile type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_ICCPROFILE_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Image Filter type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_IMAGEFILTER_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Image Merge type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_IMAGEMERGE_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Job Control type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_JOBCONTROL_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP JPEG Quality type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_JPEGQUALITY_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Light Path type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_LIGHTPATH_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Light Source type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_LIGHTSOURCE_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Noise Filter type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_NOISEFILTER_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Orientation type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_ORIENTATION_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Overscan type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_OVERSCAN_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Planar Chunky type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_PLANARCHUNKY_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Printer Mode type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_PRINTERMODE_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Printer type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_PRINTER_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Power Supply type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_POWERSUPPLY_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Segmented type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertCAP_SEGMENTED_toString(const TW_UINT16 _unItem);
/**
* converts the integer CAP Supported Sizes type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertICAP_SUPPORTEDSIZES_toString(const TW_UINT16 _unItem);
/**
* converts the integer TWEI File System type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertTWEI_FILESYSTEM_toString(const TW_UINT16 _unItem);
/**
* converts the integer TWEI Barcode Rotation type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertTWEI_BARCODEROTATION_toString(const TW_UINT16 _unItem);
/**
* converts the integer TWEI Deskew Status type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertTWEI_DESKEWSTATUS_toString(const TW_UINT16 _unItem);
/**
* converts the integer TWEI MAG Type type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertTWEI_MAGTYPE_toString(const TW_UINT16 _unItem);
/**
* converts the integer TWEI Patch code type value into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertTWEI_PATCHCODE_toString(const TW_UINT16 _unItem);
/**
* converts the integer TWTY value into string form
* @param[in] _unItem the TWTY value
* @return the equivalent string
*/
const char* convertTWTY_toString(const TW_UINT16 _unItem);
/**
* retrieve the extended image info name for a given Info ID for the current image
* @param[in] InfoID the id to retrieve the info of
* @return string of the extended image info
*/
const char* convertExtImageInfoName_toString(int InfoID);
/**
* retrieve the extended image info value for a given Info
* @param[in] ImgInfo the TW_INFO to retrieve the extended image info of
* @return string of the extended image info value
*/
const char* convertExtImageInfoItem_toString(const TW_INFO &ImgInfo);
/**
* converts the TWAIN Return Code into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertReturnCode_toString(const TW_UINT16 _unItem);
/**
* converts the TWAIN Condition Code into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertConditionCode_toString(const TW_UINT16 _unItem);
/**
* converts the TWAIN Message into string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertMessage_toString(const TW_UINT16 _unItem);
/**
* converts the TWAIN Data Group to string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertDataGroup_toString(const TW_UINT16 _unItem);
/**
* converts the TWAIN Data Argument Type to string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertDataArgType_toString(const TW_UINT16 _unItem);
/**
* converts the TWAIN Container Type to string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertContainerType_toString(const TW_UINT16 _unItem);
/**
* converts the TWAIN QuerySupport value to string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char* convertQuerySupport_toString(const TW_UINT32 _unItem);
/**
* converts a TWAIN TWFF_ to the corresponding extension
* @param[in] _unItem the value
* @return the corresponding file extension
*/
const char* convertFileFmt_toExtension(const TW_UINT16 _unItem);
/**
* converts a TWAIN Capability Item value to string form
* @param[in] twCapId the Id of the capability to convert
* @param[in] twItemType the type of the capability item
* @param[in] pValue a pointer to the item
* @return the equivalent string
*/
const char *CapabilityValueToString(TW_UINT16 twCapId, TW_UINT16 twItemType, const void *pValue);
/**
* converts the TWAIN TWFY_ value to string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char *convertFileType_toString(const TW_UINT16 _unItem);
/**
* converts the TWAIN TWFF_ value to string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char *convertFileFormat_toString(const TW_UINT16 _unItem);
/**
* converts the TWAIN TWEJ_ value to string form
* @param[in] _unItem the value
* @return the equivalent string
*/
const char *convertEOJ_toString(const TW_UINT16 _unItem);
#endif // __TWAINSTRING_H__

BIN
hugaotwainds/TwainUIDlg.cpp Normal file

Binary file not shown.

BIN
hugaotwainds/TwainUIDlg.h Normal file

Binary file not shown.

408
hugaotwainds/gscn_drv.cpp Normal file
View File

@ -0,0 +1,408 @@
#include "stdafx.h"
#include "gscn_drv.h"
#include "stdio.h"
#include "turbojpeg.h"
#include "PublicFunc.h"
#include <map>
#include "twainEx.h"
#include "jpeglib.h"
#include "ImageProcDiscardBlank.h"
#include "ImageApply.h"
GScn_Drv::GScn_Drv()
: m_discard(new CImageProcDiscardBlank()),canUseDiscardBlank(false)
{
//run();
m_bRun = false;
devState = DEV_STOP;
isDuplex=TRUE;
m_h_usb_thread=NULL;
}
GScn_Drv::~GScn_Drv()
{
if (m_threadUsb.joinable())
{
//XdPrint("out 1");
m_bRun = false;
//m_threadUsb.join();
}
}
void GScn_Drv::open(int vid, int pid)
{
usb_scan_dev devs = Devices(vid, pid);
if (devs._NumberOfDevs != 0)
{
m_usb.open(devs.dev_infos[0].index);
}
}
static void DoEvents()
{
MSG msg;
if (PeekMessage(&msg
, NULL, 0, 0, PM_REMOVE))
{
DispatchMessage(&msg);
TranslateMessage(&msg);
}
}
cv::Mat GScn_Drv::popMat()
{
boost::lock_guard<boost::mutex> lck(m_imgLocker);
cv::Mat image = m_pImages.popMat();
return image;
}
twainImage GScn_Drv::PopTwainImage()
{
//boost::lock_guard<boost::mutex> lck(m_imgLocker);
//cv::Mat image = m_pImages.front().getMat(pixType);
//int side=m_pImages.front().getSide();
//twainImage img(image,side);
//m_pImages.pop();
return cv::Mat();
}
int GScn_Drv::aquire_image(cv::Mat& image)
{
while (true)
{
if (Get_IsImageQueueEmpty())
{
//Sleep(100);
DoEvents();
if (!is_scan())
break;
}
else
{
if (m_pImages.valid())
{
image = popMat();
return 0;
}
}
}
return -1;
}
void GScn_Drv::reset()
{
boost::lock_guard<boost::mutex> lck(m_imgLocker);
while (!m_pImages.empty())
{
m_pImages.clear();
}
}
void GScn_Drv::pushMat(JpegBuffer& data)
{
//boost::lock_guard<boost::mutex> lck(m_imgLocker);
m_pImages.pushMat(data);
}
BOOL GScn_Drv::IsConnected()
{
return m_usb.is_connected();
}
cv::Mat GScn_Drv::Get_Img_Data(int bufferSize)
{
//boost::lock_guard<boost::mutex> lck(m_Locker);
cv::Mat iData(1, bufferSize,CV_8UC1);
USBCB usbcb = { GET_IMAGE,0,bufferSize };
DWORD transfer;
m_usb.bulk_out(0x00, &usbcb, sizeof(usbcb), &transfer);
m_usb.Read_Data(iData.data, bufferSize, 600, &transfer);
return iData;
}
void GScn_Drv::run()
{
if (!m_threadUsb.joinable())
{
m_bRun = true;
m_threadUsb = boost::thread(&GScn_Drv::usbmain, this);
}
}
INT GScn_Drv::get_decompress_pix_type()
{
return pixType;
}
void GScn_Drv::set_decompress_pix_type(int pixtype)
{
if (pixtype==TWPT_RGB)
{
pixType=TJPF_BGR;
}
else
{
pixType=TJPF_GRAY;
}
}
void GScn_Drv::enableDiscardBlank(bool bVal)
{
canUseDiscardBlank=bVal;
}
void GScn_Drv::SetIsDuplex(BOOL value)
{
isDuplex=value;
}
void GScn_Drv::SetRotate(int rotateType)
{
m_rotate=rotateType;
}
void GScn_Drv::SetBackRotate(bool enBackRoate)
{
backRotate=enBackRoate;
}
void GScn_Drv::setlist(std::vector<std::shared_ptr<CImageApply> >list)
{
m_pImages.setlist(list);
}
DWORD GScn_Drv::usbmain()
{
while (m_bRun)
{
if (!m_usb.is_connected())
{
Sleep(200);
continue;
}
USBCB usbcb = Get_Scanner_Status();
switch (usbcb.u32_Data)
{
case HAVE_IMAGE:
{
int totalNum = usbcb.u32_Count;
DWORD transferCount = 0;
cv::Mat imgData = Get_Img_Data(totalNum);
cv::Mat bufferF = imgData.clone();
cv::Mat bufferB = imgData.clone();
int j = 0;
int k = 0;
for (int i = 0; i < totalNum / 1024; i++)
{
if (imgData.data[1023 + i * 1024] == 0)
{
j++;
memcpy(&(bufferB.data[(j - 1) * 1023]), &(imgData.data[(j + k - 1) * 1024]), 1023);
}
else if (imgData.data[1023 + i * 1024] == 255)
{
k++;
memcpy(&(bufferF.data[(k - 1) * 1023]), &(imgData.data[(j + k - 1) * 1024]), 1023);
}
}
pushMat(JpegBuffer(bufferB,pixType,0,0));
//XdPrint("Enter Front\n");
if (isDuplex)
{
pushMat(JpegBuffer(bufferF,pixType,1,0));
//XdPrint("Enter Back\n");
}
Pop_Image();
break;
}
case STOP_SCAN:
{
devState = DEV_STOP;
break;
}
case COUNT_MODE:
MessageBox(NULL, "计数模式,请先退出计数模式!", "提示", MB_OK | MB_ICONERROR);
devState = DEV_WRONG;
break;
case NO_FEED:
MessageBox(NULL, "无纸,请放置纸张!", "提示", MB_OK | MB_ICONEXCLAMATION);
devState = DEV_WRONG;
break;
case OPEN_COVER:
MessageBox(NULL, "扫描仪开盖!", "警告", MB_OK | MB_ICONERROR);
devState = DEV_WRONG;
break;
case FEED_IN_ERROR:
MessageBox(NULL, "拾纸错误!", "提示", MB_OK | MB_ICONERROR);
devState = DEV_WRONG;
break;
case PAPER_JAM:
MessageBox(NULL, "卡纸!", "提示", MB_OK | MB_ICONERROR);
devState = DEV_WRONG;
break;
case DETECT_DOUBLE_FEED:
MessageBox(NULL, "双张!", "提示", MB_OK | MB_ICONERROR);
devState = DEV_WRONG;
break;
case DETECT_STAPLE:
MessageBox(NULL, "订书针!", "提示", MB_OK | MB_ICONERROR);
devState = DEV_WRONG;
break;
case PAPER_SKEW:
MessageBox(NULL, "纸张歪斜!", "提示", MB_OK | MB_ICONERROR);
devState = DEV_WRONG;
break;
case HARDWARE_ERROR:
MessageBox(NULL, "硬件错误!", "提示", MB_OK | MB_ICONERROR);
devState = DEV_WRONG;
break;
case PC_SCAN_BUSY_or_ERROR:
MessageBox(NULL, "PC错误", "提示", MB_OK | MB_ICONERROR);
devState = DEV_WRONG;
break;
case NORMAL:
break;
default:
break;
}
Sleep(5);
}
m_h_usb_thread = NULL;
return 0;
}
///////////////////////////////////////////////////////////////////////////
void GScn_Drv::Config_Scanner(PUSBCB pUSBCB)
{
if (m_usb.is_connected())
{
boost::lock_guard<boost::mutex> lck(m_imgLocker);
DWORD transfer;
m_usb.bulk_out(0x00, pUSBCB, sizeof(USBCB), &transfer);
}
}
///////////////////////////////////////////////////////////////////////////
void GScn_Drv::Scanner_StartScan(UINT16 count)
{
//count = 0;
if (m_usb.is_connected())
{
boost::lock_guard<boost::mutex> lck(m_imgLocker);
DWORD transfer;
USBCB usbcb = { START_COMMAND,(UINT32)count ,0 };
m_usb.bulk_out(0x00, &usbcb, sizeof(usbcb), &transfer);
devState = DEV_ISRUNNING;
m_pImages.pixType=pixType;
m_pImages.run();
}
}
///////////////////////////////////////////////////////////////////////////
std::string GScn_Drv::GetFWVersion()
{
if (m_usb.is_connected())
{
boost::lock_guard<boost::mutex> lck(m_imgLocker);
std::string pFWVersion = " ";
USBCB usbcb = { GET_FW_VERSION,8,0 };
DWORD transfer;
m_usb.bulk_out(0x00, &usbcb, sizeof(usbcb), &transfer);
m_usb.Read_Data(&pFWVersion[0], 8, 100, &transfer);
return pFWVersion;
}
return "";
}
///////////////////////////////////////////////////////////////////////////
std::string GScn_Drv::GetSerialNum()
{
if (m_usb.is_connected())
{
boost::lock_guard<boost::mutex> lck(m_imgLocker);
std::string pserialNum = " ";
USBCB usbcb = { GET_SERIAL,12,0 };
DWORD transfer;
m_usb.bulk_out(0x00, &usbcb, sizeof(usbcb), &transfer);
m_usb.Read_Data(&pserialNum[0], 12, 100, &transfer);
return pserialNum;
}
return "";
}
///////////////////////////////////////////////////////////////////////////
USBCB GScn_Drv::Get_Scanner_Status()
{
if (!m_usb.is_connected())
{
USBCB errorType = { NO_COMMAND ,PC_SCAN_BUSY_or_ERROR ,0 };
return errorType;
}
boost::lock_guard<boost::mutex> lck(m_imgLocker);
USBCB usbcb = { GET_DSP_STATUS ,0,0 };
DWORD transfer;
m_usb.bulk_out(0x00, &usbcb, sizeof(usbcb), &transfer);
m_usb.Read_Data(&usbcb, sizeof(usbcb), 100, &transfer);
return usbcb;
}
///////////////////////////////////////////////////////////////////////////
bool GScn_Drv::is_scan()
{
boost::lock_guard<boost::mutex> lck(m_imgLocker);
return devState == DEV_ISRUNNING;
}
///////////////////////////////////////////////////////////////////////////
BOOL GScn_Drv::Get_Scanner_PaperOn()
{
if (!m_usb.is_connected())
{
return FALSE;
}
USBCB usbcb = { GET_PAPER_STATUS ,0,0 };
DWORD transfer;
boost::lock_guard<boost::mutex> lck(m_imgLocker);
m_usb.bulk_out(0x00, &usbcb, sizeof(usbcb), &transfer);
m_usb.bulk_in(0x00, &usbcb, sizeof(usbcb), 200, &transfer);
return usbcb.u32_Data != 0;
}
///////////////////////////////////////////////////////////////////////////
void GScn_Drv::Pop_Image()
{
if (!m_usb.is_connected())
{
return;
}
//boost::lock_guard<boost::mutex> lck(m_imgLocker);
USBCB usbcb = { POP_IMAGE ,0,0 };
DWORD transfer;
m_usb.bulk_out(0x00, &usbcb, sizeof(usbcb), &transfer);
}
///////////////////////////////////////////////////////////////////////////
void GScn_Drv::Stop_scan()
{
if (!m_usb.is_connected())
{
return;
}
boost::lock_guard<boost::mutex> lck(m_imgLocker);
USBCB usbcb = { STOP ,0,0 };
DWORD transfer;
m_usb.bulk_out(0x00, &usbcb, sizeof(usbcb), &transfer);
}
///////////////////////////////////////////////////////////////////////////
bool GScn_Drv::Get_IsImageQueueEmpty()
{
boost::lock_guard<boost::mutex> lck(m_imgLocker);
return m_pImages.empty();
}

266
hugaotwainds/gscn_drv.h Normal file
View File

@ -0,0 +1,266 @@
#pragma once
#include "scn_usb.h"
#include <memory>
#include <vector>
#include <string>
#include <queue>
#include <Windows.h>
#include "MutexEx.h"
#include "opencv2/core/core.hpp"
#include <opencv2\highgui\highgui.hpp>
#include "jpeglib.h"
#include <time.h>
#include <boost\thread\mutex.hpp>
#include <boost\thread.hpp>
#include "ImageMatQueue.h"
using namespace cv;
typedef struct tag_USBCB {
UINT32 u32_CMD;
UINT32 u32_Data;
UINT32 u32_Count;
}USBCB, *PUSBCB;
//u32_CMD
enum tagUsbKeyWords :UINT32
{
//无命令
NO_COMMAND = 0,
//获取dsp 状态
GET_DSP_STATUS = 1,
//取图
GET_IMAGE = 2,
//销毁DSP中驻存的图
POP_IMAGE = 3,
//开始扫描命令
START_COMMAND = 4,
//停止扫描命令
STOP = 5,
//获取扫描仪扫描模式
GET_SCAN_MODE = 6,
//获取固件版本号
GET_FW_VERSION = 7,
//返回PC端的状态
SEND_STATUS_PC = 8,
//下发扫描配置参数
CONFIGURED_DATA = 9,
//下发固件信息
SEND_FW = 10,
//获取扫描参数
GET_CONFIG_DATA = 11,
//获取扫描总张数
GET_SCANN_NUM = 12,
//获取有无纸的状态
GET_PAPERFEEDER_STATUS = 13,
//DSP初始化
INIT_HARDWARE_SYS = 14,
//获取有无纸的状态
GET_PAPER_STATUS = 0x0d,
//下发元器件配置参数灰度LED R曝光时间
SEND_COMPONENTS_GR = 15,
//下发元器件配置参数LED G/B曝光时间
SEND_COMPONENTS_GB = 16,
//下发扫描模式
SEND_SCAN_MODE = 17,
//开始进行平场矫正
START_FLAT = 18,
//停止平场矫正
STOP_FLAT = 19,
//下发200dpi彩色平场矫正参数
SEND_200_COLOR_FLAT_DATA = 20,
//下发300dpi彩色平场矫正参数
SEND_300_COLOR_FLAT_DATA = 21,
//获取200dpi彩色平场矫正参数
GET_200_COLOR_FLAT_DATA = 22,
//获取300dpi彩色平场矫正参数
GET_300_COLOR_FLAT_DATA = 23,
//下发200dpi灰度平场校正参数
SEND_200_GRAY_FLAT_DATA = 24,
//下发300dpi灰度平场校正参数
SEND_300_GRAY_FLAT_DATA = 25,
//获取200DPI灰度平场校正参数
GET_200_GRAY_FLAT_DATA = 26,
//获取300DPI灰度平场校正参数
GET_300_GRAY_FLAT_DATA = 27,
//下发序列号命令
SEND_SERIAL = 28,
//获取序列号命令
GET_SERIAL = 29
};
typedef enum tagUsbKeyWords UsbKeyWords, *PUsbKeyWords;
//u32_Data
enum tagUsbSupported
{
//停止扫描
SCAN_STOP = -2,
//异常
HAVE_ERROR = -1,
//正常状态
NORMAL = 0,
//开盖
OPEN_COVER = 1,
// 无纸
NO_FEED = 2,
// 搓纸失败
FEED_IN_ERROR = 4,
// 卡纸
PAPER_JAM = 8,
// 检测到双张
DETECT_DOUBLE_FEED = 16,
// 检测到订书钉
DETECT_STAPLE = 32,
// 纸张倾斜
PAPER_SKEW = 64,
// 自动模式
AUTO_SCAN_MODE = 65,
// 手动模式
MANAUL_SCAN_MODE = 66,
// 计数模式
COUNT_MODE = 67,
// 硬件错误
HARDWARE_ERROR = 68,
// FPGA崩溃
FPGA_ERROR = 68,
// 开始
START_SCAN = 69,
//停止
STOP_SCAN = 70,
//有图
HAVE_IMAGE = 71,
// 更新扫描参数
UPDATE_SCAN_PARAMETER = 72,
// PC繁忙或出错
PC_SCAN_BUSY_or_ERROR = 73
};
typedef enum tagUsbSupported UsbSupported, *PUsbSupported;
enum tagDevState
{
DEV_STOP = -1,
DEV_ISRUNNING,
DEV_WRONG
};
typedef enum tagDevState DevState, PDevState;
enum tagEventIndex
{
EVENT_IMAGE,
EVENT_NUM
};
class twainImage
{
public:
twainImage(){}
~twainImage()
{
release();
}
twainImage(cv::Mat image,int side=-1)
{
this->m_image=image;
this->m_side=side;
this->m_width=image.cols;
this->m_height=image.rows;
}
bool empty()
{
return m_image.empty();
}
int GetWidth()
{
return m_image.cols;
}
int GetHeight()
{
return m_image.rows;
}
void release()
{
if (!m_image.empty())
{
m_image.release();
}
}
public:
cv::Mat m_image;
int m_side;
private:
int m_height;
int m_width;
};
class CImageProcDiscardBlank;
class CImageApply;
class GScn_Drv
{
public:
GScn_Drv();
~GScn_Drv();
void open(int vid, int pid);
//int aquire_image(cv::Mat& image);
int aquire_image(cv::Mat& image);
BOOL IsConnected();
std::string GetFWVersion();
std::string GetSerialNum();
bool is_scan();
USBCB Get_Scanner_Status();
BOOL Get_Scanner_PaperOn();
void Config_Scanner(PUSBCB pUSBCB);
void Scanner_StartScan(UINT16 count);
void Stop_scan();
bool Get_IsImageQueueEmpty();
void reset();
void run();
INT get_decompress_pix_type();
void set_decompress_pix_type(int pixtype);
void enableDiscardBlank(bool bVal);
void SetIsDuplex(BOOL value);
void SetRotate(int rotateType);
void SetBackRotate(bool enBackRoate);
void setlist(std::vector<std::shared_ptr<CImageApply> >list);
private:
cv::Mat popMat();
twainImage PopTwainImage();
void pushMat(JpegBuffer& data);
cv::Mat Get_Img_Data(int buffersize);
TCHAR *m_sMutexName;
DWORD usbmain();
void Pop_Image();
cscn_usb m_usb;
HANDLE m_h_usb_thread;
DWORD m_dw_ctrl_thread_id;
volatile int devState;
ImageMatQueue m_pImages;
bool m_bRun;
boost::mutex m_Locker;
boost::mutex m_imgLocker;
std::shared_ptr<CImageProcDiscardBlank> m_discard;
int pixType;
volatile BOOL isDuplex;
int m_rotate;
bool backRotate;
BOOL canUseDiscardBlank;
boost::thread m_threadUsb;
std::vector<std::shared_ptr<CImageApply>> m_iaList;
};

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
hugaotwainds/hugaotwainds.h Normal file

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More