Exemplo n.º 1
0
void CMemFile::Write(const void* lpBuf, UINT nCount)
{
	ASSERT_VALID(this);

	if (nCount == 0)
		return;

	ASSERT(lpBuf != NULL);
	ASSERT(AfxIsValidAddress(lpBuf, nCount, FALSE));

	if (m_nPosition + nCount > m_nBufferSize)
		GrowFile(m_nPosition + nCount);

	ASSERT(m_nPosition + nCount <= m_nBufferSize);

	Memcpy((BYTE*)m_lpBuffer + m_nPosition, (BYTE*)lpBuf, nCount);

	m_nPosition += nCount;

	if (m_nPosition > m_nFileSize)
		m_nFileSize = m_nPosition;

	ASSERT_VALID(this);
}
Exemplo n.º 2
0
void CMapWordToOb::GetNextAssoc(POSITION& rNextPosition,
	WORD& rKey, CObject*& rValue) const
{
	ASSERT_VALID(this);
	ASSERT(m_pHashTable != NULL);  // never call on empty map

	CAssoc* pAssocRet = (CAssoc*)rNextPosition;
	ASSERT(pAssocRet != NULL);

	if (pAssocRet == (CAssoc*) BEFORE_START_POSITION)
	{
		// find the first association
		for (UINT nBucket = 0; nBucket < m_nHashTableSize; nBucket++)
			if ((pAssocRet = m_pHashTable[nBucket]) != NULL)
				break;
		ASSERT(pAssocRet != NULL);  // must find something
	}

	// find next association
	ASSERT(AfxIsValidAddress(pAssocRet, sizeof(CAssoc)));
	CAssoc* pAssocNext;
	if ((pAssocNext = pAssocRet->pNext) == NULL)
	{
		// go to next bucket
		for (UINT nBucket = pAssocRet->nHashValue + 1;
		  nBucket < m_nHashTableSize; nBucket++)
			if ((pAssocNext = m_pHashTable[nBucket]) != NULL)
				break;
	}

	rNextPosition = (POSITION) pAssocNext;

	// fill in return data
	rKey = pAssocRet->key;
	rValue = pAssocRet->value;
}
Exemplo n.º 3
0
BOOL CRegistry::Write (LPCTSTR pszKey, LPCTSTR pszData)
{
	if (m_bReadOnly)
	{
		ASSERT (FALSE);
		return FALSE;
	}

	ASSERT(m_hKey);
	ASSERT(pszData);
	ASSERT(AfxIsValidAddress(pszData, _tcslen(pszData), FALSE));

	LONG ReturnValue = RegSetValueEx (m_hKey, pszKey, 0L, REG_SZ,
		(CONST BYTE*) pszData, (ULONG) _tcslen(pszData) + 1);

	m_Info.lMessage = ReturnValue;
	m_Info.dwSize = (DWORD) _tcslen(pszData) + 1;
	m_Info.dwType = REG_SZ;

	if(ReturnValue == ERROR_SUCCESS)
		return TRUE;

	return FALSE;
}
Exemplo n.º 4
0
BOOL cNetworkPortController::LockPort(const UINT nPort, const int iFlags)
{
   m_strResult = "";
   
   m_bTcpResult = FALSE;
   m_bUdpResult = FALSE;
   m_strTcpResult = "";
   m_strUdpResult = "";
   
   if ( iFlags == NONE )
   {
      m_strResult = "No socket type specified";
      return FALSE;
   }
   else if ( iFlags > ALL )
   {
      m_strResult = "Invalid socket type specified";
      return FALSE;
   }
   
   CAsyncSocket *pSocket = NULL;
   CString strSocketType;
   CMapWordToOb *pMap = NULL;
   BOOL *pbResult = NULL;
   CString *pstrResult = NULL;

   int iSocketType;

   if ( iFlags & UDP )
   {
      strSocketType = "UDP";
      pMap = &m_mOpenUdpPorts;
      iSocketType = SOCK_DGRAM;
      pbResult = &m_bUdpResult;
      pstrResult = &m_strUdpResult;
   }
   else
   {
      strSocketType = "TCP";
      pMap = &m_mOpenTcpPorts;
      iSocketType = SOCK_STREAM;
      pbResult = &m_bTcpResult;
      pstrResult = &m_strTcpResult;
   }
   
   CString strTemp;

   while ( iSocketType )
   {     
      pSocket = new CAsyncSocket();

      // check for successfull construction socket
      if ( !AfxIsValidAddress( pSocket, 1, FALSE ) || pSocket <= 0 )
      {
         m_strResult = "Error while allocating memory";
         return FALSE;
      }

      // create the socket
      if ( !pSocket->Create( nPort, iSocketType, 0 ) )
      {
         DWORD dwErr = GetLastError();
         delete pSocket;

         if ( dwErr == WSAEADDRINUSE )
            *pstrResult = "In use by another app";
         else
            *pstrResult = "Not locked";

         return FALSE;
      }
      else
      {
         // save ptr to new socket for cleanup later
         pMap->SetAt( nPort, pSocket );

         *pbResult = TRUE;
         *pstrResult = "Locked";
      }

      if ( (iSocketType == SOCK_DGRAM) && (iFlags & TCP) )
      {
         iSocketType = SOCK_STREAM;
         pMap = &m_mOpenTcpPorts;
         pbResult = &m_bTcpResult;
         pstrResult = &m_strTcpResult;
      }
      else
      {
         iSocketType = 0;
         pMap = NULL;
         pbResult = NULL;
         pstrResult = NULL;
      }
   }
   
   return TRUE;
}
Exemplo n.º 5
0
BOOL COXTabViewContainer::InsertPage(int nIndex, 
									 CRuntimeClass* pClass, 
									 CCreateContext* pContext,
									 LPCTSTR lpszTitle/*=NULL*/)
{
	ASSERT_VALID(this);
	ASSERT(nIndex>=0 && nIndex<=GetPageCount());
	ASSERT(pClass!=NULL);
	ASSERT(pClass->IsDerivedFrom(RUNTIME_CLASS(CWnd)));
	ASSERT(AfxIsValidAddress(pClass,sizeof(CRuntimeClass),FALSE));

	if(!(nIndex>=0 && nIndex<=GetPageCount()) || pClass==NULL)
		return FALSE;

	CCreateContext context;
	if(pContext==NULL)
	{
		// if no context specified, generate one from the currently active
		// view if possible
		CView* pOldView=(CView*)GetActivePage();
		if(pOldView!=NULL && pOldView->IsKindOf(RUNTIME_CLASS(CView)))
		{
			// set info about last pane
			ASSERT(context.m_pCurrentFrame==NULL);
			context.m_pLastView=pOldView;
			context.m_pCurrentDoc=pOldView->GetDocument();
			if(context.m_pCurrentDoc!=NULL)
			{
				context.m_pNewDocTemplate=context.m_pCurrentDoc->
					GetDocTemplate();
			}
		}
		pContext=&context;
	}

	CWnd* pWnd;
	TRY
	{
		pWnd=(CWnd*)pClass->CreateObject();
		if(pWnd==NULL)
			AfxThrowMemoryException();
	}
	CATCH_ALL(e)
	{
		TRACE(_T("COXTabViewContainer::InsertPage: Out of memory inserting new page\n"));
		// Note: DELETE_EXCEPTION(e) not required
		return FALSE;
	}
	END_CATCH_ALL

	ASSERT_KINDOF(CWnd,pWnd);
	ASSERT(pWnd->m_hWnd==NULL);       // not yet created

	DWORD dwStyle=AFX_WS_DEFAULT_VIEW;
#if _MFC_VER < 0x0700
	if(afxData.bWin4)
#endif
		dwStyle&=~WS_BORDER;

	DWORD dwID=GetUniqueId();

	// Create with the right size
	if(!pWnd->Create(NULL,NULL,dwStyle,m_rectPage,this,dwID,pContext))
	{
		TRACE(_T("COXTabViewContainer::InsertPage: couldn't create new page\n"));
		// pWnd will be cleaned up by PostNcDestroy
		return FALSE;
	}

	if(InsertPage(nIndex,pWnd,lpszTitle))
	{
		CWnd* pWnd=GetPage(nIndex);
		ASSERT(pWnd!=NULL);
		ASSERT(::IsWindow(pWnd->m_hWnd));
		if(pWnd->IsKindOf(RUNTIME_CLASS(CView)))
		{
			// send initial notification message
			pWnd->SendMessage(WM_INITIALUPDATE);
		}
		return TRUE;
	}

	return FALSE;
}
Exemplo n.º 6
0
BOOL CStkFile::Open(LPCTSTR lpszFileName, UINT nOpenFlags, int nAddToFileEnd, CFileException* pException)
{
	ASSERT(AfxIsValidString(lpszFileName));
	ASSERT(pException == NULL || AfxIsValidAddress(pException, sizeof(CFileException)));

	nOpenFlags &= ~(UINT)typeBinary;

	m_bCloseOnDelete = FALSE;
	m_hFile = (HANDLE)hFileNull;
	m_strFileName.Empty();

	TCHAR szTemp[_MAX_PATH];
	AfxFullPath(szTemp, lpszFileName);
	m_strFileName = szTemp;

	ASSERT(sizeof(HANDLE) == sizeof(UINT));
	ASSERT(shareCompat == 0);


	int nFileLen = 0;
	if (_access(lpszFileName, 06) == -1)
	{
		nFileLen = 16;
	}


	ASSERT((modeRead | modeWrite | modeReadWrite) == 3);

	HANDLE hFile = CreateFile(lpszFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
		OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		if (pException != NULL)
		{
			pException->m_lOsError = GetLastError();
			pException->m_cause = CFileException::OsErrorToException(pException->m_lOsError);
			pException->m_strFileName = lpszFileName;
		}

		return FALSE;
	}

	m_hFile = (HANDLE)hFile;
	m_bCloseOnDelete = TRUE;
	m_nLenFile = GetFileSize((HANDLE)m_hFile, NULL);


	DWORD flProtect = 0;
	flProtect = PAGE_READWRITE;

	if (m_sNameShareMem == "")
	{
		m_hFileMap = CreateFileMapping((HANDLE)m_hFile, NULL, flProtect, 0, nFileLen + m_nLenFile + nAddToFileEnd, NULL);
	}
	else
	{
		m_hFileMap = CreateFileMapping((HANDLE)m_hFile, NULL, flProtect, 0, nFileLen + m_nLenFile + nAddToFileEnd, m_sNameShareMem);
	}
	if (m_hFileMap == NULL)
	{
		CString ss = m_strFileName;
		ss = "文件" + ss;
		AfxMessageBox("遇到错误! hFileMap 是零。请关闭程序后删除此文件!");
		CloseHandle(m_hFileMap);
		return FALSE;
	}
	else if (GetLastError() == ERROR_ALREADY_EXISTS)
	{
	}


	m_lpvFileBegin = (BYTE*)MapViewOfFile(m_hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, nFileLen + m_nLenFile + nAddToFileEnd);
	ASSERT(m_lpvFileBegin != NULL);

	m_lpvFileCurrent = m_lpvFileBegin;

	DWORD dwError;
	if (m_nLenFile == -1 && (dwError = GetLastError()) != NO_ERROR)
	{
		AfxMessageBox("GetFileSize 出错!");
		m_nLenFile = 0;
		m_lpvFileEnd = m_lpvFileBegin;
		return FALSE;
	}

	m_lpvFileEnd = m_lpvFileBegin + m_nLenFile + nAddToFileEnd;

	return TRUE;
}
Exemplo n.º 7
0
BOOL CStdioFile::Open(LPCTSTR lpszFileName, UINT nOpenFlags,
	CFileException* pException)
{
	ASSERT(pException == NULL || AfxIsValidAddress(pException, sizeof(CFileException)));
	ASSERT(lpszFileName != NULL);
	ASSERT(AfxIsValidString(lpszFileName));

	m_pStream = NULL;
	if (!CFile::Open(lpszFileName, (nOpenFlags & ~typeText), pException))
		return FALSE;

	ASSERT(m_hFile != hFileNull);
	ASSERT(m_bCloseOnDelete);

	char szMode[4]; // C-runtime open string
	int nMode = 0;

	// determine read/write mode depending on CFile mode
	if (nOpenFlags & modeCreate)
	{
		if (nOpenFlags & modeNoTruncate)
			szMode[nMode++] = 'a';
		else
			szMode[nMode++] = 'w';
	}
	else if (nOpenFlags & modeWrite)
		szMode[nMode++] = 'a';
	else
		szMode[nMode++] = 'r';

	// add '+' if necessary (when read/write modes mismatched)
	if (szMode[0] == 'r' && (nOpenFlags & modeReadWrite) ||
		szMode[0] != 'r' && !(nOpenFlags & modeWrite))
	{
		// current szMode mismatched, need to add '+' to fix
		szMode[nMode++] = '+';
	}

	// will be inverted if not necessary
	int nFlags = _O_RDONLY|_O_TEXT;
	if (nOpenFlags & (modeWrite|modeReadWrite))
		nFlags ^= _O_RDONLY;

	if (nOpenFlags & typeBinary)
		szMode[nMode++] = 'b', nFlags ^= _O_TEXT;
	else
		szMode[nMode++] = 't';
	szMode[nMode++] = '\0';

	// open a C-runtime low-level file handle
	int nHandle = _open_osfhandle(m_hFile, nFlags);

	// open a C-runtime stream from that handle
	if (nHandle != -1)
		m_pStream = _fdopen(nHandle, szMode);

	if (m_pStream == NULL)
	{
		// an error somewhere along the way...
		if (pException != NULL)
		{
			pException->m_lOsError = _doserrno;
			pException->m_cause = CFileException::OsErrorToException(_doserrno);
		}

		CFile::Abort(); // close m_hFile
		return FALSE;
	}

	return TRUE;
}
Exemplo n.º 8
0
void CObAvlTree::RemoveAt(POSITION position)
{
	//avl tree removing. 
	//For a node having children, the concept model is to find the inorder successor of the removing node,
	//copy the data of IOS to the removing node, then remove the IOS rather than the removing node.
	//the rotation balance begins from the parent of the IOS and traces back to its ancestors.
	//however, the implementation removes the true removing node so that the iterator won't point to a garbage node.

	ASSERT_VALID(this);

	CNode* pOldNode = (CNode*) position;
	ASSERT(AfxIsValidAddress(pOldNode, sizeof(CNode)));

	//block 1. regular binary tree remove, except makeing pRotateNode point to the start tracing node for rotation,
	//and the bubble node's height is replaced the height of the removed node
	
	//case 1. single child, just bubble the child the the parent place
	//case 2. double children, bubble the in order successor to the parent place.
	CNode* pBubbleNode = NULL;
	CNode* pRotateNode = NULL;
	if( pOldNode->pLChild==NULL ){
		pBubbleNode = pOldNode->pRChild;
		pRotateNode = pOldNode->pParent;
	}else if( pOldNode->pRChild==NULL ){
		pBubbleNode = pOldNode->pLChild;
		pRotateNode = pOldNode->pParent;
	}else{
		//case 2
		pBubbleNode = pOldNode->pRChild;
		while( pBubbleNode->pLChild )pBubbleNode = pBubbleNode->pLChild;
		//now pBubbleNode is the IOS, but if bubble node is the right child of the removing node,
		//do not change the right child of the bubble node
		if( pBubbleNode->pParent!=pOldNode ){ //the bubble node is more than one height below the removing node
			pBubbleNode->pParent->pLChild = pBubbleNode->pRChild;
			if( pBubbleNode->pRChild )pBubbleNode->pRChild->pParent=pBubbleNode->pParent;
			//save the rotation place.
			pRotateNode = pBubbleNode->pParent;
			//link the right child of the removing node to bubble node
			pBubbleNode->pRChild = pOldNode->pRChild;
			pOldNode->pRChild->pParent = pBubbleNode;
		}else{
			pRotateNode = pBubbleNode;
		}
		//link the left child of the removing node to the bubble node
		pBubbleNode->pLChild = pOldNode->pLChild;
		pOldNode->pLChild->pParent = pBubbleNode;

		//replace the height of the bubble node by the removed node
		ASSERT(AfxIsValidAddress(pBubbleNode, sizeof(CNode)));
		pBubbleNode->nHeight = pOldNode->nHeight;
	}
	CNode** ppNode=NULL;
	if( pOldNode==m_pNodeRoot )ppNode = &m_pNodeRoot;
	else if( pOldNode->pParent->pLChild==pOldNode )ppNode=&pOldNode->pParent->pLChild;
	else ppNode=&pOldNode->pParent->pRChild;

	*ppNode = pBubbleNode;
	if( pBubbleNode )pBubbleNode->pParent = pOldNode->pParent;

	FreeNode(pOldNode);
	
	//block 2, avl tree balance rotation
	//the loop goes upward to find the rotation node until the root node is reached or the current subtree's height is not changed.
	//if a rotation is done, LOOP CONTINUE beause the height of the subtree at the rotation node may decrease,
	//so the ancestors may need rotation.
	//if the rotation is not done for the node, then adjust the height of the current node.
	while( pRotateNode ){
		int nOldHeight = NODEHEIGHT(pRotateNode);
		if( NODEHEIGHT(pRotateNode->pLChild)-NODEHEIGHT(pRotateNode->pRChild)==2 ){
			//left subtree is too high, rotate to right
			CNode* pChildNode = pRotateNode->pLChild;
			ASSERT( pChildNode!=NULL );
			if( NODEHEIGHT(pChildNode->pLChild)>=NODEHEIGHT(pChildNode->pRChild) ){
				SingleRightRotation( pRotateNode );
			}else{
				ASSERT( NODEHEIGHT(pChildNode->pLChild)<NODEHEIGHT(pChildNode->pRChild) );
				DoubleRightRotation( pRotateNode );
			}
			//after the rotation, the pRotateNode becomes a child of the node at the rotation point
			pRotateNode = pRotateNode->pParent;
		}else if( NODEHEIGHT(pRotateNode->pRChild)-NODEHEIGHT(pRotateNode->pLChild)==2 ){
			//right subtree is too high, rotate to left
			CNode* pChildNode = pRotateNode->pRChild;
			ASSERT( pChildNode!=NULL );
			if( NODEHEIGHT(pChildNode->pLChild)<=NODEHEIGHT(pChildNode->pRChild) ){
				SingleLeftRotation( pRotateNode );
			}else{
				ASSERT( NODEHEIGHT(pChildNode->pLChild)>NODEHEIGHT(pChildNode->pRChild) );
				DoubleLeftRotation( pRotateNode );
			}
			//after the rotation, the pRotateNode becomes a child of the node at the rotation point
			pRotateNode = pRotateNode->pParent;
		}else{
			//no rotation happend here, adjust the height
			CalcHeight( pRotateNode );
		}

		if( nOldHeight==NODEHEIGHT(pRotateNode) ){
			//since the subtree's height is not changed, STOP LOOP since the ancestors' height is maintained.
			break;
		}
		pRotateNode = pRotateNode->pParent;
	}
}
Exemplo n.º 9
0
		AfxInitThread();

	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CFile implementation helpers

#ifdef AfxGetFileName
#undef AfxGetFileName
#endif

UINT AFXAPI AfxGetFileName(LPCTSTR lpszPathName, _Out_opt_cap_(nMax) LPTSTR lpszTitle, UINT nMax)
{
	ASSERT(lpszTitle == NULL ||
		AfxIsValidAddress(lpszTitle, nMax));
	ASSERT(AfxIsValidString(lpszPathName));

	ENSURE_ARG(lpszPathName != NULL);

	// always capture the complete file name including extension (if present)
	LPTSTR lpszTemp = ::PathFindFileName(lpszPathName);

	// lpszTitle can be NULL which just returns the number of bytes
	if (lpszTitle == NULL)
		return lstrlen(lpszTemp)+1;

	// otherwise copy it into the buffer provided
	Checked::tcsncpy_s(lpszTitle, nMax, lpszTemp, _TRUNCATE);
	return 0;
}
Exemplo n.º 10
0
// AfxLoadString must not only check for the appropriate string segment
//   in the resource file, but also that the string is non-zero
int AFXAPI AfxLoadString(UINT nID, LPTSTR lpszBuf, UINT nMaxBuf)
{
	ASSERT(AfxIsValidAddress(lpszBuf, nMaxBuf*sizeof(TCHAR)));

	LPCTSTR lpszName = MAKEINTRESOURCE((nID>>4)+1);
	HINSTANCE hInst;
	int nLen;

	// first check the main module state
	AFX_MODULE_STATE* pModuleState = AfxGetModuleState();
	if (!pModuleState->m_bSystem)
	{
		hInst = AfxGetResourceHandle();
		if (::FindResource(hInst, lpszName, RT_STRING) != NULL &&
			(nLen = ::LoadString(hInst, nID, lpszBuf, nMaxBuf)) != 0)
		{
			// found a non-zero string in app
			return nLen;
		}
	}

	// check non-system DLLs in proper order
	AfxLockGlobals(CRIT_DYNLINKLIST);
	for (CDynLinkLibrary* pDLL = pModuleState->m_libraryList; pDLL != NULL;
		pDLL = pDLL->m_pNextDLL)
	{
		if (!pDLL->m_bSystem && (hInst = pDLL->m_hResource) != NULL &&
		  ::FindResource(hInst, lpszName, RT_STRING) != NULL &&
		  (nLen = ::LoadString(hInst, nID, lpszBuf, nMaxBuf)) != 0)
		{
			AfxUnlockGlobals(CRIT_DYNLINKLIST);
			return nLen;
		}
	}
	AfxUnlockGlobals(CRIT_DYNLINKLIST);

	// check language specific DLL next
	hInst = pModuleState->m_appLangDLL;
	if (hInst != NULL && ::FindResource(hInst, lpszName, RT_STRING) != NULL &&
		(nLen = ::LoadString(hInst, nID, lpszBuf, nMaxBuf)) != 0)
	{
		// found a non-zero string in language DLL
		return nLen;
	}

	// check the system module state
	if (pModuleState->m_bSystem)
	{
		hInst = AfxGetResourceHandle();
		if (::FindResource(hInst, lpszName, RT_STRING) != NULL &&
			(nLen = ::LoadString(hInst, nID, lpszBuf, nMaxBuf)) != 0)
		{
			// found a non-zero string in app
			return nLen;
		}
	}

	// check system DLLs in proper order
	AfxLockGlobals(CRIT_DYNLINKLIST);
	for (pDLL = pModuleState->m_libraryList; pDLL != NULL; pDLL = pDLL->m_pNextDLL)
	{
		if (pDLL->m_bSystem && (hInst = pDLL->m_hResource) != NULL &&
		  ::FindResource(hInst, lpszName, RT_STRING) != NULL &&
		  (nLen = ::LoadString(hInst, nID, lpszBuf, nMaxBuf)) != 0)
		{
			AfxUnlockGlobals(CRIT_DYNLINKLIST);
			return nLen;
		}
	}
	AfxUnlockGlobals(CRIT_DYNLINKLIST);

	// did not find it
	lpszBuf[0] = '\0';
	return 0;
}
Exemplo n.º 11
0
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.

#include "stdafx.h"
#include "sal.h"



/////////////////////////////////////////////////////////////////////////////
// Windows extensions to strings

#ifndef _AFXDLL
int AFXAPI AfxLoadString(UINT nID, __out_ecount(nMaxBuf) LPSTR lpszBuf, UINT nMaxBuf)
{
	ASSERT(AfxIsValidAddress(lpszBuf, nMaxBuf*sizeof(CHAR)));
	if( lpszBuf == NULL || nMaxBuf == 0)
		AfxThrowInvalidArgException();

	const ATLSTRINGRESOURCEIMAGE* pImage;
	int nBytes;

	pImage = AtlGetStringResourceImage(AfxGetResourceHandle(), nID);
	if (pImage == NULL)
	{
		lpszBuf[0] = '\0';
		return 0;
	}
	ASSERT(pImage->nLength != 0);
	nBytes = ::WideCharToMultiByte(CP_ACP, 0, pImage->achString, pImage->nLength, lpszBuf, nMaxBuf-1, NULL, NULL);
	lpszBuf[nBytes] = '\0';
Exemplo n.º 12
0
void CHSCalculate::AutoAdjustUnit(WORD wKey, double dbData, CString &strUnit, int *pUnit)
{
	ASSERT(pUnit && AfxIsValidAddress(pUnit, sizeof(int), TRUE));

	//	首先对于股本类的项
	if( wKey >=COLUMN_CAPITALIZATION_TOTAL 
		&& wKey <= COLUMN_CAPITALIZATION_A2_GIVE )
	{
		if ( dbData >= 10000 || dbData <= -10000 )
		{
			*pUnit	= 10000;
			strUnit	= _T("亿");
		}
		else
		{
			*pUnit	= 1;
			strUnit	= _T("万");
		}
	}

	//	对于金额类的项
	else if ( wKey == COLUMN_FINANCE_TOTAL_ASSETS		//	总资产

		|| wKey == COLUMN_FINANCE_CURRENT_ASSETS		//	流动资产
		|| wKey == COLUMN_FINANCE_CAPITAL_ASSETS		//	固定资产
		|| wKey == COLUMN_FINANCE_UNBODIED_ASSETS		//	无形资产
		|| wKey == COLUMN_FINANCE_LONG_INVESTMENT		//	长期投资
		|| wKey == COLUMN_FINANCE_CURRENT_LIABILITIES	//	流动负债

		|| wKey == COLUMN_FINANCE_LONG_LIABILITIES		//	长期负债

		|| wKey == COLUMN_FINANCE_CAPITAL_ACCFUND		//	资本公积金
		|| wKey == COLUMN_FINANCE_PARTNER_RIGHT			//	股东权益
		|| wKey == COLUMN_FINANCE_MAIN_INCOME			//	主营收入
		|| wKey == COLUMN_FINANCE_MAIN_PROFIT			//	主营利润
		|| wKey == COLUMN_FINANCE_OTHER_PROFIT			//	其他利润

		|| wKey == COLUMN_FINANCE_TAKING_PROFIT			//	营业利润
		|| wKey == COLUMN_FINANCE_YIELD					//	投资收益
		|| wKey == COLUMN_FINANCE_SUBSIDY				//	补贴收入
		|| wKey == COLUMN_FINANCE_OTHER_INCOME			//	营业外收入
		|| wKey == COLUMN_FINANCE_LAST_PROFIT_LOSS		//	上年损益调整

		|| wKey == COLUMN_FINANCE_TOTAL_PROFIT			//	利润总额
		|| wKey == COLUMN_FINANCE_SCOT_PROFIT			//	税后利润
		|| wKey == COLUMN_FINANCE_RETAINED_PROFITS		//	净利润
		|| wKey == COLUMN_FINANCE_UNPAID_PROFIT			//	未分配利润
		)
	{
		if ( dbData >= 100000 || dbData <= -100000 )
		{
			*pUnit	= 100000;
			strUnit	= _T("亿");
		}
		else
		{
			*pUnit	= 10;
			strUnit	= _T("万");
		}
	}
	//	对于每股有关的项
	else if ( wKey == COLUMN_FINANCE_PERSTOCK_ACCFUND	//	每股公积金
		|| wKey == COLUMN_FINANCE_PER_UNPAID			//	每股未分配
		|| wKey == COLUMN_FINANCE_PER_INCOME			//	每股收益
		|| wKey == COLUMN_FINANCE_PER_ASSETS			//	每股净资产
		|| wKey == COLUMN_FINANCE_ADJUST_PER_ASSETS )	//	调整每股净资产
	{
		*pUnit	= 1;
		strUnit	= _T("元");
	}
	//	对于含有%的项来说
	else if ( wKey == COLUMN_FINANCE_PARTNER_RIGHT_RATIO//	股东权益比
		|| wKey == COLUMN_FINANCE_ASSETS_YIELD )		//	净资产收益率
	{
		*pUnit	= 1;
		strUnit	= "%";
	}
	else
	{
		*pUnit	= 1;
		strUnit	= _T("元");
	}
}
Exemplo n.º 13
0
BOOL COXMonthCalCtrl::SetDayState(int nMonths, LPMONTHDAYSTATE pStates)
{
	ASSERT(::IsWindow(m_hWnd));
	ASSERT(AfxIsValidAddress(pStates, nMonths * sizeof(MONTHDAYSTATE), FALSE));
	return (BOOL) ::SendMessage(m_hWnd, MCM_SETDAYSTATE, (WPARAM) nMonths, (LPARAM) pStates);
}
Exemplo n.º 14
0
BOOL COleServerItem::GetMetafileData(LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium)
{
	ASSERT_VALID(this);
	ASSERT(AfxIsValidAddress(lpFormatEtc, sizeof(FORMATETC), FALSE));
	ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM)));
	ASSERT(lpStgMedium->tymed == TYMED_NULL);   // GetDataHere not valid
	ASSERT(lpStgMedium->pUnkForRelease == NULL);

	// medium must be TYMED_MFPICT -- cannot fill in existing HGLOBAL
	if (!(lpFormatEtc->tymed & TYMED_MFPICT) || lpStgMedium->hGlobal != NULL)
		return FALSE;

	// create appropriate memory metafile DC
	CMetaFileDC dc;
	if (!dc.Create())
		return FALSE;

	// create attribute DC according to lpFormatEtc->ptd
	HDC hAttribDC = _AfxOleCreateDC(lpFormatEtc->ptd);
	if (hAttribDC == NULL)
		return FALSE;
	dc.SetAttribDC(hAttribDC);

	// Paint directly into the metafile.
	CSize size(0, 0);
	BOOL bResult = OnDrawEx(&dc, (DVASPECT)lpFormatEtc->dwAspect, size);

	// attribute DC is no longer necessary
	dc.SetAttribDC(NULL);
	::DeleteDC(hAttribDC);

	if (!bResult)
	{
#ifdef _DEBUG
		if (afxTraceFlags & traceOle)
			TRACE0("calling COleServerItem::OnDrawEx()failed.\n");
#endif
		return FALSE;
	}

	HMETAFILE hMF = dc.Close();
	if (hMF == NULL)
		return FALSE;

	HGLOBAL hPict;
	if ((hPict =
		::GlobalAlloc(GMEM_SHARE|GMEM_MOVEABLE, sizeof(METAFILEPICT))) == NULL)
	{
		DeleteMetaFile(hMF);
		return FALSE;
	}
	LPMETAFILEPICT lpPict;
	if ((lpPict = (LPMETAFILEPICT)::GlobalLock(hPict)) == NULL)
	{
		DeleteMetaFile(hMF);
		::GlobalFree(hPict);
		return FALSE;
	}

	// set the metafile size
	lpPict->mm = MM_ANISOTROPIC;
	lpPict->hMF = hMF;
	if (size.cx == 0 && size.cy == 0 &&
		!OnGetExtent((DVASPECT)lpFormatEtc->dwAspect, size))
	{
		TRACE0("Warning: OnGetExtent failed during OnDrawEx --\n");
		TRACE0("\tpresentation metafile may be badly formed!\n");
	}
	lpPict->xExt = size.cx;
	lpPict->yExt = size.cy;  // HIMETRIC height
	if (lpPict->yExt < 0)
	{
		TRACE0("Warning: HIMETRIC natural size is negative.\n");
		lpPict->yExt = -lpPict->yExt;   // backward compatibility fix
	}

#ifdef _DEBUG
	if (lpPict->xExt == 0 || lpPict->yExt == 0)
	{
		// usually the natural extent is set to something interesting
		TRACE0("Warning: COleServerItem has no natural size --\n");
		TRACE0("\twill not work with some apps like MS Write.\n");
	}
#endif

	// return the medium with the hGlobal to the METAFILEPICT
	::GlobalUnlock(hPict);
	lpStgMedium->hGlobal = hPict;
	lpStgMedium->tymed = TYMED_MFPICT;
	return TRUE;
}
Exemplo n.º 15
0
BOOL COleLinkingDoc::Register(COleObjectFactory* pFactory, LPCTSTR lpszPathName)
{
	ASSERT_VALID(this);
	ASSERT(pFactory == NULL ||
		AfxIsValidAddress(pFactory, sizeof(COleObjectFactory)));
	ASSERT(lpszPathName == NULL || AfxIsValidString(lpszPathName));
	ASSERT(m_dwRegister == 0);

	// attach the document to the server
	ASSERT(m_pFactory == NULL || m_pFactory == pFactory);
	m_pFactory = pFactory;

	BOOL bResult = TRUE;

	// create file moniker based on path name
	RELEASE(m_lpMonikerROT);
	m_strMoniker.Empty();
	if (lpszPathName != NULL)
	{
		if (CreateFileMoniker(CStringW(lpszPathName), &m_lpMonikerROT) != S_OK)
			bResult = FALSE;
	}

	// register file moniker as running
	if (m_lpMonikerROT != NULL)
	{
		// see if the object is already running in the ROT
		LPRUNNINGOBJECTTABLE lpROT = NULL;
		VERIFY(GetRunningObjectTable(0, &lpROT) == S_OK);
		ASSERT(lpROT != NULL);
		LPUNKNOWN lpUnk;
		if (lpROT->GetObject(m_lpMonikerROT, &lpUnk) == S_OK)
		{
			// fatal error -- can't register same moniker twice!
			lpUnk->Release();
			RELEASE(m_lpMonikerROT);
			return FALSE;
		}
		// not already running -- so ok to attempt registration
		SCODE sc = lpROT->Register(NULL, (LPUNKNOWN)
			GetInterface(&IID_IUnknown), m_lpMonikerROT, &m_dwRegister);
		lpROT->Release();
		m_strMoniker = lpszPathName;
		if (sc != S_OK)
			bResult = FALSE;
	}

	// update all objects with new moniker
	POSITION pos = GetStartPosition();
	COleClientItem* pItem;
	while ((pItem = GetNextClientItem(pos)) != NULL)
	{
		if (pItem->m_bMoniker)
		{
			ASSERT(pItem->m_lpObject != NULL);
			pItem->m_lpObject->SetMoniker(OLEWHICHMK_CONTAINER,
				m_lpMonikerROT);
		}
	}

	return bResult;
}
Exemplo n.º 16
0
BOOL COleClientItem::SetPrintDevice(const DVTARGETDEVICE* ptd)
{
    ASSERT(ptd == NULL ||
           AfxIsValidAddress(ptd, sizeof(DVTARGETDEVICE), FALSE));

    // get printer device information from cache
    LPOLECACHE lpOleCache;
    DVTARGETDEVICE* ptdCur = NULL;
    DWORD dwConnection;
    if (!GetPrintDeviceInfo(&lpOleCache, &ptdCur, &dwConnection))
    {
        lpOleCache = QUERYINTERFACE(m_lpObject, IOleCache);
        if (lpOleCache == NULL)
            return FALSE;   // no print device info available
    }
    ASSERT(lpOleCache != NULL);

    // both may have no target device (considered equal)
    if (ptd == NULL && ptdCur == NULL)
    {
        lpOleCache->Release();
        CoTaskMemFree(ptdCur);
        return TRUE;
    }

    if (ptd != NULL && ptdCur != NULL)
    {
        // should be non-NULL and valid addresses
        ASSERT(AfxIsValidAddress(ptd, (size_t)ptd->tdSize));
        ASSERT(AfxIsValidAddress(ptdCur, (size_t)ptdCur->tdSize));
        // see if they compare equal
        if (ptdCur->tdSize == ptd->tdSize &&
                memcmp(ptdCur, ptd, (size_t)ptd->tdSize) == 0)
        {
            lpOleCache->Release();
            CoTaskMemFree(ptdCur);
            return TRUE;
        }
    }

    // calling this with NULL will just remove the prevous printer cache
    if (ptd != NULL)
    {
        // new cache is for CF_METAFILEPICT, DVASPECT_CONTENT
        FORMATETC formatEtc;
        formatEtc.cfFormat = CF_METAFILEPICT;
        formatEtc.ptd = (DVTARGETDEVICE*)ptd;
        formatEtc.dwAspect = DVASPECT_CONTENT;
        formatEtc.lindex = -1;
        formatEtc.tymed = TYMED_MFPICT;

        // attempt to cache new format
        DWORD dwNewConnection;
        if (lpOleCache->Cache(&formatEtc, ADVFCACHE_ONSAVE,
                              &dwNewConnection) != S_OK)
        {
            lpOleCache->Release();
            CoTaskMemFree(ptdCur);
            return FALSE;
        }
    }
    // new format is cached successfully, uncache old format
    if (ptdCur != NULL)
    {
        lpOleCache->Uncache(dwConnection);
        CoTaskMemFree(ptdCur);
    }
    // cleanup & return
    lpOleCache->Release();
    return TRUE;
}
Exemplo n.º 17
0
void PLWEMFDecoder::Open (PLDataSource * pDataSrc)
{
	PLASSERT_VALID(this);
  PLASSERT(m_bm == 0);
  PLASSERT(m_memdc == 0);
  PLASSERT(m_hemf == 0);

	SAPMFILEHEADER* pplaceablehdr = NULL;
	bool isadobe = false;
      bool isemf;

	// Get the type of the file (WMF or EMF) from the file name
      if (pDataSrc->NameIsWide()){
        wchar_t* strname = _wcsdup(pDataSrc->GetNameW());
        PLASSERT(strname);
        if (strname == NULL) {
                // This should never happen under 32-Bit, but who knows?
                PLASSERT(false);
                raiseError (PL_ERRNO_MEMORY,"Out of memory during strdup.");
        }
        _wcsupr(strname);
        isemf = wcsstr(strname,L".EMF") != NULL;
        free(strname);
      }
      else{
	char* strname = _strdup(pDataSrc->GetName());
	PLASSERT(strname);
	if (strname == NULL) {
		// This should never happen under 32-Bit, but who knows?
		PLASSERT(false);
		raiseError (PL_ERRNO_MEMORY,"Out of memory during strdup.");
	}
	_strupr(strname);
	bool isemf = strstr(strname,".EMF") != NULL;
	free(strname);
      }

	// Get a DC for the display
	m_dc = ::GetDC(NULL);
	PLASSERT(m_dc);
	if (m_dc == NULL) {
		PLASSERT(false);
		raiseError (PL_ERRNO_MEMORY,"Cannot allocate device context.");
	}

	if (isemf) {
		// We have an enhanced meta file which makes it alot easier
		m_hemf = SetEnhMetaFileBits(pDataSrc->GetFileSize(),pDataSrc->ReadEverything());
	}
	else {
		// Buh, old 16-Bit WMF, Convert it to an enhanced metafile before proceeding.
		// Also, check if this is a placeable metafile with an Adobe Placeable header
		pplaceablehdr = (SAPMFILEHEADER*)pDataSrc->ReadEverything();
		PLBYTE* p = NULL;
		UINT size;
		// If we have an adobe header, skip it to use only the real windows-conform data
		if (pplaceablehdr->key == ALDUSKEY) {
			isadobe = true;
			p = pDataSrc->ReadEverything()+sizeof(SAPMFILEHEADER);
			size = pDataSrc->GetFileSize() - sizeof(SAPMFILEHEADER);
		}
		else {
			// Else use the whole file contents as the metafile and assume
			// a native 16-Bit Windows-conform WMF
			p = pDataSrc->ReadEverything();
			size = pDataSrc->GetFileSize();
		}
		#ifdef _MFC_VER
		PLASSERT(AfxIsValidAddress(p,size,false));
		#endif
		m_hemf = SetWinMetaFileBits(size,p,m_dc,NULL);
	}

	// If m_hemf is NULL, windows refused to load the metafile. If this is
	// the case, we're done. Notify the caller
	if (m_hemf == NULL) {
		raiseError (PL_ERRFORMAT_NOT_SUPPORTED,"Windows Metafile functions failed to load this image.");
	}

	// Get the header from the enhanced metafile, It contains some
	// useful information which will aid us during constuction of
	// the bitmap.
	// The header is of variable length. First get the amount of
	//  memory required for the header
	UINT sizeneeded = GetEnhMetaFileHeader(m_hemf,0,NULL);
	if (sizeneeded == 0) {
		raiseError (PL_ERRFORMAT_UNKNOWN,"No header information in metafile");
	}

	// Allocate storage for the header and read it in
	m_phdr = (LPENHMETAHEADER) new PLBYTE[sizeneeded];
	if (m_phdr == NULL) {
		PLASSERT(false);
		raiseError (PL_ERRNO_MEMORY,"Out of memory during allocation of header.");
	}
	m_phdr->iType = EMR_HEADER;
	m_phdr->nSize = sizeneeded;
	#ifdef _MFC_VER
	PLASSERT(AfxIsValidAddress(m_phdr,sizeneeded,true));
	#endif
	GetEnhMetaFileHeader(m_hemf,sizeneeded,m_phdr);

	int bpp = GetDeviceCaps(m_dc,BITSPIXEL);

	// Calculate the dimensions of the final bitmap. If we have
	// a placeable header in the WMF, we use the dimensions of
	// that image, else we use the calculated dimensions in the
	// EMF
	int width,height;
	if (isadobe) {
		PLASSERT(pplaceablehdr);
		int lpx = GetDeviceCaps(m_dc,LOGPIXELSX);
		int lpy = GetDeviceCaps(m_dc,LOGPIXELSY);
		// Calculate the absolute with and height and transform from twips to pixel
		width  = (int) (pplaceablehdr->Right-pplaceablehdr->Left) * lpx / pplaceablehdr->inch;
		height = (int) (pplaceablehdr->Bottom-pplaceablehdr->Top) * lpy / pplaceablehdr->inch;
	}
	else {
		// Use the rclFrame of the header because it is the true device independent
		// information and also some applications (e.g. Corel) don't fill the
		// rclBounds correctly
		// Using:
		//     MetaPixelsX = MetaWidthMM * MetaPixels / (MetaMM * 100);
		// where:
		//     MetaWidthMM = metafile width in 0.01mm units
		//     MetaPixels  = width in pixels of the reference device
		//     MetaMM      = width in millimeters of the reference device
		// Same applies to the Y axis
		width  = ((m_phdr->rclFrame.right  - m_phdr->rclFrame.left) * m_phdr->szlDevice.cx) / (m_phdr->szlMillimeters.cx*100);
		height = ((m_phdr->rclFrame.bottom  - m_phdr->rclFrame.top) * m_phdr->szlDevice.cy) / (m_phdr->szlMillimeters.cy*100);
	}

	// If this is a very old WMF without a PLACEABLE info,
	// we use somewhat meaningful defaults. Also, if the header was
	// not written correctly, we use this as a fallback
	if (width <= 0) {
		width = 320;
	}
	if (height <= 0) {
		height = 200;
	}

	// Create a device content for the screen, and a memory device
	// content to play the metafile to

	m_memdc = CreateCompatibleDC(m_dc);
	PLASSERT(m_memdc);
	if (m_memdc == NULL) {
		PLASSERT(false);
		raiseError (PL_ERRNO_MEMORY,"Cannot allocate device context.");
	}

	m_bm = CreateCompatibleBitmap(m_dc,width,height);
	if (m_bm == NULL) {
		PLASSERT(false);
		raiseError (PL_ERRNO_MEMORY,"Cannot allocate memory bitmap.");
	}

	m_holdbm = SelectObject(m_memdc,m_bm);

	// If the metafile has a palette, read it in
	UINT pe = GetEnhMetaFilePaletteEntries(m_hemf, 0, NULL);

	// pe is the real number of palette entries. To make the resulting
	// bitmap more useful, we always setup a 256 color palette if the
	// metafile has a palette
  if (pe>0 && pe<256)
  {
    SetBmpInfo (PLPoint (width, height), PLPoint(0,0), 
             PLPixelFormat::L8);
	}
	else 
  {
    SetBmpInfo (PLPoint (width, height), PLPoint(0,0), 
            PLPixelFormat::B8G8R8A8);
  }
}
Exemplo n.º 18
0
void CModuleWnd::GetDragInfoData(LPSTGMEDIUM lpStgMedium)
{
	ASSERT_VALID(this);
	ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM)));
	
	int nItem;
	CModuleDoc::CModule* pModule;
	CRect rcBound;
	rcBound.SetRectEmpty();
	
	CClientDC dc(this);
	dc.BeginPath();
	
	POSITION pos = GetListCtrl()->GetFirstSelectedItemPosition();
	while (pos)
	{
		nItem = GetListCtrl()->GetNextSelectedItem(pos);
		pModule = m_pCurrentDocument->GetModule(nItem);

		CRect rcObj = pModule->m_rcPosition.GetRECT();
		rcObj.NormalizeRect();
		rcBound.UnionRect(rcBound, rcObj);

		dc.MoveTo(rcObj.left, rcObj.top);
		dc.LineTo(rcObj.right, rcObj.top);
		dc.LineTo(rcObj.right, rcObj.bottom);
		dc.LineTo(rcObj.left, rcObj.bottom);
		dc.LineTo(rcObj.left, rcObj.top);
	}
	
	dc.EndPath();
	
	
	CPoint ptStart = rcBound.CenterPoint();
	theApp.AlignToGrid(ptStart);
	
	LPSTREAM lpStream;
	if (::CreateStreamOnHGlobal(NULL, TRUE, &lpStream) != S_OK)
		AfxThrowMemoryException();
	
	ASSERT(lpStream != NULL);
	
	lpStream->Write(&rcBound, sizeof(CRect), NULL);
	lpStream->Write(&ptStart, sizeof(CPoint), NULL);
	
	int iNumPoints = dc.GetPath(NULL, NULL, 0);
	
	CPoint* pPoints = new CPoint[iNumPoints];
	if (pPoints == NULL)
		AfxThrowMemoryException();
	BYTE* pTypes = new BYTE[iNumPoints];
	if (pTypes == NULL)
		AfxThrowMemoryException();
	
	iNumPoints = dc.GetPath(pPoints, pTypes, iNumPoints);
	
	lpStream->Write(&iNumPoints, sizeof(int), NULL);
	lpStream->Write(pPoints, sizeof(CPoint) * iNumPoints, NULL);
	lpStream->Write(pTypes, sizeof(BYTE) * iNumPoints, NULL);
	
	if (pPoints != NULL)
		delete pPoints;
	if (pTypes != NULL)
		delete pTypes;
	
	// setup the STGMEDIUM
	lpStgMedium->tymed = TYMED_ISTREAM;
	lpStgMedium->pstm = lpStream;
	lpStgMedium->pUnkForRelease = NULL;
}
Exemplo n.º 19
0
static BOOL AFXAPI _ParseURLWorker(LPCTSTR pstrURL,
	LPURL_COMPONENTS lpComponents, DWORD& dwServiceType,
	INTERNET_PORT& nPort, DWORD dwFlags)
{
	// this function will return bogus stuff if lpComponents
	// isn't set up to copy the components

	ASSERT(lpComponents != NULL && pstrURL != NULL);
	if (lpComponents == NULL || pstrURL == NULL)
		return FALSE;
	ASSERT(lpComponents->dwHostNameLength == 0 ||
			lpComponents->lpszHostName != NULL);
	ASSERT(lpComponents->dwUrlPathLength == 0 ||
			lpComponents->lpszUrlPath != NULL);
	ASSERT(lpComponents->dwUserNameLength == 0 ||
			lpComponents->lpszUserName != NULL);
	ASSERT(lpComponents->dwPasswordLength == 0 ||
			lpComponents->lpszPassword != NULL);

	ASSERT(AfxIsValidAddress(lpComponents, sizeof(URL_COMPONENTS), TRUE));

	LPTSTR pstrCanonicalizedURL;
	TCHAR szCanonicalizedURL[INTERNET_MAX_URL_LENGTH];
	DWORD dwNeededLength = INTERNET_MAX_URL_LENGTH;
	BOOL bRetVal;
	BOOL bMustFree = FALSE;
	DWORD dwCanonicalizeFlags = dwFlags &
		(ICU_NO_ENCODE | ICU_DECODE | ICU_NO_META |
		ICU_ENCODE_SPACES_ONLY | ICU_BROWSER_MODE);
	DWORD dwCrackFlags = dwFlags & (ICU_ESCAPE | ICU_USERNAME);

	bRetVal = InternetCanonicalizeUrl(pstrURL, szCanonicalizedURL,
		&dwNeededLength, dwCanonicalizeFlags);

	if (!bRetVal)
	{
		if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER)
			return FALSE;

		pstrCanonicalizedURL = new TCHAR[dwNeededLength];
		bMustFree = TRUE;
		bRetVal = InternetCanonicalizeUrl(pstrURL, pstrCanonicalizedURL,
			&dwNeededLength, dwCanonicalizeFlags);
		if (!bRetVal)
		{
			delete [] pstrCanonicalizedURL;
			return FALSE;
		}
	}
	else
		pstrCanonicalizedURL = szCanonicalizedURL;

	// now that it's safely canonicalized, crack it

	bRetVal = InternetCrackUrl(pstrCanonicalizedURL, 0,
						dwCrackFlags, lpComponents);
	if (bMustFree)
		delete [] pstrCanonicalizedURL;

	// convert to MFC-style service ID

	if (!bRetVal)
		dwServiceType = INET_SERVICE_UNK;
	else
	{
		nPort = lpComponents->nPort;
		switch (lpComponents->nScheme)
		{
		case INTERNET_SCHEME_FTP:
			dwServiceType = INET_SERVICE_FTP;
			break;

		case INTERNET_SCHEME_GOPHER:
			dwServiceType = INET_SERVICE_GOPHER;
			break;

		case INTERNET_SCHEME_HTTP:
			dwServiceType = INET_SERVICE_HTTP;
			break;

		case INTERNET_SCHEME_HTTPS:
			dwServiceType = INET_SERVICE_HTTPS;
			break;

		case INTERNET_SCHEME_FILE:
			dwServiceType = INET_SERVICE_FILE;
			break;

		case INTERNET_SCHEME_NEWS:
			dwServiceType = INET_SERVICE_NNTP;
			break;

		case INTERNET_SCHEME_MAILTO:
			dwServiceType = INET_SERVICE_MAILTO;
			break;

		default:
			dwServiceType = INET_SERVICE_UNK;
		}
	}

	return bRetVal;
}
Exemplo n.º 20
0
cServerSocket::~cServerSocket()
{
   if ( AfxIsValidAddress( m_pDataSocket, 1, FALSE ) )
      delete m_pDataSocket;
}
Exemplo n.º 21
0
void CDC::DrawDragRect(LPCRECT lpRect, SIZE size,
	LPCRECT lpRectLast, SIZE sizeLast, CBrush* pBrush, CBrush* pBrushLast)
{
	ASSERT(AfxIsValidAddress(lpRect, sizeof(RECT), FALSE));
	ASSERT(lpRectLast == NULL ||
		AfxIsValidAddress(lpRectLast, sizeof(RECT), FALSE));

	// first, determine the update region and select it
	CRgn rgnNew;
	CRgn rgnOutside, rgnInside;
	rgnOutside.CreateRectRgnIndirect(lpRect);
	CRect rect = *lpRect;
	rect.InflateRect(-size.cx, -size.cy);
	rect.IntersectRect(rect, lpRect);
	rgnInside.CreateRectRgnIndirect(rect);
	rgnNew.CreateRectRgn(0, 0, 0, 0);
	rgnNew.CombineRgn(&rgnOutside, &rgnInside, RGN_XOR);

	CBrush* pBrushOld = NULL;
	if (pBrush == NULL)
		pBrush = CDC::GetHalftoneBrush();
	if (pBrushLast == NULL)
		pBrushLast = pBrush;

	CRgn rgnLast, rgnUpdate;
	if (lpRectLast != NULL)
	{
		// find difference between new region and old region
		rgnLast.CreateRectRgn(0, 0, 0, 0);
		rgnOutside.SetRectRgn(lpRectLast);
		rect = *lpRectLast;
		rect.InflateRect(-sizeLast.cx, -sizeLast.cy);
		rect.IntersectRect(rect, lpRectLast);
		rgnInside.SetRectRgn(rect);
		rgnLast.CombineRgn(&rgnOutside, &rgnInside, RGN_XOR);

		// only diff them if brushes are the same
		if (pBrush->m_hObject == pBrushLast->m_hObject)
		{
			rgnUpdate.CreateRectRgn(0, 0, 0, 0);
			rgnUpdate.CombineRgn(&rgnLast, &rgnNew, RGN_XOR);
		}
	}
	if (pBrush->m_hObject != pBrushLast->m_hObject && lpRectLast != NULL)
	{
		// brushes are different -- erase old region first
		SelectClipRgn(&rgnLast);
		GetClipBox(&rect);
		pBrushOld = SelectObject(pBrushLast);
		PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);
		SelectObject(pBrushOld);
		pBrushOld = NULL;
	}

	// draw into the update/new region
	SelectClipRgn(rgnUpdate.m_hObject != NULL ? &rgnUpdate : &rgnNew);
	GetClipBox(&rect);
	pBrushOld = SelectObject(pBrush);
	PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT);

	// cleanup DC
	if (pBrushOld != NULL)
		SelectObject(pBrushOld);
	SelectClipRgn(NULL);
}
Exemplo n.º 22
0
BOOL COleControl::SetPropsetData(LPFORMATETC lpFormatEtc,
		LPSTGMEDIUM lpStgMedium, REFCLSID fmtid)
{
	UNUSED(lpFormatEtc); // unused in release builds

	ASSERT_VALID(this);
	ASSERT(AfxIsValidAddress(lpFormatEtc, sizeof(FORMATETC), FALSE));
	ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM)));

	// Get the stream that contains the property set.

	LPSTORAGE lpStorage = NULL;
	LPSTREAM lpStream = NULL;

	switch (lpStgMedium->tymed)
	{
	case TYMED_ISTORAGE:
		{
			lpStorage = lpStgMedium->pstg;
			ASSERT_POINTER(lpStorage, IStorage);
			if (FAILED(lpStorage->OpenStream(OLESTR("Contents"), 0,
					STGM_SHARE_EXCLUSIVE|STGM_READ, 0, &lpStream)))
			{
				TRACE0("Failed to open content stream.\n");
				return FALSE;
			}
		}
		break;

	case TYMED_ISTREAM:
		lpStorage = NULL;
		lpStream = lpStgMedium->pstm;
		break;

	default:
		TRACE0("Propset only supported for stream or storage.\n");
		return FALSE;
	}

	ASSERT_POINTER(lpStream, IStream);

	// Read the property set from the stream.

	CPropertySet pset;
	if (!pset.ReadFromStream(lpStream))
	{
		TRACE0("CPropertySet::ReadFromStream failed.\n");
		return FALSE;
	}

	CPropertySection* ppsec = pset.GetSection(fmtid);
	if (ppsec == NULL)
	{
		TRACE0("CLSID_PersistPropset section not found in property set.\n");
		return FALSE;
	}

	// Detect whether we're converting a VBX
	m_bConvertVBX = (BYTE)IsEqualGUID(fmtid, CLSID_ConvertVBX);

	// Parse the property set.

	CPropsetPropExchange propx(*ppsec, lpStorage, TRUE);

	BOOL bPropExchange = FALSE;
	TRY
	{
		DoPropExchange(&propx);
		bPropExchange = TRUE;
	}
	END_TRY

	// Properties have probably changed
	BoundPropertyChanged(DISPID_UNKNOWN);
	InvalidateControl();

	m_bConvertVBX = FALSE;

	// Clear the modified flag.
	m_bModified = FALSE;

	// Unless IOleObject::SetClientSite is called after this, we can
	// count on ambient properties being available while loading.
	m_bCountOnAmbients = TRUE;

	// Properties have been initialized
	m_bInitialized = TRUE;

	// Cleanup.
	if (lpStorage != NULL)      // If we called OpenStream(), release now.
		lpStream->Release();

	BoundPropertyChanged(DISPID_UNKNOWN);
	return bPropExchange;
}
Exemplo n.º 23
0
static UINT AFXAPI
ClipLine(CDC* pDC, int aCharWidths[256], int cxLine, int nTabStop,
	LPCTSTR lpszText, UINT nIndex, UINT nIndexEnd)
{
	ASSERT_VALID(pDC);
	ASSERT(nIndex < nIndexEnd);
	ASSERT(AfxIsValidAddress(lpszText, nIndexEnd, FALSE));
	UNUSED_ALWAYS(nTabStop);    // unused in Mac build

	TEXTMETRIC tm;
	::GetTextMetrics(pDC->m_hDC, &tm);

	// make an initial guess on the number of characters that will fit
	int cx = 0;
	LPCTSTR lpszStart = lpszText + nIndex;
	LPCTSTR lpszStop = lpszText + nIndexEnd;
	LPCTSTR lpsz = lpszStart;
	while (lpsz < lpszStop)
	{
#ifndef _MAC
		if (*lpsz == '\t')
			cx += nTabStop - (cx % nTabStop);
		else
#endif
		{
#ifdef _UNICODE
			if (*lpsz <= 0xFF)
				cx += aCharWidths[(BYTE)*lpsz];
			else
				cx += tm.tmAveCharWidth;
#else //_UNICODE
			if (_afxDBCS && _istlead(*lpsz))
			{
				++lpsz;
				cx += tm.tmAveCharWidth;
			}
			else
				cx += aCharWidths[(BYTE)*lpsz];
#endif //!_UNICODE
		}
		++lpsz;
		if (cx > cxLine)
			break;
	}

	// adjust for errors in the guess
#ifndef _MAC
	cx = pDC->GetTabbedTextExtent(lpszStart, lpsz-lpszStart, 1, &nTabStop).cx;
#else
	cx = pDC->GetTextExtent(lpszStart, lpsz-lpszStart).cx;
#endif
	if (cx > cxLine)
	{
		// remove characters until it fits
		do
		{
			ASSERT(lpsz != lpszStart);
			if (_afxDBCS)
				lpsz = _tcsdec(lpszStart, lpsz);
			else
				--lpsz;
#ifndef _MAC
			cx = pDC->GetTabbedTextExtent(lpszStart, lpsz-lpszStart, 1, &nTabStop).cx;
#else
			cx = pDC->GetTextExtent(lpszStart, lpsz-lpszStart).cx;
#endif
		} while (cx > cxLine);
	}
	else if (cx < cxLine)
	{
		// add characters until it doesn't fit
		while (lpsz < lpszStop)
		{
			lpsz = _tcsinc(lpsz);
			ASSERT(lpsz <= lpszStop);
#ifndef _MAC
			cx = pDC->GetTabbedTextExtent(lpszStart, lpsz-lpszStart, 1, &nTabStop).cx;
#else
			cx = pDC->GetTextExtent(lpszStart, lpsz-lpszStart).cx;
#endif
			if (cx > cxLine)
			{
				if (_afxDBCS)
					lpsz = _tcsdec(lpszStart, lpsz);
				else
					--lpsz;
				break;
			}
		}
	}

	// return index of character just past the last that would fit
	return lpsz - lpszText;
}
Exemplo n.º 24
0
BOOL CPropsetPropExchange::ExchangeProp(LPCTSTR pszPropName, VARTYPE vtProp,
	void* pvProp, const void* pvDefault)
{
	USES_CONVERSION;

	ASSERT(AfxIsValidString(pszPropName));
	ASSERT(AfxIsValidAddress(pvProp, 1, FALSE));
	ASSERT((pvDefault == NULL) || AfxIsValidAddress(pvDefault, 1, FALSE));

	BOOL bSuccess = FALSE;

	if (m_bLoading)
	{
		DWORD dwPropID;
		LPVOID pvData;
		CProperty* pprop;

		if (m_psec.GetID(pszPropName, &dwPropID) &&
			((pprop = m_psec.GetProperty(dwPropID)) != NULL) &&
			((pvData = pprop->Get()) != NULL))
		{
			VARTYPE vtData = (VARTYPE)pprop->GetType();

			CString strTmp;

#ifdef _UNICODE
			// Unicode is "native" format
			if ((vtData == VT_BSTR) || (vtData == VT_LPWSTR))
#else
			// ANSI is "native" format
			if ((vtData == VT_BSTR) || (vtData == VT_LPSTR))
#endif
			{
				strTmp = (LPCTSTR)pvData;
			}

#ifdef _UNICODE
			else if (vtData == VT_LPSTR)
			{
				// Convert from ANSI to Unicode
				strTmp = (LPCSTR)pvData;
			}
#else
			else if (vtData == VT_LPWSTR)
			{
				// Convert from Unicode to ANSI
				strTmp = (LPCWSTR)pvData;
			}
#endif

			switch (vtProp)
			{
			case VT_LPSTR:
			case VT_BSTR:
				bSuccess = _AfxCopyPropValue(VT_BSTR, pvProp, &strTmp);
				break;

			case VT_BOOL:
				{
					short sProp;
					BSTR bstrTmp = NULL;

					if ((vtData == VT_BSTR) || (vtData == VT_LPSTR) ||
						(vtData == VT_LPWSTR))
					{
						bstrTmp = SysAllocString(T2COLE(strTmp));
						pvData = &bstrTmp;
						vtData = VT_BSTR;
					}

					bSuccess = _AfxCoerceNumber(&sProp, VT_BOOL, pvData,
						vtData);

					if (bstrTmp != NULL)
						SysFreeString(bstrTmp);

					if (bSuccess)
					{
						ASSERT((sProp == -1) || (sProp == 0));
						*(BOOL*)pvProp = !!sProp;
					}
				}
				break;

			case VT_I2:
			case VT_I4:
			case VT_CY:
			case VT_R4:
			case VT_R8:
				bSuccess = _AfxCoerceNumber(pvProp, vtProp, pvData, vtData);
				break;
			}
		}
		else
		{
			bSuccess = _AfxCopyPropValue(vtProp, pvProp, pvDefault);
		}
	}
	else
	{
		if (!_AfxIsSamePropValue(vtProp, pvProp, pvDefault))
		{
			++m_dwPropID;

			LPVOID pvData = NULL;
			BOOL bData;

			switch (vtProp)
			{
			case VT_LPSTR:
			case VT_BSTR:
				pvData = (LPVOID)(LPCTSTR)*(CString*)pvProp;
				break;

			case VT_BOOL:
				// Convert boolean value to -1 or 0.
				bData = (*(BOOL*)pvProp) ? -1 : 0;
				pvData = &bData;
				break;

			case VT_I2:
			case VT_I4:
			case VT_CY:
			case VT_R4:
			case VT_R8:
				pvData = pvProp;
				break;
			}

			bSuccess = m_psec.SetName(m_dwPropID, pszPropName) &&
				m_psec.Set(m_dwPropID, pvData, vtProp);
		}
		else
		{
			bSuccess = TRUE;
		}
	}

	return bSuccess;
}
Exemplo n.º 25
0
BOOL CSizingTabCtrlBar::AddView(LPCTSTR lpszLabel, CRuntimeClass *pViewClass, CCreateContext *pContext)
{	

#ifdef _DEBUG
	ASSERT_VALID(this);
	ASSERT(pViewClass != NULL);
	ASSERT(pViewClass->IsDerivedFrom(RUNTIME_CLASS(CWnd)));
	ASSERT(AfxIsValidAddress(pViewClass, sizeof(CRuntimeClass), FALSE));
#endif

	CCreateContext context;
	if (pContext == NULL)
	{
		// if no context specified, generate one from the currently selected
		//  client if possible
		CView* pOldView = NULL;
		if (pOldView != NULL && pOldView->IsKindOf(RUNTIME_CLASS(CView)))
		{
			// set info about last pane
			ASSERT(context.m_pCurrentFrame == NULL);
			context.m_pLastView = pOldView;
			context.m_pCurrentDoc = pOldView->GetDocument();
			if (context.m_pCurrentDoc != NULL)
				context.m_pNewDocTemplate =
				context.m_pCurrentDoc->GetDocTemplate();
		}
		pContext = &context;
	}
	
	CWnd* pWnd;
	TRY
	{
		pWnd = (CWnd*)pViewClass->CreateObject();
		if (pWnd == NULL)
			AfxThrowMemoryException();
	}
	CATCH_ALL(e)
	{
		TRACE0("Out of memory creating a view.\n");
		// Note: DELETE_EXCEPTION(e) not required
		return FALSE;
	}
	END_CATCH_ALL
		
    ASSERT_KINDOF(CWnd, pWnd);
	ASSERT(pWnd->m_hWnd == NULL);       // not yet created
	
	DWORD dwStyle = AFX_WS_DEFAULT_VIEW;
	CRect rect;
	// Create with the right size and position
	if (!pWnd->Create(NULL, NULL, dwStyle, rect, this, 0, pContext))
	{
		TRACE0("Warning: couldn't create client pane for view.\n");
		// pWnd will be cleaned up by PostNcDestroy
		return FALSE;
	}
	m_pActiveView = (CView*) pWnd;

	TCB_ITEM *pMember=new TCB_ITEM;
	pMember->pWnd=pWnd;
	_tcscpy(pMember->szLabel, lpszLabel);
	m_views.AddTail(pMember);

	int nViews = m_views.GetCount();
	if (nViews!=1)
	{
		pWnd->EnableWindow(FALSE);
		pWnd->ShowWindow(SW_HIDE);
	}
	else
	{
		((CFrameWnd *)GetParent())->SetActiveView((CView *)m_pActiveView);
	}

	TC_ITEM tci;
	tci.mask = TCIF_TEXT | TCIF_IMAGE;
	tci.pszText = (LPTSTR)(LPCTSTR)lpszLabel;
	tci.iImage = nViews-1;
	m_tabctrl.InsertItem(nViews, &tci);

	return TRUE;
}
Exemplo n.º 26
0
BOOL COleControl::GetPropsetData(LPFORMATETC lpFormatEtc,
		LPSTGMEDIUM lpStgMedium, REFCLSID fmtid)
{
	ASSERT_VALID(this);
	ASSERT(AfxIsValidAddress(lpFormatEtc, sizeof(FORMATETC), FALSE));
	ASSERT(AfxIsValidAddress(lpStgMedium, sizeof(STGMEDIUM)));

	BOOL bGetDataHere = (lpStgMedium->tymed != TYMED_NULL);

	// Allow IStream or IStorage as the storage medium.

	if (!(lpFormatEtc->tymed & (TYMED_ISTREAM|TYMED_ISTORAGE)))
	{
		TRACE0("Propset only supported for stream or storage.\n");
		return FALSE;
	}

	LPSTORAGE lpStorage = NULL;
	LPSTREAM lpStream = NULL;

	if (lpFormatEtc->tymed & TYMED_ISTORAGE)
	{
		// Caller wants propset data in a storage object.

		if (bGetDataHere)
		{
			// Use the caller-supplied storage object.
			lpStorage = lpStgMedium->pstg;
		}
		else
		{
			// Create a storage object on a memory ILockBytes implementation.
			LPLOCKBYTES lpLockBytes = NULL;

			if (FAILED(CreateILockBytesOnHGlobal(NULL, TRUE, &lpLockBytes)))
			{
				TRACE0("CreateILockBytesOnHGlobal failed.\n");
				return FALSE;
			}

			ASSERT_POINTER(lpLockBytes, ILockBytes);

			if (FAILED(StgCreateDocfileOnILockBytes(lpLockBytes,
					STGM_SHARE_EXCLUSIVE|STGM_CREATE|STGM_READWRITE, 0,
					&lpStorage)))
			{
				TRACE0("StgCreateDocfileOnILockBytes failed.\n");
				lpLockBytes->Release();
				return FALSE;
			}

			// Docfile now has reference to ILockBytes, so release ours.
			lpLockBytes->Release();
		}

		ASSERT_POINTER(lpStorage, IStorage);

		// Create a stream within the storage.
		if (FAILED(lpStorage->CreateStream(OLESTR("Contents"),
				STGM_SHARE_EXCLUSIVE|STGM_CREATE|STGM_READWRITE, 0, 0,
				&lpStream)))
		{
			TRACE0("IStorage::CreateStream failed.\n");
			if (!bGetDataHere)
				lpStorage->Release();
			return FALSE;
		}
	}
	else
	{
		// Caller wants propset data in a stream object.

		if (bGetDataHere)
		{
			// Use the caller-supplied stream object
			lpStream = lpStgMedium->pstm;
		}
		else
		{
			lpStream = _AfxCreateMemoryStream();
			if (lpStream == NULL)
				return FALSE;
		}
	}

	ASSERT_POINTER(lpStream, IStream);

	// Create the property set.

	CLSID clsid;
	GetClassID(&clsid);
	CPropertySet pset(clsid);
	pset.SetOSVersion(MAKELONG(LOWORD(GetVersion()), OSTYPE));
	CPropertySection* ppsec = pset.AddSection(fmtid);
	if (ppsec == NULL)
	{
		TRACE0("CPropertySet::AddSection failed.\n");
		lpStream->Release();
		lpStorage->Release();
		return FALSE;
	}

	// Set the name, based on the ambient display name (from the container).
	ppsec->SetSectionName(AmbientDisplayName());

	CPropsetPropExchange propx(*ppsec, lpStorage, FALSE);

	BOOL bPropExchange = FALSE;
	TRY
	{
		DoPropExchange(&propx);
		bPropExchange = TRUE;
	}
	END_TRY

	if (!bPropExchange)
	{
		TRACE0("DoPropExchange failed.\n");
		lpStream->Release();
		lpStorage->Release();
		return FALSE;
	}

	// Store the property set in the stream.

	if (FAILED(pset.WriteToStream(lpStream)))
	{
		TRACE0("CPropertySet::WriteToStream failed.\n");
		lpStream->Release();
		lpStorage->Release();
		return FALSE;
	}

	// Return the property set in the requested medium.

	if (lpFormatEtc->tymed & TYMED_ISTORAGE)
	{
		// Return as a storage object.

		ASSERT_POINTER(lpStorage, IStorage);
		lpStream->Release();
		lpStgMedium->pstg = lpStorage;
		lpStgMedium->tymed = TYMED_ISTORAGE;
		lpStgMedium->pUnkForRelease = NULL;
	}
	else
	{
		// Return as a stream.

		ASSERT_POINTER(lpStream, IStream);
		lpStgMedium->pstm = lpStream;
		lpStgMedium->tymed = TYMED_ISTREAM;
		lpStgMedium->pUnkForRelease = NULL;
	}

	return TRUE;
}
Exemplo n.º 27
0
BOOL CStkFile::OpenShare(LPCTSTR lpszFileName, UINT nOpenFlags, int nAddToFileEnd, CString sShareName, CFileException* pException)
{
	m_bShareMem = TRUE;

	ASSERT(AfxIsValidString(lpszFileName));
	ASSERT(pException == NULL || AfxIsValidAddress(pException, sizeof(CFileException)));


	nOpenFlags &= ~(UINT)typeBinary;

	m_bCloseOnDelete = FALSE;
	m_hFile = (HANDLE)hFileNull;
	m_strFileName.Empty();

	TCHAR szTemp[_MAX_PATH];
	AfxFullPath(szTemp, lpszFileName);
	m_strFileName = szTemp;


	ASSERT(sizeof(HANDLE) == sizeof(UINT));
	ASSERT(shareCompat == 0);


	CString sFileN = lpszFileName;
	int nFileLen = 0;
	if (sFileN != "")
	{
		CFile fl;
		if (fl.Open(m_strFileName, CFile::shareDenyNone | CFile::modeReadWrite) == FALSE)
		{
			return FALSE;
		}

		nFileLen = fl.GetLength();
		if (nFileLen <= 0)
		{
			nFileLen = 16;
		}

		fl.Close();
	}


	m_bCloseOnDelete = TRUE;
	m_nLenFile = nFileLen;


	DWORD flProtect = 0;
	flProtect = PAGE_READWRITE;

	m_sNameShareMem = sShareName;
	m_hFileMap = CreateFileMapping((HANDLE)m_hFile, NULL, flProtect, 0, m_nLenFile + nAddToFileEnd, m_sNameShareMem);
	if (m_hFileMap == NULL)
	{
		AfxMessageBox("Error! hFileMap is Null.");
		CloseHandle(m_hFileMap);
		return FALSE;
	}
	else if (GetLastError() == ERROR_ALREADY_EXISTS)
	{
	}


	m_lpvFileBegin = (BYTE*)MapViewOfFile(m_hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, m_nLenFile + nAddToFileEnd);
	ASSERT(m_lpvFileBegin != NULL);

	m_lpvFileCurrent = m_lpvFileBegin;

	DWORD dwError;
	if (m_nLenFile == -1 && (dwError = GetLastError()) != NO_ERROR)
	{
		AfxMessageBox("GetFileSize 出错!");
		m_nLenFile = 0;
		m_lpvFileEnd = m_lpvFileBegin;
		return FALSE;
	}

	m_lpvFileEnd = m_lpvFileBegin + m_nLenFile + nAddToFileEnd;

	if (sFileN == "")
	{
		m_nLenFile = nAddToFileEnd;
	}

	return TRUE;
}
Exemplo n.º 28
0
BOOL CFile::Open(LPCTSTR lpszFileName, UINT nOpenFlags,
	CFileException* pException)
{
	ASSERT_VALID(this);
	ASSERT(AfxIsValidString(lpszFileName));
	ASSERT(pException == NULL ||
		AfxIsValidAddress(pException, sizeof(CFileException)));
	ASSERT((nOpenFlags & typeText) == 0);   // text mode not supported

	// CFile objects are always binary and CreateFile does not need flag
	nOpenFlags &= ~(UINT)typeBinary;

	m_bCloseOnDelete = FALSE;
	m_hFile = (UINT)hFileNull;
	m_strFileName.Empty();

	TCHAR szTemp[_MAX_PATH];
	AfxFullPath(szTemp, lpszFileName);
	m_strFileName = szTemp;

	ASSERT(sizeof(HANDLE) == sizeof(UINT));
	ASSERT(shareCompat == 0);

	// map read/write mode
	ASSERT((modeRead|modeWrite|modeReadWrite) == 3);
	DWORD dwAccess;
	switch (nOpenFlags & 3)
	{
	case modeRead:
		dwAccess = GENERIC_READ;
		break;
	case modeWrite:
		dwAccess = GENERIC_WRITE;
		break;
	case modeReadWrite:
		dwAccess = GENERIC_READ|GENERIC_WRITE;
		break;
	default:
		ASSERT(FALSE);  // invalid share mode
	}

	// map share mode
	DWORD dwShareMode;
	switch (nOpenFlags & 0x70)
	{
	case shareCompat:       // map compatibility mode to exclusive
	case shareExclusive:
		dwShareMode = 0;
		break;
	case shareDenyWrite:
		dwShareMode = FILE_SHARE_READ;
		break;
	case shareDenyRead:
		dwShareMode = FILE_SHARE_WRITE;
		break;
	case shareDenyNone:
		dwShareMode = FILE_SHARE_WRITE|FILE_SHARE_READ;
		break;
	default:
		ASSERT(FALSE);  // invalid share mode?
	}

	// Note: typeText and typeBinary are used in derived classes only.

	// map modeNoInherit flag
	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(sa);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = (nOpenFlags & modeNoInherit) == 0;

	// map creation flags
	DWORD dwCreateFlag;
	if (nOpenFlags & modeCreate)
	{
		if (nOpenFlags & modeNoTruncate)
			dwCreateFlag = OPEN_ALWAYS;
		else
			dwCreateFlag = CREATE_ALWAYS;
	}
	else
		dwCreateFlag = OPEN_EXISTING;

	// attempt file creation
	HANDLE hFile = ::CreateFile(lpszFileName, dwAccess, dwShareMode, &sa,
		dwCreateFlag, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		if (pException != NULL)
		{
			pException->m_lOsError = ::GetLastError();
			pException->m_cause =
				CFileException::OsErrorToException(pException->m_lOsError);

			// use passed file name (not expanded vesion) when reporting
			// an error while opening

			pException->m_strFileName = lpszFileName;
		}
		return FALSE;
	}
	m_hFile = (HFILE)hFile;
	m_bCloseOnDelete = TRUE;

	return TRUE;
}
Exemplo n.º 29
0
COleConvertDialog::COleConvertDialog(COleClientItem* pItem, DWORD dwFlags,
	CLSID* pClassID, CWnd* pParentWnd) : COleDialog(pParentWnd)
{
	if (pItem != NULL)
		ASSERT_VALID(pItem);
	ASSERT(pClassID == NULL || AfxIsValidAddress(pClassID, sizeof(CLSID), FALSE));

	memset(&m_cv, 0, sizeof(m_cv)); // initialize structure to 0/NULL
	if (pClassID != NULL)
		m_cv.clsid = *pClassID;

	// fill in common part
	m_cv.cbStruct = sizeof(m_cv);
	m_cv.dwFlags = dwFlags;
	if (!afxData.bWin4 && AfxHelpEnabled())
		m_cv.dwFlags |= CF_SHOWHELPBUTTON;
	m_cv.lpfnHook = AfxOleHookProc;
	m_nIDHelp = AFX_IDD_CONVERT;

	// specific to this dialog
	m_cv.fIsLinkedObject = pItem->GetType() == OT_LINK;
	m_cv.dvAspect = pItem->GetDrawAspect();
	if (pClassID == NULL && !m_cv.fIsLinkedObject)
	{
		// for embeddings, attempt to get class ID from the storage
		if (ReadClassStg(pItem->m_lpStorage, &m_cv.clsid) == S_OK)
			pClassID = &m_cv.clsid;

		// attempt to get user type from storage
		CLIPFORMAT cf = 0;
		LPOLESTR lpOleStr = NULL;
		ReadFmtUserTypeStg(pItem->m_lpStorage, &cf, &lpOleStr);
		m_cv.lpszUserType = TASKSTRINGOLE2T(lpOleStr);

		m_cv.wFormat = (WORD)cf;
	}
	// get class id if neded
	if (pClassID == NULL)
	{
		// no class ID in the storage, use class ID of the object
		pItem->GetClassID(&m_cv.clsid);
	}

	// get user type if needed
	if (m_cv.lpszUserType == NULL)
	{
		// no user type in storge, get user type from class ID
		LPTSTR lpszUserType = NULL;
		LPOLESTR lpOleStr = NULL;
		if (OleRegGetUserType(m_cv.clsid, USERCLASSTYPE_FULL,
			&lpOleStr) == S_OK)
		{
			lpszUserType = TASKSTRINGOLE2T(lpOleStr);
		}
		else
		{
			lpszUserType = (LPTSTR)CoTaskMemAlloc(256 * sizeof(TCHAR));
			if (lpszUserType != NULL)
			{
				lpszUserType[0] = '?';
				lpszUserType[1] = 0;
				VERIFY(AfxLoadString(AFX_IDS_UNKNOWNTYPE, lpszUserType) != 0);
			}
		}
		m_cv.lpszUserType = lpszUserType;
	}
	m_cv.hMetaPict = pItem->GetIconicMetafile();
}
Exemplo n.º 30
0
BOOL CShellFileOp::Go ( BOOL* lpbOperationStarted,
                        int*  lpnAPIReturn /*=NULL*/,
                        BOOL* lpbAnyOperationsAborted  /*=NULL*/ )
{
TCHAR* szzSourceFiles = NULL;
TCHAR* szzDestFiles = NULL;
DWORD  dwSourceBufferSize;
DWORD  dwDestBufferSize;
int    nAPIRet;

    // Validate the pointers....
    ASSERT ( AfxIsValidAddress ( lpbOperationStarted, sizeof(BOOL) ) );
    ASSERT ( lpnAPIReturn == NULL  ||
             AfxIsValidAddress ( lpnAPIReturn, sizeof(int) ) );
    ASSERT ( lpbAnyOperationsAborted == NULL  ||
             AfxIsValidAddress ( lpbAnyOperationsAborted, sizeof(BOOL) ) );


    m_bGoCalledAPI = FALSE;

    if ( NULL != lpbOperationStarted )
        {
        *lpbOperationStarted = FALSE;
        }

                                        // Do a bunch of validation before
                                        // calling the API.

                                        // 1. Did you call SetOperationFlags()?

    if ( ! m_bFlagsSet )
        {
        TRACE0("Go() aborting because SetOperationFlags() was not called first.\n");
        goto bailout;
        }

                                        // 2 Is the op type valid?

    if ( ! ( m_rFOS.wFunc == FO_COPY  ||  m_rFOS.wFunc == FO_DELETE  ||
             m_rFOS.wFunc == FO_MOVE  ||  m_rFOS.wFunc == FO_RENAME ) )
        {
        TRACE0("Go() aborting because the operation type was invalid.\n");
        goto bailout;
        }

                                        // 3 Is the source file list nonempty?
    
    if ( m_lcstrSourceFiles.IsEmpty() ) 
        {
        TRACE0("Go() aborting because the source file list is empty.\n");
        goto bailout;
        }

                                        // 4. Is the dest file list nonempty
                                        // if the op needs dest files?

    if ( m_rFOS.wFunc != FO_DELETE  &&  m_lcstrDestFiles.IsEmpty() )
        {
        TRACE0("Go() aborting because the destination file list is empty.\n");
        goto bailout;
        }

                                        // 5. Is the dest file list OK?  There
                                        // must either be one entry, or the same
                                        // number of entries as in the source
                                        // list.

    if ( m_rFOS.wFunc != FO_DELETE )
        {
        if ( m_lcstrDestFiles.GetCount() != 1  &&
             m_lcstrDestFiles.GetCount() != m_lcstrSourceFiles.GetCount() )
            {
            TRACE0("Go() aborting because the destination file list has the wrong number of strings.\n");
            goto bailout;
            }
        }


                                        // Everything checked out OK, so now
                                        // build the big double-null-terminated
                                        // buffers.

    dwSourceBufferSize = GetRequiredBufferSize ( m_lcstrSourceFiles );

    if ( m_rFOS.wFunc != FO_DELETE )
        {
        dwDestBufferSize = GetRequiredBufferSize ( m_lcstrDestFiles );
        }

    try
        {
        szzSourceFiles = (LPTSTR) new BYTE [ dwSourceBufferSize ];

        if ( m_rFOS.wFunc != FO_DELETE )
            {
            szzDestFiles = (LPTSTR) new BYTE [ dwDestBufferSize ];
            }
        }
    catch (...)
        {
        TRACE0("Memory exception in CShellFileOp::Go()!\n");
        throw;
        }

    FillSzzBuffer ( szzSourceFiles, m_lcstrSourceFiles );

    if ( m_rFOS.wFunc != FO_DELETE )
        {
        FillSzzBuffer ( szzDestFiles, m_lcstrDestFiles );
        }

                                        // and now, the moment you've all been
                                        // waiting for

    m_rFOS.pFrom = szzSourceFiles;
    m_rFOS.pTo = szzDestFiles;
    m_rFOS.lpszProgressTitle = (LPCTSTR) m_cstrProgressDlgTitle;


                                        // If there are 2 or more strings in
                                        // the destination list, set the 
                                        // MULTIDESTFILES flag.
                                    
    if ( m_lcstrDestFiles.GetCount() > 1 )
        {
        m_rFOS.fFlags |= FOF_MULTIDESTFILES;
        }


    m_bGoCalledAPI = TRUE;
    
    if ( NULL != lpbOperationStarted )
        {
        *lpbOperationStarted = TRUE;
        }

                                        // drum roll please....
    nAPIRet = SHFileOperation ( &m_rFOS );  // tah-dah!

                                        // Save the return value from the API.    
    if ( NULL != lpnAPIReturn )
        {
        *lpnAPIReturn = nAPIRet;
        }

                                        // Check if the user cancelled the
                                        // operation.

    if ( NULL != lpbAnyOperationsAborted )
        {
        *lpbAnyOperationsAborted = m_rFOS.fAnyOperationsAborted;
        }

bailout:
    // If we got here via one of the gotos, fire off an assert.
    // If this assert fires, check the debug window for a TRACE output
    // line that describes the problem.
    ASSERT ( m_bGoCalledAPI );

                                        // Free buffers.
    if ( NULL != szzSourceFiles )
        {
        delete [] szzSourceFiles;
        }

    if ( NULL != szzDestFiles )
        {
        delete [] szzDestFiles;
        }


    return m_bGoCalledAPI  &&  0 == nAPIRet;
}