Пример #1
0
void CFormat::DelUselessSpaces(CRichEditView *pRichEditView)
{
	CRichEditCtrl* pRichEditCtrl=&pRichEditView->GetRichEditCtrl();
	int lineCun=pRichEditCtrl->GetLineCount();
	int pos=-1;
	//第一:删除段前多余空格
	for(int i=0;i<lineCun;i++){
		//删除多余空格
		pos=pRichEditCtrl->LineIndex(i);
		pRichEditCtrl->SetSel(pos,pos+1);
		CString strSel=pRichEditCtrl->GetSelText();
		if(!strSel.IsEmpty()){
			CHARFORMAT2 cf;
			pRichEditCtrl->GetSelectionCharFormat(cf);
			CString cstr;
			PARAFORMAT pf;
			pRichEditCtrl->GetParaFormat(pf);
			if(pf.dxStartIndent>4)
				pf.dxStartIndent=4;
			pRichEditCtrl->SetParaFormat(pf);
		}
	}
	//第二:删除行中多余空格
	long startPos=0,endPos=-1;
	long ChnStart=0x4E00,ChnEnd=0x9FBF;
	pRichEditCtrl->SetSel(startPos,endPos);
	pRichEditCtrl->GetSel(startPos,endPos);
	CString refString;
	CString frontStr,backStr;

	for(int i=1;i<endPos-2;i++){
		pRichEditCtrl->GetTextRange(i,i+1,refString);
		if(refString.Compare(_T(" "))==0){
			pRichEditCtrl->GetTextRange(i-1,i,frontStr);
			pRichEditCtrl->GetTextRange(i+1,i+2,backStr);
			if( frontStr.Compare(_T(","))==0||
				frontStr.Compare(_T("。"))==0||
				frontStr.Compare(_T("“"))==0||
				frontStr.Compare(_T("”"))==0||
				frontStr.Compare(_T(";"))==0||
				frontStr.Compare(_T(":"))==0||
				frontStr.Compare(_T("?"))==0||
				frontStr.Compare(_T(")"))==0||
				frontStr.Compare(_T("("))==0||
				frontStr.Compare(_T("‘"))==0||
				frontStr.Compare(_T("’"))==0){
					//中文标点符号
					pRichEditCtrl->SetSel(i,i+1);
					pRichEditCtrl->ReplaceSel(_T(""));

					//处理索引
					i=i-2;
					endPos--;
			}
			else if(((ChnStart<=frontStr[0]&&frontStr[0]<=ChnEnd)||
				(ChnStart<=backStr[0]&&backStr[0]<=ChnEnd))){
					//中文文字
					pRichEditCtrl->SetSel(i,i+1);
					pRichEditCtrl->ReplaceSel(_T(""));

					//处理索引
					i=i-2;
					endPos--;
			}
		}
	}
}
Пример #2
0
KD_TRANSFER_SYNTAX KDicomDS::GetTransferSyntax(CString str)
{
	if(str.Compare(_T("1.2.840.10008.1.2")) == 0)
		return IMPLICIT_LITTLE;
	else if(str.Compare(_T("1.2.840.10008.1.2.1")) == 0)
		return EXPLICIT_LITTLE;
	else if(str.Compare(_T("1.2.840.10008.1.2.2")) == 0)
		return EXPLICIT_BIG;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.50")) == 0)
		return JPEG_BASELINE;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.51")) == 0)
		return JPEG_EXTENDED_2_4;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.52")) == 0)
		return JPEG_EXTENDED_3_5;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.53")) == 0)
		return JPEG_SPECTRAL_6_8;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.54")) == 0)
		return JPEG_SPECTRAL_7_9;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.55")) == 0)
		return JPEG_FULL_10_12;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.56")) == 0)
		return JPEG_FULL_11_13;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.57")) == 0)
		return JPEG_LOSSLESS_14;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.58")) == 0)
		return JPEG_LOSSLESS_15;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.59")) == 0)
		return JPEG_EXTENDED_16_18;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.60")) == 0)
		return JPEG_EXTENDED_17_19;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.61")) == 0)
		return JPEG_SPECTRAL_20_22;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.62")) == 0)
		return JPEG_SPECTRAL_21_23;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.63")) == 0)
		return JPEG_FULL_24_26;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.64")) == 0)
		return JPEG_FULL_25_27;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.65")) == 0)
		return JPEG_LOSSLESS_28;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.66")) == 0)
		return JPEG_LOSSLESS_29;
	else if(str.Compare(_T("1.2.840.10008.1.2.4.70")) == 0)
		return JPEG_LOSSLESS_FIRST_14;
   else if(str.Compare(_T("1.2.840.10008.1.2.4.90")) == 0)
      return JPEG_2000_IMAGE_COMPRESSON_LOSSLESS_ONLY;
   else if(str.Compare(_T("1.2.840.10008.1.2.4.91")) == 0)
      return JPEG_2000_IMAGE_COMPRESSON;
	else if(str.Compare(_T("1.2.840.10008.1.2.5")) == 0)
		return RLE;
	return UNKNOWN_TRANSFER_SYNTAX;
}
void CAddCADFrameMenu::CreateMenus()
{
 CMDIFrameWnd * pMainFrame = acedGetAcadFrame();
 pMainFrame->LockWindowUpdate();
 
 //!!!二次加载有问题!

 ////得到菜单栏上面的最后一个菜单 //!!!最后一个是自定义菜单时,插入位置是按自定义菜单组中的菜单数量计算,不正确!
 //得到菜单栏上面的第一个菜单 //取得的是CAD默认菜单组
 CString sName;
 //if(!GetLastMenuFromMenubar(sName))
 if(!GetFirstMenuFromMenubar(sName))
  return;

 sName.Replace("&","");//debug
 
 IAcadMenuGroup *mnuGrp = NULL;
 if (!GetAcadMenuGroup(&mnuGrp,sName))
  return ;

 //得到所有菜单组
 IAcadPopupMenus   *mnus = NULL;
  IAcadPopupMenu   *mnu = NULL;
 IAcadPopupMenuItem  *mnuitem = NULL;
 HRESULT hr = S_OK;
 hr = mnuGrp->get_Menus(&mnus);
 long cnt = 0l;
 hr = mnus->get_Count(&cnt);
 int i = 0;
 int j = 0;
 int k = 0;
 VARIANT index;
 VariantInit(&index);
 V_VT(&index) = VT_I4;
 CArray<IAcadPopupMenu*, IAcadPopupMenu*> MnuAdrs; 

 long lIndex=0;
 WCHAR MenuName[256];
 for (i = 0; i < m_menuCount; i++) 
 {
  CString tmpMenu=m_TopMenuNames[i];
  tmpMenu.Replace("&","");
  if(IsMenuExist(mnu,lIndex,tmpMenu,mnus))//处理二次加载
  {
   V_I4(&index) = lIndex;
  }
  else
  {
   MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, m_TopMenuNames[i], -1, MenuName, 256); 
   mnus->Add(MenuName, &mnu); 
   V_I4(&index) = cnt++;
  }
  
  MnuAdrs.Add(mnu);
  mnu->InsertInMenuBar(index);
 }

 IAcadPopupMenu *MenuItem = NULL;
 int subMenuNum = 0;
 CCADMenuArray* Menus;
 WCHAR szSubMenu[256];
 WCHAR szSubMenuMacro[256];
 CString MenusName;
 CString Menusorder;
 for (j = 0; j < m_menuCount; j++) {
  Menus = m_menus.GetAt(j);
  subMenuNum = Menus->GetSize();
  for (k = 0; k < subMenuNum; k++) { 
   mnu = MnuAdrs.GetAt(j);
   if (!strcmp("--", Menus->GetAt(k)->name)) {
    V_I4(&index) = k;
    mnu->AddSeparator(index, &mnuitem);
   }
   else {
    V_I4(&index) = k;    
    MenusName = Menus->GetAt(k)->name; 
    Menusorder = Menus->GetAt(k)->order;
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, MenusName, -1, szSubMenu, 256); 
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Menusorder, -1, szSubMenuMacro, 256); 
    if (strcspn(Menus->GetAt(k)->name, "*") < (size_t)MenusName.GetLength()){
     MenusName.TrimLeft('*');
     MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, MenusName, -1, szSubMenu, 256); 
     hr = mnu->AddSubMenu(index, szSubMenu, &MenuItem);
    }    
    else if (strcspn(Menus->GetAt(k)->name, "$") < (size_t)MenusName.GetLength() ){        
     MenusName.TrimLeft('$');
     if(MenusName.Compare("--")==0)//添加子菜单的分隔符
     {
      hr = MenuItem->AddSeparator(index, &mnuitem);
     }
     else
     {
      MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, MenusName, -1, szSubMenu, 256); 
      hr = MenuItem->AddMenuItem(index, szSubMenu, szSubMenuMacro, &mnuitem);
     }
    }
    else {
     hr = mnu->AddMenuItem(index, szSubMenu, szSubMenuMacro, &mnuitem);
    }
   }
  }
 }

 for (i=0; i<MnuAdrs.GetSize(); i++)
 {
  MnuAdrs[i]->Release();
 }
 mnuitem->Release();
 mnus->Release();
 mnuGrp->Release();
 pMainFrame->UnlockWindowUpdate(); 
 
 stcMyTopMenuNames.Copy(m_TopMenuNames);//将顶级菜单名存入静态数组中,卸载时使用

 return ;
}
Пример #4
0
void CPropertiesWnd::SetUIValue(CMFCPropertyGridProperty* pProp,int nTag)
{
	CControlUI* pControl = m_wndUIProperties.GetCurUI();
	if(pControl == NULL)
		return;

	int nUpdate=UPDATE_REDRAW_CONTROL;
	CString strName=pProp->GetName();
	strName.MakeLower();
	CString strNewVal;
	CString strOldVal;
	strNewVal = pProp->FormatProperty();
	strOldVal = m_wndUIProperties.FormatOrigProperty(pProp);
	if(nTag!=tagName && nTag!=tagText && strName.Find(_T("image"))==-1)
	{
		strNewVal.MakeLower();
		strOldVal.MakeLower();
	}

	switch(nTag)
	{
	case tagName:
		{
			CPaintManagerUI* pManager = g_pMainFrame->GetActiveUIView()->GetPaintManager();
			if(strNewVal.IsEmpty() || pManager->FindControl(strNewVal))
			{
				if(!strNewVal.IsEmpty())
					MessageBox(strNewVal + _T(" 名称已被其他控件使用!"));
				pProp->SetValue((_variant_t)pControl->GetName());
				return;
			}
			else
				pManager->ReapObjects(pControl);

			g_pClassView->RenameUITreeItem(pControl, strNewVal);
			break;
		}
	case tagPos:
	case tagPadding:
		SetPropValue(pControl,tagSize);

		nUpdate=UPDATE_POS;
		break;
	case tagSize:
	case tagMinSize:
	case tagMaxSize:
	case tagMinMax:
		SetUIValue(pProp->GetSubItem(0),-1);
		SetUIValue(pProp->GetSubItem(1),-1);
		SetPropValue(pControl,tagPos);

		nUpdate=UPDATE_POS;
		break;
	case tagFloat:
	case tagColumns:
		nUpdate=UPDATE_POS;
		break;
	case tagVisible:
		nUpdate=UPDATE_REDRAW_PARENT;
		break;
	case tagListHeader:
		if (strNewVal.Compare(_T("false"))==0)
		{
			strNewVal = _T("hidden");
		}
		break;
	case tagAlpha:
		{
			int alpha=_ttoi(strNewVal);
			if (alpha<0)
			{
				strNewVal=_T("0");
				pProp->SetValue((_variant_t)(LONG)0);
			}
			else
			{
				strNewVal=_T("255");
				pProp->SetValue((_variant_t)(LONG)255);
			}
			break;
		}
	}

	CUIDesignerView* pUIView=g_pMainFrame->GetActiveUIView();
	ASSERT(pUIView);
	TNotifyUI Msg;
	UIAttribute oldAttrib = {strName, strOldVal};
	Msg.pSender=pControl;
	Msg.sType=_T("PropertyBeginChanged");
	Msg.wParam=0;
	Msg.lParam=(LPARAM)&oldAttrib;
	pUIView->Notify(Msg);
	//设置控件属性
	pControl->SetAttribute(strName,strNewVal);
	pProp->SetOriginalValue(pProp->GetValue());

	UIAttribute newAttrib = {strName, strNewVal};
	Msg.sType = _T("PropertyEndChanged");
	Msg.lParam = (LPARAM)&newAttrib;
	pUIView->Notify(Msg);

	if(nTag==tagWindowSize)
	{
		Msg.sType=_T("formsize");
		Msg.lParam = NULL;
		pUIView->Notify(Msg);
	}
	else if(nTag == tagName)
	{
		CPaintManagerUI* pManager = pUIView->GetPaintManager();
		pManager->InitControls(pControl);
	}

	CControlUI* pParent=pControl->GetParent();
	if(pParent==NULL)
		pParent=pControl;
	switch(nUpdate)
	{
	case UPDATE_POS:
		pParent->SetPos(pParent->GetPos());

		break;
	case UPDATE_REDRAW_CONTROL:
		pControl->NeedUpdate();

		break;
	case UPDATE_REDRAW_PARENT:
		pParent->NeedUpdate();
	}
}
Пример #5
0
BOOL CPatch::PatchFile(const CString& sPath, const CString& sSavePath, const CString& sBaseFile)
{
	if (PathIsDirectory(sPath))
	{
		m_sErrorMessage.Format(IDS_ERR_PATCH_INVALIDPATCHFILE, (LPCTSTR)sPath);
		return FALSE;
	}
	// find the entry in the patch file which matches the full path given in sPath.
	int nIndex = -1;
	// use the longest path that matches
	int nMaxMatch = 0;
	for (int i=0; i<GetNumberOfFiles(); i++)
	{
		CString temppath = sPath;
		CString temp = GetFilename(i);
		temppath.Replace('/', '\\');
		temp.Replace('/', '\\');
		if (temppath.Mid(temppath.GetLength()-temp.GetLength()-1, 1).CompareNoCase(_T("\\"))==0)
		{
			temppath = temppath.Right(temp.GetLength());
			if ((temp.CompareNoCase(temppath)==0))
			{
				if (nMaxMatch < temp.GetLength())
				{
					nMaxMatch = temp.GetLength();
					nIndex = i;
				}
			}
		}
		else if (temppath.CompareNoCase(temp)==0)
		{
			if ((nIndex < 0)&&(! temp.IsEmpty()))
			{
				nIndex = i;
			}
		}
	}
	if (nIndex < 0)
	{
		m_sErrorMessage.Format(IDS_ERR_PATCH_FILENOTINPATCH, (LPCTSTR)sPath);
		return FALSE;
	}

	CString sLine;
	CString sPatchFile = sBaseFile.IsEmpty() ? sPath : sBaseFile;
	if (PathFileExists(sPatchFile))
	{
		g_crasher.AddFile((LPCSTR)(LPCTSTR)sPatchFile, (LPCSTR)(LPCTSTR)_T("File to patch"));
	}
	CFileTextLines PatchLines;
	CFileTextLines PatchLinesResult;
	PatchLines.Load(sPatchFile);
	PatchLinesResult = PatchLines;  //.Copy(PatchLines);
	PatchLines.CopySettings(&PatchLinesResult);

	Chunks * chunks = m_arFileDiffs.GetAt(nIndex);

	for (int i=0; i<chunks->chunks.GetCount(); i++)
	{
		Chunk * chunk = chunks->chunks.GetAt(i);
		LONG lRemoveLine = chunk->lRemoveStart;
		LONG lAddLine = chunk->lAddStart;
		for (int j=0; j<chunk->arLines.GetCount(); j++)
		{
			CString sPatchLine = chunk->arLines.GetAt(j);
			EOL ending = chunk->arEOLs[j];
			if ((m_UnicodeType != CFileTextLines::UTF8)&&(m_UnicodeType != CFileTextLines::UTF8BOM))
			{
				if ((PatchLines.GetUnicodeType()==CFileTextLines::UTF8)||(m_UnicodeType == CFileTextLines::UTF8BOM))
				{
					// convert the UTF-8 contents in CString sPatchLine into a CStringA
					sPatchLine = CUnicodeUtils::GetUnicode(CStringA(sPatchLine));
				}
			}
			int nPatchState = (int)chunk->arLinesStates.GetAt(j);
			switch (nPatchState)
			{
			case PATCHSTATE_REMOVED:
				{
					if ((lAddLine > PatchLines.GetCount())||(PatchLines.GetCount()==0))
					{
						m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, _T(""), (LPCTSTR)sPatchLine);
						return FALSE; 
					}
					if (lAddLine == 0)
						lAddLine = 1;
					if ((sPatchLine.Compare(PatchLines.GetAt(lAddLine-1))!=0)&&(!HasExpandedKeyWords(sPatchLine)))
					{
						m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)sPatchLine, (LPCTSTR)PatchLines.GetAt(lAddLine-1));
						return FALSE; 
					}
					if (lAddLine > PatchLines.GetCount())
					{
						m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)sPatchLine, _T(""));
						return FALSE; 
					}
					PatchLines.RemoveAt(lAddLine-1);
				} 
				break;
			case PATCHSTATE_ADDED:
				{
					if (lAddLine == 0)
						lAddLine = 1;
					PatchLines.InsertAt(lAddLine-1, sPatchLine, ending);
					lAddLine++;
				}
				break;
			case PATCHSTATE_CONTEXT:
				{
					if (lAddLine > PatchLines.GetCount())
					{
						m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, _T(""), (LPCTSTR)sPatchLine);
						return FALSE; 
					}
					if (lAddLine == 0)
						lAddLine++;
					if (lRemoveLine == 0)
						lRemoveLine++;
					if ((sPatchLine.Compare(PatchLines.GetAt(lAddLine-1))!=0) &&
						(!HasExpandedKeyWords(sPatchLine)) &&
						(lRemoveLine <= PatchLines.GetCount()) &&
						(sPatchLine.Compare(PatchLines.GetAt(lRemoveLine-1))!=0))
					{
						if ((lAddLine < PatchLines.GetCount())&&(sPatchLine.Compare(PatchLines.GetAt(lAddLine))==0))
							lAddLine++;
						else if (((lAddLine + 1) < PatchLines.GetCount())&&(sPatchLine.Compare(PatchLines.GetAt(lAddLine+1))==0))
							lAddLine += 2;
						else if ((lRemoveLine < PatchLines.GetCount())&&(sPatchLine.Compare(PatchLines.GetAt(lRemoveLine))==0))
							lRemoveLine++;
						else
						{
							m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)sPatchLine, (LPCTSTR)PatchLines.GetAt(lAddLine-1));
							return FALSE; 
						}
					} 
					lAddLine++;
					lRemoveLine++;
				}
				break;
			default:
				ASSERT(FALSE);
				break;
			} // switch (nPatchState) 
		} // for (j=0; j<chunk->arLines.GetCount(); j++) 
	} // for (int i=0; i<chunks->chunks.GetCount(); i++) 
	if (!sSavePath.IsEmpty())
	{
		PatchLines.Save(sSavePath, false);
	}
	return TRUE;
}
Пример #6
0
BOOL CMsgHandlerDlg::bValidateMessageNameAndID(const CStringArray* pomStrArray,
        const CString& omStrHandlerType,
        CString omStrMessageNameOrID)
{
    BOOL bReturn = TRUE;
    CString omStrMakeHandler = "";

    if(pomStrArray != NULL )
    {
        omStrMakeHandler = CGlobalObj::omGetBusSpecMsgHndlrName(m_eBus);

        // compare if the handler written is message name or message ID.
        if(omStrHandlerType.Compare(defMSG_ID_HANDLER) == 0)
        {
            omStrMakeHandler += defMSG_NAME_HANDLER;
        }
        else if(omStrHandlerType.Compare(defMSG_NAME_HANDLER) == 0)
        {
            omStrMakeHandler += defMSG_ID_HANDLER;
        }

        // Make the current handler by getting its ID from name and vice
        // versa.
        omStrMakeHandler += omStrMessageNameOrID;
        UINT unCount = (COMMANUINT)pomStrArray->GetSize();
        CString omStrMsgPro = "";

        for(UINT i = 0; i<unCount; i++)
        {
            omStrMsgPro = pomStrArray->GetAt( i );
            omStrMsgPro = omStrMsgPro.Right(omStrMsgPro.GetLength()
                                            - omStrMsgPro.Find(_T(" ")) - 1);
            omStrMsgPro = omStrMsgPro.Left( omStrMsgPro.Find(_T("(") ));
            omStrMsgPro.TrimLeft();
            omStrMsgPro.TrimRight();

            if (omStrMsgPro.Compare(omStrMakeHandler) == 0)
            {
                // Form the message to be dispalyed
                omStrMsgPro = defDUPL_CORR_MSG_HANDLER;

                if(omStrHandlerType.Compare(defMSG_ID_HANDLER) == 0)
                {
                    omStrMsgPro.Replace( _T("TYPE"), defMSG_NAME_TEXT);
                    m_odEditMsgID.SetFocus();
                }
                else if(omStrHandlerType.Compare(defMSG_NAME_HANDLER) == 0)
                {
                    omStrMsgPro.Replace( _T("TYPE"), defMSG_ID_TEXT);
                    omStrMessageNameOrID.Insert(0,_T("0x"));
                    m_omListMsgName.SetFocus();
                }

                omStrMsgPro.Replace( _T("MESSAGENAME"),omStrMessageNameOrID );
                // Duplicate message hanlder, shout
                AfxMessageBox( omStrMsgPro,MB_OK|MB_ICONINFORMATION );
                unCount = (COMMANUINT)pomStrArray->GetSize();
                bReturn = FALSE;
            }
        }
    }
    else
    {
        bReturn = FALSE;
    }

    return bReturn ;
}
Пример #7
0
void SMTPServersNT( CCFXRequest* pRequest )
{
	USES_CONVERSION;

#ifdef _DEBUG
	CString tmp;
	pRequest->Write("DEBUGGING: ENTRY: SMTPServersNT<br>");
#endif
	
	// fields
	CCFXStringSet* pColumns = pRequest->CreateStringSet();
	int iServer = pColumns->AddString( "Server" );
	int iState = pColumns->AddString( "State" );
	int iDescription = pColumns->AddString( "Description" );
	
	int iBindings = pColumns->AddString( "Bindings" );
	
	int iVersion = pColumns->AddString( "Version" );
	
	int iMessageSizeLimit = pColumns->AddString( "MessageSizeLimit" );
	int iSessionSizeLimit = pColumns->AddString( "SessionSizeLimit" );
	int iMessagesPerConnectionLimit = pColumns->AddString( "MessagesPerConnectionLimit" );
	int iRecipientsPerMessageLimit = pColumns->AddString( "RecipientsPerMessageLimit" );
	
	int iBadMailDirectory = pColumns->AddString( "BadMailDirectory" );
	
	int iNonDeliveryMailTo = pColumns->AddString( "NonDeliveryMailTo" );
	int iBadMailTo = pColumns->AddString( "BadMailTo" );
	
	int iRetryInterval = pColumns->AddString( "RetryInterval" );
	
	int iDelayNotification = pColumns->AddString( "DelayNotification" );
	int iExpirationTimeout = pColumns->AddString( "ExpirationTimeout" );
	
	int iHopCount = pColumns->AddString( "HopCount" );
	int iMasqueradeDomain = pColumns->AddString( "MasqueradeDomain" );
	int iFullyQualifiedDomainName = pColumns->AddString( "FullyQualifiedDomainName" );
	int iSmartHost = pColumns->AddString( "SmartHost" );
	int iEnableReverseDnsLookup = pColumns->AddString( "EnableReverseDnsLookup" );
	CCFXQuery* pQuery = pRequest->AddQuery( get_query_variable(), pColumns );
	
	// optional
	CString strinComputer = pRequest->GetAttribute( "COMPUTER" );
	pRequest->SetVariable( "IISComputer", strinComputer );
	CString computer;
	if(	strinComputer.IsEmpty() )
		computer="LocalHost";
	else
		computer=strinComputer;
	
	//
    HRESULT hr,hr2,hrw;
	CString pathe;
	
	//
	pathe.Format("IIS://%s/SmtpSVC",computer);

#ifdef _DEBUG
	tmp.Format("DEBUGGING: Trying container %s...<br>",pathe);
	pRequest->Write(tmp);
#endif
    IADsContainer *pContainer=NULL;
    hr=ADsGetObject(A2W(pathe), IID_IADsContainer, (void**)&pContainer);
	log_COMError(__LINE__,hr);
	
	//
	if(SUCCEEDED(hr))
	{
#ifdef _DEBUG
	pRequest->Write("DEBUGGING: success<br>");
#endif

#ifdef _DEBUG
	pRequest->Write("DEBUGGING: enumerating container...<br>");
#endif

		//
		IEnumVARIANT *pEnum=NULL;
		hrw = ADsBuildEnumerator(pContainer, &pEnum); 
		log_COMError(__LINE__,hrw);
		
		//
		hr2=pContainer->Release();
		log_COMError(__LINE__,hr2);
		
		//
		if(SUCCEEDED(hrw))
		{
#ifdef _DEBUG
	pRequest->Write("DEBUGGING: success<br>");
#endif
			//
			VARIANT var;
			ULONG ulElements=1;
			
			//
			while ( (SUCCEEDED(hrw)) && (ulElements==1) )
			{
#ifdef _DEBUG
	tmp.Format("DEBUGGING: enumerating %d elements...<br>",ulElements);
	pRequest->Write(tmp);
#endif
				//
				hrw = ADsEnumerateNext(pEnum, 1, &var, &ulElements);
				log_COMError(__LINE__,hrw);
				
				//
				if(SUCCEEDED(hrw) && (ulElements==1) )
				{
#ifdef _DEBUG
	pRequest->Write("DEBUGGING: success<br>");
#endif
					//
					CString strServer;
					CString strState;
					CString strDescription;
					
					CString strBindings;
					
					CString strVersion;
					
					CString strMessageSizeLimit;
					CString strSessionSizeLimit;
					CString strMessagesPerConnectionLimit;
					CString strRecipientsPerMessageLimit;
					
					CString strBadMailDirectory;
					
					CString strNonDeliveryMailTo;
					CString strBadMailTo;
					
					CString strRetryInterval;
					
					CString strDelayNotification;
					CString strExpirationTimeout;
					
					CString strHopCount;
					CString strMasqueradeDomain;
					CString strFullyQualifiedDomainName;
					CString strSmartHost;
					CString strEnableReverseDnsLookup;
					
					//
					IADs *pADs=(IADs*)var.pdispVal;
					
					//
					BSTR bstrName;
					hr2 = pADs->get_Name(&bstrName);
					log_COMError(__LINE__,hr2);
					if(SUCCEEDED(hr2)) strServer=bstrName;
					
					BSTR bstrClass;
					hr2 = pADs->get_Class(&bstrClass);
					log_COMError(__LINE__,hr2);
					CString strClass;
					if(SUCCEEDED(hr2)) strClass=bstrClass;
					
#ifdef _DEBUG
	tmp.Format("DEBUGGING: server %s class %s...<br>",strServer,strClass);
	pRequest->Write(tmp);
#endif
					//
					if(strClass.Compare("IIsSmtpServer")==0)
					{
#ifdef _DEBUG
	pRequest->Write("DEBUGGING: success<br>");
#endif
						//
						VARIANT var;
						VariantInit(&var);
						
						//
						hr2 = pADs->Get(L"ServerState",&var);
						if(SUCCEEDED(hr2))
						{
							switch(V_INT(&var))
							{
							case MD_SERVER_STATE_STARTING: strState="Starting"; break;
							case MD_SERVER_STATE_STARTED: strState="Started"; break;
							case MD_SERVER_STATE_STOPPING: strState="Stopping"; break;
							case MD_SERVER_STATE_STOPPED: strState="Stopped"; break;
							case MD_SERVER_STATE_PAUSING: strState="Pausing"; break;
							case MD_SERVER_STATE_PAUSED: strState="Paused"; break;
							case MD_SERVER_STATE_CONTINUING: strState="Continuing"; break;
							default: strState="Unknown";
							}
						}
						VariantClear(&var);
						
						hr2 = pADs->Get(L"ServerComment",&var);
						if(SUCCEEDED(hr2)) strDescription = V_BSTR(&var) ;
						VariantClear(&var);
						
						hr2 = pADs->Get(L"ServerBindings",&var);
						if(SUCCEEDED(hr2))
						{
							VARIANTARRAYtoCString(var,strBindings,pRequest,';');
						}
						VariantClear(&var);
						
						hr2 = pADs->Get(L"SmtpServiceVersion",&var);
						if(SUCCEEDED(hr2)) strVersion.Format("%d",V_INT(&var));
						VariantClear(&var);
						
						hr2 = pADs->Get(L"MaxMessageSize",&var);
						if(SUCCEEDED(hr2)) strMessageSizeLimit.Format("%d",V_INT(&var));
						VariantClear(&var);
						hr2 = pADs->Get(L"MaxSessionSize",&var);
						if(SUCCEEDED(hr2)) strSessionSizeLimit.Format("%d",V_INT(&var));
						VariantClear(&var);
						hr2 = pADs->Get(L"MaxBatchedMessages",&var);
						if(SUCCEEDED(hr2)) strMessagesPerConnectionLimit.Format("%d",V_INT(&var));
						VariantClear(&var);
						hr2 = pADs->Get(L"MaxRecipients",&var);
						if(SUCCEEDED(hr2)) strRecipientsPerMessageLimit.Format("%d",V_INT(&var));
						VariantClear(&var);
						
						hr2 = pADs->Get(L"BadMailDirectory",&var);
						if(SUCCEEDED(hr2)) strBadMailDirectory = V_BSTR(&var) ;
						VariantClear(&var);
						
						hr2 = pADs->Get(L"SendNdrTo",&var);
						if(SUCCEEDED(hr2)) strNonDeliveryMailTo = V_BSTR(&var) ;
						VariantClear(&var);
						hr2 = pADs->Get(L"SendBadTo",&var);
						if(SUCCEEDED(hr2)) strBadMailTo = V_BSTR(&var) ;
						VariantClear(&var);
						
						hr2 = pADs->Get(L"SmtpRemoteProgressiveRetry",&var);
						if(SUCCEEDED(hr2)) strRetryInterval = V_BSTR(&var) ;
						VariantClear(&var);
						
						hr2 = pADs->Get(L"SmtpLocalDelayExpireMinutes",&var);
						if(SUCCEEDED(hr2)) strDelayNotification.Format("%d",V_INT(&var));
						VariantClear(&var);
						hr2 = pADs->Get(L"SmtpLocalNDRExpireMinutes",&var);
						if(SUCCEEDED(hr2)) strExpirationTimeout.Format("%d",V_INT(&var));
						VariantClear(&var);
						
						hr2 = pADs->Get(L"HopCount",&var);
						if(SUCCEEDED(hr2)) strHopCount.Format("%d",V_INT(&var));
						VariantClear(&var);
						hr2 = pADs->Get(L"MasqueradeDomain",&var);
						if(SUCCEEDED(hr2)) strMasqueradeDomain = V_BSTR(&var) ;
						VariantClear(&var);
						hr2 = pADs->Get(L"FullyQualifiedDomainName",&var);
						if(SUCCEEDED(hr2)) strFullyQualifiedDomainName = V_BSTR(&var) ;
						VariantClear(&var);
						hr2 = pADs->Get(L"SmartHost",&var);
						if(SUCCEEDED(hr2)) strSmartHost = V_BSTR(&var) ;
						VariantClear(&var);
						hr2 = pADs->Get(L"EnableReverseDnsLookup",&var);
						if(SUCCEEDED(hr2)) strEnableReverseDnsLookup.Format("%d",abs(V_BOOL(&var)));
						VariantClear(&var);
						
						//
						int iRow = pQuery->AddRow();
						pQuery->SetData( iRow, iServer, strServer );
						pQuery->SetData( iRow, iState, strState );
						pQuery->SetData( iRow, iDescription, strDescription );
						
						pQuery->SetData( iRow, iBindings, strBindings );
						
						pQuery->SetData( iRow, iVersion, strVersion );
						
						pQuery->SetData( iRow, iMessageSizeLimit, strMessageSizeLimit );
						pQuery->SetData( iRow, iSessionSizeLimit, strSessionSizeLimit );
						pQuery->SetData( iRow, iMessagesPerConnectionLimit, strMessagesPerConnectionLimit );
						pQuery->SetData( iRow, iRecipientsPerMessageLimit, strRecipientsPerMessageLimit );
						
						pQuery->SetData( iRow, iBadMailDirectory, strBadMailDirectory );
						
						pQuery->SetData( iRow, iNonDeliveryMailTo, strNonDeliveryMailTo );
						pQuery->SetData( iRow, iBadMailTo, strBadMailTo );
						
						pQuery->SetData( iRow, iRetryInterval, strRetryInterval );
						
						pQuery->SetData( iRow, iDelayNotification, strDelayNotification );
						pQuery->SetData( iRow, iExpirationTimeout, strExpirationTimeout );
						
						pQuery->SetData( iRow, iHopCount, strHopCount );
						pQuery->SetData( iRow, iMasqueradeDomain, strMasqueradeDomain );
						pQuery->SetData( iRow, iFullyQualifiedDomainName, strFullyQualifiedDomainName );
						pQuery->SetData( iRow, iSmartHost, strSmartHost );
						pQuery->SetData( iRow, iEnableReverseDnsLookup, strEnableReverseDnsLookup );
					}
					
					//
					hr2=pADs->Release();
					log_COMError(__LINE__,hr2);
					
					//
					SysFreeString(bstrClass);
					SysFreeString(bstrName);
				}

			}
		}
		//
		hr2 = ADsFreeEnumerator(pEnum);
		log_COMError(__LINE__,hr2);
	}
#ifdef _DEBUG
	pRequest->Write("DEBUGGING: EXIT: SMTPServersNT<br>");
#endif
}
Пример #8
0
boolean CUSBDevice::Initialize (void)
{
	assert (m_pDeviceDesc == 0);
	m_pDeviceDesc = new TUSBDeviceDescriptor;
	assert (m_pDeviceDesc != 0);
	
	assert (m_pHost != 0);
	assert (m_pEndpoint0 != 0);
	
	assert (sizeof *m_pDeviceDesc >= USB_DEFAULT_MAX_PACKET_SIZE);
	if (m_pHost->GetDescriptor (m_pEndpoint0,
				    DESCRIPTOR_DEVICE, DESCRIPTOR_INDEX_DEFAULT,
				    m_pDeviceDesc, USB_DEFAULT_MAX_PACKET_SIZE)
	    != USB_DEFAULT_MAX_PACKET_SIZE)
	{
		LogWrite (LogError, "Cannot get device descriptor (short)");

		delete m_pDeviceDesc;
		m_pDeviceDesc = 0;

		return FALSE;
	}

	if (   m_pDeviceDesc->bLength	      != sizeof *m_pDeviceDesc
	    || m_pDeviceDesc->bDescriptorType != DESCRIPTOR_DEVICE)
	{
		LogWrite (LogError, "Invalid device descriptor");

		delete m_pDeviceDesc;
		m_pDeviceDesc = 0;

		return FALSE;
	}

	m_pEndpoint0->SetMaxPacketSize (m_pDeviceDesc->bMaxPacketSize0);

	if (m_pHost->GetDescriptor (m_pEndpoint0,
				    DESCRIPTOR_DEVICE, DESCRIPTOR_INDEX_DEFAULT,
				    m_pDeviceDesc, sizeof *m_pDeviceDesc)
	    != (int) sizeof *m_pDeviceDesc)
	{
		LogWrite (LogError, "Cannot get device descriptor");

		delete m_pDeviceDesc;
		m_pDeviceDesc = 0;

		return FALSE;
	}

#ifndef NDEBUG
	//debug_hexdump (m_pDeviceDesc, sizeof *m_pDeviceDesc, FromDevice);
#endif
	
	u8 ucAddress = s_ucNextAddress++;
	if (ucAddress > USB_MAX_ADDRESS)
	{
		LogWrite (LogError, "Too many devices");

		return FALSE;
	}

	if (!m_pHost->SetAddress (m_pEndpoint0, ucAddress))
	{
		LogWrite (LogError, "Cannot set address %u", (unsigned) ucAddress);

		return FALSE;
	}
	
	SetAddress (ucAddress);

	assert (m_pConfigDesc == 0);
	m_pConfigDesc = new TUSBConfigurationDescriptor;
	assert (m_pConfigDesc != 0);

	if (m_pHost->GetDescriptor (m_pEndpoint0,
				    DESCRIPTOR_CONFIGURATION, DESCRIPTOR_INDEX_DEFAULT,
				    m_pConfigDesc, sizeof *m_pConfigDesc)
	    != (int) sizeof *m_pConfigDesc)
	{
		LogWrite (LogError, "Cannot get configuration descriptor (short)");

		delete m_pConfigDesc;
		m_pConfigDesc = 0;

		return FALSE;
	}

	if (   m_pConfigDesc->bLength         != sizeof *m_pConfigDesc
	    || m_pConfigDesc->bDescriptorType != DESCRIPTOR_CONFIGURATION
	    || m_pConfigDesc->wTotalLength    >  MAX_CONFIG_DESC_SIZE)
	{
		LogWrite (LogError, "Invalid configuration descriptor");
		
		delete m_pConfigDesc;
		m_pConfigDesc = 0;

		return FALSE;
	}

	unsigned nTotalLength = m_pConfigDesc->wTotalLength;

	delete m_pConfigDesc;

	m_pConfigDesc = (TUSBConfigurationDescriptor *) new u8[nTotalLength];
	assert (m_pConfigDesc != 0);

	if (m_pHost->GetDescriptor (m_pEndpoint0,
				    DESCRIPTOR_CONFIGURATION, DESCRIPTOR_INDEX_DEFAULT,
				    m_pConfigDesc, nTotalLength)
	    != (int) nTotalLength)
	{
		LogWrite (LogError, "Cannot get configuration descriptor");

		delete m_pConfigDesc;
		m_pConfigDesc = 0;

		return FALSE;
	}

#ifndef NDEBUG
	//debug_hexdump (m_pConfigDesc, nTotalLength, FromDevice);
#endif

	assert (m_pConfigParser == 0);
	m_pConfigParser = new CUSBConfigurationParser (m_pConfigDesc, nTotalLength);
	assert (m_pConfigParser != 0);

	if (!m_pConfigParser->IsValid ())
	{
		ConfigurationError (FromDevice);

		return FALSE;
	}

	CString *pNames = GetNames ();
	assert (pNames != 0);
	LogWrite (LogNotice, "Device %s found", (const char *) *pNames);
	delete pNames;

	unsigned nFunction = 0;
	u8 ucInterfaceNumber = 0;

	TUSBInterfaceDescriptor *pInterfaceDesc;
	while ((pInterfaceDesc = (TUSBInterfaceDescriptor *) m_pConfigParser->GetDescriptor (DESCRIPTOR_INTERFACE)) != 0)
	{
		if (   pInterfaceDesc->bInterfaceNumber != ucInterfaceNumber
		    && pInterfaceDesc->bInterfaceNumber != ucInterfaceNumber+1)
		{
			LogWrite (LogDebug, "Alternate setting %u ignored",
				  (unsigned) pInterfaceDesc->bAlternateSetting);

			if (pInterfaceDesc->bInterfaceNumber == ucInterfaceNumber+1)
			{
				ucInterfaceNumber++;
			}

			continue;
		}

		assert (m_pConfigParser != 0);
		assert (m_pFunction[nFunction] == 0);
		m_pFunction[nFunction] = new CUSBFunction (this, m_pConfigParser);
		assert (m_pFunction[nFunction] != 0);

		if (!m_pFunction[nFunction]->Initialize ())
		{
			LogWrite (LogError, "Cannot initialize function");

			delete m_pFunction[nFunction];
			m_pFunction[nFunction] = 0;

			continue;
		}

		CUSBFunction *pChild = 0;

		if (nFunction == 0)
		{
			pChild = CUSBDeviceFactory::GetDevice (m_pFunction[nFunction], GetName (DeviceNameVendor));
			if (pChild == 0)
			{
				pChild = CUSBDeviceFactory::GetDevice (m_pFunction[nFunction], GetName (DeviceNameDevice));
			}
		}

		if (pChild == 0)
		{
			CString *pName = m_pFunction[nFunction]->GetInterfaceName ();
			assert (pName != 0);
			if (pName->Compare ("unknown") != 0)
			{
				LogWrite (LogNotice, "Interface %s found", (const char *) *pName);

				pChild = CUSBDeviceFactory::GetDevice (m_pFunction[nFunction], pName);
			}
			else
			{
				delete pName;
			}
		}

		delete m_pFunction[nFunction];
		m_pFunction[nFunction] = 0;

		if (pChild == 0)
		{
			LogWrite (LogWarning, "Function is not supported");

			continue;
		}

		m_pFunction[nFunction] = pChild;

		if (++nFunction == USBDEV_MAX_FUNCTIONS)
		{
			LogWrite (LogWarning, "Too many functions per device");

			break;
		}

		ucInterfaceNumber++;
	}

	if (nFunction == 0)
	{
		LogWrite (LogWarning, "Device has no supported function");

		return FALSE;
	}

	return TRUE;
}
Пример #9
0
//在CAD中根据一个文件名打开一个文档,返回一个状态和输出打开的文档
Acad::ErrorStatus XAcDocOp::openAcDocument(CString		strFilePathName , 
										 AcApDocument	*&pDoc ,
										 BOOL			bKeepOldActive ,
										 BOOL bAutoCloseOnlyReadWarning)
{
	AcApDocuments		arrDocs , arrDocs1;
	Acad::ErrorStatus	es;

	strFilePathName.Trim();
	if(strFilePathName.GetLength() == 0)
		return Acad::eFileNotFound;

	pDoc	= NULL;

	//先获取现今的所有文档
	es	= enumAcDocument(arrDocs);
	if(es != Acad::eOk)
		return es;

	if(acDocManager->isApplicationContext())
	{
		AcApDocument	*pOldDoc = NULL;

		//判断当前是否处于SDI模式
		BOOL	bIsSDIMode = FALSE;
		resbuf	*pRb;

		pRb	= acutNewRb(RTSHORT);
		if(acedGetVar("SDI" , pRb) == RTNORM && pRb->resval.rint == 1)	//是SDI模式
		{
			bKeepOldActive	= FALSE;	//不能切换到先前的文档
			if(curDoc() != NULL)
                es = acDocManager->closeDocument(curDoc());	//关闭当前文档
        }
		acutRelRb(pRb);

		if(bKeepOldActive)
			pOldDoc = curDoc();

		if(bAutoCloseOnlyReadWarning)	//自动关闭只读提示对话框
			AutoCloseOnlyReadWarningDlg();

        es = acDocManager->appContextOpenDocument(strFilePathName);

		if(es != Acad::eOk)
			return es;

		if(bKeepOldActive && pOldDoc != NULL)
			acDocManager->activateDocument(pOldDoc);		
	}
	else
	{
		_CREATEDOCUMENTINFO	createInfo;
        ::ZeroMemory(&createInfo , sizeof(_CREATEDOCUMENTINFO));
		_tcscpy(createInfo.pszName , strFilePathName);

		if(bKeepOldActive)
		{
			createInfo.bActiveOldDoc	= TRUE;
			createInfo.pOldDoc			= curDoc();
		}

		if(bAutoCloseOnlyReadWarning)	//自动关闭只读提示对话框
			AutoCloseOnlyReadWarningDlg();

		acDocManager->executeInApplicationContext(openDocCallBack , (void *)&createInfo);
	}

	//再一次获取所有文档
	es	= enumAcDocument(arrDocs1);
	if(es != Acad::eOk)
		return es;

	if(arrDocs.GetSize() == arrDocs1.GetSize())	//创立失败
		return Acad::eCreateFailed;

	BOOL	bFind;
	for(int i = 0 ; i < arrDocs1.GetSize() ; i++)
	{
		bFind	= FALSE;
		for(int j = 0 ; j < arrDocs.GetSize() ; j++)
		{
			if(arrDocs.GetAt(j) == arrDocs1.GetAt(i))
			{
				bFind	= TRUE;
				break;
			}
		}

		if(!bFind)
		{
			pDoc = arrDocs1.GetAt(i);
			return Acad::eOk;

			//检查名字是否相等
			CString	strName;
			strName	= pDoc->fileName();

			ASSERT(strName.Compare(strFilePathName) == 0);
		}
	}

	return Acad::eCreateFailed;
}
Пример #10
0
//处里THREAD的函式
void CKThread::SomeThing(void)
{
	do
	{
        CTime time = CTime::GetCurrentTime(); 
		int m_nYear = time.GetYear(); ///年 
        int m_nMonth = time.GetMonth(); ///月
        int m_nDay = time.GetDay(); ///日
		int m_nhour = time.GetHour();
		int m_nmin = time.GetMinute();

		int m_nsec = time.GetSecond();
        
		if(m_vpArray.size() > 0 )
		{					
			/*EnterCriticalSection(&m_guard);
			for(UINT i = 0; i < m_vpArray.size();i++)
			{	
				CString str1 = m_vpArray[0];
				CString str = m_CKbirdge.SendMsg(str1);
				if(!str.Compare("ok")) 
				{

					m_vpArray.erase( m_vpArray.begin( ) );  

				}
				Sleep(30);
			}
			LeaveCriticalSection(&m_guard);*/
			if(sort == 3) {
				string bb = "xxx";
			}
			int sendflag=0;
			CString SendStr="";
			int start1 = 25;
			int start2 = 24;
			if(m_vpArray.size() < start1) {
				sendflag=m_vpArray.size()-1;		  
			}
			else
			{
				sendflag =start2;
			}
			bool rtn = false;
			EnterCriticalSection(&m_guard);
			try {							
					//m_OraDal.AddData(m_vpArray[0]);
                    //m_vpArray.erase( m_vpArray.begin( ));
					for(UINT i = 0; i <= sendflag;i++)
					{	
						SendStr +=  m_vpArray[i];
						if(i< sendflag) 	 SendStr += "$";						
						if(i == sendflag) {
							SendStr = "Stock$"+SendStr ;
							CString str = m_CKbirdge.SendMsg(SendStr);
				            if(!str.Compare("ok"))
							{
								for(UINT j = 0; j <= sendflag;j++) {
								m_vpArray.erase( m_vpArray.begin( ) );  
								}
							}

							
						}
						
						
					}	
					restartCount++;
							
				
			}
			catch(...) {
				//Release();
				//Init();

			}
            LeaveCriticalSection(&m_guard);
			if(sendCount >=10) {
				Sleep(100);
			}
			else {
			    Sleep(5);
			}
			if(sendCount > 100000) sendCount = 10;
			
			if(restartCount>=500) {				
                m_CKbirdge.Release();
				m_CKbirdge.Init();
				restartCount=0;
			}
			
		}
		else {
			//restartCount++;
   //         if(restartCount>=60) {				
   //             //m_CKbirdge.Release();
			//	//m_CKbirdge.Init();
			//	restartCount=0;
			//}
			//if(m_bInit) {
			//	AddData("$ok");
			//}			
			Sleep(300);

		}
		
		//DoEvents();	
	}while(m_SomeThingRun);
	CloseHandle( m_SomeThingThread);
	m_SomeThingThread = 0;
}
Пример #11
0
// 支持version = 1.0版本
BOOL CCheckRuleXMLParse::Load(const CString &strFilePath, 
							  CheckRuleArray &arrCheckRuleList)
{
	// 判断版本
	if (CheckVersion(strFilePath).CompareNoCase(L"1.1") == 0)
		return LoadNew(strFilePath, arrCheckRuleList);

	arrCheckRuleList.RemoveAll();

	if (!IsFileExist(strFilePath))
		return FALSE;

	BOOL bResult = TRUE;

	// 初始化
	Init();

	// 打开xml文件
	if (!m_pXMLDocument->OpenXMLForDocument(strFilePath))
		bResult = FALSE;

	// 读取数据
	if (bResult)
	{
		CheckRule checkRule;
		CString strValue;
		IBpXMLNode* pRootNode = m_pXMLDocument->GetRootElement();
		pRootNode->GetName(strValue);
		if (strValue.Compare(L"CheckRule") == 0)
		{
			IBpXMLNode *pChildNode = NULL;
			int nNodeCount = pRootNode->GetElementCount();
			for (int i = 1; i <= nNodeCount; i++)
			{
				IBpXMLNode *pRuleNode = pRootNode->GetElementChildByIndex(i);
				if (pRuleNode->GetElementCount() >= 3)
				{
					pRuleNode->GetAttributeByName(L"id", strValue);
					checkRule.nID = _wtoi(strValue);
					// 检查类型
					pRuleNode->GetAttributeByName(L"ruletype", strValue);
					checkRule.nRuleType = _wtoi(strValue);
					// 检查描述
					pChildNode = pRuleNode->GetElementChildByIndex(1);
					pChildNode->GetText(checkRule.strRuleDesc);
					DestroyXMLNode(pChildNode);
					// 检查名称
					pChildNode = pRuleNode->GetElementChildByIndex(2);
					pChildNode->GetText(checkRule.strRuleName);
					DestroyXMLNode(pChildNode);
					// 检查内容
					pChildNode = pRuleNode->GetElementChildByIndex(3);
					pChildNode->GetText(strValue);
					RuleConvertor(checkRule.nRuleType, strValue, checkRule.arrRuleContent);
					DestroyXMLNode(pChildNode);
					if (pRuleNode->GetElementCount() >= 4)
					{
						// 检查模型过滤
						pChildNode = pRuleNode->GetElementChildByIndex(4);
						pChildNode->GetText(strValue);
						checkRule.dwMdlFilter = _wtoi(strValue);
						DestroyXMLNode(pChildNode);
					}
					arrCheckRuleList.Add(checkRule);
				}
				DestroyXMLNode(pRuleNode);
			}
		}
		else
		{
			AfxMessageBox(L"XML文件不匹配!");
			bResult = FALSE;
		}
		DestroyXMLNode(pRootNode);
	}

	// 释放资源
	Uninit();
	return bResult;
}
Пример #12
0
void CI2CShell::Run (void)
{
	Print ("\n\nI2C Shell\n"
	       "Using master #%u\n"
	       "Default clock rate is %u KHz\n"
	       "Enter \"help\" for help!\n\n",
	       CMachineInfo::Get ()->GetDevice (DeviceI2CMaster),
	       m_nI2CClockHz / 1000);

	while (m_bContinue)
	{
		ReadLine ();

		CString Command;
		while (GetToken (&Command))
		{
			if (((const char *) Command)[0] == '#')
			{
				break;
			}
			else if (Command.Compare ("slave") == 0)
			{
				if (!Slave ())
				{
					break;
				}
			}
			else if (Command.Compare ("clock") == 0)
			{
				if (!Clock ())
				{
					break;
				}
			}
			else if (Command.Compare ("detect") == 0)
			{
				if (!Detect ())
				{
					break;
				}
			}
			else if (   Command.Compare ("read") == 0
				 || Command.Compare ("rd") == 0)
			{
				if (!Read ())
				{
					break;
				}
			}
			else if (   Command.Compare ("write") == 0
				 || Command.Compare ("wr") == 0)
			{
				if (!Write ())
				{
					break;
				}
			}
			else if (Command.Compare ("delay") == 0)
			{
				if (!Delay ())
				{
					break;
				}
			}
			else if (Command.Compare ("reboot") == 0)
			{
				m_bContinue = FALSE;
			}
			else if (Command.Compare ("help") == 0)
			{
				Print (HelpMsg);
			}
			else
			{
				Print ("Unknown command: %s\n", (const char *) Command);
				break;
			}
		}
	}
}
Пример #13
0
boolean CI2CShell::Detect (void)
{
	boolean bWriteMode = FALSE;

	CString Mode;
	if (GetToken (&Mode))
	{
		if (Mode.Compare ("r") == 0)
		{
			// nothing to do
		}
		else if (Mode.Compare ("w") == 0)
		{
			bWriteMode = TRUE;
		}
		else
		{
			UnGetToken (Mode);
		}
	}

	assert (m_pI2CMaster != 0);
	m_pI2CMaster->SetClock (m_nI2CClockHz);

	u8 ucFirstSlaveAddress = INVALID_SLAVE;

	for (u8 ucAddress = SLAVE_ADDRESS_MIN; ucAddress <= SLAVE_ADDRESS_MAX; ucAddress++)
	{
		boolean bPresent = FALSE;

		if (bWriteMode)
		{
			if (m_pI2CMaster->Write (ucAddress, 0, 0) == 0)
			{
				bPresent = TRUE;
			}
		}
		else
		{
			u8 Buffer[1];
			if (m_pI2CMaster->Read (ucAddress, Buffer, sizeof Buffer) >= 0)
			{
				bPresent = TRUE;
			}
		}

		if (bPresent)
		{
			if (ucFirstSlaveAddress == INVALID_SLAVE)
			{
				Print ("Slave(s) at address:");

				ucFirstSlaveAddress = ucAddress;
			}

			Print (" 0x%02X", (unsigned) ucAddress);
		}
	}

	if (ucFirstSlaveAddress == INVALID_SLAVE)
	{
		Print ("No slave present\n");

		m_ucSlaveAddress = INVALID_SLAVE;

		return FALSE;
	}

	Print ("\n");

	m_ucSlaveAddress = ucFirstSlaveAddress;

	return TRUE;
}
Пример #14
0
int CUpdateInfo::Compare(CString hash)
{
	CString oldhash = GetUpdateHash();
	return oldhash.Compare(hash);
}
// 检查开始
int CSDMdlAttrParaSpecifiedValueCheck::CheckAction(void *pData, const CheckRule &checkRule, CheckResult &checkResult)
{
	ProMdl pMdl = (ProMdl)pData;
	if (NULL == pMdl)
	{
		checkResult.nResultType = CHECK_RESULT_INVALID_MODEL;
		return checkResult.nResultType;
	}

	if (!IsMdlTypeValid(pMdl, checkRule.dwMdlFilter))
	{
		checkResult.nResultType = CHECK_RESULT_INVALID_MODEL;
		return checkResult.nResultType;
	}

	// 模型是否符合过滤器要求
	if (!IsFilterValid(checkRule.strRuleName, pMdl))
	{
		checkResult.nResultType = CHECK_RESULT_INVALID_MODEL;
		return checkResult.nResultType;
	}

	// 检查输入值有效性
	if (checkRule.arrRuleContent.GetCount() < 1)
	{
		checkResult.nResultType = CHECK_RESULT_INVALID_INPUT;
		return checkResult.nResultType;
	}

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

	ProModelitem mdlItem;
	ProMdlToModelitem(pMdl, &mdlItem);

	checkResult.arrErrorItems.RemoveAll();

	// 解析参数
	CStringArray arrItems;
	CStringToCStringArray(checkRule.arrRuleContent[0], arrItems, L";");
	CString strParaName;
	int nParaType;
	CString strParaValue;
	BOOL bDesignation;
	for (int i = 0; i < arrItems.GetSize(); i ++)
	{
		strParaName = arrItems[i].Left(arrItems[i].Find(L"("));
		int nCount = arrItems[i].Find(L")") - arrItems[i].Find(L"(")-1;
		CString strProperty;
		strProperty = arrItems[i].Mid(arrItems[i].Find(L"(") + 1, nCount);
		CStringArray arrPropertys;
		CStringToCStringArray(strProperty, arrPropertys, L",");
		nParaType = _wtoi(arrPropertys[0]);
		strParaValue = arrPropertys[1];
		ParseParaValue(mdlItem, strParaValue, strParaValue);
		bDesignation = _wtoi(arrPropertys[2]);
		
		ProName paraname;
		wcsncpy_s(paraname, PRO_NAME_SIZE, (LPCTSTR)strParaName, _TRUNCATE);
		ProParameter para;

		// 判断参数是否存在
		ErrorItem item;
		item.strItemName = strParaName;
		item.nID = i;
		if (GetSDParameter(&mdlItem, paraname, para))
		{
			// 检查参数类型
			ProParamvalue proval;
			ProParameterValueGet(&para, &proval);
			int nType = GetParaType(proval.type);
			if (nType != nParaType)
			{
				item.nType = PARAERROR_TYPE;
				checkResult.arrErrorItems.Add(item);
			}
			else
			{
				// 检查参数值
				if (PARAM_STRING == nParaType)
				{
					if (strParaValue.Compare(proval.value.s_val) != 0)
					{
						item.nType = PARAERROR_VALUE;
						checkResult.arrErrorItems.Add(item);
						continue;
					}
				}
				else if (PARAM_REAL == nParaType)
				{
					if (!DEQUAL(proval.value.d_val, _wtof(strParaValue)))
					{
						item.nType = PARAERROR_VALUE;
						checkResult.arrErrorItems.Add(item);
						continue;
					}
				}
				else if (PARAM_INTEGER == nParaType)
				{
					if (proval.value.i_val != _wtoi(strParaValue))
					{
						item.nType = PARAERROR_VALUE;
						checkResult.arrErrorItems.Add(item);
						continue;
					}
				}
				else if (PARAM_BOOL == nParaType)
				{
					if (proval.value.l_val != _wtoi(strParaValue))
					{
						item.nType = PARAERROR_VALUE;
						checkResult.arrErrorItems.Add(item);
						continue;
					}
				}
				// 检查是否指定
				ProBoolean designation;
				ProParameterDesignationVerify(&para, &designation);
				if (bDesignation != designation)
				{
					item.nType = PARAERROR_DESIGNATION;
					checkResult.arrErrorItems.Add(item);
				}
			}
		}
		else
		{
			item.nType = PARAERROR_NOEXIST;
			checkResult.arrErrorItems.Add(item);
		}
	}

	if (checkResult.arrErrorItems.GetCount() > 0)
		checkResult.nResultType = CHECK_RESULT_ERROR_VALUE;
	else
		checkResult.nResultType = CHECK_RESULT_NO_ERROR;

	return checkResult.nResultType;
}
Пример #16
0
void Optimize1( CString csDir, CString csTitle )
{
	CStdioFile fAllSongList;
	CString csAllSongList;
	CString csTemp;
	CString csSequence;
	CString csName;
	CString csPrefix;
	CString csOldName;
	CString csNewName;
	CString csSubDir;
	CString csSubTitle;
	int nResult;
	int nSuffixLen;
	int nMusicFileCount;
	int nAllSongListCount;
	CFileFind cFile;
	CFileFind *pcFile = &cFile;
	csTemp.Format( _T("%s\\*"), csDir );
	BOOL b = pcFile->FindFile( csTemp );
	
	csAllSongList.Format( _T("%s\\%s.AllSongList.m3u"), csDir, csTitle );
	csAllSongList = WordCheckLen( csAllSongList, 15 );
	fAllSongList.Open( csAllSongList, CFile::modeWrite|CFile::modeCreate );
	if( fAllSongList == 0 ) return ;
	
	nMusicFileCount = 0;
	nAllSongListCount = 0;
	b = pcFile->FindNextFile();
	b = pcFile->FindNextFile();
	while( b != NULL )
	{
		b = pcFile->FindNextFile();
		if( pcFile->IsDirectory() )
		{
			csSubDir = pcFile->GetFilePath();
			csTemp = FileCheckMusicInGroup( csSubDir );
			if( csTemp.Compare( _T("") ) != 0 )
			{
				nAllSongListCount++;
				csTemp = pcFile->GetFileName();
				csSubTitle.Format( _T("%s.%s"), csTitle, csTemp );
				Optimize2( csSubDir, csTemp, csSubTitle, &fAllSongList );
			}
		}
		else
		{
			csName = pcFile->GetFileName();
			csTemp = FileArrangeGetSuffix( csName );
			nSuffixLen = csTemp.GetLength();
			nResult = WordCheckSuffix( csTemp );
			if( nResult == 1 || nResult == 2 )
			{
				csPrefix = FileArrangeGetPrefix( csName );
				if( csPrefix.Compare( _T("CDImage") ) == 0 )
				{
					csOldName.Format( _T("%s\\%s"), csDir, csName );
					csNewName.Format( _T("%s\\%s.%s"), csDir, csTitle, csTemp );
					csNewName = WordCheckLen( csNewName, nSuffixLen );
					if( csOldName.Compare( csNewName ) != 0 )
						MoveFile( csOldName, csNewName );
				}
				if( nResult == 1 )
					nMusicFileCount++;
			}
			else if( nResult == 4 )
			{
				csOldName.Format( _T("%s\\%s"), csDir, csName );
				csNewName.Format( _T("%s\\%s.Cover.%s"), csDir, csTitle, csTemp );
				csNewName = WordCheckLen( csNewName, nSuffixLen );
				if( csOldName.Compare( csNewName ) != 0 )
					MoveFile( csOldName, csNewName );
			}
			else if( nResult == 5 )
			{
				csOldName.Format( _T("%s\\%s"), csDir, csName );
				csNewName.Format( _T("%s\\%s.Log.%s"), csDir, csTitle, csTemp );
				csNewName = WordCheckLen( csNewName, nSuffixLen );
				if( csOldName.Compare( csNewName ) != 0 )
					MoveFile( csOldName, csNewName );
			}
		}
	}

	Optimize3( csDir, _T(""), csTitle, nMusicFileCount, &fAllSongList );

	fAllSongList.Close();
	if( nAllSongListCount <= 0 )
		fAllSongList.Remove( csAllSongList );

	return ;
}
Пример #17
0
BOOL CMsgHandlerDlg::bValidateUserSelection(CFunctionEditorDoc* pDoc)

{
    BOOL bReturn              = TRUE;
    BOOL bButtonChecked       = FALSE;
    CString omStrMsgNameForID = "";
    CString omStrMsgIDForName = "";

    if(pDoc != NULL )
    {
        CString omStrText = "";
        CString omStrHandlerType = "";
        bButtonChecked =  IsDlgButtonChecked(IDC_RBTN_MSG_NAME);
        CStringArray* pMsgArray = pDoc->omStrGetMessageHandlerPrototypes();

        if(bButtonChecked)
        {
            //COMMENTED BY AK **************
            int nSelection = 0;
            UINT unMsgIDForName = 0;
            CString omStrMsgName = "";
            nSelection = m_omListMsgName.GetCurSel();
            m_omListMsgName.GetText(nSelection,omStrMsgName);
            // get the corresponding message ID from the database
            /* unMsgIDForName=CMsgSignal::ouGetMsgSignal().nGetSlotIDFromName(omStrMsgName);
             if(unMsgIDForName != -1)
             {
                 omStrMsgIDForName.Format("%x",unMsgIDForName);
                 bReturn = bValidateMessageNameAndID( pMsgArray,
                                                      defMSG_NAME_HANDLER,
                                                      omStrMsgIDForName);
             }*/
            m_omStrSelectedItemText = defMSG_NAME_HANDLER;
            m_omStrSelectedItemText += omStrMsgName;
            omStrText = "\""+ omStrMsgName + "\"";
            omStrHandlerType = defMSG_NAME_TEXT;
        }
        else
        {
            bButtonChecked =  IsDlgButtonChecked(IDC_RBTN_MSG_ID);

            if(bButtonChecked != 0)
            {
                UINT unMsgID = 0;
                unMsgID = (UINT)m_odEditMsgID.lGetValue();
                // Get the corresponding message name from the database
                /*omStrMsgNameForID = CMsgSignal::ouGetMsgSignal().
                            omStrGetMessageNameFromSlotID(unMsgID);
                bReturn = bValidateMessageNameAndID( pMsgArray,
                                                     defMSG_ID_HANDLER,
                                                     omStrMsgNameForID);*/
                m_omStrSelectedItemText = defMSG_ID_HANDLER;
                m_omStrSelectedItemText += m_omStrMsgID;
                omStrText = _T("\"")+ m_omStrMsgID + _T("\"");
                omStrHandlerType = defMSG_ID_TEXT;
            }
            else
            {
                bButtonChecked =  IsDlgButtonChecked(IDC_RBTN_MSG_RANGE);

                if(bButtonChecked != 0)
                {
                    UINT unMsgIDFrom = 0;
                    UINT unMsgIDTo   = 0;
                    m_omStrSelectedItemText = defMSG_IDRANGE_HANDLER;
                    m_omStrSelectedItemText += m_omStrMsgIDFrom;
                    m_omStrSelectedItemText += "_";
                    m_omStrSelectedItemText += m_omStrMsgIDTo;
                    unMsgIDTo    = (UINT)m_odEditMsgIDTo.lGetValue();
                    unMsgIDFrom  =(UINT) m_odEditMsgIDFrom.lGetValue();

                    if(unMsgIDFrom < unMsgIDTo)
                    {
                        omStrText = _T("\"")+ m_omStrMsgIDFrom;
                        omStrText += _T("-");
                        omStrText += m_omStrMsgIDTo;
                        omStrText += _T("\"");
                        omStrHandlerType = defMSG_IDRANGE_TEXT;
                    }
                    else
                    {
                        bReturn = FALSE;
                        AfxMessageBox(defSTRMSG_RANGE_INVALID);
                        m_odEditMsgIDFrom.SetFocus();
                    }
                }
                else
                {
                    bButtonChecked =  IsDlgButtonChecked(IDC_RBTN_MSG_ALL);

                    if(bButtonChecked != 0)
                    {
                        m_omStrSelectedItemText = defMSG_ALL;
                        omStrHandlerType = defMSG_ALL_TEXT;
                        omStrText = "message";
                    }
                }
            }
        }

        if(bReturn == TRUE)
        {
            if (pMsgArray)
            {
                CString omStrMsgPro = STR_EMPTY;
                CString omStrMsgCommon = CGlobalObj::omGetBusSpecMsgHndlrName(m_eBus);

                for (int nCount = 0; nCount<pMsgArray->GetSize(); nCount++ )
                {
                    omStrMsgPro = pMsgArray->GetAt( nCount );
                    omStrMsgPro = omStrMsgPro.Right(omStrMsgPro.GetLength()
                                                    - omStrMsgPro.Find(_T(" ")) - 1);
                    omStrMsgPro = omStrMsgPro.Right(omStrMsgPro.GetLength()
                                                    - omStrMsgCommon.GetLength());
                    omStrMsgPro = omStrMsgPro.Left( omStrMsgPro.Find(_T("(")) );
                    omStrMsgPro.TrimLeft();
                    omStrMsgPro.TrimRight();

                    if (omStrMsgPro.Compare(m_omStrSelectedItemText) == 0)
                    {
                        // Form the message to be dispalyed
                        omStrMsgPro = defMSG_DUPL_MSG_HANDLER;
                        omStrMsgPro.Replace( _T("TYPE"),
                                             omStrHandlerType );
                        omStrMsgPro.Replace( _T("MESSAGENAME"),
                                             omStrText );
                        // Duplicate message hanlder, shout
                        AfxMessageBox( omStrMsgPro,
                                       MB_OK|MB_ICONINFORMATION );
                        nCount = (COMMANINT)pMsgArray->GetSize();
                        bReturn = FALSE;

                        if(omStrHandlerType.Compare(defMSG_NAME_TEXT) ==0 )
                        {
                            m_omListMsgName.SetFocus();
                        }
                        else if(omStrHandlerType.Compare(defMSG_ID_TEXT) == 0 )
                        {
                            m_odEditMsgID.SetFocus();
                        }
                        else if(
                            omStrHandlerType.Compare(defMSG_IDRANGE_TEXT) == 0 )
                        {
                            m_odEditMsgIDFrom.SetFocus();
                        }
                    }
                }
            }
            else
            {
                bReturn = FALSE;
            }
        }
    }
    else
    {
        bReturn = FALSE;
    }

    // Remove the selected item from the list
    if( bReturn == TRUE && bButtonChecked == TRUE)
    {
        int nIndex = m_omListMsgName.GetCurSel();

        if( nIndex != -1 )
        {
            m_omListMsgName.DeleteString( nIndex );
        }
    }

    return bReturn;
}
Пример #18
0
void Optimize3( CString csDir, CString csSubDirName, CString csTitle, int nMusicFileCount, CStdioFile *pfAllSongList )
{
	CStdioFile fSongList;
	CString csSongList;
	CString csName;
	CString csSequence;
	CString csOldName;
	CString csNewName;
	CString csTemp;
	int nSuffixLen;
	CFileFind cFile;
	CFileFind *pcFile = &cFile;
	csTemp.Format( _T("%s\\*"), csDir );
	BOOL b = pcFile->FindFile( csTemp );

	if( nMusicFileCount > SINGLE_MUSIC_FILE_MAX )
	{
		csSongList.Format( _T("%s\\%s.SongList.m3u"), csDir, csTitle );
		csSongList = WordCheckLen( csSongList, 12 );
		fSongList.Open( csSongList, CFile::modeWrite|CFile::modeCreate );
	}
	
	b = pcFile->FindNextFile();
	b = pcFile->FindNextFile();
	while( b != NULL )
	{
		b = pcFile->FindNextFile();
		if( !( pcFile->IsDirectory() ) )
		{
			csName = pcFile->GetFileName();
			csTemp = FileArrangeGetSuffix( csName );
			nSuffixLen = csTemp.GetLength();
			if( WordCheckSuffix( csTemp ) == 1 )
			{
				csOldName.Format( _T("%s\\%s"), csDir, csName );
				csSequence = WordCheckSequence( csName );
				//如果需要添加序号
				if( csSequence.Compare( _T("") ) != 0 && nMusicFileCount > SINGLE_MUSIC_FILE_MAX )
				{
					csTemp = PunctuationDeleteSequence( csName );
					csNewName.Format( _T("%s\\%s.-.%s"), csDir, csSequence, csTemp );
					csNewName = WordCheckLen( csNewName, nSuffixLen );
					if( csOldName.Compare( csNewName ) != 0 )
						MoveFile( csOldName, csNewName );
					csNewName.Format( _T("%s.-.%s"), csSequence, csTemp );
					if( csSubDirName.Compare( _T("") ) != 0 )
						csName.Format( _T("%s\\%s.-.%s"), csSubDirName, csSequence, csTemp );
					else
						csName.Format( _T("%s.-.%s"), csSequence, csTemp );
				}
				//如果需要删除序号
				else if( csSequence.Compare( _T("") ) != 0 && nMusicFileCount <= NO_SEQUENCE_FILE_MAX )
				{
					csTemp = PunctuationDeleteSequence( csName );
					csNewName.Format( _T("%s\\%s"), csDir, csTemp );
					csNewName = WordCheckLen( csNewName, nSuffixLen );
					if( csOldName.Compare( csNewName ) != 0 )
						MoveFile( csOldName, csNewName );
					csNewName.Format( _T("%s"), csTemp );
					if( csSubDirName.Compare( _T("") ) != 0 )
						csName.Format( _T("%s\\%s"), csSubDirName, csTemp );
					else
						csName.Format( _T("%s"), csTemp );
				}
				//如果不需要改变
				else
				{
					csNewName.Format( _T("%s"), csName );
					csTemp.Format( _T("%s\\%s"), csSubDirName, csName );
					csName.Format( _T("%s"), csTemp );
				}
				setlocale( LC_CTYPE, "chs" );
				if( nMusicFileCount > SINGLE_MUSIC_FILE_MAX && fSongList != 0 )
				{
					fSongList.WriteString( csNewName );
					fSongList.WriteString( _T("\n") );
				}
				pfAllSongList->WriteString( csName );
				pfAllSongList->WriteString( _T("\n") );
			}
		}
	}

	if( nMusicFileCount > SINGLE_MUSIC_FILE_MAX && fSongList != 0 )
		fSongList.Close();
	
	return ;
}
Пример #19
0
void CToolTipCtrlX::CustomPaint(LPNMTTCUSTOMDRAW pNMCD)
{
	CWnd* pwnd = CWnd::FromHandle(pNMCD->nmcd.hdr.hwndFrom);
	CDC* pdc = CDC::FromHandle(pNMCD->nmcd.hdc);

	// Windows Vista (General)
	// -----------------------
	// *Need* to use (some aspects) of the 'TOOLTIP' theme to get typical Vista tooltips.
	//
	// Windows Vista *without* SP1
	// ---------------------------
	// The Vista 'TOOLTIP' theme offers a bold version of the standard tooltip font via 
	// the TTP_STANDARDTITLE part id. Furthermore TTP_STANDARDTITLE is the same font as
	// the standard tooltip font (TTP_STANDARD). So, the 'TOOLTIP' theme can get used
	// thoroughly.
	//
	// Windows Vista *with* SP1
	// ------------------------
	// The Vista SP1(!) 'TOOLTIP' theme does though *not* offer a bold font. Keep
	// in mind that TTP_STANDARDTITLE does not return a bold font. Keep also in mind
	// that TTP_STANDARDTITLE is even a *different* font than TTP_STANDARD!
	// Which means, that TTP_STANDARDTITLE should *not* be used within the same line
	// as TTP_STANDARD. It just looks weird. TTP_STANDARDTITLE could be used for a
	// single line (the title line), but it would though not give us a bold font.
	// So, actually we can use the Vista 'TOOLTIP' theme only for getting the proper
	// tooltip background.
	//
	// Windows XP
	// ----------
	// Can *not* use the 'TOOLTIP' theme at all because it would give us only a (non-bold)
	// black font on a white tooltip window background. Seems that the 'TOOLTIP' theme under 
	// WinXP is just using the default Window values (black+white) and does not
	// use any of the tooltip specific Window metrics...
	//
	bool bUseEmbeddedThemeFonts = false;
	HTHEME hTheme = NULL;
	if (theApp.IsVistaThemeActive()) {
		hTheme = OpenThemeData(*pwnd, L"TOOLTIP");
		// Using the theme's fonts works only under Vista without SP1. When SP1
		// is installed the fonts which are used for TTP_STANDARDTITLE and TTP_STANDARD
		// do no longer match (should not get displayed within the same text line).
		if (hTheme) bUseEmbeddedThemeFonts = true;
	}

	CString strText;
	pwnd->GetWindowText(strText);

	CRect rcWnd;
	pwnd->GetWindowRect(&rcWnd);

	CFont* pOldDCFont = NULL;
	if (hTheme == NULL || !bUseEmbeddedThemeFonts)
	{
		// If we have a theme, we try to query the correct fonts from it
		if (m_fontNormal.m_hObject == NULL && hTheme) {
			// Windows Vista Ultimate, 6.0.6001 SP1 Build 6001, English with German Language Pack
			// ----------------------------------------------------------------------------------
			// TTP_STANDARD, TTSS_NORMAL
			//  Height   -12
			//  Weight   400
			//  CharSet  1
			//  Quality  5
			//  FaceName "Segoe UI"
			//
			// TTP_STANDARDTITLE, TTSS_NORMAL
			//  Height   -12
			//  Weight   400
			//  CharSet  1
			//  Quality  5
			//  FaceName "Segoe UI Fett" (!!!) Note: "Fett" (that is German !?)
			//
			// That font name ("Segoe UI *Fett*") looks quite suspicious. I would not be surprised
			// if that eventually leads to a problem within the font mapper which may not be capable
			// of finding the (english) version of that font and thus falls back to the standard
			// system font. At least this would explain why the TTP_STANDARD and TTP_STANDARDTITLE
			// fonts are *different* on that particular Windows Vista system.
			LOGFONT lf = {0};
			if (GetThemeFont(hTheme, pdc->m_hDC, TTP_STANDARD, TTSS_NORMAL, TMT_FONT, &lf) == S_OK) {
				VERIFY( m_fontNormal.CreateFontIndirect(&lf) );

				if (m_bCol1Bold && m_fontBold.m_hObject == NULL) {
					memset(&lf, 0, sizeof(lf));
					if (GetThemeFont(hTheme, pdc->m_hDC, TTP_STANDARDTITLE, TTSS_NORMAL, TMT_FONT, &lf) == S_OK)
						VERIFY( m_fontBold.CreateFontIndirect(&lf) );
				}

				// Get the tooltip font color
				COLORREF crText;
				if (GetThemeColor(hTheme, TTP_STANDARD, TTSS_NORMAL, TMT_TEXTCOLOR, &crText) == S_OK)
					m_crTooltipTextColor = crText;
			}
		}

		// If needed, create the standard tooltip font which was queried from the system metrics
		if (m_fontNormal.m_hObject == NULL && m_lfNormal.lfHeight != 0)
			VERIFY( m_fontNormal.CreateFontIndirect(&m_lfNormal) );

		// Select the tooltip font
		if (m_fontNormal.m_hObject != NULL) {
			pOldDCFont = pdc->SelectObject(&m_fontNormal);

			// If needed, create the bold version of the tooltip font by deriving it from the standard font
			if (m_bCol1Bold && m_fontBold.m_hObject == NULL) {
				LOGFONT lf;
				m_fontNormal.GetLogFont(&lf);
				lf.lfWeight = FW_BOLD;
				VERIFY( m_fontBold.CreateFontIndirect(&lf) );
			}
		}

		// Set the font color (queried from system metrics or queried from theme)
		pdc->SetTextColor(m_crTooltipTextColor);
	}

	// Auto-format the text only if explicitly requested. Otherwise we would also format
	// single line tooltips for regular list items, and if those list items contain ':'
	// characters they would be shown partially in bold. For performance reasons, the
	// auto-format is to be requested by appending the TOOLTIP_AUTOFORMAT_SUFFIX_CH 
	// character. Appending, because we can remove that character efficiently without
	// re-allocating the entire string.
	bool bAutoFormatText = strText.GetLength() > 0 && strText[strText.GetLength() - 1] == TOOLTIP_AUTOFORMAT_SUFFIX_CH;
	if (bAutoFormatText)
		strText.Truncate(strText.GetLength() - 1); // truncate the TOOLTIP_AUTOFORMAT_SUFFIX_CH char by setting it to NUL
	bool bShowFileIcon = m_bShowFileIcon && bAutoFormatText;
	if (bShowFileIcon) {
		int iPosNL = strText.Find(_T('\n'));
		if (iPosNL > 0) {
			int iPosColon = strText.Find(_T(':'));
			if (iPosColon < iPosNL)
				bShowFileIcon = false; // 1st line does not contain a filename
		}
	}
	
	int iTextHeight = 0;
	int iMaxCol1Width = 0;
	int iMaxCol2Width = 0;
	int iMaxSingleLineWidth = 0;
	CSize sizText(0);
	int iPos = 0;
	int iCaptionHeight = 0;
	const int iCaptionEnd = bShowFileIcon ? max(strText.Find(_T("\n<br_head>\n")), 0) : 0; // special tooltip with file icon
	const int iLineHeightOff = 1;
	const int iIconMinYBorder = bShowFileIcon ? 3 : 0;
	const int iIconWidth = bShowFileIcon ? theApp.GetBigSytemIconSize().cx : 0;
	const int iIconHeight = bShowFileIcon ? theApp.GetBigSytemIconSize().cy : 0;
	const int iIconDrawingWidth = bShowFileIcon ? (iIconWidth + 9) : 0;
	while (iPos != -1)
	{
		CString strLine = GetNextString(strText, _T('\n'), iPos);
		int iColon = bAutoFormatText ? strLine.Find(_T(':')) : -1;
		if (iColon != -1) {
			CSize siz;
			if (hTheme && bUseEmbeddedThemeFonts) {
				CRect rcExtent;
				CRect rcBounding(0, 0, 32767, 32767);
				GetThemeTextExtent(hTheme, *pdc, m_bCol1Bold ? TTP_STANDARDTITLE : TTP_STANDARD, TTSS_NORMAL, strLine, iColon + 1, m_dwCol1DrawTextFlags, &rcBounding, &rcExtent);
				siz.cx = rcExtent.Width();
				siz.cy = rcExtent.Height();
			}
			else {
				CFont* pOldFont = m_bCol1Bold ? pdc->SelectObject(&m_fontBold) : NULL;
				siz = pdc->GetTextExtent(strLine, iColon + 1);
				if (pOldFont)
					pdc->SelectObject(pOldFont);
			}
			iMaxCol1Width = max<int>(iMaxCol1Width, siz.cx + ((bShowFileIcon && iPos <= iCaptionEnd + strLine.GetLength()) ? iIconDrawingWidth : 0));
			iTextHeight = siz.cy + iLineHeightOff; // update height with 'col1' string, because 'col2' string might be empty and therefore has no height
			if (iPos <= iCaptionEnd)
				iCaptionHeight += siz.cy + iLineHeightOff;
			else
				sizText.cy += siz.cy + iLineHeightOff;

			LPCTSTR pszCol2 = (LPCTSTR)strLine + iColon + 1;
			while (_istspace((_TUCHAR)*pszCol2))
				pszCol2++;
			if (*pszCol2 != _T('\0')) {
				if (hTheme && bUseEmbeddedThemeFonts) {
					CRect rcExtent;
					CRect rcBounding(0, 0, 32767, 32767);
					GetThemeTextExtent(hTheme, *pdc, TTP_STANDARD, TTSS_NORMAL, pszCol2, ((LPCTSTR)strLine + strLine.GetLength()) - pszCol2, m_dwCol2DrawTextFlags, &rcBounding, &rcExtent);
					siz.cx = rcExtent.Width();
					siz.cy = rcExtent.Height();
				}
				else {
					siz = pdc->GetTextExtent(pszCol2, ((LPCTSTR)strLine + strLine.GetLength()) - pszCol2);
				}
				iMaxCol2Width = max<int>(iMaxCol2Width, siz.cx);
			}
		}
		else if (bShowFileIcon && iPos <= iCaptionEnd && iPos == strLine.GetLength() + 1){
			// file name, printed bold on top without any tabbing or desc
			CSize siz;
			if (hTheme && bUseEmbeddedThemeFonts) {
				CRect rcExtent;
				CRect rcBounding(0, 0, 32767, 32767);
				GetThemeTextExtent(hTheme, *pdc, m_bCol1Bold ? TTP_STANDARDTITLE : TTP_STANDARD, TTSS_NORMAL, strLine, strLine.GetLength(), m_dwCol1DrawTextFlags, &rcBounding, &rcExtent);
				siz.cx = rcExtent.Width();
				siz.cy = rcExtent.Height();
			}
			else {
				CFont* pOldFont = m_bCol1Bold ? pdc->SelectObject(&m_fontBold) : NULL;
				siz = pdc->GetTextExtent(strLine);
				if (pOldFont)
					pdc->SelectObject(pOldFont);
			}
			iMaxSingleLineWidth = max<int>(iMaxSingleLineWidth, siz.cx + iIconDrawingWidth);
			iCaptionHeight += siz.cy + iLineHeightOff;
		}
		else if (!strLine.IsEmpty() && strLine.Compare(_T("<br>")) != 0 && strLine.Compare(_T("<br_head>")) != 0) {
			CSize siz;
			if (hTheme && bUseEmbeddedThemeFonts) {
				CRect rcExtent;
				CRect rcBounding(0, 0, 32767, 32767);
				GetThemeTextExtent(hTheme, *pdc, TTP_STANDARD, TTSS_NORMAL, strLine, strLine.GetLength(), m_dwCol2DrawTextFlags, &rcBounding, &rcExtent);
				siz.cx = rcExtent.Width();
				siz.cy = rcExtent.Height();
			}
			else {
				siz = pdc->GetTextExtent(strLine);
			}
			iMaxSingleLineWidth = max<int>(iMaxSingleLineWidth, siz.cx + ((bShowFileIcon && iPos <= iCaptionEnd) ? iIconDrawingWidth : 0));
			if (bShowFileIcon && iPos <= iCaptionEnd + strLine.GetLength())
				iCaptionHeight += siz.cy + iLineHeightOff;
			else
				sizText.cy += siz.cy + iLineHeightOff;
		}
		else{
			CSize siz;
			if (hTheme && bUseEmbeddedThemeFonts) {
				CRect rcExtent;
				CRect rcBounding(0, 0, 32767, 32767);
				GetThemeTextExtent(hTheme, *pdc, TTP_STANDARD, TTSS_NORMAL, _T(" "), 1, m_dwCol2DrawTextFlags, &rcBounding, &rcExtent);
				siz.cx = rcExtent.Width();
				siz.cy = rcExtent.Height();
			}
			else {
				// TODO: Would need to use 'GetTabbedTextExtent' here, but do we actually use 'tabbed' text here at all ??
				siz = pdc->GetTextExtent(_T(" "), 1);
			}
			sizText.cy += siz.cy + iLineHeightOff;
		}
	}
	if (bShowFileIcon && iCaptionEnd > 0)
		iCaptionHeight = max<int>(iCaptionHeight, theApp.GetBigSytemIconSize().cy + (2*iIconMinYBorder));
	sizText.cy += iCaptionHeight;
	if (hTheme && theApp.m_ullComCtrlVer >= MAKEDLLVERULL(6,16,0,0))
		sizText.cy += 2; // extra bottom margin for Vista/Theme

	iMaxCol1Width = min(m_iScreenWidth4, iMaxCol1Width);
	iMaxCol2Width = min(m_iScreenWidth4*2, iMaxCol2Width);

	const int iMiddleMargin = 6;
	iMaxSingleLineWidth = max(iMaxSingleLineWidth, iMaxCol1Width + iMiddleMargin + iMaxCol2Width);
	if (iMaxSingleLineWidth > m_iScreenWidth4*3)
		iMaxSingleLineWidth = m_iScreenWidth4*3;
	sizText.cx = iMaxSingleLineWidth;

	if (pNMCD->uDrawFlags & DT_CALCRECT)
	{
		pNMCD->nmcd.rc.left = rcWnd.left;
		pNMCD->nmcd.rc.top = rcWnd.top;
		pNMCD->nmcd.rc.right = rcWnd.left + sizText.cx;
		pNMCD->nmcd.rc.bottom = rcWnd.top + sizText.cy;
	}
	else
	{
		pwnd->ScreenToClient(&rcWnd);

		int iOldBkColor = -1;
		if (hTheme) {
			int iPartId = TTP_STANDARD;
			int iStateId = TTSS_NORMAL;
			if (IsThemeBackgroundPartiallyTransparent(hTheme, iPartId, iStateId))
				DrawThemeParentBackground(m_hWnd, pdc->m_hDC, &rcWnd);
			DrawThemeBackground(hTheme, pdc->m_hDC, iPartId, iStateId, &rcWnd, NULL);
		}
		else {
			::FillRect(*pdc, &rcWnd, GetSysColorBrush(COLOR_INFOBK));
			iOldBkColor = pdc->SetBkColor(m_crTooltipBkColor);
			// Vista: Need to draw the window border explicitly !?
			if (theApp.m_ullComCtrlVer >= MAKEDLLVERULL(6,16,0,0)) {
				CPen pen;
				pen.CreatePen(0, 1, m_crTooltipTextColor);
				CPen *pOP = pdc->SelectObject(&pen);
				pdc->MoveTo(rcWnd.left, rcWnd.top);
				pdc->LineTo(rcWnd.right - 1, rcWnd.top);
				pdc->LineTo(rcWnd.right - 1, rcWnd.bottom - 1);
				pdc->LineTo(rcWnd.left, rcWnd.bottom - 1);
				pdc->LineTo(rcWnd.left, rcWnd.top);
				pdc->SelectObject(pOP);
				pen.DeleteObject();
			}
		}

		int iOldBkMode = 0;
		if ((hTheme && !bUseEmbeddedThemeFonts) || (hTheme == NULL && iOldBkColor != -1))
			iOldBkMode = pdc->SetBkMode(TRANSPARENT);

		CPoint ptText(pNMCD->nmcd.rc.left, pNMCD->nmcd.rc.top);
		iPos = 0;
		while (iPos != -1)
		{
			CString strLine = GetNextString(strText, _T('\n'), iPos);
			int iColon = bAutoFormatText ? strLine.Find(_T(':')) : -1;
			CRect rcDT;
			if (!bShowFileIcon || (unsigned)iPos > (unsigned)iCaptionEnd + strLine.GetLength())
				rcDT.SetRect(ptText.x, ptText.y, ptText.x + iMaxCol1Width, ptText.y + iTextHeight);
			else
				rcDT.SetRect(ptText.x + iIconDrawingWidth, ptText.y, ptText.x + iMaxCol1Width, ptText.y + iTextHeight);
			if (iColon != -1) {
				// don't draw empty <col1> strings (they are still handy to use for skipping the <col1> space)
				if (iColon > 0) {
					if (hTheme && bUseEmbeddedThemeFonts)
						DrawThemeText(hTheme, pdc->m_hDC, m_bCol1Bold ? TTP_STANDARDTITLE : TTP_STANDARD, TTSS_NORMAL, strLine, iColon + 1, m_dwCol1DrawTextFlags, 0, &rcDT);
					else {
						CFont* pOldFont = m_bCol1Bold ? pdc->SelectObject(&m_fontBold) : NULL;
						pdc->DrawText(strLine, iColon + 1, &rcDT, m_dwCol1DrawTextFlags);
						if (pOldFont)
							pdc->SelectObject(pOldFont);
					}
				}

				LPCTSTR pszCol2 = (LPCTSTR)strLine + iColon + 1;
				while (_istspace((_TUCHAR)*pszCol2))
					pszCol2++;
				if (*pszCol2 != _T('\0')) {
					rcDT.left = ptText.x + iMaxCol1Width + iMiddleMargin;
					rcDT.right = rcDT.left + iMaxCol2Width;
					if (hTheme && bUseEmbeddedThemeFonts)
						DrawThemeText(hTheme, pdc->m_hDC, TTP_STANDARD, TTSS_NORMAL, pszCol2, ((LPCTSTR)strLine + strLine.GetLength()) - pszCol2, m_dwCol2DrawTextFlags, 0, &rcDT);
					else
						pdc->DrawText(pszCol2, ((LPCTSTR)strLine + strLine.GetLength()) - pszCol2, &rcDT, m_dwCol2DrawTextFlags);
				}

				ptText.y += iTextHeight;
			}
			else if (bShowFileIcon && iPos <= iCaptionEnd && iPos == strLine.GetLength() + 1){
				// first line on special fileicon tab - draw icon and bold filename
				if (hTheme && bUseEmbeddedThemeFonts)
					DrawThemeText(hTheme, pdc->m_hDC, m_bCol1Bold ? TTP_STANDARDTITLE : TTP_STANDARD, TTSS_NORMAL, strLine, strLine.GetLength(), m_dwCol1DrawTextFlags, 0, &CRect(ptText.x  + iIconDrawingWidth, ptText.y, ptText.x + iMaxSingleLineWidth, ptText.y + iTextHeight));
				else {
					CFont* pOldFont = m_bCol1Bold ? pdc->SelectObject(&m_fontBold) : NULL;
					pdc->DrawText(strLine, CRect(ptText.x  + iIconDrawingWidth, ptText.y, ptText.x + iMaxSingleLineWidth, ptText.y + iTextHeight), m_dwCol1DrawTextFlags);
					if (pOldFont)
						pdc->SelectObject(pOldFont);
				}

				ptText.y += iTextHeight;
				int iImage = (int) theApp.GetFileTypeSystemImageIdx(strLine, -1, true);
				if (theApp.GetBigSystemImageList() != NULL) {
					int iPosY = rcDT.top;
					if (iCaptionHeight > iIconHeight)
						iPosY += (iCaptionHeight - iIconHeight) / 2;
					::ImageList_Draw(theApp.GetBigSystemImageList(), iImage, pdc->GetSafeHdc(), ptText.x, iPosY, ILD_TRANSPARENT);
				}
			}
			else {
				bool bIsBrHeadLine = false;
				if (bAutoFormatText && (strLine.Compare(_T("<br>")) == 0 || (bIsBrHeadLine = strLine.Compare(_T("<br_head>")) == 0) == true)){
					CPen pen;
					pen.CreatePen(0, 1, m_crTooltipTextColor);
					CPen *pOP = pdc->SelectObject(&pen);
					if (bIsBrHeadLine)
						ptText.y = iCaptionHeight;
					pdc->MoveTo(ptText.x, ptText.y + ((iTextHeight - 2) / 2)); 
					pdc->LineTo(ptText.x + iMaxSingleLineWidth, ptText.y + ((iTextHeight - 2) / 2));
					ptText.y += iTextHeight;
					pdc->SelectObject(pOP);
					pen.DeleteObject();
				}
				else{
					if (hTheme && bUseEmbeddedThemeFonts) {
						CRect rcLine(ptText.x, ptText.y, 32767, 32767);
						DrawThemeText(hTheme, pdc->m_hDC, TTP_STANDARD, TTSS_NORMAL, strLine, strLine.GetLength(), DT_EXPANDTABS | m_dwCol2DrawTextFlags, 0, &rcLine);
						ptText.y += iTextHeight;
					}
					else {
						// Text is written in the currently selected font. If 'nTabPositions' is 0 and 'lpnTabStopPositions' is NULL,
						// tabs are expanded to eight times the average character width.
						CSize siz;
						if (strLine.IsEmpty()) // Win98: To draw an empty line we need to output at least a space.
							siz = pdc->TabbedTextOut(ptText.x, ptText.y, _T(" "), 1, NULL, 0);
						else
							siz = pdc->TabbedTextOut(ptText.x, ptText.y, strLine, strLine.GetLength(), NULL, 0);
						ptText.y += siz.cy + iLineHeightOff;
					}
				}
			}
		}
		if (iOldBkColor != -1)
			pdc->SetBkColor(iOldBkColor);
		if (hTheme && !bUseEmbeddedThemeFonts)
			pdc->SetBkMode(iOldBkMode);
	}
	if (pOldDCFont)
		pdc->SelectObject(pOldDCFont);
	if (hTheme)
		CloseThemeData(hTheme);
}
Пример #20
0
/**
 * Find the name and size of the file which will be used for logging.
 * ie. file name which contains max file count
 */
void CBaseLogObject::vGetNameAndSizeOfCurrentLogFile()
{
    //Two conditions to search for the current file present at the main file
    //path folder
    //1.If logging is initialised
    //2.if file name is modified ie.m_omCurrLogFile belongs to diff. main file cycle

    //Find file only if current file is not same as main file
    if (m_omCurrLogFile.Compare(m_sLogInfo.m_sLogFileName))
    {
        //Check if the curr file doesn't belong to main file group
        if (m_omCurrLogFile.GetLength() >= MIN_NAME_LENGTH)
        {
            CString omTempFile = m_omCurrLogFile.Left(m_omCurrLogFile.GetLength() - 2);

            if ( !omTempFile.Compare(m_sLogInfo.m_sLogFileName) )
            {
                //If curr file belongs to main file group then do nothing
                return;
            }
        }

        if (ENOENT != _taccess(m_sLogInfo.m_sLogFileName, 0))
        {
            CString strNextFile = omAddGroupCountToFileName(1, m_sLogInfo.m_sLogFileName);

            if (ENOENT != _taccess(strNextFile, 0))
            {
                //If first file is not present then current file is main file
                m_omCurrLogFile = m_sLogInfo.m_sLogFileName;
            }
            else
            {
                //Search for the file in a group with highest count
                m_nCurrFileCnt = 0;

                for (int i = 2; (i <= MAX_LOG_FILE_IN_GRP) && (m_nCurrFileCnt != 0); i++)
                {
                    strNextFile = omAddGroupCountToFileName(i, m_sLogInfo.m_sLogFileName);

                    if (ENOENT != _taccess(strNextFile, 0))
                    {
                        //If this file is not found means the last file is target file
                        m_nCurrFileCnt = --i;
                    }
                }

                m_omCurrLogFile = omAddGroupCountToFileName(m_nCurrFileCnt,
                                  m_sLogInfo.m_sLogFileName);
            }

            //Now find the size of the file
            m_dTotalBytes = dwGetFileSize(m_omCurrLogFile);
        }
        else
        {
            //If main file is not present initialise the current file
            //with main file
            m_omCurrLogFile = m_sLogInfo.m_sLogFileName;
            m_dTotalBytes = 0;
            m_nCurrFileCnt = 0;
        }
    }
}
//================================================================================
void GetLanguage(const string &FileName, string& Language )
//================================================================================
{
    IExtract2 *pIExtract2 = NULL;
    Language = _T("UNKNOWN");

    HRESULT hr = CoInitialize(NULL);
    if(FAILED(hr)) {
        return;
    }

    hr = CoCreateInstance(CLSID_Extract,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IExtract2,
                          ((void**)&pIExtract2));

    if(FAILED(hr)) {
        return;
    }

    BSTR File;
    File = CString(FileName.c_str()).AllocSysString();
    long lOffset = 0;
    BSTR sTagName = L"BODY";
    BSTR sKeyAttrName = L"";
    BSTR sKeyAttrValue = L"";
    BSTR sAttrName = L"LANG";
    BSTR sAttrValue = NULL;
    long plPos;

    pIExtract2->GetXMLAttributeValue(File,
                                     lOffset,
                                     sTagName,
                                     sKeyAttrName,
                                     sKeyAttrValue,
                                     sAttrName,
                                     &sAttrValue,
                                     &plPos);

    if (sAttrValue != NULL)
    {
        CString l = sAttrValue;
        l.MakeUpper();
        // Map ALL to SFC and map every language containing SFC to SFC.
        if ((l.Compare("ALL") == 0) || (l.Find("SFC") != -1))
        {
            l = _T("SFC");
        }
        Language = l;
        ::SysFreeString(sAttrValue);
    }

    ::SysFreeString(File);

    if (pIExtract2 != NULL)
    {
        pIExtract2->Release();
    }
    CoUninitialize( );
    return;
}
Пример #22
0
// CTortoiseMergeApp initialization
BOOL CTortoiseMergeApp::InitInstance()
{
    SetDllDirectory(L"");
    SetTaskIDPerUUID();
    CCrashReport::Instance().AddUserInfoToReport(L"CommandLine", GetCommandLine());

    {
        DWORD len = GetCurrentDirectory(0, nullptr);
        if (len)
        {
            auto originalCurrentDirectory = std::make_unique<TCHAR[]>(len);
            if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
            {
                sOrigCWD = originalCurrentDirectory.get();
                sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
            }
        }
    }

    //set the resource dll for the required language
    CRegDWORD loc = CRegDWORD(L"Software\\TortoiseSVN\\LanguageID", 1033);
    long langId = loc;
    CString langDll;
    HINSTANCE hInst = nullptr;
    do
    {
        langDll.Format(L"%sLanguages\\TortoiseMerge%ld.dll", (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId);

        hInst = LoadLibrary(langDll);
        CString sVer = _T(STRPRODUCTVER);
        CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
        if (sFileVer.Compare(sVer)!=0)
        {
            FreeLibrary(hInst);
            hInst = nullptr;
        }
        if (hInst)
            AfxSetResourceHandle(hInst);
        else
        {
            DWORD lid = SUBLANGID(langId);
            lid--;
            if (lid > 0)
            {
                langId = MAKELANGID(PRIMARYLANGID(langId), lid);
            }
            else
                langId = 0;
        }
    } while ((!hInst) && (langId != 0));
    TCHAR buf[6] = { 0 };
    wcscpy_s(buf, L"en");
    langId = loc;
    CString sHelppath;
    sHelppath = this->m_pszHelpFilePath;
    sHelppath = sHelppath.MakeLower();
    sHelppath.Replace(L".chm", L"_en.chm");
    free((void*)m_pszHelpFilePath);
    m_pszHelpFilePath=_wcsdup(sHelppath);
    sHelppath = CPathUtils::GetAppParentDirectory() + L"Languages\\TortoiseMerge_en.chm";
    do
    {
        GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf));
        CString sLang = L"_";
        sLang += buf;
        sHelppath.Replace(L"_en", sLang);
        if (PathFileExists(sHelppath))
        {
            free((void*)m_pszHelpFilePath);
            m_pszHelpFilePath=_wcsdup(sHelppath);
            break;
        }
        sHelppath.Replace(sLang, L"_en");
        GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf));
        sLang += L"_";
        sLang += buf;
        sHelppath.Replace(L"_en", sLang);
        if (PathFileExists(sHelppath))
        {
            free((void*)m_pszHelpFilePath);
            m_pszHelpFilePath=_wcsdup(sHelppath);
            break;
        }
        sHelppath.Replace(sLang, L"_en");

        DWORD lid = SUBLANGID(langId);
        lid--;
        if (lid > 0)
        {
            langId = MAKELANGID(PRIMARYLANGID(langId), lid);
        }
        else
            langId = 0;
    } while (langId);
    setlocale(LC_ALL, "");
    // We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage
    // The problems occures when the language of OS differs from the regional settings
    // See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887
    SetThreadLocale(LOCALE_SYSTEM_DEFAULT);

    // InitCommonControls() is required on Windows XP if an application
    // manifest specifies use of ComCtl32.dll version 6 or later to enable
    // visual styles.  Otherwise, any window creation will fail.
    InitCommonControls();

    CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
    CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE;
    CMFCButton::EnableWindowsTheming();
    EnableTaskbarInteraction(FALSE);

    // Initialize all Managers for usage. They are automatically constructed
    // if not yet present
    InitContextMenuManager();
    InitKeyboardManager();
    InitTooltipManager ();
    CMFCToolTipInfo params;
    params.m_bVislManagerTheme = TRUE;

    GetTooltipManager ()->SetTooltipParams (
        AFX_TOOLTIP_TYPE_ALL,
        RUNTIME_CLASS (CMFCToolTipCtrl),
        &params);

    CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine);

    g_sGroupingUUID = parser.GetVal(L"groupuuid");

    if (parser.HasKey(L"?") || parser.HasKey(L"help"))
    {
        CString sHelpText;
        sHelpText.LoadString(IDS_COMMANDLINEHELP);
        MessageBox(nullptr, sHelpText, L"TortoiseMerge", MB_ICONINFORMATION);
        return FALSE;
    }

    // Initialize OLE libraries
    if (!AfxOleInit())
    {
        AfxMessageBox(IDP_OLE_INIT_FAILED);
        return FALSE;
    }
    AfxEnableControlContainer();
    // Standard initialization
    // If you are not using these features and wish to reduce the size
    // of your final executable, you should remove from the following
    // the specific initialization routines you do not need
    // Change the registry key under which our settings are stored
    SetRegistryKey(L"TortoiseMerge");

    if (CRegDWORD(L"Software\\TortoiseMerge\\Debug", FALSE)==TRUE)
        AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

    // To create the main window, this code creates a new frame window
    // object and then sets it as the application's main window object
    CMainFrame* pFrame = new CMainFrame;
    if (!pFrame)
        return FALSE;
    m_pMainWnd = pFrame;

    // create and load the frame with its resources
    if (!pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, nullptr, nullptr))
        return FALSE;

    // Fill in the command line options
    pFrame->m_Data.m_baseFile.SetFileName(parser.GetVal(L"base"));
    pFrame->m_Data.m_baseFile.SetDescriptiveName(parser.GetVal(L"basename"));
    pFrame->m_Data.m_baseFile.SetReflectedName(parser.GetVal(L"basereflectedname"));
    pFrame->m_Data.m_theirFile.SetFileName(parser.GetVal(L"theirs"));
    pFrame->m_Data.m_theirFile.SetDescriptiveName(parser.GetVal(L"theirsname"));
    pFrame->m_Data.m_theirFile.SetReflectedName(parser.GetVal(L"theirsreflectedname"));
    pFrame->m_Data.m_yourFile.SetFileName(parser.GetVal(L"mine"));
    pFrame->m_Data.m_yourFile.SetDescriptiveName(parser.GetVal(L"minename"));
    pFrame->m_Data.m_yourFile.SetReflectedName(parser.GetVal(L"minereflectedname"));
    pFrame->m_Data.m_mergedFile.SetFileName(parser.GetVal(L"merged"));
    pFrame->m_Data.m_mergedFile.SetDescriptiveName(parser.GetVal(L"mergedname"));
    pFrame->m_Data.m_mergedFile.SetReflectedName(parser.GetVal(L"mergedreflectedname"));
    pFrame->m_Data.m_sPatchPath = parser.HasVal(L"patchpath") ? parser.GetVal(L"patchpath") : L"";
    pFrame->m_Data.m_sPatchPath.Replace('/', '\\');
    if (parser.HasKey(L"patchoriginal"))
        pFrame->m_Data.m_sPatchOriginal = parser.GetVal(L"patchoriginal");
    if (parser.HasKey(L"patchpatched"))
        pFrame->m_Data.m_sPatchPatched = parser.GetVal(L"patchpatched");
    pFrame->m_Data.m_sDiffFile = parser.GetVal(L"diff");
    pFrame->m_Data.m_sDiffFile.Replace('/', '\\');
    if (parser.HasKey(L"oneway"))
        pFrame->m_bOneWay = TRUE;
    if (parser.HasKey(L"diff"))
        pFrame->m_bOneWay = FALSE;
    if (parser.HasKey(L"reversedpatch"))
        pFrame->m_bReversedPatch = TRUE;
    if (parser.HasKey(L"saverequired"))
        pFrame->m_bSaveRequired = true;
    if (parser.HasKey(L"saverequiredonconflicts"))
        pFrame->m_bSaveRequiredOnConflicts = true;
    if (parser.HasKey(L"nosvnresolve"))
        pFrame->m_bAskToMarkAsResolved = false;
    if (pFrame->m_Data.IsBaseFileInUse() && !pFrame->m_Data.IsYourFileInUse() && pFrame->m_Data.IsTheirFileInUse())
    {
        pFrame->m_Data.m_yourFile.TransferDetailsFrom(pFrame->m_Data.m_theirFile);
    }

    if ((!parser.HasKey(L"patchpath"))&&(parser.HasVal(L"diff")))
    {
        // a patchfile was given, but not folder path to apply the patch to
        // If the patchfile is located inside a working copy, then use the parent directory
        // of the patchfile as the target directory, otherwise ask the user for a path.
        if (parser.HasKey(L"wc"))
            pFrame->m_Data.m_sPatchPath = pFrame->m_Data.m_sDiffFile.Left(pFrame->m_Data.m_sDiffFile.ReverseFind('\\'));
        else
        {
            CBrowseFolder fbrowser;
            fbrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
            if (fbrowser.Show(nullptr, pFrame->m_Data.m_sPatchPath) == CBrowseFolder::CANCEL)
                return FALSE;
        }
    }

    if ((parser.HasKey(L"patchpath"))&&(!parser.HasVal(L"diff")))
    {
        // A path was given for applying a patchfile, but
        // the patchfile itself was not.
        // So ask the user for that patchfile

        HRESULT hr;
        // Create a new common save file dialog
        CComPtr<IFileOpenDialog> pfd;
        hr = pfd.CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER);
        if (SUCCEEDED(hr))
        {
            // Set the dialog options
            DWORD dwOptions;
            if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions)))
            {
                hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
            }

            // Set a title
            if (SUCCEEDED(hr))
            {
                CString temp;
                temp.LoadString(IDS_OPENDIFFFILETITLE);
                pfd->SetTitle(temp);
            }
            CSelectFileFilter fileFilter(IDS_PATCHFILEFILTER);
            hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter);
            bool bAdvised = false;
            DWORD dwCookie = 0;
            CComObjectStackEx<PatchOpenDlgEventHandler> cbk;
            CComQIPtr<IFileDialogEvents> pEvents = cbk.GetUnknown();

            {
                CComPtr<IFileDialogCustomize> pfdCustomize;
                hr = pfd.QueryInterface(&pfdCustomize);
                if (SUCCEEDED(hr))
                {
                    // check if there's a unified diff on the clipboard and
                    // add a button to the fileopen dialog if there is.
                    UINT cFormat = RegisterClipboardFormat(L"TSVN_UNIFIEDDIFF");
                    if ((cFormat) && (OpenClipboard(nullptr)))
                    {
                        HGLOBAL hglb = GetClipboardData(cFormat);
                        if (hglb)
                        {
                            pfdCustomize->AddPushButton(101, CString(MAKEINTRESOURCE(IDS_PATCH_COPYFROMCLIPBOARD)));
                            hr = pfd->Advise(pEvents, &dwCookie);
                            bAdvised = SUCCEEDED(hr);
                        }
                        CloseClipboard();
                    }
                }
            }

            // Show the save file dialog
            if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(pFrame->m_hWnd)))
            {
                // Get the selection from the user
                CComPtr<IShellItem> psiResult;
                hr = pfd->GetResult(&psiResult);
                if (bAdvised)
                    pfd->Unadvise(dwCookie);
                if (SUCCEEDED(hr))
                {
                    PWSTR pszPath = nullptr;
                    hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
                    if (SUCCEEDED(hr))
                    {
                        pFrame->m_Data.m_sDiffFile = pszPath;
                        CoTaskMemFree(pszPath);
                    }
                }
                else
                {
                    // no result, which means we closed the dialog in our button handler
                    std::wstring sTempFile;
                    if (TrySavePatchFromClipboard(sTempFile))
                        pFrame->m_Data.m_sDiffFile = sTempFile.c_str();
                }
            }
            else
            {
                if (bAdvised)
                    pfd->Unadvise(dwCookie);
                return FALSE;
            }
        }
    }

    if ( pFrame->m_Data.m_baseFile.GetFilename().IsEmpty() && pFrame->m_Data.m_yourFile.GetFilename().IsEmpty() )
    {
        int nArgs;
        LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
        if (!szArglist)
            TRACE("CommandLineToArgvW failed\n");
        else
        {
            if ( nArgs==3 || nArgs==4 )
            {
                // Four parameters:
                // [0]: Program name
                // [1]: BASE file
                // [2]: my file
                // [3]: THEIR file (optional)
                // This is the same format CAppUtils::StartExtDiff
                // uses if %base and %mine are not set and most
                // other diff tools use it too.
                if ( PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]) )
                {
                    pFrame->m_Data.m_baseFile.SetFileName(szArglist[1]);
                    pFrame->m_Data.m_yourFile.SetFileName(szArglist[2]);
                    if ( nArgs == 4 && PathFileExists(szArglist[3]) )
                    {
                        pFrame->m_Data.m_theirFile.SetFileName(szArglist[3]);
                    }
                }
            }
            else if (nArgs == 2)
            {
                // only one path specified: use it to fill the "open" dialog
                if (PathFileExists(szArglist[1]))
                {
                    pFrame->m_Data.m_yourFile.SetFileName(szArglist[1]);
                    pFrame->m_Data.m_yourFile.StoreFileAttributes();
                }
            }
        }

        // Free memory allocated for CommandLineToArgvW arguments.
        LocalFree(szArglist);
    }

    pFrame->m_bReadOnly = !!parser.HasKey(L"readonly");
    if (GetFileAttributes(pFrame->m_Data.m_yourFile.GetFilename()) & FILE_ATTRIBUTE_READONLY)
        pFrame->m_bReadOnly = true;
    pFrame->m_bBlame = !!parser.HasKey(L"blame");
    // diffing a blame means no editing!
    if (pFrame->m_bBlame)
        pFrame->m_bReadOnly = true;

    pFrame->SetWindowTitle();

    if (parser.HasKey(L"createunifieddiff"))
    {
        // user requested to create a unified diff file
        CString origFile = parser.GetVal(L"origfile");
        CString modifiedFile = parser.GetVal(L"modifiedfile");
        if (!origFile.IsEmpty() && !modifiedFile.IsEmpty())
        {
            CString outfile = parser.GetVal(L"outfile");
            if (outfile.IsEmpty())
            {
                CCommonAppUtils::FileOpenSave(outfile, nullptr, IDS_SAVEASTITLE, IDS_COMMONFILEFILTER, false, nullptr);
            }
            if (!outfile.IsEmpty())
            {
                CRegStdDWORD regContextLines(L"Software\\TortoiseMerge\\ContextLines", 0);
                CAppUtils::CreateUnifiedDiff(origFile, modifiedFile, outfile, regContextLines, true, false);
                return FALSE;
            }
        }
    }

    pFrame->resolveMsgWnd    = parser.HasVal(L"resolvemsghwnd")   ? (HWND)parser.GetLongLongVal(L"resolvemsghwnd")     : 0;
    pFrame->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? (WPARAM)parser.GetLongLongVal(L"resolvemsgwparam") : 0;
    pFrame->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? (LPARAM)parser.GetLongLongVal(L"resolvemsglparam") : 0;

    // The one and only window has been initialized, so show and update it
    pFrame->ActivateFrame();
    pFrame->ShowWindow(SW_SHOW);
    pFrame->UpdateWindow();
    pFrame->ShowDiffBar(!pFrame->m_bOneWay);
    if (!pFrame->m_Data.IsBaseFileInUse() && pFrame->m_Data.m_sPatchPath.IsEmpty() && pFrame->m_Data.m_sDiffFile.IsEmpty())
    {
        pFrame->OnFileOpen(pFrame->m_Data.m_yourFile.InUse());
        return TRUE;
    }

    int line = -2;
    if (parser.HasVal(L"line"))
    {
        line = parser.GetLongVal(L"line");
        line--; // we need the index
    }

    return pFrame->LoadViews(line);
}
Пример #23
0
int CPatch::PatchFile(const int strip, int nIndex, const CString& sPatchPath, const CString& sSavePath, const CString& sBaseFile, const bool force)
{
    m_nStrip = strip;
    CString sPath = GetFullPath(sPatchPath, nIndex);
    if (PathIsDirectory(sPath))
    {
        m_sErrorMessage.Format(IDS_ERR_PATCH_INVALIDPATCHFILE, (LPCTSTR)sPath);
        return FALSE;
    }
    if (nIndex < 0)
    {
        m_sErrorMessage.Format(IDS_ERR_PATCH_FILENOTINPATCH, (LPCTSTR)sPath);
        return FALSE;
    }

    if (!force && sPath == _T("NUL") && PathFileExists(GetFullPath(sPatchPath, nIndex, 1)))
        return FALSE;

    if (GetFullPath(sPatchPath, nIndex, 1) == _T("NUL") && !PathFileExists(sPath))
        return 2;

    CString sLine;
    CString sPatchFile = sBaseFile.IsEmpty() ? sPath : sBaseFile;
    if (PathFileExists(sPatchFile))
    {
        CCrashReport::Instance().AddFile2(sPatchFile, nullptr, _T("File to patch"), CR_AF_MAKE_FILE_COPY);
    }
    CFileTextLines PatchLines;
    CFileTextLines PatchLinesResult;
    PatchLines.Load(sPatchFile);
    PatchLinesResult = PatchLines;  //.Copy(PatchLines);
    PatchLines.CopySettings(&PatchLinesResult);

    Chunks * chunks = m_arFileDiffs.GetAt(nIndex);

    for (int i = 0; i < chunks->chunks.GetCount(); ++i)
    {
        Chunk * chunk = chunks->chunks.GetAt(i);
        LONG lRemoveLine = chunk->lRemoveStart;
        LONG lAddLine = chunk->lAddStart;
        for (int j = 0; j < chunk->arLines.GetCount(); ++j)
        {
            CString sPatchLine = chunk->arLines.GetAt(j);
            EOL ending = chunk->arEOLs[j];
            if ((m_UnicodeType != CFileTextLines::UTF8)&&(m_UnicodeType != CFileTextLines::UTF8BOM))
            {
                if ((PatchLines.GetUnicodeType()==CFileTextLines::UTF8)||(m_UnicodeType == CFileTextLines::UTF8BOM))
                {
                    // convert the UTF-8 contents in CString sPatchLine into a CStringA
                    sPatchLine = CUnicodeUtils::GetUnicode(CStringA(sPatchLine));
                }
            }
            int nPatchState = (int)chunk->arLinesStates.GetAt(j);
            switch (nPatchState)
            {
            case PATCHSTATE_REMOVED:
            {
                if ((lAddLine > PatchLines.GetCount())||(PatchLines.GetCount()==0))
                {
                    m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, _T(""), (LPCTSTR)sPatchLine);
                    return FALSE;
                }
                if (lAddLine == 0)
                    lAddLine = 1;
                if ((sPatchLine.Compare(PatchLines.GetAt(lAddLine-1))!=0)&&(!HasExpandedKeyWords(sPatchLine)))
                {
                    m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)sPatchLine, (LPCTSTR)PatchLines.GetAt(lAddLine-1));
                    return FALSE;
                }
                if (lAddLine > PatchLines.GetCount())
                {
                    m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)sPatchLine, _T(""));
                    return FALSE;
                }
                PatchLines.RemoveAt(lAddLine-1);
            }
            break;
            case PATCHSTATE_ADDED:
            {
                if (lAddLine == 0)
                    lAddLine = 1;
                // check context after insertions in order to avoid double insertions
                bool insertOk = !(lAddLine < PatchLines.GetCount());
                int k = j;
                for (; k < chunk->arLines.GetCount(); ++k)
                {
                    if ((int)chunk->arLinesStates.GetAt(k) == PATCHSTATE_ADDED)
                        continue;
                    if (PatchLines.GetCount() >= lAddLine && chunk->arLines.GetAt(k).Compare(PatchLines.GetAt(lAddLine - 1)) == 0)
                        insertOk = true;
                    else
                        break;
                }

                if (insertOk)
                {
                    PatchLines.InsertAt(lAddLine-1, sPatchLine, ending);
                    ++lAddLine;
                }
                else
                {
                    if (k >= chunk->arLines.GetCount())
                        k = j;
                    m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)PatchLines.GetAt(lAddLine - 1), (LPCTSTR)chunk->arLines.GetAt(k));
                    return FALSE;
                }
            }
            break;
            case PATCHSTATE_CONTEXT:
            {
                if (lAddLine > PatchLines.GetCount())
                {
                    m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, _T(""), (LPCTSTR)sPatchLine);
                    return FALSE;
                }
                if (lAddLine == 0)
                    ++lAddLine;
                if (lRemoveLine == 0)
                    ++lRemoveLine;
                if ((sPatchLine.Compare(PatchLines.GetAt(lAddLine-1))!=0) &&
                        (!HasExpandedKeyWords(sPatchLine)) &&
                        (lRemoveLine <= PatchLines.GetCount()) &&
                        (sPatchLine.Compare(PatchLines.GetAt(lRemoveLine-1))!=0))
                {
                    if ((lAddLine < PatchLines.GetCount())&&(sPatchLine.Compare(PatchLines.GetAt(lAddLine))==0))
                        ++lAddLine;
                    else if (((lAddLine + 1) < PatchLines.GetCount())&&(sPatchLine.Compare(PatchLines.GetAt(lAddLine+1))==0))
                        lAddLine += 2;
                    else if ((lRemoveLine < PatchLines.GetCount())&&(sPatchLine.Compare(PatchLines.GetAt(lRemoveLine))==0))
                        ++lRemoveLine;
                    else
                    {
                        m_sErrorMessage.Format(IDS_ERR_PATCH_DOESNOTMATCH, (LPCTSTR)sPatchLine, (LPCTSTR)PatchLines.GetAt(lAddLine-1));
                        return FALSE;
                    }
                }
                ++lAddLine;
                ++lRemoveLine;
            }
            break;
            default:
                ASSERT(FALSE);
                break;
            } // switch (nPatchState)
        } // for (j=0; j<chunk->arLines.GetCount(); j++)
    } // for (int i=0; i<chunks->chunks.GetCount(); i++)
    if (!sSavePath.IsEmpty())
    {
        PatchLines.Save(sSavePath, false);
    }
    return TRUE;
}
bool UserProp::Parse( const CString& line )
{
    propType = UserPropTypeUnknown;

    int equalpos = line.Find('=');
    if (equalpos < 0)
    {
        propName = line;
        return true;
    }
    // format is
    // propertyname=propertytype;labeltext(...)
    propName = line.Left(equalpos);
    int colonpos = line.Find(';');
    if (colonpos < 0)
        return false;
    CString temp = line.Mid(equalpos+1, colonpos-equalpos-1);
    if (temp.Compare(L"bool")==0)
        propType = UserPropTypeBool;
    else if (temp.Compare(L"state")==0)
        propType = UserPropTypeState;
    else if (temp.Compare(L"singleline")==0)
        propType = UserPropTypeSingleLine;
    else if (temp.Compare(L"multiline")==0)
        propType = UserPropTypeMultiLine;
    else
        return false;
    int bracketpos = line.Find('(');
    if (bracketpos < 0)
    {
        // property has invalid format!
        propType = UserPropTypeUnknown;
        return false;
    }
    temp = line.Mid(colonpos+1, bracketpos-colonpos-1);
    labelText = temp;

    temp = line.Mid(bracketpos+1);
    if (temp.Right(1) != ")")
    {
        // property has invalid format!
        propType = UserPropTypeUnknown;
        return false;
    }
    temp = temp.Left(temp.GetLength()-1);
    switch(propType)
    {
    case UserPropTypeBool:
        {
            // format is
            // propertyname=bool;labeltext(YESVALUE;NOVALUE;Checkboxtext)
            int cpos = temp.Find(';');
            if (cpos>=0)
            {
                boolYes = temp.Left(cpos);
                int cpos2 = temp.Find(';', cpos+1);
                if (cpos2)
                {
                    boolNo = temp.Mid(cpos+1, cpos2-cpos-1);
                    boolCheckText = temp.Mid(cpos2+1);
                }
            }
            if (boolCheckText.IsEmpty())
            {
                // property has invalid format!
                propType = UserPropTypeUnknown;
                return false;
            }
            return true;
        }
        break;
    case UserPropTypeState:
        {
            // format is
            // propertyname=state;labeltext(DEFVAL;VAL1;TEXT1;VAL2;TEXT2;VAL3;TEXT3;...)
            int cpos = temp.Find(';');
            if (cpos>=0)
            {
                stateDefaultVal = temp.Left(cpos);
                temp = temp.Mid(cpos+1);
                int curPos = 0;
                CString resToken = temp.Tokenize(L";",curPos);
                while (!resToken.IsEmpty())
                {
                    CString sVal, sText;
                    sVal = resToken;
                    resToken = temp.Tokenize(L";",curPos);
                    sText = resToken;
                    if (curPos < 0)
                    {
                        // property has invalid format!
                        propType = UserPropTypeUnknown;
                        return false;
                    }
                    resToken = temp.Tokenize(L";",curPos);
                    if (!sText.IsEmpty() && !sVal.IsEmpty())
                        stateEntries.emplace_back(sVal, sText);
                    else
                    {
                        // property has invalid format!
                        propType = UserPropTypeUnknown;
                        return false;
                    }
                }
                return true;
            }
            propType = UserPropTypeUnknown;
            return false;
        }
        break;
    case UserPropTypeSingleLine:
        {
            // format is
            // propertyname=singleline;labeltext(regex)
            try
            {
                std::wregex regCheck = std::wregex (temp);
                validationRegex = temp;
            }
            catch (std::exception)
            {
            }
        }
        break;
    case UserPropTypeMultiLine:
        {
            // format is
            // propertyname=multiline;labeltext(regex)
            try
            {
                std::wregex regCheck = std::wregex (temp);
                validationRegex = temp;
            }
            catch (std::exception)
            {
            }
        }
        break;
    }
    return true;
}
Пример #25
0
void CClientDlg::OnBtnLogin() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);

	CString strIp = "";
	CString strUser = "";
	CString strPwd = "";
	int nPort = 0;
	int nError = 0;
	NET_DEVICEINFO deviceInfo = {0};

	GetDlgItemText(IDC_IPADDRESS_IP, strIp);
	GetDlgItemText(IDC_EDIT_USER, strUser);
	GetDlgItemText(IDC_EDIT_PWD, strPwd);
	nPort = GetDlgItemInt(IDC_EDIT_PORT);

	LONG lLoginHandle = CLIENT_Login((LPSTR)(LPCSTR)strIp, nPort, (LPSTR)(LPCSTR)strUser, (LPSTR)(LPCSTR)strPwd, &deviceInfo, &nError);
	if (lLoginHandle != 0)
	{
		m_lLoginHandle = lLoginHandle;

		GetDlgItem(IDC_BTN_LOGIN)->EnableWindow(FALSE);
		GetDlgItem(IDC_BTN_LOGOUT)->EnableWindow(TRUE);
		GetDlgItem(IDC_BTN_STARTTALK)->EnableWindow(TRUE);

		m_ctlEncodeType.ResetContent();
		//Search the audio talk encode formats then device supported 
		int retlen = 0;
		BOOL bSuccess = CLIENT_QueryDevState(m_lLoginHandle, DH_DEVSTATE_TALK_ECTYPE, (char*)&m_lstTalkEncode, sizeof(DHDEV_TALKFORMAT_LIST), &retlen, DEMO_SDK_WAITTIME);
		if (bSuccess && retlen == sizeof(DHDEV_TALKFORMAT_LIST))
		{
			int nIndex = 0;
			CString str;
			for (int i = 0; i < m_lstTalkEncode.nSupportNum; i++)
			{
				switch(m_lstTalkEncode.type[i].encodeType)
				{
				case DH_TALK_DEFAULT:
				case DH_TALK_PCM:
					str = ConvertString("PCM");
					break;
				case DH_TALK_G711a:
					str = ConvertString("G711a");
					break;
				case DH_TALK_AMR:
					str = ConvertString("AMR");
					break;
				case DH_TALK_G711u:
					str = ConvertString("G711u");
					break;
				case DH_TALK_G726:
					str = ConvertString("G726");
					break;
				case DH_TALK_AAC:
					str = ConvertString("AAC");
					break;
				case  DH_TALK_MP3:
					str = ConvertString("MP3");
					break;
				default:
					str = ConvertString("Unknow");
					break;
				}
                if (0 != str.Compare("Unknow"))
                {
                    CString s;
                    s.Format("_%d%s_%d%s", m_lstTalkEncode.type[i].nAudioBit, ConvertString("Bit"), m_lstTalkEncode.type[i].dwSampleRate, ConvertString("SampleRate"));
                    str += s;
                }
				nIndex = m_ctlEncodeType.AddString(str);
				m_ctlEncodeType.SetItemData(nIndex, i);
			}
			
			if (m_ctlEncodeType.GetCount() > 0)
			{
				m_ctlEncodeType.SetCurSel(0);
			}
		}

		DWORD dwRetBytes = 0;
		DHDEV_SYSTEM_ATTR_CFG stuAttr = { sizeof(DHDEV_SYSTEM_ATTR_CFG) };
		if (!CLIENT_GetDevConfig(lLoginHandle, DH_DEV_DEVICECFG, -1, &stuAttr, stuAttr.dwSize, &dwRetBytes, DEMO_SDK_WAITTIME))
		{
			MessageBox(ConvertString("Get device info failed!"), ConvertString("Prompt"));
		}
        m_ctlSpeakerChl.EnableWindow(bSuccess);
        GetDlgItem(IDC_CHECK_SPEAK)->EnableWindow(bSuccess);

		for(int i=0; i<stuAttr.byTalkOutChanNum; i++)
		{
			char szTmp[MAX_PATH] = {0};
			sprintf(szTmp,"speaker_%d", i);
			int nIndex = m_ctlSpeakerChl.AddString(szTmp);
			m_ctlSpeakerChl.SetItemData(nIndex, i);
			m_ctlSpeakerChl.SetCurSel(0);
		}
	}
	else
	{
		m_lLoginHandle = 0;
		ShowLoginErrorReason(nError);
	}
}
Пример #26
0
void CFormat::ReplaceKeySymbol(CSymbolReplaceSetDlg* pSymbolReplaceSetDlg, CRichEditView *pRichEditView)
{
	long startPos=0,endPos=0;
	CRichEditCtrl* pRichEditCtrl=&pRichEditView->GetRichEditCtrl();

	//判断是否为全文替换,确定终止位置
	if(pSymbolReplaceSetDlg->m_nSelect==1){
		long lineCount=pRichEditCtrl->GetLineCount();
		CString strLine;
		for(long i=0;i<lineCount;i++){
			pRichEditCtrl->GetLine(i,strLine.GetBuffer());
			if(strLine.Find(_T("**注释**"))!=-1){
				endPos=pRichEditCtrl->LineIndex(i);
			}
		}
	}
	else{
		endPos=pRichEditCtrl->GetTextLength();
	}

	//开始替换
	CString strCh;
	while(startPos<endPos-1){
		pRichEditCtrl->GetTextRange(startPos,startPos+1,strCh);

		//////////单个字符比较//////////////
		//逗号
		if(pSymbolReplaceSetDlg->m_Symbol1){
			if(strCh.Compare(_T(","))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString1.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString1);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T(","));
				}
			}
		}
		//句号
		if(pSymbolReplaceSetDlg->m_Symbol2){
			if(strCh.Compare(_T("."))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString2.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString2);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T("。"));
				}
			}
		}
		//分号
		if(pSymbolReplaceSetDlg->m_Symbol3){
			if(strCh.Compare(_T(";"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString3.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString3);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T(";"));
				}
			}
		}
		//冒号
		if(pSymbolReplaceSetDlg->m_Symbol4){
			if(strCh.Compare(_T(":"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString4.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString4);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T(":"));
				}
			}
		}
		//波浪号
		if(pSymbolReplaceSetDlg->m_Symbol5){
			if(strCh.Compare(_T("~"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString5.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString5);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T("~"));
				}
			}
		}
		//括号
		if(pSymbolReplaceSetDlg->m_Symbol7){
			if(strCh.Compare(_T("("))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				pRichEditCtrl->ReplaceSel(_T("("));
			}
			else if(strCh.Compare(_T(")"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				pRichEditCtrl->ReplaceSel(_T(")"));
			}
		}
		//单破折号
		if(pSymbolReplaceSetDlg->m_Symbol8){
			if(strCh.Compare(_T("-"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString8.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString8);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T("—"));
				}
			}
		}

		/////////////双字符比较///////////////
		pRichEditCtrl->GetTextRange(startPos,startPos+2,strCh);
		//破折号
		if(pSymbolReplaceSetDlg->m_Symbol6){
			if(strCh.Compare(_T("--"))==0){
				pRichEditCtrl->SetSel(startPos,startPos+1);
				if(!pSymbolReplaceSetDlg->m_editString6.IsEmpty()){
					pRichEditCtrl->ReplaceSel(
						pSymbolReplaceSetDlg->m_editString6);
				}
				else{
					pRichEditCtrl->ReplaceSel(_T("—"));
				}
			}
		}
		//双破折号替换
		if(pSymbolReplaceSetDlg->m_IsDoubleDash)
		{
			if(strCh.Compare(_T("——"))==0){
				CString replaceStr;
				pSymbolReplaceSetDlg->
					m_doubleDashEdit.GetWindowTextW(replaceStr);
				pRichEditCtrl->SetSel(startPos,startPos+2);
				pRichEditCtrl->ReplaceSel(replaceStr);
			}
		}

		startPos++;
	}
}
Пример #27
0
BOOL CTaskXml::Update( CTaskData* pData )
{
	if ( pData == NULL ) return FALSE;
	if ( m_pDoc == NULL
		|| m_pTasksNode == NULL 
		|| m_pDownLoadTasksNode == NULL
		|| m_pUpLoadTasksNode == NULL
		|| m_pCopyTasksNode == NULL)
	{
		return FALSE;
	}

	xml_node<>* pTaskNode = NULL;
	xml_node<>* pTaskNodeParent = NULL;
	CString strAttVal;
	if ( pData->m_sOperatorFlag.CompareNoCase("download") == 0 )
	{
		pTaskNodeParent = m_pDownLoadTasksNode;
	}
	else if ( pData->m_sOperatorFlag.CompareNoCase("upload") == 0 )
	{
		pTaskNodeParent = m_pUpLoadTasksNode;
	}
	else if ( pData->m_sOperatorFlag.CompareNoCase("copy") == 0 )
	{
		pTaskNodeParent = m_pCopyTasksNode;
	}

	if (pTaskNodeParent)
	{
		pTaskNode   = pTaskNodeParent->first_node("task");
		while(pTaskNode)
		{
			rapidxml::xml_attribute<char> * attr = pTaskNode->first_attribute("idPath");
			if (attr!=NULL)
			{
				strAttVal = UTF8_TO_MB(attr->value());
				if (strAttVal.Compare(pData->m_sIdPath)==0)
					break;
			}
			pTaskNode = pTaskNode->next_sibling();
		}
	}

	if (pTaskNode!=NULL)
	{
		pTaskNodeParent->remove_node(pTaskNode); // rapidxml 更新节点时先删除已经有的该节点,重新添加
		pTaskNode = NULL;
	}
	else
		return FALSE;

	pTaskNode = m_pDoc->allocate_node(node_element,"task"); 
	if ( !UpdateNode( pTaskNode, pData ) )
	{
		return FALSE;
	}

	pTaskNodeParent->insert_node(pTaskNodeParent->first_node("task"),pTaskNode);
	return TRUE;
}
CString MusicGroupBeautify( CString csName, CString csArtist, int nArtistLock, CString csType, CString csSuffix )
{
	CString csResult;
	CString csWord;
	CString csYear;
	int nLen = csName.GetLength();
	int nCount;
	int nNum;
	int nFlag;
	TCHAR *ptOrigin = new TCHAR[nLen+1];

	lstrcpy( ptOrigin, csName.GetBuffer(nLen) );
	csResult.Format( _T("") );
	
	//\u5982\u679C\u672A\u6307\u5B9A\u827A\u672F\u5BB6
	if( csArtist.Compare( _T("") ) == 0 || nArtistLock == 0 )
	{
		nCount = PunctuationGetDashPosition( ptOrigin );
		if( nCount != 0 )
		{
			*( ptOrigin + nCount ) = 0;
			csArtist.Format( _T("%s"), ptOrigin );
			ptOrigin += nCount + 1;
		}
	}

	//\u8BFB\u53D6\u540E\u9762\u5355\u8BCD
	csWord = PunctuationWordGetNext( ptOrigin, &nNum, &nFlag );
	nCount = 0;
	csResult.Format( _T("") );

	while( csWord.Compare( _T("") ) != 0 )
	{
		//\u5904\u7406\u5355\u8BCD
		if( nFlag == 2 || nFlag == -2 )
		{
			//\u5982\u679C\u662F\u5E74\u4EE3
			if( nCount > 0 && WordCheckYear( ptOrigin + nCount - 1 ) == 1 )
			{
				csYear = csWord;
			}
			//\u5982\u679C\u662F\u5531\u7247\u7C7B\u578B
			else if( WordCheckType( csWord ) == 1 )
			{
				csType = csWord;
			}
			//\u5982\u679C\u662F\u6B4C\u66F2\u683C\u5F0F
			else if( WordCheckMusic( csWord ) == 1 )
			{
				csSuffix = WordCap( csWord );
			}
			//\u5176\u4ED6
			else
			{
				csResult.AppendFormat( csWord );
			}
		}
		//\u5904\u7406\u7B26\u53F7
		else if( nFlag == 1 )
			csResult.AppendFormat( csWord );
		//\u5904\u7406\u672B\u5C3E\u7B26\u53F7
		else
		{
			csResult.AppendFormat( csWord );
			break;
		}
		nCount += nNum;
		csWord = PunctuationWordGetNext( ptOrigin + nCount, &nNum, &nFlag );
	}

	//\u5904\u7406\u62EC\u53F7
	csResult = PunctuationDeleteBlankBracket( csResult );
	csResult = PunctuationDeleteHead( csResult );
	csWord = PunctuationDeleteSingleBracket( csResult );

	//\u6574\u4F53\u7ED3\u6784
	csResult.Format( _T("") );
	if( csArtist.Compare( _T("") ) != 0 )
		csResult.AppendFormat( _T("%s-"), csArtist );
	csResult.AppendFormat( _T("[%s"), csWord );
	if( csYear.Compare( _T("") ) != 0 )
		csResult.AppendFormat( _T("(%s)]"), csYear );
	else
		csResult.AppendFormat( _T("]"), csYear );
	if( csType.Compare( _T("") ) != 0 )
		csResult.AppendFormat( _T("%s"), csType );
	else
		csResult.AppendFormat( _T("\u4E13\u8F91"));
	csResult.AppendFormat( _T("(%s)"), csSuffix );

	csName.ReleaseBuffer();

	return csResult;
}