void CPnSPresetsDlg::StringToParams(CString str, CString& label, double& PosX, double& PosY, double& ZoomX, double& ZoomY)
{
	int i = 0, j = 0;

	for (CString token = str.Tokenize(_T(","), i); !token.IsEmpty(); token = str.Tokenize(_T(","), i), j++) {
		if (j == 0) {
			label = token;
		} else {
			float f = 0;

			if (_stscanf_s(token, _T("%f"), &f) != 1) {
				continue;
			}

			switch (j) {
				case 1:
					PosX = f;
					break;
				case 2:
					PosY = f;
					break;
				case 3:
					ZoomX = f;
					break;
				case 4:
					ZoomY = f;
					break;
				default:
					break;
			}
		}
	}
}
Example #2
0
BOOL CSubtitleDlDlg::OnInitDialog()
{
    __super::OnInitDialog();

    m_status.Create(WS_CHILD | WS_VISIBLE | CCS_BOTTOM, CRect(0, 0, 0, 0), this, IDC_STATUSBAR);

    int n, curPos = 0;
    CArray<int> columnWidth;

    CString strColumnWidth = AfxGetApp()->GetProfileString(IDS_R_DLG_SUBTITLEDL, IDS_RS_DLG_SUBTITLEDL_COLWIDTH, _T(""));
    CString token = strColumnWidth.Tokenize(_T(","), curPos);
    while (!token.IsEmpty()) {
        if (_stscanf_s(token, L"%i", &n) == 1) {
            columnWidth.Add(n);
            token = strColumnWidth.Tokenize(_T(","), curPos);
        } else {
            throw 1;
        }
    }

    m_list.SetExtendedStyle(m_list.GetExtendedStyle()
                            | LVS_EX_DOUBLEBUFFER | LVS_EX_FULLROWSELECT
                            | LVS_EX_CHECKBOXES   | LVS_EX_LABELTIP);

    if (columnWidth.GetCount() != 5) {
        // default sizes
        columnWidth.RemoveAll();
        columnWidth.Add(290);
        columnWidth.Add(70);
        columnWidth.Add(50);
        columnWidth.Add(50);
        columnWidth.Add(270);
    }

    m_list.InsertColumn(COL_FILENAME, ResStr(IDS_SUBDL_DLG_FILENAME_COL), LVCFMT_LEFT, columnWidth[0]);
    m_list.InsertColumn(COL_LANGUAGE, ResStr(IDS_SUBDL_DLG_LANGUAGE_COL), LVCFMT_CENTER, columnWidth[1]);
    m_list.InsertColumn(COL_FORMAT, ResStr(IDS_SUBDL_DLG_FORMAT_COL), LVCFMT_CENTER, columnWidth[2]);
    m_list.InsertColumn(COL_DISC, ResStr(IDS_SUBDL_DLG_DISC_COL), LVCFMT_CENTER, columnWidth[3]);
    m_list.InsertColumn(COL_TITLES, ResStr(IDS_SUBDL_DLG_TITLES_COL), LVCFMT_LEFT, columnWidth[4]);

    AddAnchor(IDC_LIST1, TOP_LEFT, BOTTOM_RIGHT);
    AddAnchor(IDC_CHECK1, BOTTOM_LEFT);
    AddAnchor(IDOK, BOTTOM_RIGHT);
    AddAnchor(IDC_STATUSBAR, BOTTOM_LEFT, BOTTOM_RIGHT);

    const CSize s(420, 200);
    SetMinTrackSize(s);
    EnableSaveRestore(IDS_R_DLG_SUBTITLEDL);

    // start new worker thread to download the list of subtitles
    m_pTA = DEBUG_NEW THREADSTRUCT;
    m_pTA->url = m_url;
    m_pTA->hWND = GetSafeHwnd();

    SetStatus(ResStr(IDS_SUBDL_DLG_DOWNLOADING));
    AfxBeginThread(RunThread, static_cast<LPVOID>(m_pTA));

    return TRUE;
}
Example #3
0
static void SplitCString( const CString& content, const CString& token, AcStringArray& cc )
{
    int curPos = 0;
    CString str = content.Tokenize( token, curPos );
    while ( str != _T( "" ) )
    {
        cc.append( str );
        str = content.Tokenize( token, curPos );
    };
}
Example #4
0
inline COLORREF StringToCOLORREF( const string str )
{
	int r = 0, g = 0, b = 0;
	CString CStr = str.c_str();
	int pos = 0;
	CString resToken;
	r = atoi( CStr.Tokenize( ",", pos ) );
	g = atoi( CStr.Tokenize( ",", pos ) );
	b = atoi( CStr.Tokenize( ",", pos ) );

	COLORREF ret = RGB( r, g, b );
	return ret;
}
Example #5
0
int CTGitPathList::ParserFromLsFile(BYTE_VECTOR &out,bool /*staged*/)
{
	int pos=0;
	CString one;
	CTGitPath path;
	CString part;
	this->Clear();

	while (pos >= 0 && pos < (int)out.size())
	{
		one.Empty();
		path.Reset();

		CGit::StringAppend(&one, &out[pos], CP_UTF8);
		int tabstart=0;
		// m_Action is never used and propably never worked (needs to be set after path.SetFromGit)
		// also dropped LOGACTIONS_CACHE for 'H'
		// path.m_Action=path.ParserAction(out[pos]);
		one.Tokenize(_T("\t"),tabstart);

		if(tabstart>=0)
			path.SetFromGit(one.Right(one.GetLength()-tabstart));
		else
			return -1;

		tabstart=0;

		part=one.Tokenize(_T(" "),tabstart); //Tag
		if (tabstart < 0)
			return -1;

		part=one.Tokenize(_T(" "),tabstart); //Mode
		if (tabstart < 0)
			return -1;

		part=one.Tokenize(_T(" "),tabstart); //Hash
		if (tabstart < 0)
			return -1;

		part=one.Tokenize(_T("\t"),tabstart); //Stage
		if (tabstart < 0)
			return -1;

		path.m_Stage=_ttol(part);

		this->AddPath(path);

		pos=out.findNextString(pos);
	}
	return 0;
}
void ColumnManager::ParseUserPropSettings(const CString& userPropList, const CString& shownUserProps)
{
	assert (userProps.empty());

	static CString delimiters (_T(" "));

	// parse list of visible user-props

	std::set<CString> visibles;

	int pos = 0;
	CString name = shownUserProps.Tokenize (delimiters, pos);
	while (!name.IsEmpty())
	{
		visibles.insert (name);
		name = shownUserProps.Tokenize (delimiters, pos);
	}

	// create list of all user-props

	pos = 0;
	name = userPropList.Tokenize (delimiters, pos);
	while (!name.IsEmpty())
	{
		bool visible = visibles.find (name) != visibles.end();

		UserProp newEntry;
		newEntry.name = name;
		newEntry.width = 0;

		userProps.push_back (newEntry);

		// auto-create columns for visible user-props
		// (others may be added later)

		if (visible)
		{
			ColumnInfo newColumn;
			newColumn.width = 0;
			newColumn.visible = true;
			newColumn.relevant = true;
			newColumn.index = static_cast<int>(userProps.size())
							+ GITSLC_USERPROPCOLOFFSET - 1;

			columns.push_back (newColumn);
		}

		name = userPropList.Tokenize (delimiters, pos);
	}
}
Example #7
0
/*************************************************
Function:   SplitCString
Desc:
Input:
Return:		SUCCESS 成功
            FAIL 失败
**************************************************/
vector<CString> CDialogSetting::SplitCString(CString strSource, CString ch)
{
    vector<CString> vecString;
    int iPos = 0;
    CString strTmp;
    strSource.ReleaseBuffer();
    strTmp = strSource.Tokenize(ch,iPos);
    while(strTmp.Trim() != _T(""))
    {
        vecString.push_back(strTmp);
        strTmp = strSource.Tokenize(ch,iPos);
    }
    return vecString;
}
bool parseHTTPResponse(const CString& response, CString& result)
{
	int pos = 0;

	CString status = response.Tokenize(_T("\r\n"), pos);

	result = response;
	result.Delete(0, pos);

	pos = 0;
	status.Tokenize(_T(" "), pos);
	status = status.Tokenize(_T(" "), pos);
	if (status.IsEmpty() || status[0]!='2') return false;
	return true;
}
Example #9
0
inline CIntArray StringToCIntArray( const string &str )
{
	CIntArray ret;
	CString cstr = str.c_str();
	int pos = 0;

	CString resToken;
	resToken = cstr.Tokenize( ",", pos);
	while ( resToken != "" )
	{
		ret.push_back( atoi( resToken.GetBuffer() ) );
		resToken = cstr.Tokenize( ",", pos );
	};

	return ret;
}
Example #10
0
//截取Key
void CINIsoc::CutString(char* fid, int len, ATF_MAP& f_map)
{
	char *pline_head = fid;
	int readtotal = 0;
	for(int i=0;i<len;i++)
	{
		if(fid[i] == 0x0)
		{
			CString str ;
			str.Format("%s",pline_head);
			//读取key对应的数据
			str.Trim();
			if( !str.IsEmpty() )
			{
				CString sKey,sVal;
				int curpos = 0;
				sKey = str.Tokenize("=",curpos);
				sVal = str.Right(str.GetLength()-curpos);
				sKey.MakeUpper(); //统一大写 2011.10.17
				sVal.Trim();
				f_map.insert( ATF_PAIRMAP( sKey, sVal ) );
			}
			if(fid[i+1] == 0x0)
				break;//字段结束;
			pline_head = fid+i+1;
		}
	}
}
Example #11
0
void CSelectUnitsDlg::OnCbnSelchangeComboBook()
{
	m_nSelectedBookID = m_cboBook.GetItemData(m_cboBook.GetCurSel());
	CString str;
	str.Format(_T("BOOKID=%d"), m_nSelectedBookID);
	m_rsBook.FindFirst(str);

	m_cboPartFrom.ResetContent();
	m_cboPartTo.ResetContent();
	CString strParts = m_rsBook.GetFieldValueAsString(_T("PARTS"));
	for(int curPos = 0;;){
		CString str = strParts.Tokenize(_T(" "), curPos);
		if(str.IsEmpty()) break;
		m_cboPartFrom.AddString(str);
		m_cboPartTo.AddString(str);
	}

	int nNumUnits = m_rsBook.GetFieldValueAsInt(_T("UNITSINBOOK"));
	str.Format(_T("(%d in all)"), nNumUnits);
	m_stcUnitInAllFrom.SetWindowText(str);
	m_stcUnitInAllTo.SetWindowText(str);
	m_spnUnitFrom.SetRange32(1, nNumUnits);
	m_spnUnitTo.SetRange32(1, nNumUnits);
	int nUnitFrom = m_rsBook.GetFieldValueAsInt(_T("UNITFROM"));
	int nPartFrom = m_rsBook.GetFieldValueAsInt(_T("PARTFROM"));
	int nUnitTo = m_rsBook.GetFieldValueAsInt(_T("UNITTO"));
	int nPartTo = m_rsBook.GetFieldValueAsInt(_T("PARTTO"));
	m_spnUnitFrom.SetPos32(nUnitFrom);
	m_cboPartFrom.SetCurSel(nPartFrom - 1);
	m_spnUnitTo.SetPos32(nUnitTo);
	m_cboPartTo.SetCurSel(nPartTo - 1);
	m_chkTo.SetCheck(nUnitFrom == nUnitTo && nPartFrom == nPartTo ? BST_UNCHECKED : BST_CHECKED);
	OnBnClickedCheckTo();
}
Example #12
0
void CChildView::OnFileSave()
{
	CString strFilter;
	CSimpleArray<GUID> aguidFileTypes;
	CImage *pImage;
	CString fmt;
	HRESULT hResult;
	INT_PTR nResult;

	pImage = m_pSurface->GetImage();
	ASSERT(pImage != NULL);
	hResult = pImage->GetExporterFilterString( strFilter, aguidFileTypes );
	if(FAILED(hResult)) {
		fmt.Format(IDS_ERROR_GETEXPORTERFILTER, hResult, _com_error(hResult).ErrorMessage());
		::AfxMessageBox(fmt);
		return;
	}

	CFileDialog dlg(FALSE, NULL, NULL, 
		OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, strFilter);
	dlg.m_ofn.nFilterIndex = m_nFilterSave;

	nResult = dlg.DoModal();
	if( nResult != IDOK ) {
		return;
	}
	m_nFilterSave = dlg.m_ofn.nFilterIndex;
	GUID guid = m_nFilterSave > 0 ? aguidFileTypes[m_nFilterSave-1] : GUID(GUID_NULL);
	CString strFileName = dlg.GetPathName();
	if (dlg.GetFileExt().IsEmpty()) {
		if (strFileName[strFileName.GetLength()-1] == '.') {
			strFileName = strFileName.Left(strFileName.GetLength()-1);
		}
		CString strExt;
		if (m_nFilterSave == 0) {
			strExt = _T(".jpg"); // default to JPEG
		}
		else {
			// Look up the first extension in the filters
			int nCount = (m_nFilterSave*2)-1;
			int nLeft = 0;
			while (nCount) {
				if (strFilter[nLeft++] == '|') {
					nCount--;
				}
			}
			ASSERT(nLeft < strFilter.GetLength());
			strExt = strFilter.Tokenize(_T(";|"), nLeft).MakeLower();
			strExt = ::PathFindExtension(strExt);
		}
		strFileName += strExt;
	}

	hResult = pImage->Save(strFileName, guid);
	if(FAILED(hResult)) {
		fmt.Format(IDS_ERROR_SAVE, hResult, _com_error(hResult).ErrorMessage());
		::AfxMessageBox(fmt);
	}
}
Example #13
0
inline CMusikCrossfader StringToCrossfader( const string& str )
{
	CMusikCrossfader ret;
	CString CStr = str.c_str();

	int pos = 0;

	double new_song		= atof( CStr.Tokenize( ",", pos ) );
	double pause_resume	= atof( CStr.Tokenize( ",", pos ) );
	double seek			= atof( CStr.Tokenize( ",", pos ) );
	double stop			= atof( CStr.Tokenize( ",", pos ) );
	double exit			= atof( CStr.Tokenize( ",", pos ) );

	ret.Set( (float)new_song, (float)pause_resume, (float)seek, (float)stop, (float)exit );

	return ret;
}
CString CPathUtils::ParsePathInString(const CString& Str)
{
	CString sToken;
	int curPos = 0;
	sToken = Str.Tokenize(_T("'\t\r\n"), curPos);
	while (!sToken.IsEmpty())
	{
		if ((sToken.Find('/')>=0)||(sToken.Find('\\')>=0))
		{
			sToken.Trim(_T("'\""));
			return sToken;
		}
		sToken = Str.Tokenize(_T("'\t\r\n"), curPos);
	}
	sToken.Empty();
	return sToken;
}
Example #15
0
CString CGitRefCompareList::GetCommitMessage(git_commit *commit)
{
	int encode = CP_UTF8;
	const char *encodingString = git_commit_message_encoding(commit);
	if (encodingString != nullptr)
		encode = CUnicodeUtils::GetCPCode(CUnicodeUtils::GetUnicode(encodingString));

	CString message = CUnicodeUtils::GetUnicode(git_commit_message(commit), encode);
	int start = 0;
	message = message.Tokenize(_T("\n"), start);
	return message;
}
Example #16
0
BOOL KGInIFileEditDlg::OnInitDialog()
{
    int nResult  = false;
    int nRetCode = false;

    DWORD dwStyle;

    nRetCode = CDialog::OnInitDialog();
    KG_PROCESS_ERROR(nRetCode);

    m_imageList.Create(15, 15, ILC_COLOR24, 2, 2);
    m_imageList.Add(AfxGetApp()->LoadIcon(IDC_GLEAN));

    m_list.InsertColumn(0, "属性名");
    m_list.InsertColumn(1, "属性值");
    m_list.SetColumnWidth(0, 150);
    m_list.SetColumnWidth(1, 700);
    m_list.SetBkColor(RGB(92, 92, 92));

    m_list.SetupToolTip(200, RGB(68, 68, 68), RGB(255, 255, 255));
    m_list.SetHoverTime(100);

    m_tree.SetImageList(&m_imageList, TVSIL_NORMAL);
    m_tree.SetBkColor(RGB( 92,  92, 92));
    m_tree.SetTextColor(RGB(255, 255, 255));
    m_tree.SetLineColor(RGB(255, 255, 255));

    dwStyle = GetWindowLong(m_tree.m_hWnd, GWL_STYLE);
    dwStyle |= TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT;
    SetWindowLong(m_tree.m_hWnd, GWL_STYLE, dwStyle);

    m_list.BandDate(m_vecStrIniProperty, m_strIniDateType);
    //m_list.UpdateProperty(0);

    for (int i = 0; i < (int)m_list.m_vecIniProperty.size(); i ++)
    {
        CString strTitle = m_list.m_vecIniProperty[i]->strPath;
        CString strName  = PathFindFileName(strTitle.GetBuffer());
        CString strPlate;
        HTREEITEM hItem = NULL;
        int nPos = 0;
        strPlate = strName.Tokenize(_T("."), nPos);
        hItem = m_tree.InsertItem(strPlate);
        if (hItem)
            m_tree.SetItemData(hItem, static_cast<DWORD_PTR>(i));
    }

    m_tree.SelectItem(m_tree.GetRootItem());

    nResult = true;
Exit0:
    return nResult;
}
Example #17
0
BOOL CPPgSecurity::OnApply()
{
	TCHAR buffer[510];
	if(GetDlgItem(IDC_FILTERLEVEL)->GetWindowTextLength())
	{
		GetDlgItem(IDC_FILTERLEVEL)->GetWindowText(buffer,4);
		thePrefs.filterlevel=_tstoi(buffer);
	}

	thePrefs.filterserverbyip = (uint8)IsDlgButtonChecked(IDC_FILTERSERVERBYIPFILTER);
	thePrefs.msgonlyfriends = (uint8)IsDlgButtonChecked(IDC_MSGONLYFRIENDS);
	thePrefs.msgsecure = (uint8)IsDlgButtonChecked(IDC_MSGONLYSEC);
	thePrefs.m_bAdvancedSpamfilter = IsDlgButtonChecked(IDC_ADVSPAMFILTER);
	thePrefs.m_bUseSecureIdent = IsDlgButtonChecked(IDC_USESECIDENT);
	thePrefs.m_bRunAsUser = (uint8)IsDlgButtonChecked(IDC_RUNASUSER);

	GetDlgItem(IDC_FILTER)->GetWindowText(thePrefs.messageFilter,ARRSIZE(thePrefs.messageFilter));

	CString strCommentFilters;
	GetDlgItem(IDC_COMMENTFILTER)->GetWindowText(strCommentFilters);
	strCommentFilters.MakeLower();
	CString strNewCommentFilters;
	int curPos = 0;
	CString strFilter(strCommentFilters.Tokenize(_T("|"), curPos));
	while (!strFilter.IsEmpty())
	{
		strFilter.Trim();
		if (!strNewCommentFilters.IsEmpty())
			strNewCommentFilters += _T('|');
		strNewCommentFilters += strFilter;
		strFilter = strCommentFilters.Tokenize(_T("|"), curPos);
	}
	thePrefs.commentFilter = strNewCommentFilters;
	if (thePrefs.commentFilter != strCommentFilters)
		SetDlgItemText(IDC_COMMENTFILTER, thePrefs.commentFilter);

	LoadSettings();
	SetModified(FALSE);
	return CPropertyPage::OnApply();
}
Example #18
0
void CWordFilterDlg::OnOK()
{
    thePrefs.m_strWordFilterPass = m_strPassword;
    thePrefs.m_bWordFilterLocked = m_bFilterLocked;

    CString strWords;
    GetDlgItemText(IDC_MOD_WORDS, strWords);
    strWords.MakeLower();

    thePrefs.m_strAdultWordsArray.RemoveAll();

    int curPos = 0;
    CString resToken = strWords.Tokenize(_T("\r\n"),curPos);
    while (resToken != _T(""))
    {
        thePrefs.m_strAdultWordsArray.Add(resToken);
        resToken = strWords.Tokenize(_T("\r\n"), curPos);
    }

    thePrefs.m_strAdultWordsArray.Sort();

    CDialog::OnOK();
}
Example #19
0
void CTGitPathList::LoadFromAsteriskSeparatedString(const CString& sPathString)
{
	int pos = 0;
	CString temp;
	for(;;)
	{
		temp = sPathString.Tokenize(_T("*"),pos);
		if(temp.IsEmpty())
		{
			break;
		}
		AddPath(CTGitPath(CPathUtils::GetLongPathname(temp)));
	}
}
static CString NGetAddressFromUrl(const CString& str, CString& post, CString& host, int& port)
{
	CString s = str;

	post = _T("");
	host = post;
	port = 0;
	int pos = s.Find(_T("://"));
	if (!pos) return CString();
	s.Delete(0, pos + 3);

	pos = s.Find('/');
	if (!pos) {
		host = s;
		s = _T("");
	} else {
		host = s.Mid(0, pos);
		s.Delete(0, pos);
	}

	if (s.IsEmpty()) {
		post = _T("");
	} else {
		post = s;
	}

	pos = 0;
	CString addr = host.Tokenize(_T(":"), pos);
	s = host.Tokenize(_T(":"), pos);
	if (s.IsEmpty()) {
		port = 80;
	} else {
		port = _tstoi(s);
	}

	return addr;
}
Example #21
0
void CServerWnd::PasteServerFromClipboard()
{
	CString strServer = theApp.CopyTextFromClipboard();
	strServer.Trim();
	if (strServer.IsEmpty())
		return;

	int nPos = 0;
	CString strTok = strServer.Tokenize(_T(" \t\r\n"), nPos);
	while (!strTok.IsEmpty())
	{
		CString strAddress;
		uint16 nPort = 0;
		CED2KLink* pLink = NULL;
		try{
			pLink = CED2KLink::CreateLinkFromUrl(strTok);
			if (pLink && pLink->GetKind() == CED2KLink::kServer){
				CED2KServerLink* pServerLink = pLink->GetServerLink();
				if (pServerLink){
					strAddress = pServerLink->GetAddress();
					nPort = pServerLink->GetPort();
				}
			}
		}
		catch(CString strError){
			AfxMessageBox(strError);
		}
		delete pLink;

		if (strAddress.IsEmpty() || nPort == 0)
			break;

		(void)AddServer(nPort, strAddress, _T(""), false);
		strTok = strServer.Tokenize(_T(" \t\r\n"), nPos);
	}
}
Example #22
0
void CPWToolBar::CustomizeButtons(CString csButtonNames)
{
  if (csButtonNames.IsEmpty()) {
    // Add all buttons
    Reset();
    return;
  }

  int i, nCount;
  CToolBarCtrl& tbCtrl = GetToolBarCtrl();

  // Remove all of the existing buttons
  nCount = tbCtrl.GetButtonCount();

  for (i = nCount - 1; i >= 0; i--) {
    tbCtrl.DeleteButton(i);
  }

  csButtonNames.MakeLower();
  int curPos(0);
  // Note all separators will be treated as the first!
  i = 0;
  CString csToken = csButtonNames.Tokenize(L" ", curPos);
  while (csToken != L"" && curPos != -1) {
    GuiInfoFinder finder(csToken);
    const GuiRecord *iter = std::find_if(MainGuiInfo,
                                         MainGuiInfo + _countof(MainGuiInfo), finder);
    if (iter != MainGuiInfo + _countof(MainGuiInfo)) {
      int index = int(std::distance(MainGuiInfo, iter));
      tbCtrl.AddButtons(1, &m_pOriginalTBinfo[index]);
    }
    csToken = csButtonNames.Tokenize(L" ", curPos);
  }

  tbCtrl.AutoSize();
}
void CSubmoduleUpdateDlg::Refresh()
{
	while (m_PathListBox.GetCount() > 0)
		m_PathListBox.DeleteString(m_PathListBox.GetCount() - 1);

	CString WorkingDir = g_Git.m_CurrentDir;
	WorkingDir.Replace(L':', L'_');

	m_regPath = CRegString(L"Software\\TortoiseGit\\History\\SubmoduleUpdatePath\\" + WorkingDir);
	CString path = m_regPath;
	STRING_VECTOR emptylist;
	STRING_VECTOR list;
	GetSubmodulePathList(list, m_bWholeProject ? emptylist : m_PathFilterList);
	STRING_VECTOR selected;
	if (m_PathList.empty())
	{
		int pos = 0;
		while (pos >= 0)
		{
			CString part = path.Tokenize(L"|", pos);
			if (!part.IsEmpty())
				selected.push_back(part);
		}
	}
	else
	{
		for (size_t i = 0; i < m_PathList.size(); ++i)
			selected.push_back(m_PathList[i]);
	}

	for (size_t i = 0; i < list.size(); ++i)
	{
		m_PathListBox.AddString(list[i]);
		if (selected.size() == 0)
			m_PathListBox.SetSel((int)i);
		else
		{
			for (size_t j = 0; j < selected.size(); ++j)
			{
				if (selected[j] == list[i])
					m_PathListBox.SetSel((int)i);
			}
		}
	}

	OnLbnSelchangeListPath();
}
Example #24
0
inline CSize StringToCSize( const string &str )
{
	CSize ret;
	CString cstr = str.c_str();
	if ( cstr.Find( "x", 0 ) )
	{
		int currpos = 0;
		CString strx = cstr.Tokenize( "x", currpos );
		CString stry = cstr.Tokenize( "x", currpos );
		ret.cx = atoi( strx );
		ret.cy = atoi( stry );
	}
	else
		ret.SetSize( 0, 0 );

	return ret;
}
Example #25
0
inline CPoint StringToCPoint( const string &str )
{
	CPoint ret;
	CString cstr = str.c_str();
	if ( cstr.Find( ",", 0 ) )
	{
		int currpos = 0;
		CString strx = cstr.Tokenize( ",", currpos );
		CString stry = cstr.Tokenize( ",", currpos );
		ret.x = atoi( strx );
		ret.y = atoi( stry );
	}
	else
	{
		ret.x = 0;
		ret.y = 0;
	}

	return ret;
}
Example #26
0
/////////////////////////////////////////////
// CED2KFileLink implementation
/////////////////////////////////////////////
CED2KFileLink::CED2KFileLink(const TCHAR* pszName, const TCHAR* pszSize, const TCHAR* pszHash, 
							 const CStringArray& astrParams, const TCHAR* pszSources)
	: m_size(pszSize)
{
	// Here we have a little problem.. Actually the proper solution would be to decode from UTF8,
	// only if the string does contain escape sequences. But if user pastes a raw UTF8 encoded
	// string (for whatever reason), we would miss to decode that string. On the other side, 
	// always decoding UTF8 can give flaws in case the string is valid for Unicode and UTF8
	// at the same time. However, to avoid the pasting of raw UTF8 strings (which would lead
	// to a greater mess in the network) we always try to decode from UTF8, even if the string
	// did not contain escape sequences.
	m_name = OptUtf8ToStr(URLDecode(pszName));
	m_name.Trim();
	if (m_name.IsEmpty())
		throw GetResString(IDS_ERR_NOTAFILELINK);

	SourcesList = NULL;
	m_hashset = NULL;
	m_bAICHHashValid = false;

	if (_tcslen(pszHash) != 32)
		throw GetResString(IDS_ERR_ILLFORMEDHASH);

	if (_tstoi64(pszSize)>=4294967295)
		throw GetResString(IDS_ERR_TOOLARGEFILE);
	if (_tstoi64(pszSize)<=0)
		throw GetResString(IDS_ERR_NOTAFILELINK);
	
	for (int idx = 0; idx < 16; ++idx) {
		m_hash[idx] = FromHexDigit(*pszHash++)*16;
		m_hash[idx] += FromHexDigit(*pszHash++);
	}

	bool bError = false;
	for (int i = 0; !bError && i < astrParams.GetCount(); i++)
	{
		const CString& strParam = astrParams.GetAt(i);
		ASSERT( !strParam.IsEmpty() );

		CString strTok;
		int iPos = strParam.Find(_T('='));
		if (iPos != -1)
			strTok = strParam.Left(iPos);
		if (strTok == _T("s"))
		{
			CString strURL = strParam.Mid(iPos + 1);
			if (!strURL.IsEmpty())
			{
				TCHAR szScheme[INTERNET_MAX_SCHEME_LENGTH];
				TCHAR szHostName[INTERNET_MAX_HOST_NAME_LENGTH];
				TCHAR szUrlPath[INTERNET_MAX_PATH_LENGTH];
				TCHAR szUserName[INTERNET_MAX_USER_NAME_LENGTH];
				TCHAR szPassword[INTERNET_MAX_PASSWORD_LENGTH];
				TCHAR szExtraInfo[INTERNET_MAX_URL_LENGTH];
				URL_COMPONENTS Url = {0};
				Url.dwStructSize = sizeof(Url);
				Url.lpszScheme = szScheme;
				Url.dwSchemeLength = ARRSIZE(szScheme);
				Url.lpszHostName = szHostName;
				Url.dwHostNameLength = ARRSIZE(szHostName);
				Url.lpszUserName = szUserName;
				Url.dwUserNameLength = ARRSIZE(szUserName);
				Url.lpszPassword = szPassword;
				Url.dwPasswordLength = ARRSIZE(szPassword);
				Url.lpszUrlPath = szUrlPath;
				Url.dwUrlPathLength = ARRSIZE(szUrlPath);
				Url.lpszExtraInfo = szExtraInfo;
				Url.dwExtraInfoLength = ARRSIZE(szExtraInfo);
				if (InternetCrackUrl(strURL, 0, 0, &Url) && Url.dwHostNameLength > 0)
				{
					SUnresolvedHostname* hostname = new SUnresolvedHostname;
					hostname->strURL = strURL;
					hostname->strHostname = szHostName;
					m_HostnameSourcesList.AddTail(hostname);
				}
			}
			else
				ASSERT(0);
		}
		else if (strTok == _T("p"))
		{
			CString strPartHashs = strParam.Tokenize(_T("="), iPos);

			if (m_hashset != NULL){
				ASSERT(0);
				bError = true;
				break;
			}

			m_hashset = new CSafeMemFile(256);
			m_hashset->WriteHash16(m_hash);
			m_hashset->WriteUInt16(0);

			int iPartHashs = 0;
			int iPosPH = 0;
			CString strHash = strPartHashs.Tokenize(_T(":"), iPosPH);
			while (!strHash.IsEmpty())
			{
				uchar aucPartHash[16];
				if (!strmd4(strHash, aucPartHash)){
					bError = true;
					break;
				}
				m_hashset->WriteHash16(aucPartHash);
				iPartHashs++;
				strHash = strPartHashs.Tokenize(_T(":"), iPosPH);
			}
			if (bError)
				break;

			m_hashset->Seek(16, CFile::begin);
			m_hashset->WriteUInt16(iPartHashs);
			m_hashset->Seek(0, CFile::begin);
		}
		else if (strTok == _T("h"))
		{
			CString strHash = strParam.Mid(iPos + 1);
			if (!strHash.IsEmpty())
			{
				if (DecodeBase32(strHash, m_AICHHash.GetRawHash(), CAICHHash::GetHashSize()) == CAICHHash::GetHashSize()){
					m_bAICHHashValid = true;
					ASSERT( m_AICHHash.GetString().CompareNoCase(strHash) == 0 );
				}
				else
					ASSERT( false );
			}
			else
				ASSERT( false );
		}
		else
			ASSERT(0);
	}

	if (bError)
	{
		delete m_hashset;
		m_hashset = NULL;
	}

	if (pszSources)
	{
		TCHAR* pNewString = _tcsdup(pszSources);
		autoFree liberator(pNewString);
		TCHAR* pCh = pNewString;
		TCHAR* pEnd;
		TCHAR* pIP;
		TCHAR* pPort;

		bool bAllowSources;
		TCHAR date[3];
		COleDateTime expirationDate;
		int nYear,nMonth,nDay;

		uint16 nCount = 0;
		uint32 dwID;
		uint16 nPort;
		uint32 dwServerIP = 0; 
		uint16 nServerPort = 0;
		unsigned long ul;

		int nInvalid = 0;

		pCh = _tcsstr( pCh, _T("sources") );
		if( pCh != NULL ) {
			pCh = pCh + 7; // point to char after "sources"
			pEnd = pCh;
			while( *pEnd ) pEnd++; // make pEnd point to the terminating NULL
			bAllowSources=true;
			// if there's an expiration date...
			if( *pCh == _T('@') && (pEnd-pCh) > 7 )
			{
				pCh++; // after '@'
				date[2] = 0; // terminate the two character string
				date[0] = *(pCh++); date[1] = *(pCh++);
				nYear = _tcstol( date, 0, 10 ) + 2000;
				date[0] = *(pCh++); date[1] = *(pCh++);
				nMonth = _tcstol( date, 0, 10 );
				date[0] = *(pCh++); date[1] = *(pCh++);
				nDay = _tcstol( date, 0, 10 );
				bAllowSources = ( expirationDate.SetDate(nYear,nMonth,nDay) == 0 );
				if (bAllowSources) bAllowSources=(COleDateTime::GetCurrentTime() < expirationDate);
			}

			// increment pCh to point to the first "ip:port" and check for sources
			if ( bAllowSources && ++pCh < pEnd ) {
				SourcesList = new CSafeMemFile(256);
				SourcesList->WriteUInt16(nCount); // init to 0, we'll fix this at the end.
				// for each "ip:port" source string until the end
				// limit to prevent overflow (uint16 due to CPartFile::AddClientSources)
				while( *pCh != 0 && nCount < MAXSHORT ) {
					pIP = pCh;
					// find the end of this ip:port string & start of next ip:port string.
					if( (pCh = _tcschr(pCh, _T(','))) != NULL ) {
						*pCh = 0; // terminate current "ip:port"
						pCh++; // point to next "ip:port"
					}
					else
						pCh = pEnd;

					// if port is not present for this ip, go to the next ip.
					if( (pPort = _tcschr(pIP, _T(':'))) == NULL )
					{	nInvalid++;	continue;	}

					*pPort = 0;	// terminate ip string
					pPort++;	// point pPort to port string.

					dwID = inet_addr(CStringA(pIP));
					ul = _tcstoul( pPort, 0, 10 );
					nPort = static_cast<uint16>(ul);

					// skip bad ips / ports
					if (ul > 0xFFFF || ul == 0 )	// port
					{	nInvalid++;	continue;	}
					if( dwID == INADDR_NONE) {	// hostname?
						if (_tcslen(pIP) > 512)
						{	nInvalid++;	continue;	}
						SUnresolvedHostname* hostname = new SUnresolvedHostname;
						hostname->nPort = nPort;
						hostname->strHostname = pIP;
						m_HostnameSourcesList.AddTail(hostname);
						continue;
					}
					//TODO: This will filter out *.*.*.0 clients. Is there a nice way to fix?
					if( IsLowID(dwID) )	// ip
					{	nInvalid++;	continue;	}

					SourcesList->WriteUInt32(dwID);
					SourcesList->WriteUInt16(nPort);
					SourcesList->WriteUInt32(dwServerIP);
					SourcesList->WriteUInt16(nServerPort);
					nCount++;
				}
				SourcesList->SeekToBegin();
				SourcesList->WriteUInt16(nCount);
				SourcesList->SeekToBegin();
				if (nCount==0) {
					delete SourcesList;
					SourcesList=NULL;
				}
			}
		}
	}
}
Example #27
0
void CClientDlg::SendHttp()
{
	USES_CONVERSION;

	if(!CheckStarted(TRUE))
		return;

	CString strMethod;
	CString strSchema;
	CString strAddress;
	CString strPort;
	CString strPath;

	m_Method.GetWindowText(strMethod);
	m_Schema.GetWindowText(strSchema);
	m_Address.GetWindowText(strAddress);
	m_Port.GetWindowText(strPort);

	if(m_Method.GetCurSel() != 8)
	{
		m_Path.GetWindowText(strPath);
		strPath.Trim();

		if(strPath.IsEmpty() || strPath.GetAt(0) != '/')
			strPath.Insert(0, '/');
	}

	THttpHeaderMap headers;

	int iCount = m_Headers.GetCount();

	for(int i = 0; i < iCount; i++)
	{
		CString strHeader;
		m_Headers.GetText(i, strHeader);

		int j = 0;
		CString strName  = strHeader.Tokenize(_T(": "), j);
		CString strValue = strHeader.Mid(j + 1);

		headers.emplace(THttpHeaderMap::value_type(T2A(strName), T2A(strValue)));
	}

	CStringA strBodyA;
	CStringA strPathA;

	if(m_Method.GetCurSel() <= 2)
	{
		CString strBody;
		m_Body.GetWindowText(strBody);

		strBodyA = T2A(strBody);
	}
	else if(m_Method.GetCurSel() == 8)
	{
		THttpHeaderMapCI it = headers.find("Host");

		if(it != headers.end() && !it->second.IsEmpty())
			strPathA = it->second;
		else
		{
			CString strHost;
			strHost.Format(_T("%s:%s"), strAddress, strPort);
			strPathA = strHost;
		}
	}

	if(strPathA.IsEmpty())
		strPathA = T2A(strPath);

	DWORD dwIndex	= 0;
	DWORD dwSize	= (DWORD)headers.size();
	unique_ptr<THeader[]> szHeaders(new THeader[dwSize]);

	for(THttpHeaderMapCI it = headers.begin(), end = headers.end(); it != end; ++it, ++dwIndex)
	{
		szHeaders[dwIndex].name  = it->first;
		szHeaders[dwIndex].value = it->second;
	}

	CONNID dwConnID = m_pClient->GetConnectionID();

	if(m_pClient->SendRequest(T2A(strMethod), strPathA, szHeaders.get(), dwSize, (const BYTE*)(LPCSTR)strBodyA, strBodyA.GetLength()))
	{
		CString strContent;
		strContent.Format(_T("[%s] %s://%s:%s%s"), strMethod, strSchema, strAddress, strPort, strPath);

		::LogSend(dwConnID, strContent);

		if(!m_bListener)
		{
			CStringA strSummary = GetHeaderSummary(m_pClient.get(), "    ", 0, TRUE);
			::PostOnHeadersComplete(dwConnID, strSummary);
		}

		LPCBYTE pData	= nullptr;
		int iLength		= 0;

		m_pClient->GetResponseBody(&pData, &iLength);

		if(iLength > 0)
		{
			if(!m_bListener) ::PostOnBody(dwConnID, pData, iLength);

			LPCSTR lpszEnc = m_pClient->GetContentEncoding();

			if(lpszEnc && ::StrStrIA(lpszEnc, "gzip"))
			{
				int rs		= 0;
				DWORD dwLen	= ::GZipGuessUncompressBound(pData, iLength);

				if(dwLen == 0 || dwLen > 5 * 1024 * 1024)
					rs = -10;
				else
				{
					CBufferPtr szBuff(dwLen);
					rs = ::GZipUncompress(pData, iLength, szBuff, dwLen);
				}

				if(rs == 0)
					::PostUncompressBody(dwConnID, dwLen);
				else
				{
					::PostUncompressBodyFail(dwConnID, rs);

					if(!m_bListener) ::PostOnMessageComplete(dwConnID);

					OnBnClickedStop();
					return;
				}
			}
		}

		if(!m_bListener) ::PostOnMessageComplete(dwConnID);

		EnHttpUpgradeType enUpgrade = m_pClient->GetUpgradeType();

		if(enUpgrade == HUT_WEB_SOCKET)
		{
			if(!m_bListener) ::PostOnUpgrade(dwConnID, enUpgrade);

			m_bWebSocket = TRUE;
			OnCbnSelchangeMethod();
		}
	}
	else
	{
		::LogSendFail(dwConnID, ::GetLastError(), ::GetSocketErrorDesc(SE_DATA_SEND));
		SetAppState(ST_STOPPED);
	}

	m_pClient->CleanupRequestResult();
}
Example #28
0
/***********************************************************
功能:执行adb devices命令获取设备列表
***********************************************************/
BOOL AdbUtils::GetSerialNo(StringArray &serials)
{
	int					iFirstDevLinePos;
	CString				strCmd;
	CString				strTemp;
	CString				strResult;
	StringArray			tempSnVector;

	strCmd.Format(_T("%s devices"), m_strAdbPathName);
	strResult = ConsoleUtil::Execute(strCmd).c_str();
	if(strResult.Find(_T("error:")) != -1)	// adb 出错
	{
		RestartServer();
		strResult = ConsoleUtil::Execute(strCmd).c_str();
		if (strResult.Find(_T("error:")) != -1)
		{
			return FALSE;
		}
	}

	if ((iFirstDevLinePos = strResult.Find(_T("device\r\n"))) < 0)
		return TRUE;
	strTemp				= strResult.Left(iFirstDevLinePos - 2);
	iFirstDevLinePos	= strTemp.ReverseFind(_T('\n'));
	strResult			= strResult.Mid(iFirstDevLinePos+1);
	tempSnVector.clear();

	int			nPos		= 0;
	int			nTokenPos	= 0;
	CString		resToken;
	resToken	= strResult.Tokenize(_T("\r\n"), nTokenPos);
	while(!resToken.IsEmpty())
	{
		if ((nPos = resToken.Find(_T("device"))) > 0)
		{
			CString strSn(resToken.GetBuffer(0), nPos);
			strSn.TrimLeft(_T("\t "));
			strSn.TrimRight(_T("\t "));
			if (!strSn.IsEmpty())
				tempSnVector.push_back(strSn.GetBuffer());
		}
		
		resToken = strResult.Tokenize(_T("\r\n"), nTokenPos);
	}

	// 去重
	serials.clear();
	BOOL bRepeated = FALSE;
	for(auto iter = tempSnVector.begin(); iter != tempSnVector.end(); iter++)
	{
		auto& szCurSn = *iter;

		for (auto sn = serials.begin(), end = serials.end(); sn != end; sn++)
		{
			if (*sn == szCurSn)
			{
				bRepeated = TRUE;
				break;
			}
		}
		if (bRepeated)
		{ 
			bRepeated = FALSE;
			continue;
		}
		serials.push_back(szCurSn);
	}

	return TRUE;
}
Example #29
0
/*-----------------------------------------------------------------------------
	Dynamically configure the location and server for an EC2 instance
-----------------------------------------------------------------------------*/
void CurlBlastDlg::GetEC2Config()
{
    log.Trace(_T("GetEC2Config"));

    CString server, location, locationKey;

    CString userData;
    if( GetUrlText(_T("http://169.254.169.254/latest/user-data"), userData) )
    {
        int pos = 0;
        do {
            CString token = userData.Tokenize(_T(" &"), pos).Trim();
            if( token.GetLength() )
            {
                int split = token.Find(_T('='), 0);
                if( split > 0 )
                {
                    CString key = token.Left(split).Trim();
                    CString value = token.Mid(split + 1).Trim();

                    if( key.GetLength() )
                    {
                        if( !key.CompareNoCase(_T("wpt_server")) && value.GetLength() )
                            server = CString(_T("http://")) + value + _T("/work/");
                        else if( !key.CompareNoCase(_T("wpt_location")) && value.GetLength() )
                            location = value;
                        else if( !key.CompareNoCase(_T("wpt_key")) )
                            locationKey = value;
                        else if( !key.CompareNoCase(_T("wpt_timeout")) && value.GetLength() )
                            timeout = _ttol(value);
                        else if( !key.CompareNoCase(_T("wpt_keep_DNS")) && value.GetLength() )
                            keepDNS = _ttol(value);
                    }
                }
            }
        } while(pos > 0);
    }

    if( location.IsEmpty() )
    {
        // build the location name automatically from the availability zone
        CString zone;
        if( GetUrlText(_T("http://169.254.169.254/latest/meta-data/placement/availability-zone"), zone) )
        {
            int pos = zone.Find('-');
            if( pos )
            {
                pos = zone.Find('-', pos + 1);
                if( pos )
                {
                    // figure out the browser version
                    TCHAR buff[1024];
                    CRegKey key;
                    CString ieVer;
                    if( SUCCEEDED(key.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer"), KEY_READ)) )
                    {
                        DWORD len = _countof(buff);
                        if( SUCCEEDED(key.QueryStringValue(_T("Version"), buff, &len)) )
                        {
                            ieVer = buff;
                            ieVer.Trim();
                            ULONG ver = _ttol(ieVer);
                            ieVer.Format(_T("%d"), ver);
                            location = CString(_T("ec2-")) + zone.Left(pos).Trim() + CString(_T("-IE")) + ieVer;
                        }
                    }
                }
            }
        }
    }

    CString instance;
    GetUrlText(_T("http://169.254.169.254/latest/meta-data/instance-id"), instance);
    instance = instance.Trim();

    log.Trace(_T("EC2 server: %s"), (LPCTSTR)server);
    log.Trace(_T("EC2 location: %s"), (LPCTSTR)location);
    log.Trace(_T("EC2 locationKey: %s"), (LPCTSTR)locationKey);
    log.Trace(_T("EC2 Instance ID: %s"), (LPCTSTR)instance);

    if( !server.IsEmpty() )
        urlManager.SetHttp(server);

    if( !location.IsEmpty() )
        urlManager.SetHttpLocation(location);

    if( !locationKey.IsEmpty() )
        urlManager.SetHttpKey(locationKey);

    if( !instance.IsEmpty() )
        urlManager.SetHttpEC2Instance(instance);

    // force EC2 to use the current OS user account
    useCurrentAccount = 1;
}
Example #30
0
int CGitHeadFileList::ReadHeadHash(CString gitdir)
{
    int ret = 0;
    CAutoWriteLock lock(&this->m_SharedMutex);
    m_Gitdir = g_AdminDirMap.GetAdminDir(gitdir);

    m_HeadFile = m_Gitdir + _T("HEAD");

    if( g_Git.GetFileModifyTime(m_HeadFile, &m_LastModifyTimeHead))
        return -1;

    try
    {
        do
        {
            CAutoFile hfile = CreateFile(m_HeadFile,
                                         GENERIC_READ,
                                         FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
                                         NULL,
                                         OPEN_EXISTING,
                                         FILE_ATTRIBUTE_NORMAL,
                                         NULL);

            if (!hfile)
            {
                ret = -1;
                break;
            }

            DWORD size = 0;
            unsigned char buffer[40] ;
            ReadFile(hfile, buffer, 4, &size, NULL);
            if (size != 4)
            {
                ret = -1;
                break;
            }
            buffer[4]=0;
            if (strcmp((const char*)buffer,"ref:") == 0)
            {
                DWORD filesize = GetFileSize(hfile, NULL);
                if (filesize < 5)
                {
                    m_HeadRefFile.Empty();
                    ret = -1;
                    break;
                }

                unsigned char *p = (unsigned char*)malloc(filesize -4);

                ReadFile(hfile, p, filesize - 4, &size, NULL);

                m_HeadRefFile.Empty();
                g_Git.StringAppend(&this->m_HeadRefFile, p, CP_UTF8, filesize - 4);
                CString ref = this->m_HeadRefFile;
                ref = ref.Trim();
                int start = 0;
                ref = ref.Tokenize(_T("\n"), start);
                free(p);
                m_HeadRefFile = m_Gitdir + m_HeadRefFile.Trim();
                m_HeadRefFile.Replace(_T('/'),_T('\\'));

                __int64 time;
                if (g_Git.GetFileModifyTime(m_HeadRefFile, &time, NULL))
                {
                    m_HeadRefFile.Empty();
                    if (GetPackRef(gitdir))
                    {
                        ret = -1;
                        break;
                    }
                    if (this->m_PackRefMap.find(ref) == m_PackRefMap.end())
                    {
                        ret = -1;
                        break;
                    }
                    this ->m_Head = m_PackRefMap[ref];
                    ret = 0;
                    break;
                }

                CAutoFile href = CreateFile(m_HeadRefFile,
                                            GENERIC_READ,
                                            FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
                                            NULL,
                                            OPEN_EXISTING,
                                            FILE_ATTRIBUTE_NORMAL,
                                            NULL);

                if (!href)
                {
                    m_HeadRefFile.Empty();

                    if (GetPackRef(gitdir))
                    {
                        ret = -1;
                        break;
                    }

                    if (this->m_PackRefMap.find(ref) == m_PackRefMap.end())
                    {
                        ret = -1;
                        break;
                    }
                    this ->m_Head = m_PackRefMap[ref];
                    ret = 0;
                    break;
                }
                ReadFile(href, buffer, 40, &size, NULL);
                if (size != 40)
                {
                    ret = -1;
                    break;
                }
                this->m_Head.ConvertFromStrA((char*)buffer);

                this->m_LastModifyTimeRef = time;

            }
            else
            {
                ReadFile(hfile, buffer + 4, 40 - 4, &size, NULL);
                if(size != 36)
                {
                    ret = -1;
                    break;
                }
                m_HeadRefFile.Empty();

                this->m_Head.ConvertFromStrA((char*)buffer);
            }
        } while(0);
    }
    catch(...)
    {
        ret = -1;
    }

    return ret;
}