Example #1
0
int tm_strncmp(str_char *left_str, str_char *right_str, size_t len)
{
	ASSERT(left_str);
	ASSERT(right_str);
	return(_tcsncmp(left_str, right_str, len));
}
Example #2
0
void CMainWnd::SaveM3uPlayList(LPTSTR pszFile)
{
	// M3Uの形式
	// #EXTM3U
	// #EXTINF:<演奏時間(秒)>,<タイトル>
	// <ファイルのパス>
	// ...

#ifdef _UNICODE
	char szFile[MAX_PATH * 2];
	WideCharToMultiByte(CP_ACP, NULL, pszFile, -1, szFile, MAX_PATH, NULL, NULL);
	FILE* fp = fopen(szFile, "w");
#else
	FILE* fp = fopen(pszFile, "w");
#endif
	if (!fp) return;

	TCHAR szPath[MAX_PATH];
	_tcscpy(szPath, pszFile);
	LPTSTR psz = _tcsrchr(szPath, _T('\\'));
	if (psz) *(psz + 1) = NULL;

	// ヘッダを記述
	fprintf(fp, "#EXTM3U\n");

	// リストを記述
	for (int i = 0; i < m_pListFile->GetCount(); i++) {
		FILEINFO* p = (FILEINFO*)m_pListFile->GetAt(i);
		if (p) {
			TCHAR szTitle[MAX_PATH];
			GetTitle(i, szTitle);
#ifdef _UNICODE
			TCHAR szBuff[MAX_PATH * 2]; // ...越えることないでしょ?

			// #EXTINF:<演奏時間(秒)>,<タイトル>
			wsprintf(szBuff, _T("#EXTINF:%d,%s\n"), 
				p->info.nDuration == 0 ? -1 : p->info.nDuration / 1000, szTitle);
			WideCharToMultiByte(CP_ACP, NULL, szBuff, -1, szFile, MAX_PATH * 2, NULL, NULL);
			fprintf(fp, szFile);
			
			// <ファイルのパス>
			if (_tcsncmp(szPath, p->szPath, _tcslen(szPath)) == 0)
				WideCharToMultiByte(CP_ACP, NULL, p->szPath + _tcslen(szPath), -1, szFile, MAX_PATH * 2, NULL, NULL);
			else
				WideCharToMultiByte(CP_ACP, NULL, p->szPath, -1, szFile, MAX_PATH * 2, NULL, NULL);
			fprintf(fp, szFile);
			fprintf(fp, "\n");
#else
			// #EXTINF:<演奏時間(秒)>,<タイトル>
			fprintf(fp, "#EXTINF:%d", 
				p->info.nDuration == 0 ? -1 : p->info.nDuration / 1000);
			fprintf(fp, ",%s\n", szTitle);

			// <ファイルのパス>
			if (_tcsncmp(szPath, p->szPath, _tcslen(szPath)) == 0)
				fprintf(fp, p->szPath + _tcslen(szPath)); // 相対パス
			else
				fprintf(fp, p->szPath); // 絶対パス
			fprintf(fp, "\n");
#endif
		}
	}
	fclose(fp);
}
Example #3
0
INT_PTR CALLBACK DlgProcSMPInitProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch ( msg ) {
	case WM_INITDIALOG: 
		{
			if (!lParam) {
				EndDialog(hwndDlg, IDCANCEL);
				return FALSE;
			}
			TranslateDialogDefault( hwndDlg );

			ConnContext *context = (ConnContext*)lParam;
			if (smp_for_contact.find(context->app_data) != smp_for_contact.end()) {
				EndDialog(hwndDlg, IDCANCEL);
				return FALSE;
			}

			TCHAR title[512], *proto = mir_a2t(contact_get_proto((HANDLE)context->app_data));
			mir_sntprintf(title, 512, TranslateT(LANG_SMP_VERIFY_TITLE), contact_get_nameT((HANDLE)context->app_data), proto);
			mir_free(proto);
			SendMessage(hwndDlg, WM_SETTEXT, 0, (LPARAM)title);
			SetDlgItemText(hwndDlg, IDC_STC_SMP_HEAD, title);
			SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);

			// Move window to screen center
			// Get the owner window and dialog box rectangles. 
			HWND hwndOwner; RECT rcOwner, rcDlg, rc;
			if ((hwndOwner = GetParent(hwndDlg)) == NULL) 
			{
				hwndOwner = GetDesktopWindow(); 
			}

			GetWindowRect(hwndOwner, &rcOwner); 
			GetWindowRect(hwndDlg, &rcDlg); 
			CopyRect(&rc, &rcOwner); 

			// Offset the owner and dialog box rectangles so that right and bottom 
			// values represent the width and height, and then offset the owner again 
			// to discard space taken up by the dialog box. 

			OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top); 
			OffsetRect(&rc, -rc.left, -rc.top); 
			OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom); 

			// The new position is the sum of half the remaining space and the owner's 
			// original position. 

			SetWindowPos(hwndDlg, 
				HWND_TOP, 
				rcOwner.left + (rc.right / 2), 
				rcOwner.top + (rc.bottom / 2), 
				0, 0,          // Ignores size arguments. 
				SWP_NOSIZE); 

			// end center dialog


			HWND cmb = GetDlgItem(hwndDlg, IDC_CBO_SMP_CHOOSE);
			SendMessage(cmb, CB_ADDSTRING, 0, (WPARAM)TranslateT(LANG_SMPTYPE_QUESTION));
			SendMessage(cmb, CB_ADDSTRING, 0, (WPARAM)TranslateT(LANG_SMPTYPE_PASSWORD));
			SendMessage(cmb, CB_ADDSTRING, 0, (WPARAM)TranslateT(LANG_SMPTYPE_FINGERPRINT));
			SendMessage(cmb, CB_SELECTSTRING, -1, (WPARAM)TranslateT(LANG_SMPTYPE_QUESTION));
			EnableWindow(GetDlgItem(hwndDlg, IDC_CBO_SMP_CHOOSE), TRUE);

			
			Fingerprint *fp = context->active_fingerprint;
			if (!fp) {
				EndDialog(hwndDlg, IDCANCEL);
				return FALSE;
			}
			TCHAR buff[1024];
			if (!fp->trust || fp->trust[0] == '\0')
				mir_sntprintf(buff, 512, TranslateT(LANG_OTR_SMPQUESTION_VERIFY_DESC), contact_get_nameT((HANDLE)context->app_data));
			else
				mir_sntprintf(buff, 512, TranslateT(LANG_OTR_SMPQUESTION_VERIFIED_DESC), contact_get_nameT((HANDLE)context->app_data));

			SetDlgItemText(hwndDlg, IDC_STC_SMP_INFO, buff);

			SetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD1, _T(""));
			SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD1, EM_SETREADONLY, FALSE, 0);
			SetDlgItemText(hwndDlg, IDC_STC_SMP_FIELD1, TranslateT(LANG_SMP_QUESTION));
			
			SetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD2, _T(""));
			SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD2, EM_SETREADONLY, FALSE, 0);
			SetDlgItemText(hwndDlg, IDC_STC_SMP_FIELD2, TranslateT(LANG_SMP_ANSWER));

			
			ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_SHOWNA);
			ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_HIDE);
			ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_HIDE);
			SetFocus(GetDlgItem(hwndDlg, IDC_CBO_SMP_CHOOSE));
			
			return FALSE;
		}

	case WM_COMMAND: 
		switch ( HIWORD( wParam )) {
			case BN_CLICKED: 
						{
							ConnContext* context = (ConnContext*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
							TCHAR msg[1024];
						switch ( LOWORD( wParam )) {
							case IDCANCEL:
								EndDialog(hwndDlg, LOWORD( wParam ));
								break;
							case IDOK:
								GetDlgItemText(hwndDlg, IDC_CBO_SMP_CHOOSE, msg, 255);
								if (_tcsncmp(msg, TranslateT(LANG_SMPTYPE_QUESTION), 255)==0) {
									if (smp_for_contact.find(context->app_data) != smp_for_contact.end()) {
										TCHAR msg[512];
										mir_sntprintf(msg, 512, TranslateT(LANG_SMP_IN_PROGRESS), contact_get_nameT((HANDLE)context->app_data));
										ShowError(msg);
									}else {
									int len = SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD1, WM_GETTEXTLENGTH, 0, 0);
									TCHAR *question = new TCHAR[len+1];
									GetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD1, question, len+1);
									char *quest = mir_utf8encodeT(question);
									delete question;

									len = SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD2, WM_GETTEXTLENGTH, 0, 0);
									TCHAR *answer = new TCHAR[len+1];
									GetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD2, answer, len+1);
									char *ans = mir_utf8encodeT(answer);
									delete answer;

									SMPInitUpdateDialog(context, false);
									otr_start_smp(context, quest, (const unsigned char*)ans, strlen(ans));
									mir_free(quest);
									mir_free(ans);
									}

								}else if (_tcsncmp(msg, TranslateT(LANG_SMPTYPE_PASSWORD), 255)==0) {
									if (smp_for_contact.find(context->app_data) != smp_for_contact.end()) {
										TCHAR msg[512];
										mir_sntprintf(msg, 512, TranslateT(LANG_SMP_IN_PROGRESS), contact_get_nameT((HANDLE)context->app_data));
										ShowError(msg);
									}else {
									int len = SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD2, WM_GETTEXTLENGTH, 0, 0);
									TCHAR *answer = new TCHAR[len+1];
									GetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD2, answer, len+1);
									char *ans = mir_utf8encodeT(answer);
									delete answer;

									SMPInitUpdateDialog(context, false);
									otr_start_smp(context, NULL, (const unsigned char*)ans, strlen(ans));
									mir_free(ans);
									}

								}else break;
								EndDialog(hwndDlg, LOWORD( wParam ));
								break;
							case IDYES:
								VerifyFingerprint(context, true);
								EndDialog(hwndDlg, LOWORD( wParam ));
								break;
							case IDNO:
								VerifyFingerprint(context, false);
								EndDialog(hwndDlg, LOWORD( wParam ));
								break;
						}
						}
						break;
			case CBN_SELCHANGE:
				switch ( LOWORD( wParam )) {	
					case IDC_CBO_SMP_CHOOSE:
						{ 
							ConnContext* context = (ConnContext*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
							Fingerprint *fp = context->active_fingerprint;
							if (!fp) {
								EndDialog(hwndDlg, IDCANCEL);
								return TRUE;
							}
							BOOL trusted = false;
							if (fp->trust && fp->trust[0] != '\0') trusted = true;

							TCHAR buff[512];
							GetDlgItemText(hwndDlg, IDC_CBO_SMP_CHOOSE, buff, 255);
							if (_tcsncmp(buff, TranslateT(LANG_SMPTYPE_QUESTION), 255)==0) {
								if (trusted)
									mir_sntprintf(buff, 512, TranslateT(LANG_OTR_SMPQUESTION_VERIFIED_DESC), contact_get_nameT((HANDLE)context->app_data));
								else
									mir_sntprintf(buff, 512, TranslateT(LANG_OTR_SMPQUESTION_VERIFY_DESC), contact_get_nameT((HANDLE)context->app_data));

								SetDlgItemText(hwndDlg, IDC_STC_SMP_INFO, buff);

								SetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD1, _T(""));
								SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD1, EM_SETREADONLY, FALSE, 0);
								SetDlgItemText(hwndDlg, IDC_STC_SMP_FIELD1, TranslateT(LANG_SMP_QUESTION));

								SetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD2, _T(""));
								SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD2, EM_SETREADONLY, FALSE, 0);
								SetDlgItemText(hwndDlg, IDC_STC_SMP_FIELD2, TranslateT(LANG_SMP_ANSWER));


								ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_SHOWNA);
								ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_HIDE);
								ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_HIDE);
							} else if (_tcsncmp(buff, TranslateT(LANG_SMPTYPE_PASSWORD), 255)==0) {
								if (trusted)
									mir_sntprintf(buff, 512, TranslateT(LANG_OTR_SMPPASSWORD_VERIFIED_DESC), contact_get_nameT((HANDLE)context->app_data));
								else
									mir_sntprintf(buff, 512, TranslateT(LANG_OTR_SMPPASSWORD_VERIFY_DESC), contact_get_nameT((HANDLE)context->app_data));

								SetDlgItemText(hwndDlg, IDC_STC_SMP_INFO, buff);

								SetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD1, _T(""));
								SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD1, EM_SETREADONLY, TRUE, 0);
								SetDlgItemText(hwndDlg, IDC_STC_SMP_FIELD1, _T(""));

								SetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD2, _T(""));
								SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD2, EM_SETREADONLY, FALSE, 0);
								SetDlgItemText(hwndDlg, IDC_STC_SMP_FIELD2, TranslateT(LANG_SMP_PASSWORD));


								ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_SHOWNA);
								ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_HIDE);
								ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_HIDE);
							} else if (_tcsncmp(buff, TranslateT(LANG_SMPTYPE_FINGERPRINT), 255)==0) {
								if (trusted)
									mir_sntprintf(buff, 512, TranslateT(LANG_OTR_FPVERIFIED_DESC), contact_get_nameT((HANDLE)context->app_data));
								else
									mir_sntprintf(buff, 512, TranslateT(LANG_OTR_FPVERIFY_DESC), contact_get_nameT((HANDLE)context->app_data));

								SetDlgItemText(hwndDlg, IDC_STC_SMP_INFO, buff);

								unsigned char hash[20];
								lib_cs_lock();
								if (!otrl_privkey_fingerprint_raw(otr_user_state, hash, context->accountname, context->protocol)) {
									lib_cs_unlock();
									EndDialog(hwndDlg, IDCANCEL);
									return FALSE;
								}
								otrl_privkey_hash_to_humanT(buff, hash);
								lib_cs_unlock();
								SetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD1, buff);
								SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD1, EM_SETREADONLY, TRUE, 0);
								SetDlgItemText(hwndDlg, IDC_STC_SMP_FIELD1, TranslateT(LANG_YOUR_PRIVKEY));

								otrl_privkey_hash_to_humanT(buff, fp->fingerprint);
								SetDlgItemText(hwndDlg, IDC_EDT_SMP_FIELD2, buff);
								SendDlgItemMessage(hwndDlg, IDC_EDT_SMP_FIELD2, EM_SETREADONLY, TRUE, 0);
								SetDlgItemText(hwndDlg, IDC_STC_SMP_FIELD2, TranslateT(LANG_CONTACT_FINGERPRINT));

								ShowWindow(GetDlgItem(hwndDlg, IDOK), SW_HIDE);
								ShowWindow(GetDlgItem(hwndDlg, IDYES), SW_SHOWNA);
								ShowWindow(GetDlgItem(hwndDlg, IDNO), SW_SHOWNA);

							}
						}break;
				}
		}
		break;

	}

	return FALSE;
}
Example #4
0
BOOL devInit(LPCTSTR CommandLine) {
    TCHAR DeviceName[DEVNAMESIZE + 1];
    PDeviceDescriptor_t pDevNmeaOut = NULL;

    TCHAR Port[MAX_PATH] = {_T('\0')};
    DWORD SpeedIndex = 2;
    DWORD BitIndex = (BitIndex_t) bit8N1;

    static bool doinit = true;

    pDevPrimaryBaroSource = NULL;
    pDevSecondaryBaroSource = NULL;

    std::set<std::wstring> UsedPort; // list of already used port
    
    for (unsigned i = 0; i < NUMDEV; i++) {
        DeviceList[i].InitStruct(i);

        ComPortStatus[i] = CPS_UNUSED; // 100210
        ComPortHB[i] = 0; // counter
        if (doinit) {
            ComPortRx[i] = 0;
            ComPortTx[i] = 0;
            ComPortErrTx[i] = 0;
            ComPortErrRx[i] = 0;
            ComPortErrors[i] = 0;

            doinit = false;
        }
        
        if (SIMMODE){
            continue;
        }
        
        ReadDeviceSettings(i, DeviceName);
        DeviceList[i].Disabled = (wcscmp(DeviceName, _T(DEV_DISABLED_NAME)) == 0);
        if (DeviceList[i].Disabled) {
            StartupStore(_T(". Device %c is DISABLED.%s"), (_T('A') + i), NEWLINE);
            continue;
        }

        DeviceRegister_t* pDev = std::find_if(&DeviceRegister[0], &DeviceRegister[DeviceRegisterCount], devNameCompare(DeviceName));
        if (pDev == &DeviceRegister[DeviceRegisterCount]) {
            DeviceList[i].Disabled = true;
            StartupStore(_T(". Device %c : invalide drivers name <%s>%s"), (_T('A') + i), DeviceName, NEWLINE);
            continue;
        }
        if(_tcscmp(pDev->Name,TEXT("Internal")) == 0) {
            _tcscpy(Port, _T("GPSID"));
        } else { 
            Port[0] = _T('\0');
            SpeedIndex = 2;
            BitIndex = (BitIndex_t) bit8N1;
            ReadPortSettings(i, Port, &SpeedIndex, &BitIndex);
        }
        // remember: Port1 is the port used by device A, port1 may be Com3 or Com1 etc

        if(std::find(UsedPort.begin(), UsedPort.end(), Port) != UsedPort.end()) {
            StartupStore(_T(". Port <%s> Already used, Device %c Disabled ! %s"), Port, (_T('A') + i), NEWLINE);
            continue;
        }
        UsedPort.insert(Port);
        
        // remember: Port1 is the port used by device A, port1 may be Com3 or Com1 etc
        StartupStore(_T(". Device %c is <%s> Port=%s%s"), (_T('A') + i), DeviceName, Port, NEWLINE);
        
        ComPort *Com = NULL;
        if (_tcsncmp(Port, _T("BT:"), 3) == 0) {
            CBtHandler* pBtHandler = CBtHandler::Get();
            StartupStore(_T(".. Initialise Bluetooth Device %s%s"), Port, NEWLINE);
            if (pBtHandler && pBtHandler->IsOk()) {
                if (pBtHandler->StartHW()) {
                    Com = new BthPort(i, &Port[3]);
                }
            }
        } else if (_tcscmp(Port, _T("GPSID")) == 0) {
            Com = new GpsIdPort(i, Port);
        } else {
            Com = new SerialPort(i, Port, dwSpeed[SpeedIndex], (BitIndex_t)BitIndex, PollingMode);
        }

        if (Com && Com->Initialize()) {
            ComPortStatus[i] = CPS_OPENOK;
            pDev->Installer(&DeviceList[i]);

            if ((pDevNmeaOut == NULL) && (pDev->Flags & (1l << dfNmeaOut))) {
                pDevNmeaOut = &DeviceList[i];
            }

            DeviceList[i].Com = Com;

            devInit(&DeviceList[i]);
            devOpen(&DeviceList[i], i);

            if (devIsBaroSource(&DeviceList[i])) {
                if (pDevPrimaryBaroSource == NULL) {
                    pDevPrimaryBaroSource = &DeviceList[i];
                } else if (pDevSecondaryBaroSource == NULL) {
                    pDevSecondaryBaroSource = &DeviceList[i];
                }
            }
        } else {
            delete Com;
            ComPortStatus[i] = CPS_OPENKO;
        }
    }

    if (pDevNmeaOut != NULL) {
        if (pDevNmeaOut == devA()) {
            devB()->pDevPipeTo = devA();
        }
        if (pDevNmeaOut == devB()) {
            devA()->pDevPipeTo = devB();
        }
    }

    return (TRUE);
}
Example #5
0
int _tmain( int argc, _TCHAR* argv[] )
{
	int retval = 0;
	e_opmode opmode = E_OPMODE_NONE;
	_TCHAR * pFilename = NULL;

	/*	sanity checks	*/
	if ( 1 >= argc || NULL == argv || NULL == argv[1] )
	{
		_ftprintf_s( stdout, _T( "%s" ), _T( "error:  parameter not found!\n" ) );
		retval = usage();
		exit( retval > 1 ? retval : 1 );
	}

	/*	argument check, collect operating parameters	*/
	if ( 0 == _tcsicmp( _T( "--help" ), argv[1] ) ||
			0 == _tcsicmp( _T( "-h" ), argv[1] ) )
	{
		retval = usage();
		exit( retval );
	}
	if ( 0 == _tcsicmp( _T( "-d" ), argv[1] ) ||
			0 == _tcsicmp( _T( "--decode" ), argv[1] ) )
	{
		opmode = E_OPMODE_DECODE;
	}
	else if ( 0 == _tcsicmp( _T( "-e" ), argv[1] ) ||
				0 == _tcsicmp( _T( "--encode" ), argv[1] ) )
	{
		opmode = E_OPMODE_ENCODE;
	}
	else if ( 0 == _tcsncmp( _T( "-" ), argv[1], 1 ) )
	{
		_ftprintf_s( stdout, _T( "%s" ), _T( "error:  parameter not recognized!\n" ) );
		retval = usage();
		exit( retval > 1 ? retval : 1 );
	}

	/*	some operating modes require a filename;	**
	**	for such modes, retrieve it					*/
	if ( E_OPMODE_NONE != opmode )
	{
		if ( 2 >= argc || NULL == argv[2] )
		{
			_ftprintf_s( stdout, _T( "%s" ), _T( "error:  filename parameter not found!\n" ) );
			retval = usage();
			exit( retval > 1 ? retval : 1 );
		}
		pFilename = argv[2];
	}

	/*	a program with more complex parameter sets would	**
	**	further validate its retrieved parameters here;		**
	**	this program is content with existing processing	*/

	/*	do useful work	*/
	switch ( opmode )
	{
		case E_OPMODE_DECODE:
			retval = decode( pFilename );
			break;
		case E_OPMODE_ENCODE:
			retval = encode( pFilename );
			break;
		default:
			/*	this is redundant only until	**
			**	a new operating mode is added	**
			**	to the parameter parsing.		*/
			_ftprintf_s( stdout, _T( "%s" ), _T( "error:  unrecognized operating mode!\n" ) );
			retval = usage();
			exit( retval > 1 ? retval : 1 );
			break;
	}

	/*	done	*/
	exit( retval );
	return retval;
}
Example #6
0
INT cmd_copy(LPTSTR param)
{
    LPTSTR *arg;
    INT argc, i, nFiles, nOverwrite = 0, nSrc = -1, nDes = -1;
    /* this is the path up to the folder of the src and dest ie C:\windows\ */
    TCHAR szDestPath[MAX_PATH];
    TCHAR szSrcPath[MAX_PATH];
    DWORD dwFlags = 0;
    /* If this is the type of copy where we are adding files */
    BOOL bAppend = FALSE;
    WIN32_FIND_DATA findBuffer;
    HANDLE hFile = NULL;
    BOOL bTouch = FALSE;
    /* Used when something like "copy c*.exe d*.exe" during the process of
       figuring out the new name */
    /* Pointer to keep track of how far through the append input(file1+file2+file3) we are */
    TCHAR  * appendPointer = _T("\0");
    /* The full path to src and dest.  This has drive letter, folders, and filename */
    TCHAR tmpDestPath[MAX_PATH];
    TCHAR tmpSrcPath[MAX_PATH];
    /* A bool on weather or not the destination name will be taking from the input */
    BOOL bSrcName = FALSE;
    /* Seems like a waste but it is a pointer used to copy from input to PreserveName */
    TCHAR * UseThisName;
    /* for CMDCOPY env */
    TCHAR *evar;
    int size;
    TCHAR * szTouch;
    BOOL bHasWildcard, bDone = FALSE, bMoreFiles = FALSE;
    BOOL bMultipleSource = FALSE, bMultipleDest = FALSE;


    /* Show help/usage info */
    if (!_tcsncmp(param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE, STRING_COPY_HELP2);
        return 0;
    }

    nErrorLevel = 0;

    /* Get the envor value if it exists */
    evar = cmd_alloc(512 * sizeof(TCHAR));
    if (evar == NULL)
        size = 0;
    else
        size = GetEnvironmentVariable (_T("COPYCMD"), evar, 512);

    if (size > 512)
    {
        TCHAR *old_evar = evar;
        evar = cmd_realloc(evar,size * sizeof(TCHAR) );
        if (evar!=NULL)
            size = GetEnvironmentVariable (_T("COPYCMD"), evar, size);
        else
        {
            size=0;
            evar = old_evar;
        }
    }

    /* check see if we did get any env variable */
    if (size != 0)
    {
        int t = 0;

        /* scan and set the flags */
        for (t = 0; t < size; t++)
        {
            if (_tcsncicmp(_T("/A"),&evar[t],2) == 0)
            {
                dwFlags |=COPY_ASCII;
                t++;
            }
            else if (_tcsncicmp(_T("/B"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_BINARY;
                t++;
            }
            else if (_tcsncicmp(_T("/D"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_DECRYPT;
                t++;
            }
            else if (_tcsncicmp(_T("/V"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_VERIFY;
                t++;
            }
            else if (_tcsncicmp(_T("/N"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_SHORTNAME;
                t++;
            }
            else if (_tcsncicmp(_T("/Y"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_NO_PROMPT;
                t++;
            }
            else if (_tcsncicmp(_T("/-Y"),&evar[t],3) == 0)
            {
                dwFlags |= COPY_PROMPT;
                t+=2;
            }
            else if (_tcsncicmp(_T("/Z"),&evar[t],2) == 0)
            {
                dwFlags |= COPY_PROMPT;
                t++;
            }
        }
    }
    cmd_free(evar);


    /* Split the user input into array */
    arg = split(param, &argc, FALSE, TRUE);
    nFiles = argc;

    /* Read switches and count files */
    for (i = 0; i < argc; i++)
    {
        if (*arg[i] == _T('/'))
        {
            if (_tcslen(arg[i]) >= 2)
            {
                switch (_totupper(arg[i][1]))
                {
                    case _T('A'):
                        dwFlags |= COPY_ASCII;
                        break;

                    case _T('B'):
                        dwFlags |= COPY_BINARY;
                        break;

                    case _T('D'):
                        dwFlags |= COPY_DECRYPT;
                        break;

                    case _T('V'):
                        dwFlags |= COPY_VERIFY;
                        break;

                    case _T('N'):
                        dwFlags |= COPY_SHORTNAME;
                        break;

                    case _T('Y'):
                        dwFlags |= COPY_NO_PROMPT;
                        dwFlags &= ~COPY_PROMPT;
                        break;

                    case _T('-'):
                        if (_tcslen(arg[i]) >= 3)
                            if (_totupper(arg[i][2]) == _T('Y'))
                            {
                                dwFlags &= ~COPY_NO_PROMPT;
                                dwFlags |= COPY_PROMPT;
                            }

                            break;

                    case _T('Z'):
                        dwFlags |= COPY_RESTART;
                        break;

                    default:
                        /* Invalid switch */
                        ConOutResPrintf(STRING_ERROR_INVALID_SWITCH, _totupper(arg[i][1]));
                        nErrorLevel = 1;
                        freep (arg);
                        return 1;
                        break;
                }
            }
            /* If it was a switch, subtract from total arguments */
            nFiles--;
        }
        else
        {
            /* If it isn't a switch then it is the source or destination */
            if (nSrc == -1)
            {
                nSrc = i;
            }
            else if (*arg[i] == _T('+'))
            {
                /* Next file should be appended */
                bMoreFiles = TRUE;
                nFiles -= 1;
            }
            else if (bMoreFiles)
            {
                /* Add this file to the source string
                   this way we can do all checks
                    directly on source string later on */
                TCHAR * ptr;
                int length = (_tcslen(arg[nSrc]) + _tcslen(arg[i]) + 2) * sizeof(TCHAR);
                ptr = cmd_alloc(length);
                if (ptr)
                {
                    _tcscpy(ptr, arg[nSrc]);
                    _tcscat(ptr, _T("|"));
                    _tcscat(ptr, arg[i]);
                    cmd_free(arg[nSrc]);
                    arg[nSrc] = ptr;
                    nFiles -= 1;
                }

                bMoreFiles = FALSE;
            }
            else if (nDes == -1)
            {
                nDes = i;
            }
        }
    }

    /* keep quiet within batch files */
    if (bc != NULL)
    {
        dwFlags |= COPY_NO_PROMPT;
        dwFlags &= ~COPY_PROMPT;
    }

    if (nFiles < 1)
    {
        /* There are not enough files, there has to be at least 1 */
        ConOutResPuts(STRING_ERROR_REQ_PARAM_MISSING);
        freep(arg);
        return 1;
    }

    if (nFiles > 2)
    {
        /* There are too many file names in command */
        ConErrResPrintf(STRING_ERROR_TOO_MANY_PARAMETERS,_T(""));
        nErrorLevel = 1;
        freep(arg);
        return 1;
    }

    if ((_tcschr(arg[nSrc], _T('|')) != NULL) ||
        (_tcschr(arg[nSrc], _T('*')) != NULL) ||
        (_tcschr(arg[nSrc], _T('?')) != NULL) ||
        IsExistingDirectory(arg[nSrc]))
    {
        bMultipleSource = TRUE;
    }

    /* Reusing the number of files variable */
    nFiles = 0;

    /* Check if no destination argument is passed */
    if (nDes == -1)
    {
        /* If no destination was entered then just use
        the current directory as the destination */
        GetCurrentDirectory(MAX_PATH, szDestPath);
    }
    else
    {
        /* Check if the destination is 'x:' */
        if ((arg[nDes][1] == _T(':')) && (arg[nDes][2] == _T('\0')))
        {
            GetRootPath(arg[nDes], szDestPath, MAX_PATH);
        }
        else
        {
            /* If the user entered two file names then form the full string path */
            GetFullPathName(arg[nDes], MAX_PATH, szDestPath, NULL);
        }

        /* Make sure there is an ending slash to the path if the dest is a folder */
        if ((_tcschr(szDestPath, _T('*')) == NULL) &&
            IsExistingDirectory(szDestPath))
        {
            bMultipleDest = TRUE;
            if (szDestPath[_tcslen(szDestPath) -  1] != _T('\\'))
                _tcscat(szDestPath, _T("\\"));
        }

        /* Check if the destination uses wildcards */
        if ((_tcschr(arg[nDes], _T('*')) != NULL) ||
            (_tcschr(arg[nDes], _T('?')) != NULL))
        {
            bMultipleDest = TRUE;
        }
    }

    if (nDes != -1) /* you can only append files when there is a destination */
    {
        if (bMultipleSource && !bMultipleDest)
        {
            /* We have multiple source files, but not multiple destination
               files. This means we are appending the soruce files. */
            bAppend = TRUE;
            if (_tcschr(arg[nSrc], _T('|')) != NULL)
                appendPointer = arg[nSrc];
        }
    }

    /* Save the name the user entered */
    UseThisName = _tcsrchr(szDestPath,_T('\\'));
    if (UseThisName)
    {
        /* Split the name from the path */
        *UseThisName++ = _T('\0');

        /* Check if the dest path ends with '\*' or '\' */
        if (((UseThisName[0] == _T('*')) && (UseThisName[1] == _T('\0'))) ||
            (UseThisName[0] == _T('\0')))
        {
            /* In this case we will be using the same name as the source file
            for the destination file because destination is a folder */
            bSrcName = TRUE;
            UseThisName = NULL;
        }
    }
    else
    {
        /* Something's seriously wrong! */
        UseThisName = szDestPath;
    }

    do
    {
        /* Get the full string of the path to the source file */
        if (_tcschr(arg[nSrc], _T('|')) != NULL)
        {
            /* Reset the source path */
            szSrcPath[0] = _T('\0');

            /* Loop through the source file name and copy all
            the chars one at a time until it gets too + */
            while(TRUE)
            {
                if (appendPointer[0] == _T('|'))
                {
                    /* Skip the | and go to the next file name */
                    appendPointer++;
                    break;
                }
                else if (appendPointer[0] == _T('\0'))
                {
                    bDone = TRUE;
                    break;
                }

                _tcsncat(szSrcPath, appendPointer, 1);
                appendPointer++;
            }

            if (_tcschr(arg[nSrc], _T(',')) != NULL)
            {
                /* Only time there is a , in the source is when they are using touch
                   Cant have a destination and can only have on ,, at the end of the string
                    Cant have more then one file name */
                szTouch = _tcsstr(arg[nSrc], _T("|"));
                if (_tcsncmp(szTouch,_T("|,,\0"), 4) || (nDes != -1))
                {
                    ConErrResPrintf(STRING_ERROR_INVALID_PARAM_FORMAT,arg[nSrc]);
                    nErrorLevel = 1;
                    freep (arg);
                    return 1;
                }
                bTouch = TRUE;
                bDone = TRUE;
            }
        }
        else
        {
            bDone = TRUE;
            _tcscpy(szSrcPath, arg[nSrc]);
        }

        /* "x:" is not a valid source path format. */
        if ((szSrcPath[1] == _T(':')) && (szSrcPath[2] == _T('\0')))
        {
            ConOutPrintf(_T("%s\n"), szSrcPath);
            ConOutFormatMessage(ERROR_FILE_NOT_FOUND, szSrcPath);
            nErrorLevel = 1;
            break;
        }


        /* From this point on, we can assume that the shortest path is 3 letters long
        and that would be [DriveLetter]:\ */

        /* Check if the path has a wildcard */
        bHasWildcard = (_tcschr(szSrcPath, _T('*')) != NULL);

        /* If there is no * in the path name and it is a folder then we will
           need to add a wildcard to the pathname so FindFirstFile comes up
           with all the files in that folder */
        if (!bHasWildcard && IsExistingDirectory(szSrcPath))
        {
            /* If it doesnt have a \ at the end already then on needs to be added */
            if (szSrcPath[_tcslen(szSrcPath) -  1] != _T('\\'))
                _tcscat(szSrcPath, _T("\\"));
            _tcscat(szSrcPath, _T("*"));
            bHasWildcard = TRUE;
        }

        /* If the path ends with '\' add a wildcard at the end */
        if (szSrcPath[_tcslen(szSrcPath) -  1] == _T('\\'))
        {
            _tcscat(szSrcPath, _T("*"));
            bHasWildcard = TRUE;
        }

        /* Get a list of all the files */
        hFile = FindFirstFile(szSrcPath, &findBuffer);

        /* If it couldnt open the file handle, print out the error */
        if (hFile == INVALID_HANDLE_VALUE)
        {
            /* only print source name when more then one file */
            if (bMultipleSource)
                ConOutPrintf(_T("%s\n"), szSrcPath);

            ConOutFormatMessage(GetLastError(), szSrcPath);
            freep(arg);
            nErrorLevel = 1;
            return 1;
        }

        /* Strip the paths back to the folder they are in */
        for (i = (_tcslen(szSrcPath) -  1); i > -1; i--)
            if (szSrcPath[i] != _T('\\'))
                szSrcPath[i] = _T('\0');
            else
                break;

        do
        {
            /* Check Breaker */
            if (CheckCtrlBreak(BREAK_INPUT))
            {
                FindClose(hFile);
                freep(arg);
                return 1;
            }

            /* Set the override to yes each new file */
            nOverwrite = 1;

            /* Ignore the . and .. files */
            if (!_tcscmp(findBuffer.cFileName, _T("."))  ||
                !_tcscmp(findBuffer.cFileName, _T("..")) ||
                findBuffer.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                continue;
            }

            /* Copy the base folder over to a tmp string */
            _tcscpy(tmpDestPath, szDestPath);
            _tcscat(tmpDestPath, _T("\\"));

            /* Can't put a file into a folder that isn't there */
            if (_tcscmp(tmpDestPath, _T("\\\\.\\")) &&
                !IsExistingDirectory(tmpDestPath))
            {
                FindClose(hFile);
                ConOutFormatMessage(GetLastError(), szSrcPath);
                freep(arg);
                nErrorLevel = 1;
                return 1;
            }

            /* Copy over the destination path name */
            if (bSrcName)
                _tcscat(tmpDestPath, findBuffer.cFileName);
            else
            {
                /* If there is no wildcard you can use the name the user entered */
                if ((_tcschr(UseThisName, _T('*')) == NULL) &&
                    (_tcschr(UseThisName, _T('?')) == NULL))
                {
                    _tcscat(tmpDestPath, UseThisName);
                }
                else
                {
                    TCHAR DoneFile[MAX_PATH];

                    BuildFileName(findBuffer.cFileName,
                                  UseThisName,
                                  DoneFile);


                    /* Add the filename to the tmp string path */
                    _tcscat(tmpDestPath, DoneFile);
                }
            }

            /* Build the string path to the source file */
            _tcscpy(tmpSrcPath,szSrcPath);
            _tcscat (tmpSrcPath, findBuffer.cFileName);

            /* Check to see if the file is the same file */
            if (!bTouch && !_tcscmp(tmpSrcPath, tmpDestPath))
            {
                ConOutResPrintf(STRING_COPY_ERROR2);

                nErrorLevel = 1;
                break;
            }

            /* only print source name when more then one file */
            if (bMultipleSource)
                ConOutPrintf(_T("%s\n"), tmpSrcPath);

            /* Handle any overriding / prompting that needs to be done */
            if (((!(dwFlags & COPY_NO_PROMPT) && IsExistingFile (tmpDestPath)) || dwFlags & COPY_PROMPT) && !bTouch)
                nOverwrite = CopyOverwrite(tmpDestPath);
            if (nOverwrite == PROMPT_NO || nOverwrite == PROMPT_BREAK)
                continue;
            if (nOverwrite == PROMPT_ALL || (nOverwrite == PROMPT_YES && bAppend))
                dwFlags |= COPY_NO_PROMPT;

            /* Tell weather the copy was successful or not */
            if (copy(tmpSrcPath,tmpDestPath, bAppend, dwFlags, bTouch))
            {
                nFiles++;
                //LoadString(CMD_ModuleHandle, STRING_MOVE_ERROR1, szMsg, RC_STRING_MAX_SIZE);
            }
            else
            {
                /* print out the error message */
                ConOutResPrintf(STRING_COPY_ERROR3);
                ConOutFormatMessage (GetLastError(), szSrcPath);
                nErrorLevel = 1;
            }

        /* Loop through all wildcard files */
        } while (FindNextFile(hFile, &findBuffer));

    /* Loop through all files in src string with a + */
    } while(!bDone);

    /* print out the number of files copied */
    ConOutResPrintf(STRING_COPY_FILE, bAppend ? 1 : nFiles);

    if (hFile) FindClose(hFile);

    if (arg != NULL)
        freep(arg);

    return 0;
}
Example #7
0
INT cmd_replace (LPTSTR param)
{
	LPTSTR *arg;
	INT argc, i,filesReplaced = 0, nFiles, srcIndex = -1, destIndex = -1;
	DWORD dwFlags = 0;
	TCHAR szDestPath[MAX_PATH], szSrcPath[MAX_PATH], tmpSrcPath[MAX_PATH];
	BOOL doMore = TRUE;

	/* Help wanted? */
	if (!_tcsncmp (param, _T("/?"), 2))
	{
		ConOutResPaging(TRUE,STRING_REPLACE_HELP1);
		return 0;
	}

	/* Divide the argument in to an array of c-strings */
	arg = split (param, &argc, FALSE);
	nFiles = argc;

	/* Read options */
	for (i = 0; i < argc; i++)
	{
		if (arg[i][0] == _T('/'))
		{
			if (_tcslen(arg[i]) == 2)
			{
				switch (_totupper(arg[i][1]))
				{
				case _T('A'):
					dwFlags |= REPLACE_ADD;
					break;
				case _T('P'):
					dwFlags |= REPLACE_CONFIRM;
					break;
				case _T('R'):
					dwFlags |= REPLACE_READ_ONLY;
					break;
				case _T('S'):
					dwFlags |= REPLACE_SUBDIR;
					break;
				case _T('W'):
					dwFlags |= REPLACE_DISK;
					break;
				case _T('U'):
					dwFlags |= REPLACE_UPDATE;
					break;
				default:
					invalid_switch(arg[i]);
					return 0;
				}
			}
			else
			{
				invalid_switch(arg[i]);
				freep(arg);
				return 0;
			}
			nFiles--;
		}
		else
		{
			if(srcIndex == -1)
			{
				srcIndex = i;
			}
			else if(destIndex == -1)
			{
				destIndex = i;
			}
			else
			{
				invalid_switch(arg[i]);
				freep(arg);
				return 0;
			}
		}
	}

	/* See so that at least source is there */
	if (nFiles < 1)
	{
		ConOutResPaging(TRUE,STRING_REPLACE_HELP2);
		ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
		freep(arg);
		return 1;
	}
	/* Check so that not both update and add switch is added and subdir */
	if((dwFlags & REPLACE_UPDATE || dwFlags & REPLACE_SUBDIR) && (dwFlags & REPLACE_ADD))
	{
		ConOutResPaging(TRUE,STRING_REPLACE_ERROR4);
		ConOutResPaging(TRUE,STRING_REPLACE_HELP7);
		freep(arg);
		return 1;
	}

	/* If we have a destination get the full path */
	if(destIndex != -1)
	{
		if(_tcslen(arg[destIndex]) == 2 && arg[destIndex][1] == ':')
			GetRootPath(arg[destIndex],szDestPath,MAX_PATH);
		else
		{
			/* Check for wildcards in destination directory */
			if (_tcschr (arg[destIndex], _T('*')) != NULL ||
				_tcschr (arg[destIndex], _T('?')) != NULL)
			{
				ConOutResPrintf(STRING_REPLACE_ERROR2,arg[destIndex]);
				ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
				freep(arg);
				return 1;
			}
			getPath(szDestPath, arg[destIndex]);
			/* Make sure that destination exists */
			if(!IsExistingDirectory(szDestPath))
			{
				ConOutResPrintf(STRING_REPLACE_ERROR2, szDestPath);
				ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
				freep(arg);
				return 1;
			}
		}
	}
	else
	{
		/* Dest is current dir */
		GetCurrentDirectory(MAX_PATH,szDestPath);
	}

	/* Get the full source path */
	if(!(_tcslen(arg[srcIndex]) == 2 && arg[srcIndex][1] == ':'))
		getPath(szSrcPath, arg[srcIndex]);
	else
 		_tcscpy(szSrcPath,arg[srcIndex]);

	/* Source does not have wildcards */
	if (_tcschr (arg[srcIndex], _T('*')) == NULL &&
		_tcschr (arg[srcIndex], _T('?')) == NULL)
	{
		/* Check so that source is not a directory, because that is not allowed */
		if(IsExistingDirectory(szSrcPath))
		{
			ConOutResPrintf(STRING_REPLACE_ERROR6, szSrcPath);
			ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
			freep(arg);
			return 1;
		}
		/* Check if the file exists */
		if(!IsExistingFile(szSrcPath))
		{
			ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
			freep(arg);
			return 1;
		}
	}
	/* /w switch is set so wait for any key to be pressed */
	if(dwFlags & REPLACE_DISK)
	{
		msg_pause();
		cgetchar();
	}

	/* Add an extra \ to the destination path if needed */
	if(szDestPath[_tcslen(szDestPath) -  1] != _T('\\'))
		_tcscat(szDestPath, _T("\\"));

	/* Save source path */
	_tcscpy(tmpSrcPath,szSrcPath);
	/* Replace in dest dir */
	filesReplaced += recReplace(dwFlags, tmpSrcPath, szDestPath, &doMore);
	/* If subdir switch is set replace in the subdirs to */
	if(dwFlags & REPLACE_SUBDIR && doMore)
	{
		filesReplaced += recFindSubDirs(dwFlags, szSrcPath,  szDestPath, &doMore);
	}

	/* If source == dest write no more */
	if(filesReplaced != -1)
	{
		/* No files replaced */
		if(filesReplaced==0)
		{
			/* Add switch dependent output */
			if(dwFlags & REPLACE_ADD)
				ConOutResPaging(TRUE,STRING_REPLACE_HELP7);
			else
				ConOutResPaging(TRUE,STRING_REPLACE_HELP3);
		}
		/* Some files replaced */
		else
		{
			/* Add switch dependent output */
			if(dwFlags & REPLACE_ADD)
				ConOutResPrintf(STRING_REPLACE_HELP8, filesReplaced);
			else
				ConOutResPrintf(STRING_REPLACE_HELP4, filesReplaced);
		}
	}
	/* Return memory */
	freep(arg);
	return 1;
}
Example #8
0
void GetDataValue(WIDATAITEM *UpdateData, TCHAR *Data, TCHAR** szData)
{
	TCHAR last = 0, current, *start, *end;
	unsigned startloc = 0, endloc = 0, respos = 0;
	BOOL tag = FALSE, symb = FALSE;
	TCHAR *szInfo = *szData;

	Data[0] = 0;
	// parse the data if available
	if (UpdateData->Start[0] == 0 && UpdateData->End[0] == 0) return;
	start = szInfo;
	// the start string must be found
	if (UpdateData->Start[0] != 0) {
		start = _tcsstr(szInfo, UpdateData->Start);
		if (start != NULL) {
			// set the starting location for getting data
			start += mir_tstrlen(UpdateData->Start);
			szInfo = start;
		}
	}

	// the end string must be found too
	if (UpdateData->End[0] != 0)
		end = _tcsstr(szInfo, UpdateData->End);
	else
		end = _tcsstr(szInfo, _T(" "));

	if (end != NULL) {
		// set the ending location
		startloc = 0;
		endloc = end - szInfo;
		end += mir_tstrlen(UpdateData->End);
		last = '\n';
	}

	// ignore if not both of the string found - this prevent crashes
	if (start != NULL && end != NULL) {
		// begin reading the data from start location to end location
		// remove all HTML tag in between, as well as leading space, ending space,
		// multiple spaces, tabs, and return key
		while (startloc < endloc) {
			if (szInfo[startloc] == '<')	tag = TRUE;
			else if (szInfo[startloc] == '&' &&
				(szInfo[startloc + 1] == ';' || szInfo[startloc + 2] == ';' || szInfo[startloc + 3] == ';' ||
					szInfo[startloc + 4] == ';' || szInfo[startloc + 5] == ';' || szInfo[startloc + 6] == ';')) {
				// ...but do NOT strip &minus;
				if ((endloc - startloc) > 7 && _tcsncmp(szInfo + startloc, _T("&minus;"), 7) == 0) {
					Data[respos++] = '-';
					startloc += 7;
					continue;
				}
				symb = TRUE;
			}
			else if (szInfo[startloc] == '>')	tag = FALSE;
			else if (szInfo[startloc] == ';')	symb = FALSE;
			else {
				if (!tag && !symb) {
					current = szInfo[startloc];
					if (current == '\n' || current == '\t' || current == '	' || current == '\r')
						current = ' ';
					if (current != ' ' || last != ' ') {
						if (last != '\n' && (respos != 0 || (respos == 0 && last != ' ')))
							Data[respos++] = last;
						last = current;
					}
				}
			}
			++startloc;
			// prevent crashes if the string go over maximun length -> generate an error
			if (respos >= MAX_DATA_LEN) {
				if (opt.ShowWarnings && UpdateData->Name[0] != 0 && mir_tstrcmp(UpdateData->Name, _T("Ignore"))) {
					mir_sntprintf(Data, MAX_DATA_LEN, TranslateT("Error when obtaining data: %s"), UpdateData->Name);
					WPShowMessage(Data, SM_WARNING);
				}
				_tcsncpy(Data, TranslateT("<Error>"), MAX_DATA_LEN);
				last = ' ';
				respos = MAX_DATA_LEN - 1;
				break;
			}
		}

		// get the last character
		if (last != ' ')
			Data[respos++] = last;

		// null terminate the string
		Data[respos] = 0;

		// convert the unit
		ConvertDataValue(UpdateData, Data);

		// remove the string before the data from szInfo
		szInfo = end;
	}
	*szData = szInfo;
}
Example #9
0
INT CommandAttrib (LPTSTR param)
{
	LPTSTR *arg;
	INT    argc, i;
	TCHAR  szPath[MAX_PATH];
	TCHAR  szFileName [MAX_PATH];
	BOOL   bRecurse = FALSE;
	BOOL   bDirectories = FALSE;
	DWORD  dwAttrib = 0;
	DWORD  dwMask = 0;

	/* initialize strings */
	szPath[0] = _T('\0');
	szFileName[0] = _T('\0');

	/* print help */
	if (!_tcsncmp (param, _T("/?"), 2))
	{
		ConOutResPaging(TRUE,STRING_ATTRIB_HELP);
		return 0;
	}

  nErrorLevel = 0;

	/* build parameter array */
	arg = split (param, &argc, FALSE);

	/* check for options */
	for (i = 0; i < argc; i++)
	{
		if (_tcsicmp (arg[i], _T("/s")) == 0)
			bRecurse = TRUE;
		else if (_tcsicmp (arg[i], _T("/d")) == 0)
			bDirectories = TRUE;
	}

	/* create attributes and mask */
	for (i = 0; i < argc; i++)
	{
		if (*arg[i] == _T('+'))
		{
			if (_tcslen (arg[i]) != 2)
			{
				error_invalid_parameter_format (arg[i]);
				freep (arg);
				return -1;
			}

			switch ((TCHAR)_totupper (arg[i][1]))
			{
				case _T('A'):
					dwMask   |= FILE_ATTRIBUTE_ARCHIVE;
					dwAttrib |= FILE_ATTRIBUTE_ARCHIVE;
					break;

				case _T('H'):
					dwMask   |= FILE_ATTRIBUTE_HIDDEN;
					dwAttrib |= FILE_ATTRIBUTE_HIDDEN;
					break;

				case _T('R'):
					dwMask   |= FILE_ATTRIBUTE_READONLY;
					dwAttrib |= FILE_ATTRIBUTE_READONLY;
					break;

				case _T('S'):
					dwMask   |= FILE_ATTRIBUTE_SYSTEM;
					dwAttrib |= FILE_ATTRIBUTE_SYSTEM;
					break;

				default:
					error_invalid_parameter_format (arg[i]);
					freep (arg);
					return -1;
			}
		}
		else if (*arg[i] == _T('-'))
		{
			if (_tcslen (arg[i]) != 2)
			{
				error_invalid_parameter_format (arg[i]);
				freep (arg);
				return -1;
			}

			switch ((TCHAR)_totupper (arg[i][1]))
			{
				case _T('A'):
					dwMask   |= FILE_ATTRIBUTE_ARCHIVE;
					dwAttrib &= ~FILE_ATTRIBUTE_ARCHIVE;
					break;

				case _T('H'):
					dwMask   |= FILE_ATTRIBUTE_HIDDEN;
					dwAttrib &= ~FILE_ATTRIBUTE_HIDDEN;
					break;

				case _T('R'):
					dwMask   |= FILE_ATTRIBUTE_READONLY;
					dwAttrib &= ~FILE_ATTRIBUTE_READONLY;
					break;

				case _T('S'):
					dwMask   |= FILE_ATTRIBUTE_SYSTEM;
					dwAttrib &= ~FILE_ATTRIBUTE_SYSTEM;
					break;

				default:
					error_invalid_parameter_format (arg[i]);
					freep (arg);
					return -1;
			}
		}
	}

	if (argc == 0)
	{
		DWORD len;

		len = GetCurrentDirectory (MAX_PATH, szPath);
		if (szPath[len-1] != _T('\\'))
		{
			szPath[len] = _T('\\');
			szPath[len + 1] = 0;
		}
		_tcscpy (szFileName, _T("*.*"));
		PrintAttribute (szPath, szFileName, bRecurse);
		freep (arg);
		return 0;
	}

	/* get full file name */
	for (i = 0; i < argc; i++)
	{
		if ((*arg[i] != _T('+')) && (*arg[i] != _T('-')) && (*arg[i] != _T('/')))
		{
			LPTSTR p;
			GetFullPathName (arg[i], MAX_PATH, szPath, NULL);
			p = _tcsrchr (szPath, _T('\\')) + 1;
			_tcscpy (szFileName, p);
			*p = _T('\0');

			if (dwMask == 0)
				PrintAttribute (szPath, szFileName, bRecurse);
			else
				ChangeAttribute (szPath, szFileName, dwMask,
						 dwAttrib, bRecurse, bDirectories);
		}
	}

	freep (arg);
	return 0;
}
Example #10
0
//
/// Internal routine used to match a portion of a filename (i.e. name or
/// extension) to a wilcard pattern.
//
static bool
nameMatch(LPCTSTR name, LPCTSTR wc)
{
  while (true) {
    //if (*wc == _T('*') || (!*wc && !*name))
    // Greg Bullock suggestion
    if ((*wc == _T('*') && (wc[1] == _T('\0'))) || (!*wc && !*name))
      return true;
    if (*wc == _T('*')) {
      // The wildcard string begins with '*' but ends with something else (e.g., "*~")
      // We'll need to verify that the ending of name matches the wildcard string.
      wc++;
      size_t namelen = _tcslen(name);
      size_t wclen = _tcslen(wc);
      if (namelen > wclen)
        name += namelen - wclen;
    }
#if defined(BI_DBCS_SUPPORT)
    int n = CharSize(name);
    if (*wc == _T('?') && *name) {
      wc++;
      name += n;
      continue;
    }
    else if (n > 1) { // if double byte character
      if (_tcsncmp(name, wc, n) == 0) {
        wc += n;
        name += n;
        continue;
      }
    }
    else if (_totupper(*name) == _totupper(*wc)) {
#else
    if ((*wc == _T('?') && *name) || (_totupper(*name) == _totupper(*wc))) {
#endif
      wc++;
      name++;
      continue;
    }
    break;
  }
  return false;
}

//
/// Helper function used by 'MatchTemplate'. Returns true if the specified file name
/// (path) matches the pattern of the 'filter' parameter. Returns false otherwise.
//
bool
TDocManager::IsAMatch(LPCTSTR path, LPCTSTR fltr)
{
  PRECONDITION(path);
  PRECONDITION(fltr);

  // Ensure path has at least a valid file name
  //
  TFileName fname(path);
  if (!fname.HasParts(TFileName::File)) {
    TRACEX(OwlDocView, 0, _T("IsAMatch: Invoked with invalid path"));
    return false;
  }

  // Retrieve name/extension from path
  //
  tstring name = fname.GetParts(TFileName::File);
  tstring ext  = fname.GetParts(TFileName::Ext);

  // Get pointers to path's name and extension
  //
  LPCTSTR ppn = name.c_str();
  LPCTSTR ppe = fname.HasParts(TFileName::Ext) ? ext.c_str() : _T("");
  if (*ppe == _T('.'))
    ppe++;

  // Get pointers to filter's name and extension
  //
  TAPointer<tchar> filter(nstrnewdup(fltr));
  tchar* pfn = filter;
  tchar* pfe = _tcsrchr(filter, _T('.'));

  // Skip past '.' separator of filter
  //
  if (pfe)
    *pfe++ = 0;
  const tchar* const cpfe = pfe ? pfe : _T("");

  // Match the name and extension
  //
  return nameMatch(ppn, pfn) && nameMatch(ppe, cpfe);
}
Example #11
0
/**
 * Returns TRUE on success, FALSE otherwise. To get extended error
 * information, call GetLastError.
 *
 * ERRORS:
 *   ERROR_DLL_INIT_FAILED
 *   ERROR_OUTOFMEMORY was not possible to get mappings.
 *   ERROR_INVALID_DATA was not possible to add the device.
 */
BOOL DefineCommDevice(/* DWORD dwFlags,*/ LPCTSTR lpDeviceName,
        LPCTSTR lpTargetPath)
{
	int i = 0;
	LPTSTR storedDeviceName = NULL;
	LPTSTR storedTargetPath = NULL;

	if (!CommInitialized())
		return FALSE;

	EnterCriticalSection(&_CommDevicesLock);

	if (_CommDevices == NULL)
	{
		SetLastError(ERROR_DLL_INIT_FAILED);
		goto error_handle;
	}

	if (_tcsncmp(lpDeviceName, _T("\\\\.\\"), 4) != 0)
	{
		if (!_IsReservedCommDeviceName(lpDeviceName))
		{
			SetLastError(ERROR_INVALID_DATA);
			goto error_handle;
		}
	}

	storedDeviceName = _tcsdup(lpDeviceName);

	if (storedDeviceName == NULL)
	{
		SetLastError(ERROR_OUTOFMEMORY);
		goto error_handle;
	}

	storedTargetPath = _tcsdup(lpTargetPath);

	if (storedTargetPath == NULL)
	{
		SetLastError(ERROR_OUTOFMEMORY);
		goto error_handle;
	}

	for (i = 0; i < COMM_DEVICE_MAX; i++)
	{
		if (_CommDevices[i] != NULL)
		{
			if (_tcscmp(_CommDevices[i]->name, storedDeviceName) == 0)
			{
				/* take over the emplacement */
				free(_CommDevices[i]->name);
				free(_CommDevices[i]->path);
				_CommDevices[i]->name = storedDeviceName;
				_CommDevices[i]->path = storedTargetPath;
				break;
			}
		}
		else
		{
			/* new emplacement */
			_CommDevices[i] = (COMM_DEVICE*)calloc(1, sizeof(COMM_DEVICE));

			if (_CommDevices[i] == NULL)
			{
				SetLastError(ERROR_OUTOFMEMORY);
				goto error_handle;
			}

			_CommDevices[i]->name = storedDeviceName;
			_CommDevices[i]->path = storedTargetPath;
			break;
		}
	}

	if (i == COMM_DEVICE_MAX)
	{
		SetLastError(ERROR_OUTOFMEMORY);
		goto error_handle;
	}

	LeaveCriticalSection(&_CommDevicesLock);
	return TRUE;
error_handle:
	free(storedDeviceName);
	free(storedTargetPath);
	LeaveCriticalSection(&_CommDevicesLock);
	return FALSE;
}
Example #12
0
int GCEventHook(WPARAM wParam,LPARAM lParam) {
	GCHOOK *gch = (GCHOOK*) lParam;
	gchat_contacts *gc = GetChat(gch->pDest->ptszID);

	UNREFERENCED_PARAMETER(wParam);

	if(gch) {
		if (!_stricmp(gch->pDest->pszModule, SKYPE_PROTONAME)) {

			switch (gch->pDest->iType) {
			case GC_SESSION_TERMINATE: {
				MCONTACT hContact;

				if (gc->mJoinedCount == 1) {
					// switch back to normal session
                    // I don't know if this behaviour isn't a bit annoying, therefore, we
					// don't do this now, until a user requests this feature :)
                    
					// open up srmm dialog when quit while 1 person left
//					CallService(MS_MSG_SENDMESSAGE, (WPARAM)gc->mJoinedContacts[0].hContact, 0);

					RemChatContact(gc, gc->mJoinedContacts[0].who);
				}
				// Delete Chatroom from Contact list, as we don't need it anymore...?
				if (hContact = find_chat(gc->szChatName))
					CallService(MS_DB_CONTACT_DELETE, hContact, 0); 
				RemChat(gc->szChatName);

				break;
			}
			case GC_USER_MESSAGE:
				if(gch && gch->ptszText && _tcslen(gch->ptszText) > 0) {
					DBVARIANT dbv, dbv2;
					CCSDATA ccs = {0};
					TCHAR *pEnd;

					// remove the ending linebreak
					for (pEnd = &gch->ptszText[_tcslen(gch->ptszText) - 1];
						 *pEnd==_T('\r') || *pEnd==_T('\n'); pEnd--) *pEnd=0;
                    // Send message to the chat-contact    
					if (ccs.hContact = find_chat(gch->pDest->ptszID)) {
#ifdef _UNICODE
						// If PREF_UTF is supported, just convert it to UTF8 and pass the buffer to PSS_MESSAGE
						if (mirandaVersion >= 0x070000) {
							ccs.lParam = (LPARAM)make_utf8_string(gch->ptszText);
							ccs.wParam = PREF_UTF;
							CallProtoService (SKYPE_PROTONAME, PSS_MESSAGE, 0, (LPARAM)&ccs);
							free ((void*)ccs.lParam);
						} else {
						// Otherwise create this strange dual miranda-format
							ccs.lParam = (LPARAM)calloc(3, _tcslen(gch->ptszText)+1);
							wcstombs ((char*)ccs.lParam, gch->ptszText, _tcslen(gch->ptszText)+1);
							_tcscpy ((TCHAR*)((char*)ccs.lParam+strlen((char*)ccs.lParam)+1), gch->ptszText);
							ccs.wParam = PREF_UNICODE;
							CallProtoService (SKYPE_PROTONAME, PSS_MESSAGE, 0, (LPARAM)&ccs);
							free ((void*)ccs.lParam);
						}
#else
						ccs.lParam = (LPARAM)gch->ptszText;
						ccs.wParam = PREF_TCHAR;
						CallProtoService (SKYPE_PROTONAME, PSS_MESSAGE, 0, (LPARAM)&ccs);
#endif
					}

					// Add our line to the chatlog	
					GCDEST gcd = { gch->pDest->pszModule, gch->pDest->ptszID, 0 };
					GCEVENT gce = { sizeof(gce), &gcd };
					if ( _tcsncmp(gch->ptszText, _T("/me "), 4)==0 && _tcslen(gch->ptszText)>4) {
						gce.ptszText = gch->ptszText+4;
						gcd.iType = GC_EVENT_ACTION;
					}
					else {
						gce.ptszText = gch->ptszText;
						gcd.iType = GC_EVENT_MESSAGE;
					}

					if (db_get_ts(NULL, SKYPE_PROTONAME, "Nick", &dbv))
						gce.ptszNick = TranslateT("Me");
					else
						gce.ptszNick = dbv.ptszVal;
					db_get_ts(NULL, SKYPE_PROTONAME, SKYPE_NAME, &dbv2);
					gce.ptszUID = dbv2.ptszVal;
					gce.time = (DWORD)time(NULL);
					gce.dwFlags = GCEF_ADDTOLOG;
					gce.bIsMe = TRUE;
					CallService(MS_GC_EVENT, 0, (LPARAM)&gce);
					if (dbv.pszVal) db_free(&dbv);
					if (dbv2.pszVal) db_free(&dbv2);
				}
				break;
			case GC_USER_CHANMGR:
				InviteUser(gch->pDest->ptszID);
				break;
			case GC_USER_PRIVMESS: {
				MCONTACT hContact = find_contactT(gch->ptszUID);
				if (hContact) CallService(MS_MSG_SENDMESSAGE, hContact, 0);
				break;

			}
			case GC_USER_LOGMENU:
				switch(gch->dwData) {
				case 10: InviteUser(gch->pDest->ptszID); break;
				case 20: KillChatSession(gch->pDest); break;
                case 30: 
					{
						TCHAR *ptr, buf[MAX_BUF];

						ptr = SkypeGetT ("CHAT", (TCHAR*)gch->pDest->ptszID, "TOPIC");
						_tcscpy(buf, ptr);
						free(ptr);
						if (DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_INPUTBOX), NULL, InputBoxDlgProc, (LPARAM)&buf))
							SetChatTopic(gch->pDest->ptszID, buf, TRUE);
						break;
					}
				}
				break;
			case GC_USER_NICKLISTMENU: {
				MCONTACT hContact = find_contactT(gch->ptszUID);

				switch(gch->dwData) {
				case 10:CallService(MS_USERINFO_SHOWDIALOG, hContact, 0); break;
				case 20:CallService(MS_HISTORY_SHOWCONTACTHISTORY, hContact, 0); break;
				case 30: KickUser(hContact, gch); break;
				case 110: KillChatSession(gch->pDest); break;
				}
				break;
			}			
			default:
				break;
			}
		}

	}
	return 0;
}
Example #13
0
// returns -1 if error, or the WpFileType 
int ReadWayPointFile(ZZIP_FILE *fp, TCHAR *CurrentWpFileName)
{
  WAYPOINT *new_waypoint;
  TCHAR szTemp[100];
  DWORD fSize, fPos=0;
  int nLineNumber=0;
  short fileformat=LKW_DAT;

  HWND hProgress;

  hProgress = CreateProgressDialog(gettext(TEXT("_@M903_"))); // Loading Waypoints File...

  fSize = zzip_file_size(fp);

  fileformat=GetWaypointFileFormatType(CurrentWpFileName);

  if (fileformat<0) {
	StartupStore(_T("... Unknown file format in waypoint file <%s\n"),CurrentWpFileName);
	// We do NOT return, because first we analyze the content.
  }

  if (fSize <10) {
	StartupStore(_T("... ReadWayPointFile: waypoint file %s type=%d is empty%s"), CurrentWpFileName,fileformat,NEWLINE);
	return -1;
  }

  if (!AllocateWaypointList()) {
	StartupStore(_T("!!!!!! ReadWayPointFile: AllocateWaypointList FAILED%s"),NEWLINE);
	return -1;
  }

  new_waypoint = WayPointList+NumberOfWayPoints;


  memset(nTemp2String, 0, sizeof(nTemp2String)); // clear Temp Buffer

  // check file format
  bool fempty=true;
  int  slen=0; // 100204 WIP
  while ( ReadString(fp,READLINE_LENGTH,nTemp2String) ) {
	slen=_tcslen(nTemp2String);
	if (slen<1) continue;
	if ( _tcsncmp(_T("G  WGS 84"),nTemp2String,9) == 0 ||
	   _tcsncmp(_T("G WGS 84"),nTemp2String,8) == 0 ||
	   // consider UCS header, 3 bytes in fact. This is a workaround.
	   _tcsncmp(_T("G  WGS 84"),&nTemp2String[3],9) == 0) {
		if ( !ReadString(fp,READLINE_LENGTH,nTemp2String) ) {
			StartupStore(_T(". Waypoint file %d format: CompeGPS truncated, rejected%s"),globalFileNum+1,NEWLINE);
			return -1;
		}
		slen=_tcslen(nTemp2String);
		if (slen<1) {
			StartupStore(_T(". Waypoint file %d format: CompeGPS MISSING second U line, rejected%s"),globalFileNum+1,NEWLINE);
			return -1;
		}
		if ( (_tcsncmp(_T("U  0"),nTemp2String,4) == 0) ||
		     (_tcsncmp(_T("U 0"),nTemp2String,3) == 0)) {
			StartupStore(_T(". Waypoint file %d format: CompeGPS with UTM coordinates UNSUPPORTED%s"),globalFileNum+1,NEWLINE);
			return -1;
		}
		if ( _tcsncmp(_T("U  1"),nTemp2String,4) != 0 && 
		     _tcsncmp(_T("U 1"),nTemp2String,3) != 0 ) {
			StartupStore(_T(". Waypoint file %d format: CompeGPS unknown U field, rejected%s"),globalFileNum+1,NEWLINE);
			return -1;
		}
		
		StartupStore(_T(". Waypoint file %d format: CompeGPS, LatLon coordinates%s"),globalFileNum+1,NEWLINE);
		fempty=false;
		fileformat=LKW_COMPE;
		break;
	}
	if ( (_tcsncmp(_T("name,code,country"),nTemp2String,17) == 0) || 
		(_tcsncmp(_T("Title,Code,Country"),nTemp2String,18) == 0)  // 100314
	) {
		StartupStore(_T(". Waypoint file %d format: SeeYou%s"),globalFileNum+1,NEWLINE);
		fempty=false;
		fileformat=LKW_CUP;
		break;
	}

	if ( ( _tcsstr(nTemp2String, _T("OziExplorer Waypoint File")) == nTemp2String )||
			   // consider UCS header, 3 bytes in fact. This is a workaround.
			(_tcsstr(&nTemp2String[3], _T("OziExplorer Waypoint File")) == &nTemp2String[3]) ) {
		StartupStore(_T(". Waypoint file %d format: OziExplorer%s"),globalFileNum+1,NEWLINE);
		fempty=false;
		fileformat=LKW_OZI;
		break;
	}

	// consider also the case of empty file, when a waypoint if saved starting with numbering after
	// the virtual wps (including the 0);
	// Warning, using virtualdatheader 3 tcsncmp because virtuals are now more than 9.
	TCHAR virtualdatheader[5];
	_stprintf(virtualdatheader,_T("%d,"),RESWP_END+2);
	if ( _tcsncmp(_T("1,"),nTemp2String,2) == 0 ||
	  _tcsncmp(virtualdatheader,nTemp2String,3) == 0) {
		StartupStore(_T(". Waypoint file %d format: WinPilot%s"),globalFileNum+1,NEWLINE);
		fempty=false;
		fileformat=LKW_DAT;
		break;
	}
	// Otherwise we use the fileformat .xxx suffix. 
	// Why we did not do it since the beginning? Simply because we should not rely on .xxx suffix
	// because some formats like CompeGPS and OZI, for example, share the same .WPT suffix.
	// 
	if (fileformat<0) {
		StartupStore(_T(".. Unknown WP header, unknown format in <%s>%s"),nTemp2String,NEWLINE);
		// leaving fempty true, so no good file available
		break;
	} else {
		fempty=false;
		StartupStore(_T(".. Unknown WP header, using format %d.  Header: <%s>%s"),fileformat,nTemp2String,NEWLINE);
		break;
	}
  }
  if (fempty) {
	return -1;
  }

  // SetFilePointer(hFile,0,NULL,FILE_BEGIN);
  fPos = 0;

  // a real shame, too lazy to change into do while loop
  // Skip already read lines containing header, unless we are using DAT, which has no header
  if ( fileformat==LKW_DAT) goto goto_inloop; 

  memset(nTemp2String, 0, sizeof(nTemp2String)); // clear Temp Buffer

  while(ReadString(fp, READLINE_LENGTH, nTemp2String)){
goto_inloop:    
	nLineNumber++;
	nTemp2String[READLINE_LENGTH]=_T('\0');
	nTemp2String[READLINE_LENGTH-1]=_T('\n');
	nTemp2String[READLINE_LENGTH-2]=_T('\r');
	fPos += _tcslen(nTemp2String);
   
	if (_tcsstr(nTemp2String, TEXT("**")) == nTemp2String) // Look For Comment
		continue;

	if (_tcsstr(nTemp2String, TEXT("*")) == nTemp2String)  // Look For SeeYou Comment
		continue;

	if (nTemp2String[0] == '\0')
		continue;

	new_waypoint->Details = NULL; 
	new_waypoint->Comment = NULL; 

	if ( fileformat == LKW_DAT || fileformat== LKW_XCW ) {
		if (ParseDAT(nTemp2String, new_waypoint)) {

			if ( (_tcscmp(new_waypoint->Name, gettext(TEXT(RESWP_TAKEOFF_NAME)))==0) && (new_waypoint->Number==RESWP_ID)) {
				StartupStore(_T("... FOUND TAKEOFF (%s) INSIDE WAYPOINTS FILE%s"), gettext(TEXT(RESWP_TAKEOFF_NAME)), NEWLINE);
				memcpy(WayPointList,new_waypoint,sizeof(WAYPOINT));
				continue;
			}

			if (WaypointInTerrainRange(new_waypoint)) { 
				new_waypoint = GrowWaypointList();
				if (!new_waypoint) {
					return -1; // failed to allocate
				}
				new_waypoint++; // we want the next blank one
			}	
	  	}
	}
	if ( fileformat == LKW_CUP ) {
		if ( _tcsncmp(_T("-----Related Tasks"),nTemp2String,18)==0) {
			break;
		}
		if (ParseCUPWayPointString(nTemp2String, new_waypoint)) {
			if ( (_tcscmp(new_waypoint->Name, gettext(TEXT(RESWP_TAKEOFF_NAME)))==0) && (new_waypoint->Number==RESWP_ID)) {
				StartupStore(_T("... FOUND TAKEOFF (%s) INSIDE WAYPOINTS FILE%s"), gettext(TEXT(RESWP_TAKEOFF_NAME)), NEWLINE);
				memcpy(WayPointList,new_waypoint,sizeof(WAYPOINT));
				continue;
			}

			if (WaypointInTerrainRange(new_waypoint)) { 
				new_waypoint = GrowWaypointList();
				if (!new_waypoint) {
					return -1; // failed to allocate
				}
				new_waypoint++; // we want the next blank one
			}
		}
	}
	if ( fileformat == LKW_COMPE ) {
		if (ParseCOMPEWayPointString(nTemp2String, new_waypoint)) {
			if ( (_tcscmp(new_waypoint->Name, gettext(TEXT(RESWP_TAKEOFF_NAME)))==0) && (new_waypoint->Number==RESWP_ID)) {
				StartupStore(_T("... FOUND TAKEOFF (%s) INSIDE WAYPOINTS FILE%s"), gettext(TEXT(RESWP_TAKEOFF_NAME)), NEWLINE);
				memcpy(WayPointList,new_waypoint,sizeof(WAYPOINT));
				continue;
			}

			if (WaypointInTerrainRange(new_waypoint)) { 
				new_waypoint = GrowWaypointList();
				if (!new_waypoint) {
					return -1; // failed to allocate
				}
				new_waypoint++; // we want the next blank one
			}
		}
	}

	if(fileformat == LKW_OZI){
		// Ignore first four header lines
		if(nLineNumber <= 3)
			continue;

		if(ParseOZIWayPointString(nTemp2String, new_waypoint)){
			if ( (_tcscmp(new_waypoint->Name, gettext(TEXT(RESWP_TAKEOFF_NAME)))==0) && (new_waypoint->Number==RESWP_ID)) {
				StartupStore(_T("... FOUND TAKEOFF (%s) INSIDE WAYPOINTS FILE%s"), gettext(TEXT(RESWP_TAKEOFF_NAME)), NEWLINE);
				memcpy(WayPointList,new_waypoint,sizeof(WAYPOINT));
				continue;
			}

			if (WaypointInTerrainRange(new_waypoint)) {
				new_waypoint = GrowWaypointList();
				if (!new_waypoint) {
					return -1; // failed to allocate
				}
				new_waypoint++; // we want the next blank one
			}
		}
	}

	memset(nTemp2String, 0, sizeof(nTemp2String)); // clear Temp Buffer

	continue;

  }

  if (hProgress) {
	_stprintf(szTemp,TEXT("100%%"));       
	SetDlgItemText(hProgress,IDC_PROGRESS,szTemp);
  }
  return fileformat;

}
Example #14
0
INT cmd_rmdir (LPTSTR param)
{
    TCHAR ch;
    INT args;
    INT dirCount;
    LPTSTR *arg;
    INT i;
    BOOL RD_SUB = FALSE;
    BOOL RD_QUIET = FALSE;
    INT res;
    INT nError = 0;
    TCHAR szFullPath[MAX_PATH];

    if (!_tcsncmp (param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE,STRING_RMDIR_HELP);
        return 0;
    }

    arg = split (param, &args, FALSE, FALSE);
    dirCount = 0;

    /* check for options anywhere in command line */
    for (i = 0; i < args; i++)
    {
        if (*arg[i] == _T('/'))
        {
            /*found a command, but check to make sure it has something after it*/
            if (_tcslen (arg[i]) == 2)
            {
                ch = _totupper (arg[i][1]);

                if (ch == _T('S'))
                {
                    RD_SUB = TRUE;
                }
                else if (ch == _T('Q'))
                {
                    RD_QUIET = TRUE;
                }
            }
        }
        else
        {
            dirCount++;
        }
    }

    if (dirCount == 0)
    {
        /* No folder to remove */
        error_req_param_missing();
        freep(arg);
        return 1;
    }

    for (i = 0; i < args; i++)
    {
        if (*arg[i] == _T('/'))
            continue;

        if (RD_SUB)
        {
            /* ask if they want to delete evrything in the folder */
            if (!RD_QUIET)
            {
                res = FilePromptYNA (STRING_DEL_HELP2);
                if (res == PROMPT_NO || res == PROMPT_BREAK)
                {
                    nError = 1;
                    continue;
                }
                if (res == PROMPT_ALL)
                    RD_QUIET = TRUE;
            }
            /* get the folder name */
            GetFullPathName(arg[i],MAX_PATH,szFullPath,NULL);

            /* remove trailing \ if any, but ONLY if dir is not the root dir */
            if (_tcslen (szFullPath) >= 2 && szFullPath[_tcslen (szFullPath) - 1] == _T('\\'))
                szFullPath[_tcslen(szFullPath) - 1] = _T('\0');

            res = DeleteFolder(szFullPath);
        }
        else
        {
            res = RemoveDirectory(arg[i]);
        }

        if (!res)
        {
            /* Couldn't delete the folder, print out the error */
            nError = GetLastError();
            ErrorMessage(nError, _T("RD"));
        }
    }

    freep (arg);
    return nError;
}
Example #15
0
void AddContactToTree(HWND hwnd, ClcData *dat, HANDLE hContact, int updateTotalCount, int checkHideOffline)
{
	if ( FindItem(hwnd,dat,hContact,NULL,NULL,NULL) == 1)
		return;

	ClcCacheEntry *cacheEntry = GetContactFullCacheEntry(hContact);
	if (cacheEntry == NULL)
		return;

	char *szProto = cacheEntry->szProto;

	dat->needsResort = 1;
	ClearRowByIndexCache();
	ClearClcContactCache(dat,hContact);

	WORD status;
	DWORD style = GetWindowLongPtr(hwnd,GWL_STYLE);
	if (style & CLS_NOHIDEOFFLINE) checkHideOffline = 0;
	if (checkHideOffline) {
		if (szProto == NULL) status = ID_STATUS_OFFLINE;
		else status = cacheEntry->status;
	}

	ClcGroup *group;
	if (lstrlen(cacheEntry->tszGroup) == 0)
		group = &dat->list;
	else {
		group = AddGroup(hwnd,dat,cacheEntry->tszGroup,(DWORD)-1,0,0);
		if (group == NULL) {
			DWORD groupFlags;
			int i;
			if ( !(style & CLS_HIDEEMPTYGROUPS))
				return;

			if (checkHideOffline && pcli->pfnIsHiddenMode(dat,status)) {
				for (i = 1;;i++) {
					TCHAR *szGroupName = pcli->pfnGetGroupName(i, &groupFlags);
					if (szGroupName == NULL)
						return;   //never happens
					if ( !lstrcmp(szGroupName,cacheEntry->tszGroup))
						break;
				}
				if (groupFlags & GROUPF_HIDEOFFLINE)
					return;
			}
			for (i = 1;; i++) {
				TCHAR *szGroupName = pcli->pfnGetGroupName(i, &groupFlags);
				if (szGroupName == NULL)
					return;   //never happens
				if ( !lstrcmp(szGroupName,cacheEntry->tszGroup))
					break;
				size_t len = lstrlen(szGroupName);
				if ( !_tcsncmp(szGroupName,cacheEntry->tszGroup,len) && cacheEntry->tszGroup[len] == '\\')
					AddGroup(hwnd,dat,szGroupName,groupFlags,i,1);
			}
			group = AddGroup(hwnd,dat,cacheEntry->tszGroup,groupFlags,i,1);
		}
	}

	if (checkHideOffline) {
		if (pcli->pfnIsHiddenMode(dat,status) && (style & CLS_HIDEOFFLINE || group->hideOffline)) {
			if (updateTotalCount) group->totalMembers++;
			return;
		}
	}
	ClcContact *cont = AddContactToGroup(dat,group,cacheEntry);
	if (cont && cont->proto) {
		cont->SubAllocated = 0;
		if (strcmp(cont->proto,"MetaContacts") == 0)
			AddSubcontacts(cont);
	}
	if (updateTotalCount)
		group->totalMembers++;
	ClearRowByIndexCache();
}
Example #16
0
HWND TSAPI CreateNewTabForContact(TContainerData *pContainer, MCONTACT hContact, int isSend, const char *pszInitialText, BOOL bActivateTab, BOOL bPopupContainer, BOOL bWantPopup, MEVENT hdbEvent)
{
	if (M.FindWindow(hContact) != 0) {
		_DebugPopup(hContact, _T("Warning: trying to create duplicate window"));
		return 0;
	}

	// if we have a max # of tabs/container set and want to open something in the default container...
	if (hContact != 0 && M.GetByte("limittabs", 0) && !_tcsncmp(pContainer->szName, _T("default"), 6))
		if ((pContainer = FindMatchingContainer(_T("default"))) == NULL)
			if ((pContainer = CreateContainer(_T("default"), CNT_CREATEFLAG_CLONED, hContact)) == NULL)
				return 0;

	TNewWindowData newData = { 0 };
	newData.hContact = hContact;
	newData.isWchar = isSend;
	newData.szInitialText = pszInitialText;
	char *szProto = GetContactProto(newData.hContact);

	memset(&newData.item, 0, sizeof(newData.item));

	// obtain various status information about the contact
	TCHAR *contactName = pcli->pfnGetContactDisplayName(newData.hContact, 0);

	// cut nickname if larger than x chars...
	TCHAR newcontactname[128], tabtitle[128];
	if (contactName && mir_tstrlen(contactName) > 0) {
		if (M.GetByte("cuttitle", 0))
			CutContactName(contactName, newcontactname, _countof(newcontactname));
		else
			_tcsncpy_s(newcontactname, contactName, _TRUNCATE);

		Utils::DoubleAmpersands(newcontactname, _countof(newcontactname));
	}
	else _tcsncpy_s(newcontactname, _T("_U_"), _TRUNCATE);

	TCHAR *szStatus = pcli->pfnGetStatusModeDescription(szProto == NULL ? ID_STATUS_OFFLINE : db_get_w(newData.hContact, szProto, "Status", ID_STATUS_OFFLINE), 0);

	if (M.GetByte("tabstatus", 1))
		mir_sntprintf(tabtitle, _T("%s (%s)  "), newcontactname, szStatus);
	else
		mir_sntprintf(tabtitle, _T("%s   "), newcontactname);

	newData.item.pszText = tabtitle;
	newData.item.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_PARAM;
	newData.item.iImage = 0;
	newData.item.cchTextMax = _countof(tabtitle);

	HWND hwndTab = GetDlgItem(pContainer->hwnd, IDC_MSGTABS);
	// hide the active tab
	if (pContainer->hwndActive && bActivateTab)
		ShowWindow(pContainer->hwndActive, SW_HIDE);

	int iTabIndex_wanted = M.GetDword(hContact, "tabindex", pContainer->iChilds * 100);
	int iCount = TabCtrl_GetItemCount(hwndTab);
	TCITEM item = { 0 };

	pContainer->iTabIndex = iCount;
	if (iCount > 0) {
		for (int i = iCount - 1; i >= 0; i--) {
			item.mask = TCIF_PARAM;
			TabCtrl_GetItem(hwndTab, i, &item);
			HWND hwnd = (HWND)item.lParam;
			TWindowData *dat = (TWindowData*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
			if (dat) {
				int relPos = M.GetDword(dat->hContact, "tabindex", i * 100);
				if (iTabIndex_wanted <= relPos)
					pContainer->iTabIndex = i;
			}
		}
	}

	int newItem = TabCtrl_InsertItem(hwndTab, pContainer->iTabIndex, &newData.item);
	SendMessage(hwndTab, EM_REFRESHWITHOUTCLIP, 0, 0);
	if (bActivateTab)
		TabCtrl_SetCurSel(hwndTab, newItem);
	newData.iTabID = newItem;
	newData.iTabImage = newData.item.iImage;
	newData.pContainer = pContainer;
	newData.iActivate = (int)bActivateTab;
	pContainer->iChilds++;
	newData.bWantPopup = bWantPopup;
	newData.hdbEvent = hdbEvent;
	HWND hwndNew = CreateDialogParam(g_hInst, MAKEINTRESOURCE(IDD_MSGSPLITNEW), hwndTab, DlgProcMessage, (LPARAM)&newData);

	// switchbar support
	if (pContainer->dwFlags & CNT_SIDEBAR) {
		TWindowData *dat = (TWindowData*)GetWindowLongPtr(hwndNew, GWLP_USERDATA);
		if (dat)
			pContainer->SideBar->addSession(dat, pContainer->iTabIndex);
	}
	SendMessage(pContainer->hwnd, WM_SIZE, 0, 0);

	// if the container is minimized, then pop it up...
	if (IsIconic(pContainer->hwnd)) {
		if (bPopupContainer) {
			SendMessage(pContainer->hwnd, WM_SYSCOMMAND, SC_RESTORE, 0);
			SetFocus(pContainer->hwndActive);
		}
		else {
			if (pContainer->dwFlags & CNT_NOFLASH)
				SendMessage(pContainer->hwnd, DM_SETICON, 0, (LPARAM)Skin_LoadIcon(SKINICON_EVENT_MESSAGE));
			else
				FlashContainer(pContainer, 1, 0);
		}
	}

	if (bActivateTab) {
		ActivateExistingTab(pContainer, hwndNew);
		SetFocus(hwndNew);
		RedrawWindow(pContainer->hwnd, NULL, NULL, RDW_ERASENOW);
		UpdateWindow(pContainer->hwnd);
		if (GetForegroundWindow() != pContainer->hwnd && bPopupContainer == TRUE)
			SetForegroundWindow(pContainer->hwnd);
	}
	else if (!IsIconic(pContainer->hwnd) && IsWindowVisible(pContainer->hwnd)) {
		SendMessage(pContainer->hwndActive, WM_SIZE, 0, 0);
		RedrawWindow(pContainer->hwndActive, NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
		RedrawWindow(pContainer->hwndActive, NULL, NULL, RDW_ERASENOW | RDW_UPDATENOW);
	}

	if (PluginConfig.m_bHideOnClose&&!IsWindowVisible(pContainer->hwnd)) {
		WINDOWPLACEMENT wp = { 0 };
		wp.length = sizeof(wp);
		GetWindowPlacement(pContainer->hwnd, &wp);

		BroadCastContainer(pContainer, DM_CHECKSIZE, 0, 0); // make sure all tabs will re-check layout on activation
		if (wp.showCmd == SW_SHOWMAXIMIZED)
			ShowWindow(pContainer->hwnd, SW_SHOWMAXIMIZED);
		else {
			if (bPopupContainer)
				ShowWindow(pContainer->hwnd, SW_SHOWNORMAL);
			else
				ShowWindow(pContainer->hwnd, SW_SHOWMINNOACTIVE);
		}
		SendMessage(pContainer->hwndActive, WM_SIZE, 0, 0);
	}

	if (PluginConfig.m_bIsWin7 && PluginConfig.m_useAeroPeek && CSkin::m_skinEnabled)
		CWarning::show(CWarning::WARN_AEROPEEK_SKIN, MB_ICONWARNING | MB_OK);

	if (ServiceExists(MS_HPP_EG_EVENT) && ServiceExists(MS_IEVIEW_EVENT) && db_get_b(0, "HistoryPlusPlus", "IEViewAPI", 0))
		if (IDYES == CWarning::show(CWarning::WARN_HPP_APICHECK, MB_ICONWARNING | MB_YESNO))
			db_set_b(0, "HistoryPlusPlus", "IEViewAPI", 0);

	return hwndNew;		// return handle of the new dialog
}
Example #17
0
static amodes mode_from_str (const TCHAR *str)
{
	if (_tcsncmp (str, _T("Dreg"), 4) == 0) return Dreg;
	if (_tcsncmp (str, _T("Areg"), 4) == 0) return Areg;
	if (_tcsncmp (str, _T("Aind"), 4) == 0) return Aind;
	if (_tcsncmp (str, _T("Apdi"), 4) == 0) return Apdi;
	if (_tcsncmp (str, _T("Aipi"), 4) == 0) return Aipi;
	if (_tcsncmp (str, _T("Ad16"), 4) == 0) return Ad16;
	if (_tcsncmp (str, _T("Ad8r"), 4) == 0) return Ad8r;
	if (_tcsncmp (str, _T("absw"), 4) == 0) return absw;
	if (_tcsncmp (str, _T("absl"), 4) == 0) return absl;
	if (_tcsncmp (str, _T("PC16"), 4) == 0) return PC16;
	if (_tcsncmp (str, _T("PC8r"), 4) == 0) return PC8r;
	if (_tcsncmp (str, _T("Immd"), 4) == 0) return imm;
	abort ();
	return 0;
}
Example #18
0
int KTestCommon::CleanPathExceptLogAndPak(const TCHAR cszPath[])
{
	int nRetCode = false;
	int nResult	 = false;
	TCHAR szPathName[MAX_PATH];
	TCHAR szFullPathFile[MAX_PATH];
	TCHAR* pszFile	 = NULL;
	HANDLE hFindFile = INVALID_HANDLE_VALUE;
	WIN32_FIND_DATA FindFileData;

	ASSERT(cszPath);

	nRetCode = _sntprintf(szPathName, MAX_PATH, _T("%s\\%s"), cszPath, _T("*.*"));
	KGLOG_PROCESS_ERROR(nRetCode != -1);
	szPathName[MAX_PATH - 1] = _T('\0');

	hFindFile = ::FindFirstFile(szPathName, &FindFileData);
	KGLOG_PROCESS_ERROR(hFindFile != INVALID_HANDLE_VALUE);
	while (true)
	{
		pszFile = FindFileData.cFileName;
		if (_tcsncmp(pszFile, _T("."), MAX_PATH)   != 0  &&
			_tcsncmp(pszFile, _T(".."), MAX_PATH)  != 0	 &&
			_tcsncmp(pszFile, _T("logs"), MAX_PATH) != 0	 &&
			_tcsncmp(pszFile, _T("pak"), MAX_PATH) != 0)
		{
			nRetCode = _sntprintf(szFullPathFile, MAX_PATH, _T("%s\\%s"), cszPath, pszFile);
			KGLOG_PROCESS_ERROR(nRetCode != -1);
			szFullPathFile[MAX_PATH - 1] = _T('\0');
			if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
			{
				nRetCode = _tremove(szFullPathFile);
				KGLOG_PROCESS_ERROR(nRetCode == 0);
			}
			else
			{
				nRetCode = CleanPath(szFullPathFile);
				KGLOG_PROCESS_ERROR(nRetCode);
				nRetCode = ::RemoveDirectory(szFullPathFile);
				KGLOG_PROCESS_ERROR(nRetCode);
			}
		}

		if (_tcsncmp(pszFile, _T("pak"), MAX_PATH) == 0)
		{
			nRetCode = _sntprintf(szFullPathFile, MAX_PATH, _T("%s\\pak\\update_2.pak"), cszPath);
			KGLOG_PROCESS_ERROR(nRetCode != -1);
			szFullPathFile[MAX_PATH - 1] = _T('\0');
			
			nRetCode = _tremove(szFullPathFile);
			//KGLOG_PROCESS_ERROR(nRetCode == 0);
		}

		nRetCode = ::FindNextFile(hFindFile, &FindFileData);
		if (!nRetCode)
		{
			nRetCode = ::GetLastError();
			KG_PROCESS_SUCCESS(nRetCode == ERROR_NO_MORE_FILES);
		}
	}

Exit1:
	nResult = true;
Exit0:
	if (hFindFile != INVALID_HANDLE_VALUE)
	{
		::FindClose(hFindFile);
		hFindFile = INVALID_HANDLE_VALUE;
	}
	return nResult;
}
Example #19
0
int OnButtonPressed(WPARAM, LPARAM lParam)
{
	CustomButtonClickData *cbcd = (CustomButtonClickData *)lParam;

	int iType;
	if (!mir_strcmp(cbcd->pszModule, "Switch Layout and Send"))
		iType = 1;
	else if (!mir_strcmp(cbcd->pszModule, "Translit and Send"))
		iType = 2;
	else if (!mir_strcmp(cbcd->pszModule, "Invert Case and Send"))
		iType = 3;
	else
		return 0;

	HWND hEdit = GetDlgItem(cbcd->hwndFrom, IDC_MESSAGE);
	if (!hEdit)
		hEdit = GetDlgItem(cbcd->hwndFrom, IDC_CHATMESSAGE);

	BYTE byKeybState[256];
	GetKeyboardState(byKeybState);
	byKeybState[VK_CONTROL] = 128;
	SetKeyboardState(byKeybState);
	SendMessage(hEdit, WM_KEYDOWN, VK_UP, 0);
	byKeybState[VK_CONTROL] = 0;
	SetKeyboardState(byKeybState);

	TCHAR *sel = Message_GetFromStream(hEdit, SF_TEXT | SF_UNICODE);
	size_t slen = mir_tstrlen(sel);
	if (slen != 0) {
		switch (iType) {
		case 3: Invert(sel); break;
		case 2: Transliterate(sel); break;
		case 1:
			DWORD dwProcessID;
			DWORD dwThreadID = GetWindowThreadProcessId(cbcd->hwndFrom, &dwProcessID);
			HKL hkl = GetKeyboardLayout(dwThreadID);

			memset(&smgp, 0, sizeof(smgp));
			smgp.cbSize = sizeof(smgp);
			smgp.str = sel;
			smgp.flag = SAFL_TCHAR;

			if (ServiceExists(MS_SMILEYADD_BATCHPARSE))
				smileyPrs = (SMADD_BATCHPARSERES *)CallService(MS_SMILEYADD_BATCHPARSE, 0, (LPARAM)&smgp);

			ActivateKeyboardLayout((HKL)HKL_PREV, KLF_ACTIVATE);

			for (int i = 0; i < (int)slen; i++) {
				TCHAR tchr;
				BYTE keys[256] = { 0 };
				SHORT vks = VkKeyScanEx(sel[i], hkl);

				keys[VK_SHIFT] = (HIBYTE(vks) & 1) ? 0xFF : 0x00; // shift
				keys[VK_CONTROL] = (HIBYTE(vks) & 2) ? 0xFF : 0x00; // ctrl
				keys[VK_MENU] = (HIBYTE(vks) & 4) ? 0xFF : 0x00;	// alt

				if (!isItSmiley(i)) {
					if (ToUnicodeEx(LOBYTE(vks), 0, keys, &tchr, 1, 0, GetKeyboardLayout(dwThreadID)) == 1)
						sel[i] = tchr;
				}
			}
			if (smileyPrs != NULL)
				CallService(MS_SMILEYADD_BATCHFREE, 0, (LPARAM)smileyPrs);
			break;
		}
	}

	ptrT tszSymbol(db_get_tsa(NULL, "TranslitSwitcher", "ResendSymbol"));
	if (tszSymbol == NULL) {
		SetWindowText(hEdit, sel);
		SendMessage(hEdit, EM_SETSEL, 0, (LPARAM)slen);
		SendMessage(cbcd->hwndFrom, WM_COMMAND, IDOK, 0);
	}
	else if (_tcsncmp(sel, tszSymbol, mir_tstrlen(tszSymbol)) == 0) {
		SetWindowText(hEdit, sel);
		SendMessage(hEdit, EM_SETSEL, 0, (LPARAM)slen);
		SendMessage(cbcd->hwndFrom, WM_COMMAND, IDOK, 0);
	}
	else {
		CMString tszFinal(FORMAT, _T("%s %s"), tszSymbol, sel);
		SetWindowText(hEdit, tszFinal.GetString());
		SendMessage(hEdit, EM_SETSEL, 0, tszFinal.GetLength());
		SendMessage(cbcd->hwndFrom, WM_COMMAND, IDOK, 0);
	}

	mir_free(sel);
	return 1;
}
Example #20
0
bool CServerSocket::ProcessPacket(char* packet, uint32 size, uint8 opcode) {
    try {
        switch(opcode) {
        case OP_SERVERMESSAGE: {
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_ServerMessage\n"));

            CServer* pServer = cur_server ? theApp.serverlist->GetServerByAddress(cur_server->GetAddress(),cur_server->GetPort()) : NULL;
            CSafeMemFile data((const BYTE*)packet, size);
            CString strMessages(data.ReadString(pServer ? pServer->GetUnicodeSupport() : false));

            if (thePrefs.GetDebugServerTCPLevel() > 0) {
                UINT uAddData = data.GetLength() - data.GetPosition();
                if (uAddData > 0) {
                    Debug(_T("*** NOTE: OP_ServerMessage: ***AddData: %u bytes\n"), uAddData);
                    DebugHexDump((uint8*)packet + data.GetPosition(), uAddData);
                }
            }

            // 16.40 servers do not send separate OP_SERVERMESSAGE packets for each line;
            // instead of this they are sending all text lines with one OP_SERVERMESSAGE packet.
            int iPos = 0;
            CString message = strMessages.Tokenize(_T("\r\n"), iPos);
            while (!message.IsEmpty())
            {
                bool bOutputMessage = true;
                if (_tcsnicmp(message, _T("server version"), 14) == 0) {
                    CString strVer = message.Mid(14);
                    strVer.Trim();
                    strVer = strVer.Left(64); // truncate string to avoid misuse by servers in showing ads
                    if (pServer) {
                        pServer->SetVersion(strVer);
                        theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer);
                        theApp.emuledlg->serverwnd->UpdateMyInfo();
                    }
                    if (thePrefs.GetDebugServerTCPLevel() > 0)
                        Debug(_T("%s\n"), message);
                }
                else if (_tcsncmp(message, _T("ERROR"), 5) == 0) {
                    LogError(LOG_STATUSBAR, _T("%s %s (%s:%u) - %s"),
                             GetResString(IDS_ERROR),
                             pServer ? pServer->GetListName() : GetResString(IDS_PW_SERVER),
                             cur_server ? cur_server->GetAddress() : _T(""),
                             cur_server ? cur_server->GetPort() : 0, message.Mid(5).Trim(_T(" :")));
                    bOutputMessage = false;
                }
                else if (_tcsncmp(message, _T("WARNING"), 7) == 0) {
                    LogWarning(LOG_STATUSBAR, _T("%s %s (%s:%u) - %s"),
                               GetResString(IDS_WARNING),
                               pServer ? pServer->GetListName() : GetResString(IDS_PW_SERVER),
                               cur_server ? cur_server->GetAddress() : _T(""),
                               cur_server ? cur_server->GetPort() : 0, message.Mid(7).Trim(_T(" :")));
                    bOutputMessage = false;
                }

                if (message.Find(_T("[emDynIP: ")) != -1 && message.Find(_T("]")) != -1 && message.Find(_T("[emDynIP: ")) < message.Find(_T("]"))) {
                    CString dynip = message.Mid(message.Find(_T("[emDynIP: ")) + 10, message.Find(_T("]")) - (message.Find(_T("[emDynIP: ")) + 10));
                    dynip.Trim(_T(" "));
                    if (dynip.GetLength() && dynip.GetLength() < 51) {
                        if (pServer) {
                            pServer->SetDynIP(dynip);
                            if (cur_server)
                                cur_server->SetDynIP(dynip);
                            theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer);
                            theApp.emuledlg->serverwnd->UpdateMyInfo();
                        }
                    }
                }
                if (bOutputMessage)
                    theApp.emuledlg->AddServerMessageLine(message);

                message = strMessages.Tokenize(_T("\r\n"), iPos);
            }
            break;
        }
        case OP_IDCHANGE: {
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_IDChange\n"));
            if (size < sizeof(LoginAnswer_Struct)) {
                throw GetResString(IDS_ERR_BADSERVERREPLY);
            }
            LoginAnswer_Struct* la = (LoginAnswer_Struct*)packet;

            // save TCP flags in 'cur_server'
            ASSERT( cur_server );
            if (cur_server) {
                if (size >= sizeof(LoginAnswer_Struct)+4) {
                    DWORD dwFlags = *((uint32*)(packet + sizeof(LoginAnswer_Struct)));
                    if (thePrefs.GetDebugServerTCPLevel() > 0) {
                        CString strInfo;
                        strInfo.AppendFormat(_T("  TCP Flags=0x%08x"), dwFlags);
                        const DWORD dwKnownBits = SRV_TCPFLG_COMPRESSION | SRV_TCPFLG_NEWTAGS | SRV_TCPFLG_UNICODE;
                        if (dwFlags & ~dwKnownBits)
                            strInfo.AppendFormat(_T("  ***UnkBits=0x%08x"), dwFlags & ~dwKnownBits);
                        if (dwFlags & SRV_TCPFLG_COMPRESSION)
                            strInfo.AppendFormat(_T("  Compression=1"));
                        if (dwFlags & SRV_TCPFLG_NEWTAGS)
                            strInfo.AppendFormat(_T("  NewTags=1"));
                        if (dwFlags & SRV_TCPFLG_UNICODE)
                            strInfo.AppendFormat(_T("  Unicode=1"));
                        Debug(_T("%s\n"), strInfo);
                    }
                    cur_server->SetTCPFlags(dwFlags);
                }
                else
                    cur_server->SetTCPFlags(0);

                // copy TCP flags into the server in the server list
                CServer* pServer = theApp.serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort());
                if (pServer)
                    pServer->SetTCPFlags(cur_server->GetTCPFlags());
            }

            if (la->clientid == 0) {
                uint8 state = thePrefs.GetSmartIdState();
                if ( state > 0 ) {
                    state++;
                    if( state > 3 )
                        thePrefs.SetSmartIdState(0);
                    else
                        thePrefs.SetSmartIdState(state);
                }
                break;
            }
            if( thePrefs.GetSmartIdCheck() ) {
                if (!IsLowID(la->clientid))
                    thePrefs.SetSmartIdState(1);
                else {
                    uint8 state = thePrefs.GetSmartIdState();
                    if ( state > 0 ) {
                        state++;
                        if( state > 3 )
                            thePrefs.SetSmartIdState(0);
                        else
                            thePrefs.SetSmartIdState(state);
                        break;
                    }
                }
            }

//==>Lowid retry by SlugFiller [cyrex2001]
#ifdef LOWID
            if (thePrefs.GetLowIdRetried())
            {
                if (la->clientid < 16777216 )
                {
                    SetConnectionState(CS_ERROR);
                    AddLogLine(true,GetResString(IDS_LOWIDRETRYING),thePrefs.GetLowIdRetried());
                    thePrefs.SetLowIdRetried();
                    break;
                }
            }
#endif //Lowid retry
//<==Lowid retry [cyrex2001]
            // we need to know our client's HighID when sending our shared files (done indirectly on SetConnectionState)
            serverconnect->clientid = la->clientid;

            if (connectionstate != CS_CONNECTED) {
                SetConnectionState(CS_CONNECTED);
                theApp.OnlineSig();       // Added By Bouc7
            }
            serverconnect->SetClientID(la->clientid);
            AddLogLine(false, GetResString(IDS_NEWCLIENTID), la->clientid);
//==>Reask sourcen after ip change [cyrex2001]
#ifdef RSAIC_MAELLA
            theApp.CheckIDChange();
#endif //Reask sourcen after ip change
//<==Reask sourcen after ip change [cyrex2001]
            theApp.downloadqueue->ResetLocalServerRequests();
            break;
        }
        case OP_SEARCHRESULT: {
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_SearchResult\n"));
            CServer* cur_srv = (serverconnect) ? serverconnect->GetCurrentServer() : NULL;
            CServer* pServer = cur_srv ? theApp.serverlist->GetServerByAddress(cur_srv->GetAddress(), cur_srv->GetPort()) : NULL;
            bool bMoreResultsAvailable;
            uint16 uSearchResults = theApp.searchlist->ProcessSearchanswer(packet, size, true/*pServer ? pServer->GetUnicodeSupport() : false*/, cur_srv ? cur_srv->GetIP() : 0, cur_srv ? cur_srv->GetPort() : 0, &bMoreResultsAvailable);
            theApp.emuledlg->searchwnd->LocalSearchEnd(uSearchResults, bMoreResultsAvailable);
            break;
        }
        case OP_FOUNDSOURCES: {
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_FoundSources; Sources=%u  %s\n"), (UINT)(uchar)packet[16], DbgGetFileInfo((uchar*)packet));
            ASSERT( cur_server );
            if (cur_server)
            {
                CSafeMemFile sources((BYTE*)packet,size);
                uchar fileid[16];
                sources.ReadHash16(fileid);
                if (CPartFile* file = theApp.downloadqueue->GetFileByID(fileid))
                    file->AddSources(&sources,cur_server->GetIP(), cur_server->GetPort());
            }
            break;
        }
        case OP_SERVERSTATUS: {
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_ServerStatus\n"));
            // FIXME some statuspackets have a different size -> why? structur?
            if (size < 8)
                break;//throw "Invalid status packet";
            uint32 cur_user = PeekUInt32(packet);
            uint32 cur_files = PeekUInt32(packet+4);
            CServer* update = cur_server ? theApp.serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort()) : NULL;
            if (update) {
                update->SetUserCount(cur_user);
                update->SetFileCount(cur_files);
                theApp.emuledlg->ShowUserCount();
                theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer( update );
                theApp.emuledlg->serverwnd->UpdateMyInfo();
            }
            if (thePrefs.GetDebugServerTCPLevel() > 0) {
                if (size > 8) {
                    Debug(_T("*** NOTE: OP_ServerStatus: ***AddData: %u bytes\n"), size - 8);
                    DebugHexDump((uint8*)packet + 8, size - 8);
                }
            }
            break;
        }
        case OP_SERVERIDENT: {
            // OP_SERVERIDENT - this is sent by the server only if we send a OP_GETSERVERLIST
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_ServerIdent\n"));
            if (size<16+4+2+4) {
                if (thePrefs.GetVerbose())
                    DebugLogError(_T("%s"), GetResString(IDS_ERR_KNOWNSERVERINFOREC));
                break;// throw "Invalid server info received";
            }

            CServer* pServer = cur_server ? theApp.serverlist->GetServerByAddress(cur_server->GetAddress(),cur_server->GetPort()) : NULL;
            CString strInfo;
            CSafeMemFile data((BYTE*)packet, size);

            uint8 aucHash[16];
            data.ReadHash16(aucHash);
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                strInfo.AppendFormat(_T("Hash=%s (%s)"), md4str(aucHash), DbgGetHashTypeString(aucHash));
            uint32 nServerIP = data.ReadUInt32();
            uint16 nServerPort = data.ReadUInt16();
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                strInfo.AppendFormat(_T("  IP=%s:%u"), ipstr(nServerIP), nServerPort);
            UINT nTags = data.ReadUInt32();
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                strInfo.AppendFormat(_T("  Tags=%u"), nTags);

            CString strName;
            CString strDescription;
            for (UINT i = 0; i < nTags; i++) {
                CTag tag(&data, pServer ? pServer->GetUnicodeSupport() : false);
                if (tag.GetNameID() == ST_SERVERNAME) {
                    if (tag.IsStr()) {
                        strName = tag.GetStr();
                        if (thePrefs.GetDebugServerTCPLevel() > 0)
                            strInfo.AppendFormat(_T("  Name=%s"), strName);
                    }
                }
                else if (tag.GetNameID() == ST_DESCRIPTION) {
                    if (tag.IsStr()) {
                        strDescription = tag.GetStr();
                        if (thePrefs.GetDebugServerTCPLevel() > 0)
                            strInfo.AppendFormat(_T("  Desc=%s"), strDescription);
                    }
                }
                else if (thePrefs.GetDebugServerTCPLevel() > 0)
                    strInfo.AppendFormat(_T("  ***UnkTag: 0x%02x=%u"), tag.GetNameID(), tag.GetInt());
            }
            if (thePrefs.GetDebugServerTCPLevel() > 0) {
                strInfo += _T('\n');
                Debug(_T("%s"), strInfo);

                UINT uAddData = data.GetLength() - data.GetPosition();
                if (uAddData > 0) {
                    Debug(_T("*** NOTE: OP_ServerIdent: ***AddData: %u bytes\n"), uAddData);
                    DebugHexDump((uint8*)packet + data.GetPosition(), uAddData);
                }
            }

            if (pServer) {
                pServer->SetListName(strName);
                pServer->SetDescription(strDescription);
                if (((uint32*)aucHash)[0] == 0x2A2A2A2A) {
                    const CString& rstrVersion = pServer->GetVersion();
                    if (!rstrVersion.IsEmpty())
                        pServer->SetVersion(_T("eFarm ") + rstrVersion);
                    else
                        pServer->SetVersion(_T("eFarm"));
                }
                theApp.emuledlg->ShowConnectionState();
                theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer);
                theApp.emuledlg->serverwnd->UpdateMyInfo();
            }
            break;
        }
        // tecxx 1609 2002 - add server's serverlist to own serverlist
        case OP_SERVERLIST: {
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_ServerList\n"));
            try {
                CSafeMemFile servers((BYTE*)packet,size);
                UINT count = servers.ReadUInt8();
                // check if packet is valid
                if (1 + count*(4+2) > size)
                    count = 0;
                int addcount = 0;
                while(count)
                {
                    uint32 ip = servers.ReadUInt32();
                    uint16 port = servers.ReadUInt16();
                    CServer* srv = new CServer(port, ipstr(ip));
                    srv->SetListName(srv->GetFullIP());
                    if (!theApp.emuledlg->serverwnd->serverlistctrl.AddServer(srv, true))
                        delete srv;
                    else
                        addcount++;
                    count--;
                }
                if (addcount)
                    AddLogLine(false, GetResString(IDS_NEWSERVERS), addcount);
                if (thePrefs.GetDebugServerTCPLevel() > 0) {
                    UINT uAddData = servers.GetLength() - servers.GetPosition();
                    if (uAddData > 0) {
                        Debug(_T("*** NOTE: OP_ServerList: ***AddData: %u bytes\n"), uAddData);
                        DebugHexDump((uint8*)packet + servers.GetPosition(), uAddData);
                    }
                }
            }
            catch(CFileException* error) {
                if (thePrefs.GetVerbose())
                    DebugLogError(_T("%s"), GetResString(IDS_ERR_BADSERVERLISTRECEIVED));
                error->Delete();
            }
            break;
        }
        case OP_CALLBACKREQUESTED: {
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_CallbackRequested\n"));
            if (size == 6)
            {
                uint32 dwIP = PeekUInt32(packet);

                if (theApp.ipfilter->IsFiltered(dwIP)) {
                    theStats.filteredclients++;
                    if (thePrefs.GetLogFilteredIPs())
                        AddDebugLogLine(false, _T("Ignored callback request (IP=%s) - IP filter (%s)"), ipstr(dwIP), theApp.ipfilter->GetLastHit());
                    break;
                }

                if (theApp.clientlist->IsBannedClient(dwIP)) {
                    if (thePrefs.GetLogBannedClients()) {
                        CUpDownClient* pClient = theApp.clientlist->FindClientByIP(dwIP);
                        AddDebugLogLine(false, _T("Ignored callback request from banned client %s; %s"), ipstr(dwIP), pClient->DbgGetClientInfo());
                    }
                    break;
                }

                uint16 nPort = PeekUInt16(packet+4);
                CUpDownClient* client = theApp.clientlist->FindClientByIP(dwIP,nPort);
                if (client)
                    client->TryToConnect();
                else
                {
                    client = new CUpDownClient(0,nPort,dwIP,0,0,true);
                    theApp.clientlist->AddClient(client);
                    client->TryToConnect();
                }
            }
            break;
        }
        case OP_CALLBACK_FAIL: {
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_Callback_Fail %s\n"), DbgGetHexDump((uint8*)packet, size));
            break;
        }
        case OP_REJECT: {
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("ServerMsg - OP_Reject %s\n"), DbgGetHexDump((uint8*)packet, size));
            // this could happen if we send a command with the wrong protocol (e.g. sending a compressed packet to
            // a server which does not support that protocol).
            if (thePrefs.GetVerbose())
                DebugLogError(_T("Server rejected last command"));
            break;
        }
        default:
            if (thePrefs.GetDebugServerTCPLevel() > 0)
                Debug(_T("***NOTE: ServerMsg - Unknown message; opcode=0x%02x  %s\n"), opcode, DbgGetHexDump((uint8*)packet, size));
            ;
        }

        return true;
    }
    catch(CFileException* error)
    {
        if (thePrefs.GetVerbose())
        {
            TCHAR szError[MAX_CFEXP_ERRORMSG];
            error->m_strFileName = _T("server packet");
            error->GetErrorMessage(szError, ARRSIZE(szError));
            DebugLogError(GetResString(IDS_ERR_PACKAGEHANDLING), szError);
        }
        error->Delete();
        ASSERT(0);
        if (opcode==OP_SEARCHRESULT || opcode==OP_FOUNDSOURCES)
            return true;
    }
    catch(CMemoryException* error)
    {
        if (thePrefs.GetVerbose())
            DebugLogError(GetResString(IDS_ERR_PACKAGEHANDLING), _T("CMemoryException"));
        error->Delete();
        ASSERT(0);
        if (opcode==OP_SEARCHRESULT || opcode==OP_FOUNDSOURCES)
            return true;
    }
    catch(CString error)
    {
        if (thePrefs.GetVerbose())
            DebugLogError(GetResString(IDS_ERR_PACKAGEHANDLING), error);
        ASSERT(0);
    }
    catch(...)
    {
        if (thePrefs.GetVerbose())
            DebugLogError(GetResString(IDS_ERR_PACKAGEHANDLING), _T("Unknown exception"));
        ASSERT(0);
    }

    SetConnectionState(CS_DISCONNECTED);
    return false;
}
Example #21
0
INT
CommandChoice (LPTSTR param)
{
    LPTSTR lpOptions;
    TCHAR Options[6];
    LPTSTR lpText    = NULL;
    BOOL   bNoPrompt = FALSE;
    BOOL   bCaseSensitive = FALSE;
    BOOL   bTimeout = FALSE;
    INT    nTimeout = 0;
    TCHAR  cDefault = _T('\0');
    INPUT_RECORD ir;
    LPTSTR p, np;
    LPTSTR *arg;
    INT    argc;
    INT    i;
    INT    val;

    INT GCret;
    TCHAR Ch;
    DWORD amount,clk;

    LoadString(CMD_ModuleHandle, STRING_CHOICE_OPTION, Options, 4);
    lpOptions = Options;

    if (_tcsncmp (param, _T("/?"), 2) == 0)
    {
        ConOutResPaging(TRUE,STRING_CHOICE_HELP);
        return 0;
    }

    /* retrieve text */
    p = param;

    while (TRUE)
    {
        if (*p == _T('\0'))
            break;

        if (*p != _T('/'))
        {
            lpText = p;
                break;
        }
        np = _tcschr (p, _T(' '));
        if (!np)
            break;
        p = np + 1;
    }

    /* build parameter array */
    arg = split (param, &argc, FALSE, FALSE);

    /* evaluate arguments */
    if (argc > 0)
    {
        for (i = 0; i < argc; i++)
        {
            if (_tcsnicmp (arg[i], _T("/c"), 2) == 0)
            {
                if (arg[i][2] == _T(':'))
                    lpOptions = &arg[i][3];
                else
                    lpOptions = &arg[i][2];

                if (_tcslen (lpOptions) == 0)
                {
                    ConErrResPuts(STRING_CHOICE_ERROR);
                    freep (arg);
                    return 1;
                }
            }
            else if (_tcsnicmp (arg[i], _T("/n"), 2) == 0)
            {
                bNoPrompt = TRUE;
            }
            else if (_tcsnicmp (arg[i], _T("/s"), 2) == 0)
            {
                bCaseSensitive = TRUE;
            }
            else if (_tcsnicmp (arg[i], _T("/t"), 2) == 0)
            {
                LPTSTR s;

                if (arg[i][2] == _T(':'))
                {
                    cDefault = arg[i][3];
                    s = &arg[i][4];
                }
                else
                {
                    cDefault = arg[i][2];
                    s = &arg[i][3];
                }

                if (*s != _T(','))
                {
                    ConErrResPuts(STRING_CHOICE_ERROR_TXT);
                    freep (arg);
                    return 1;
                }

                s++;
                nTimeout = _ttoi(s);
                bTimeout = TRUE;
            }
            else if (arg[i][0] == _T('/'))
            {
                ConErrResPrintf(STRING_CHOICE_ERROR_OPTION, arg[i]);
                freep (arg);
                return 1;
            }
        }
    }

    /* print text */
    if (lpText)
        ConOutPrintf (_T("%s"), lpText);

    /* print options */
    if (bNoPrompt == FALSE)
    {
        ConOutPrintf (_T("[%c"), lpOptions[0]);

        for (i = 1; (unsigned)i < _tcslen (lpOptions); i++)
            ConOutPrintf (_T(",%c"), lpOptions[i]);

        ConOutPrintf (_T("]?"));
    }

    ConInFlush ();

    if (!bTimeout)
    {
        while (TRUE)
        {
            ConInKey (&ir);

            val = IsKeyInString (lpOptions,
#ifdef _UNICODE
                                 ir.Event.KeyEvent.uChar.UnicodeChar,
#else
                                 ir.Event.KeyEvent.uChar.AsciiChar,
#endif
                                 bCaseSensitive);

            if (val >= 0)
            {
                ConOutPrintf (_T("%c\n"), lpOptions[val]);

                nErrorLevel = val + 1;

                break;
            }

            Beep (440, 50);
        }

        freep (arg);
        TRACE ("ErrorLevel: %d\n", nErrorLevel);
        return 0;
    }

    clk = GetTickCount ();
    amount = nTimeout*1000;

loop:
    GCret = GetCharacterTimeout (&Ch, amount - (GetTickCount () - clk));

    switch (GCret)
    {
        case GC_TIMEOUT:
            TRACE ("GC_TIMEOUT\n");
            TRACE ("elapsed %d msecs\n", GetTickCount () - clk);
            break;

        case GC_NOKEY:
            TRACE ("GC_NOKEY\n");
            TRACE ("elapsed %d msecs\n", GetTickCount () - clk);
            goto loop;

        case GC_KEYREAD:
            TRACE ("GC_KEYREAD\n");
            TRACE ("elapsed %d msecs\n", GetTickCount () - clk);
            TRACE ("read %c", Ch);
            if ((val=IsKeyInString(lpOptions,Ch,bCaseSensitive))==-1)
            {
                Beep (440, 50);
                goto loop;
            }
            cDefault=Ch;
            break;
    }

    TRACE ("exiting wait loop after %d msecs\n",
                GetTickCount () - clk);

    val = IsKeyInString (lpOptions, cDefault, bCaseSensitive);
    ConOutPrintf(_T("%c\n"), lpOptions[val]);

    nErrorLevel = val + 1;

    freep (arg);

    TRACE ("ErrorLevel: %d\n", nErrorLevel);

    return 0;
}
Example #22
0
static TCHAR* GetWindowTitle(HANDLE *hContact, const char *szProto)
{
	DBVARIANT dbv;
	int isTemplate;
	int len, contactNameLen = 0, statusLen = 0, statusMsgLen = 0, protocolLen = 0;
	TCHAR *p, *tmplt, *szContactName = NULL, *szStatus = NULL, *szStatusMsg = NULL, *szProtocol = NULL, *title;
	TCHAR *pszNewTitleEnd = _tcsdup(TranslateT("Message Session"));
	isTemplate = 0;
	if (hContact && szProto) {
		szContactName = GetNickname(hContact, szProto);
		contactNameLen = lstrlen(szContactName);
		szStatus = strToWcs((char *) CallService(MS_CLIST_GETSTATUSMODEDESCRIPTION, szProto == NULL ? ID_STATUS_OFFLINE : DBGetContactSettingWord(hContact, szProto, "Status", ID_STATUS_OFFLINE), 0), -1, CP_ACP);
		statusLen = lstrlen(szStatus);
		if (!DBGetContactSetting(hContact, "CList", "StatusMsg",&dbv)) {
			if (strlen(dbv.pszVal) > 0) {
				int i, j;
       			szStatusMsg = strToWcs(dbv.pszVal, -1, CP_ACP);
				statusMsgLen = lstrlen(szStatusMsg);
				for (i = j = 0; i < statusMsgLen; i++) {
					if (szStatusMsg[i] == '\r') {
						continue;
					} else if (szStatusMsg[i] == '\n') {
						szStatusMsg[j++] = ' ';
					} else {
						szStatusMsg[j++] = szStatusMsg[i];
					}
				}
				szStatusMsg[j] = '\0';
				statusMsgLen = j;
			}
       		DBFreeVariant(&dbv);
		}

		if (!DBGetContactSetting(NULL, SRMMMOD, SRMSGSET_WINDOWTITLE, &dbv)) {
			isTemplate = 1;
			tmplt = strToWcs(dbv.pszVal, -1, CP_ACP);
			DBFreeVariant(&dbv);
		} else {
			int statusIcon = DBGetContactSettingByte(NULL, SRMMMOD, SRMSGSET_STATUSICON, SRMSGDEFSET_STATUSICON);
			if (statusIcon) {
				tmplt = _T("%name% - ");
			} else {
				tmplt = _T("%name% (%status%) : ");
			}
		}
	} else {
		tmplt = _T("");
	}
	for (len = 0, p = tmplt; *p; p++) {
		if (*p == '%') {
			if (!_tcsncmp(p, _T("%name%"), 6)) {
				len += contactNameLen;
				p += 5;
				continue;
			} else if (!_tcsncmp(p, _T("%status%"), 8)) {
				len += statusLen;
				p += 7;
				continue;
			} else if (!_tcsncmp(p, _T("%statusmsg%"), 11)) {
				len += statusMsgLen;
				p += 10;
				continue;
			}
		}
		len++;
	}
	if (!isTemplate) {
		len += lstrlen(pszNewTitleEnd);
	}
	title = (TCHAR *)malloc(sizeof(TCHAR) * (len + 1));
	for (len = 0, p = tmplt; *p; p++) {
		if (*p == '%') {
			if (!_tcsncmp(p, _T("%name%"), 6)) {
				memcpy(title+len, szContactName, sizeof(TCHAR) * contactNameLen);
				len += contactNameLen;
				p += 5;
				continue;
			} else if (!_tcsncmp(p, _T("%status%"), 8)) {
				memcpy(title+len, szStatus, sizeof(TCHAR) * statusLen);
				len += statusLen;
				p += 7;
				continue;
			} else if (!_tcsncmp(p, _T("%statusmsg%"), 11)) {
				memcpy(title+len, szStatusMsg, sizeof(TCHAR) * statusMsgLen);
				len += statusMsgLen;
				p += 10;
				continue;
			}
		}
		title[len++] = *p;
	}
	if (!isTemplate) {
		memcpy(title+len, pszNewTitleEnd, sizeof(TCHAR) * lstrlen(pszNewTitleEnd));
		len += lstrlen(pszNewTitleEnd);
	}
	title[len] = '\0';
	if (isTemplate) {
		free(tmplt);
	}
	free(szContactName);
	free(szStatus);
	free(pszNewTitleEnd);
	return title;
}
Example #23
0
int UsbSerial::ScanEnumTree( LPCTSTR lpEnumPath, TCHAR** openPorts )
{
  static const TCHAR lpstrPortsClass[] = TEXT("PORTS");
  static const TCHAR lpstrPortsClassGUID[] = TEXT("{4D36E978-E325-11CE-BFC1-08002BE10318}");

  DWORD  dwError=0;
  HKEY   hkEnum=NULL;
  DWORD  dwIndex1;
  HKEY   hkLevel1=NULL;
  DWORD  dwIndex2;
  HKEY   hkLevel2=NULL;
  HKEY   hkDeviceParameters=NULL;
  TCHAR  lpClass[sizeof(lpstrPortsClass)/sizeof(lpstrPortsClass[0])];
  DWORD  cbClass;
  TCHAR  lpClassGUID[sizeof(lpstrPortsClassGUID)/sizeof(lpstrPortsClassGUID[0])];
  DWORD  cbClassGUID;
  LPTSTR lpPortName=NULL;
  LPTSTR lpFriendlyName=NULL;
  
  int openCount = 0;

  typedef struct
  {
    LPCTSTR lpPortName;     /* "COM1", etc. */
    LPCTSTR lpFriendlyName; /* Suitable to describe the port, as for  */
                          /* instance "Infrared serial port (COM4)" */
  }LISTPORTS_PORTINFO;

  //printf( "ScanEnumTree(): top\n" );

  if(dwError=RegOpenKeyEx(HKEY_LOCAL_MACHINE,lpEnumPath,0,KEY_ENUMERATE_SUB_KEYS,&hkEnum)){
    goto end;
  }

  for(dwIndex1=0;;++dwIndex1)
  {
	//printf("finding loop; dwIndex1 = %d\n", dwIndex1);

    if(hkLevel1!=NULL){
      RegCloseKey(hkLevel1);
      hkLevel1=NULL;
    }
    if(dwError=OpenSubKeyByIndex(hkEnum,dwIndex1,KEY_ENUMERATE_SUB_KEYS,&hkLevel1)){
      if(dwError==ERROR_NO_MORE_ITEMS){
        dwError=0;
        break;
      }
      else goto end;
    }

      for(dwIndex2=0;;++dwIndex2){
        BOOL               bFriendlyNameNotFound=FALSE;
        LISTPORTS_PORTINFO portinfo;

        if(hkLevel2!=NULL){
          RegCloseKey(hkLevel2);
          hkLevel2=NULL;
        }
        if(dwError=OpenSubKeyByIndex(hkLevel1,dwIndex2,KEY_READ,&hkLevel2)){
          if(dwError==ERROR_NO_MORE_ITEMS){
            dwError=0;
            break;
          }
          else goto end;
        }

        /* Look if the driver class is the one we're looking for.
         * We accept either "CLASS" or "CLASSGUID" as identifiers.
         * No need to dynamically arrange for space to retrieve the values,
         * they must have the same length as the strings they're compared to
         * if the comparison is to be succesful.
         */

        cbClass=sizeof(lpClass);
        if(RegQueryValueEx(hkLevel2,TEXT("CLASS"),NULL,NULL,
                           (LPBYTE)lpClass,&cbClass)==ERROR_SUCCESS&&
           _tcsicmp(lpClass,lpstrPortsClass)==0){
          /* ok */
        }
        else{
          cbClassGUID=sizeof(lpClassGUID);
          if(RegQueryValueEx(hkLevel2,TEXT("CLASSGUID"),NULL,NULL,
                             (LPBYTE)lpClassGUID,&cbClassGUID)==ERROR_SUCCESS&&
             _tcsicmp(lpClassGUID,lpstrPortsClassGUID)==0){
            /* ok */
          }
          else continue;
        }

        /* get "PORTNAME" */

        dwError=QueryStringValue(hkLevel2,TEXT("PORTNAME"),&lpPortName);
        if(dwError==ERROR_FILE_NOT_FOUND){
          /* In Win200, "PORTNAME" is located under the subkey "DEVICE PARAMETERS".
           * Try and look there.
           */

          if(hkDeviceParameters!=NULL){
            RegCloseKey(hkDeviceParameters);
            hkDeviceParameters=NULL;
          }
          if(RegOpenKeyEx(hkLevel2,TEXT("DEVICE PARAMETERS"),0,KEY_READ,
                          &hkDeviceParameters)==ERROR_SUCCESS){
             dwError=QueryStringValue(hkDeviceParameters,TEXT("PORTNAME"),&lpPortName);
          }
        }
        if(dwError){
          if(dwError==ERROR_FILE_NOT_FOUND){ 
            /* boy that was strange, we better skip this device */
            dwError=0;
            continue;
          }
          else goto end;
        }
         //printf("found port, name %ls\n", lpPortName);

        /* check if it is a serial port (instead of, say, a parallel port) */

        if(_tcsncmp(lpPortName,TEXT("COM"),3)!=0)continue;

        /* now go for "FRIENDLYNAME" */

        if(dwError=QueryStringValue(hkLevel2,TEXT("FRIENDLYNAME"),&lpFriendlyName)){
          if(dwError==ERROR_FILE_NOT_FOUND){
            bFriendlyNameNotFound=TRUE;
            dwError=0;
          }
          else goto end;
        }
        
        /* Assemble the information and pass it on to the callback.
         * In the unlikely case there's no friendly name available,
         * use port name instead.
         */
        portinfo.lpPortName=lpPortName;
        portinfo.lpFriendlyName=bFriendlyNameNotFound?lpPortName:lpFriendlyName;
		{
			//printf( "Friendly name: %ls\n", portinfo.lpFriendlyName );
			if (!_tcsncmp(TEXT("Make Controller Kit"), portinfo.lpFriendlyName, 19))
			{
				TCHAR* pname;
				pname = _tcsdup(portinfo.lpPortName);
				//messageInterface->message( 1, "Found matching registry entry...\n" );
				// We've found a matching entry in the registry...
				// Now see if it's actually there by trying to open it
				int result = testOpen( pname );
				// if it is, store it
				if( result == 0 )
					openPorts[ openCount++ ] = pname; 
			}
        }
      }
  }
  goto end;

end:
  free(lpFriendlyName);
  free(lpPortName);
  if(hkDeviceParameters!=NULL)RegCloseKey(hkDeviceParameters);
  if(hkLevel2!=NULL)          RegCloseKey(hkLevel2);
  if(hkLevel1!=NULL)          RegCloseKey(hkLevel1);
  if(hkEnum!=NULL)            RegCloseKey(hkEnum);
  if(dwError!=0)
  {
    SetLastError(dwError);
    return 0; //TELEO_E_UNKNOWN;
  }
  else return openCount; //TELEO_OK;
}
Example #24
0
KD_TRANSFER_SYNTAX KDicomDS::GetTransferSyntax()
{
	KDicomElement * pDE;
   if((pDE = GetElement(0x0002,0x0010)) == NULL){
		return IMPLICIT_LITTLE;
   }
	CString str = pDE->GetValueUI(0);
	str.TrimRight(' ');

	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(_tcsncmp(str, _T("1.2.840.10008.1.2.4.50"), 22) == 0)
		return JPEG_BASELINE;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.51"), 22) == 0)
		return JPEG_EXTENDED_2_4;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.52"), 22) == 0)
		return JPEG_EXTENDED_3_5;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.53"), 22) == 0)
		return JPEG_SPECTRAL_6_8;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.54"), 22) == 0)
		return JPEG_SPECTRAL_7_9;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.55"), 22) == 0)
		return JPEG_FULL_10_12;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.56"), 22) == 0)
		return JPEG_FULL_11_13;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.57"), 22) == 0)
		return JPEG_LOSSLESS_14;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.58"), 22) == 0)
		return JPEG_LOSSLESS_15;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.59"), 22) == 0)
		return JPEG_EXTENDED_16_18;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.60"), 22) == 0)
		return JPEG_EXTENDED_17_19;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.61"), 22) == 0)
		return JPEG_SPECTRAL_20_22;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.62"), 22) == 0)
		return JPEG_SPECTRAL_21_23;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.63"), 22) == 0)
		return JPEG_FULL_24_26;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.64"), 22) == 0)
		return JPEG_FULL_25_27;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.65"), 22) == 0)
		return JPEG_LOSSLESS_28;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.66"), 22) == 0)
		return JPEG_LOSSLESS_29;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.70"), 22) == 0)
		return JPEG_LOSSLESS_FIRST_14;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.90"), 22) == 0)
		return JPEG_2000_IMAGE_COMPRESSON_LOSSLESS_ONLY;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.4.91"), 22) == 0)
		return JPEG_2000_IMAGE_COMPRESSON;
	else if(_tcsncmp(str, _T("1.2.840.10008.1.2.5"), 19) == 0)
		return RLE;
	else
		return IMPLICIT_LITTLE;
}
Example #25
0
int parseArguments(int argc, _TCHAR* argv[], encodingParameters *params)
{
	int i;
	for(i=1;i<argc;i++) {
		if(!_tcscmp(argv[i],_T("--fastest"))) params->overallQuality = kQualityFastest;
		else if(!_tcscmp(argv[i],_T("--fast"))) params->overallQuality = kQualityFast;
		else if(!_tcscmp(argv[i],_T("--normal"))) params->overallQuality = kQualityNormal;
		else if(!_tcscmp(argv[i],_T("--high"))) params->overallQuality = kQualityHigh;
		else if(!_tcscmp(argv[i],_T("--highest"))) params->overallQuality = kQualityHighest;
		else if(!_tcscmp(argv[i],_T("--quiet"))) params->quiet = true;
		else if(!_tcscmp(argv[i],_T("--cbr"))) {
			params->mode = kConfigCBR;
			if(++i<argc) {
				params->modeQuality = _tstoi(argv[i]);
				if(params->modeQuality < 8) params->modeQuality = 8;
				else if(params->modeQuality > 1280) params->modeQuality = 1280;
			}
		}
		else if(!_tcscmp(argv[i],_T("--abr"))) {
			params->mode = kConfigABR;
			if(++i<argc) {
				params->modeQuality = _tstoi(argv[i]);
				if(params->modeQuality < 8) params->modeQuality = 8;
				else if(params->modeQuality > 1280) params->modeQuality = 1280;
			}
		}
		else if(!_tcscmp(argv[i],_T("--cvbr"))) {
			params->mode = kConfigConstrainedVBR;
			if(++i<argc) {
				params->modeQuality = _tstoi(argv[i]);
				if(params->modeQuality < 8) params->modeQuality = 8;
				else if(params->modeQuality > 1280) params->modeQuality = 1280;
			}
		}
		else if(!_tcscmp(argv[i],_T("--tvbr"))) {
			params->mode = kConfigTrueVBR;
			if(++i<argc) {
				params->modeQuality = _tstoi(argv[i]);
				if(params->modeQuality < 0) params->modeQuality = 0;
				else if(params->modeQuality > 127) params->modeQuality = 127;
			}
		}
		else if(!_tcscmp(argv[i],_T("--samplerate"))) {
			if(++i<argc) {
				if(!_tcscmp(argv[i],_T("auto"))) params->outSamplerate = 0;
				else if(!_tcscmp(argv[i],_T("keep"))) params->outSamplerate = 1;
				else params->outSamplerate = _tstoi(argv[i]);
				if(params->outSamplerate < 0) params->outSamplerate = 0;
			}
		}
		else if(!_tcscmp(argv[i],_T("--title"))) {
			if(++i<argc) params->metadata.title = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--album"))) {
			if(++i<argc) params->metadata.album = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--artist"))) {
			if(++i<argc) params->metadata.artist = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--albumartist"))) {
			if(++i<argc) params->metadata.albumArtist = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--composer"))) {
			if(++i<argc) params->metadata.composer = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--grouping"))) {
			if(++i<argc) params->metadata.group = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--genre"))) {
			if(++i<argc) params->metadata.genre = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--date"))) {
			if(++i<argc) params->metadata.date = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--comment"))) {
			if(++i<argc) params->metadata.comment = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--track"))) {
			if(++i<argc) {
				_TCHAR *ptr;
				params->metadata.track = _tcstol(argv[i],&ptr,10);
				if(*ptr == _T('/')) params->metadata.totalTrack = _tcstol(ptr+1,&ptr,10);
			}
		}
		else if(!_tcscmp(argv[i],_T("--disc"))) {
			if(++i<argc) {
				_TCHAR *ptr;
				params->metadata.disc = _tcstol(argv[i],&ptr,10);
				if(*ptr == _T('/')) params->metadata.totalDisc = _tcstol(ptr+1,&ptr,10);
			}
		}
		else if(!_tcscmp(argv[i],_T("--compilation"))) {
			params->metadata.compilation = true;
		}
		else if(!_tcscmp(argv[i],_T("--ignorelength"))) {
			params->ignoreLength = true;
		}
		else if(!_tcscmp(argv[i],_T("--he"))) {
			params->highEfficiency = true;
		}
		else if(!_tcsncmp(argv[i],_T("--"),2)) {}
		else {
			if(!params->inFile) {
				params->inFile = argv[i];
				if(!_tcscmp(argv[i],_T("-"))) params->readFromStdin = true;
			}
			else if(!params->outFile) params->outFile = argv[i];
		}
	}
	if(!params->inFile) return -1;
	if(params->highEfficiency) {
		if(params->mode < 3) params->mode = (codecConfig)(params->mode + 4);
		else {
			fprintf(stderr,"Warning: HE-AAC encoder cannot be used with true VBR mode - disabled.\n");
			params->highEfficiency = false;
		}
	}
	return 0;
}
Example #26
0
static void parse_cmdline (int argc, TCHAR **argv)
{
	int i;

	for (i = 1; i < argc; i++) {
		if (!_tcsncmp (argv[i], "-diskswapper=", 13)) {
			TCHAR *txt = parsetext (argv[i] + 13);
			parse_diskswapper (txt);
			xfree (txt);
		} else if (_tcsncmp (argv[i], "-cfgparam=", 10) == 0) {
			;
		} else if (_tcscmp (argv[i], "-cfgparam") == 0) {
			if (i + 1 < argc)
				i++;
		} else if (_tcsncmp (argv[i], "-config=", 8) == 0) {
			TCHAR *txt = parsetext (argv[i] + 8);
			currprefs.mountitems = 0;
			target_cfgfile_load (&currprefs, txt, -1, 0);
			xfree (txt);
		} else if (_tcsncmp (argv[i], "-statefile=", 11) == 0) {
			TCHAR *txt = parsetext (argv[i] + 11);
			savestate_state = STATE_DORESTORE;
			_tcscpy (savestate_fname, txt);
			xfree (txt);
		} else if (_tcscmp (argv[i], "-f") == 0) {
			/* Check for new-style "-f xxx" argument, where xxx is config-file */
			if (i + 1 == argc) {
				write_log ("Missing argument for '-f' option.\n");
			} else {
				TCHAR *txt = parsetext (argv[++i]);
				currprefs.mountitems = 0;
				target_cfgfile_load (&currprefs, txt, -1, 0);
				xfree (txt);
			}
		} else if (_tcscmp (argv[i], "-s") == 0) {
			if (i + 1 == argc)
				write_log ("Missing argument for '-s' option.\n");
			else
				cfgfile_parse_line (&currprefs, argv[++i], 0);
		} else if (_tcscmp (argv[i], "-h") == 0 || _tcscmp (argv[i], "-help") == 0) {
			usage ();
			exit (0);
		} else if (_tcsncmp (argv[i], "-cdimage=", 9) == 0) {
			TCHAR *txt = parsetext (argv[i] + 9);
			TCHAR *txt2 = xmalloc(TCHAR, _tcslen(txt) + 2);
			_tcscpy(txt2, txt);
			if (_tcsrchr(txt2, ',') != NULL)
				_tcscat(txt2, ",");
			cfgfile_parse_option (&currprefs, "cdimage0", txt2, 0);
			xfree(txt2);
			xfree (txt);
		} else {
			if (argv[i][0] == '-' && argv[i][1] != '\0') {
				const TCHAR *arg = argv[i] + 2;
				int extra_arg = *arg == '\0';
				if (extra_arg)
					arg = i + 1 < argc ? argv[i + 1] : 0;
				if (parse_cmdline_option (&currprefs, argv[i][1], arg) && extra_arg)
					i++;
			}
		}
	}
}
Example #27
0
int	CRegExp::regmatch(TCHAR *prog)
{
	TCHAR *scan;	// Current node.
	TCHAR *next;		// Next node.

	for (scan = prog; scan != NULL; scan = next) {
		next = regnext(scan);

		switch (OP(scan)) {
		case BOL:
			if (reginput != regbol)
				return(0);
			break;
		case EOL:
			if (*reginput != _T('\0'))
				return(0);
			break;
		case ANY:
			if (*reginput == _T('\0'))
				return(0);
			reginput++;
			break;
		case EXACTLY: {
			size_t len;
			TCHAR *const opnd = OPERAND(scan);

			// Inline the first character, for speed.
			if (*opnd != *reginput)
				return(0);
			len = _tcslen(opnd);
			if (len > 1 && _tcsncmp(opnd, reginput, len) != 0)
				return(0);
			reginput += len;
			break;
			}
		case ANYOF:
			if (*reginput == _T('\0') ||
					_tcschr(OPERAND(scan), *reginput) == NULL)
				return(0);
			reginput++;
			break;
		case ANYBUT:
			if (*reginput == _T('\0') ||
					_tcschr(OPERAND(scan), *reginput) != NULL)
				return(0);
			reginput++;
			break;
		case NOTHING:
			break;
		case BACK:
			break;
		case OPEN+1: case OPEN+2: case OPEN+3:
		case OPEN+4: case OPEN+5: case OPEN+6:
		case OPEN+7: case OPEN+8: case OPEN+9: {
			const int no = OP(scan) - OPEN;
			TCHAR *const input = reginput;

			if (regmatch(next)) {
				// Don't set startp if some later
				// invocation of the same parentheses
				// already has.

				if (startp[no] == NULL)
					startp[no] = input;
				return(1);
			} else
				return(0);
			break;
			}
		case CLOSE+1: case CLOSE+2: case CLOSE+3:
		case CLOSE+4: case CLOSE+5: case CLOSE+6:
		case CLOSE+7: case CLOSE+8: case CLOSE+9: {
			const int no = OP(scan) - CLOSE;
			TCHAR *const input = reginput;

			if (regmatch(next)) {
				// Don't set endp if some later
				// invocation of the same parentheses
				// already has.

				if (endp[no] == NULL)
					endp[no] = input;
				return(1);
			} else
				return(0);
			break;
			}
		case BRANCH: {
			TCHAR *const save = reginput;

			if (OP(next) != BRANCH)		// No choice.
				next = OPERAND(scan);	// Avoid recursion.
			else {
				while (OP(scan) == BRANCH) {
					if (regmatch(OPERAND(scan)))
						return(1);
					reginput = save;
					scan = regnext(scan);
				}
				return(0);
				// NOTREACHED
			}
			break;
			}
		case STAR:
		case PLUS: {
			const TCHAR nextch =
				(OP(next) == EXACTLY) ? *OPERAND(next) : _T('\0');
			size_t no;
			TCHAR *const save = reginput;
			const size_t min = (OP(scan) == STAR) ? 0 : 1;

			for (no = regrepeat(OPERAND(scan)) + 1; no > min; no--) {
				reginput = save + no - 1;
				// If it could work, try it.
				if (nextch == _T('\0') || *reginput == nextch)
					if (regmatch(next))
						return(1);
			}
			return(0);
			break;
			}
		case END:
			return(1);	// Success!
			break;
		default:
			TRACE0("regexp corruption\n");
			return(0);
			break;
		}
	}

	// We get here only if there's trouble -- normally "case END" is
	// the terminating point.

	TRACE0("corrupted pointers\n");
	return(0);
}
Example #28
0
		ArrayBlock<RawMouse> getRawMouseArray()
		{
			UINT nDevices;
			PRAWINPUTDEVICELIST pRawInputDeviceList;
			list<RawMouse> rawMiceList;

			if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST)) != 0)
			{
				showErrorMessageAndExit(L"GetRawInputDeviceList() count");
			}

			pRawInputDeviceList = safeMallocExitOnFailure<RAWINPUTDEVICELIST>(nDevices);

			if (((INT) GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) < 0)
			{
				showErrorMessageAndExit(L"GetRawInputDeviceList() get");
			}

			for (UINT currentDeviceIndex = 0; currentDeviceIndex < nDevices; currentDeviceIndex++)
			{
				DWORD currentDeviceType = pRawInputDeviceList[currentDeviceIndex].dwType;
				HANDLE hDevice = pRawInputDeviceList[currentDeviceIndex].hDevice;

				if (currentDeviceType == RIM_TYPEMOUSE)
				{
					UINT cbSize;
					TCHAR* psName;

					if (GetRawInputDeviceInfo(hDevice, RIDI_DEVICENAME, NULL, &cbSize) != 0)
					{
						showErrorMessageAndExit(L"GetRawInputDeviceInfo() count");
					}

					psName = safeMallocExitOnFailure<TCHAR>(cbSize);

					if (((INT) GetRawInputDeviceInfo(hDevice, RIDI_DEVICENAME, psName, &cbSize)) < 0)
					{
						safe_free(&psName);
						showErrorMessageAndExit(L"GetRawInputDeviceInfo() get");
					}

					assert(_tcsnlen(psName, cbSize) == cbSize - 1);

					// We want to ignore RDP mice
					{
						TCHAR rdpMouseName[] = _T("\\\\?\\Root#RDP_MOU#0000#");
						size_t rdpMouseNameStrlen = _tcslen(rdpMouseName);

						if (_tcslen(psName) >= rdpMouseNameStrlen && 
							_tcsncmp(rdpMouseName, psName, rdpMouseNameStrlen) == 0)
						{
							safe_free(&psName);
							continue;
						}
					}

					safe_free(&psName);

					if (GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, NULL, &cbSize) != 0)
					{
						showErrorMessageAndExit(L"GetRawInputDeviceInfo() count");
					}

					PRID_DEVICE_INFO pDeviceInfo = safeMallocBytesExitOnFailure<RID_DEVICE_INFO>(cbSize);

					pDeviceInfo->cbSize = cbSize;

					if (((INT) GetRawInputDeviceInfo(hDevice, RIDI_DEVICEINFO, pDeviceInfo, &cbSize)) < 0)
					{
						showErrorMessageAndExit(L"GetRawInputDeviceInfo() get");
					}

					assert(pDeviceInfo->dwType == RIM_TYPEMOUSE);

					RawMouse currentMouse;
					currentMouse.deviceHandle = pRawInputDeviceList[currentDeviceIndex].hDevice;
					currentMouse.x = 0;
					currentMouse.y = 0;
					currentMouse.z = 0;
					currentMouse.buttonsPressed = ArrayBlock<bool>();
					currentMouse.buttonsPressed.allocate(pDeviceInfo->mouse.dwNumberOfButtons);

					memset(currentMouse.buttonsPressed.data(), 0, 
						sizeof(bool)*currentMouse.buttonsPressed.count());

					rawMiceList.push_back(currentMouse);
				}
			}

			safe_free(&pRawInputDeviceList);

			ArrayBlock<RawMouse> out_rawMiceArray;
			out_rawMiceArray.allocate(rawMiceList.size());

			size_t currentPos = 0;

			for (list<RawMouse>::iterator rawMouseIt = rawMiceList.begin(); 
				rawMouseIt != rawMiceList.end(); rawMouseIt++)
			{
				out_rawMiceArray.data()[currentPos] = *rawMouseIt;
				currentPos++;
			}

			return out_rawMiceArray;
		}
Example #29
0
		bool startsWith(const tchar *longString,const tchar *shortString)
		{
			if ((longString == NULL) || (shortString == NULL))
				return false;
			return (_tcsncmp(longString,shortString,_tcslen(shortString)) == 0);
		}
Example #30
0
HRESULT DeleteItemInCfgFile(IN LPTSTR szSection, IN LPTSTR szName, IN ITEM_TYPE iItemType,LPTSTR szCfgFile)
{
  HRESULT Hr=S_OK;
  //	TCHAR szCfgFile[MAX_PATH]=_T("");
  //	TCHAR szSection[MAX_PATH]=_T("");
  //	OpenDirInCfgFile(pidlCurDir,szSection,szCfgFile);
  //
  //    //3.Get the name of pidl
  //	CNWSPidlMgr pidlMgr;
  //    TCHAR szName[MAX_PATH]={};
  //    HR(pidlMgr.GetName(pidlItem,szName));
  //    //4.Get the type of pidl
  //    ITEM_TYPE iItemType;
  //     iItemType = pidlMgr.GetItemType(pidlItem);

  DWORD dwCheck;
  TCHAR tmpStr[MAX_PATH]={};
  DWORD dwLen=MAX_PATH;
  if( iItemType == NWS_FOLDER )
  {
    dwCheck = GetPrivateProfileString( szSection,_T("dir"),_T(""),tmpStr,dwLen, szCfgFile);
  }
  else if( iItemType == NWS_FILE )
  {
    dwCheck = GetPrivateProfileString( szSection,_T("file"),_T(""),tmpStr,dwLen, szCfgFile);
  }

  //5. delete the name of pidl if it exist in tmpStr and form a newstr
  TCHAR szNewStr[MAX_PATH]={};
  if(_tcsstr(tmpStr,szName)==NULL) //basiclly filter
  {
    MessageBox(NULL,_T("DeleteItemInCfgFile: the pidl to be deleted can't be found in current folder!"),_T("Error"),MB_OK);
    return E_FAIL;
  }

  INT iNameLen= (INT)_tcslen(szName);
  INT iStrLen = (INT)_tcslen(tmpStr);
  INT iPos = 0;
  TCHAR *pSplitChr=NULL;
  BOOL bFound=FALSE;
  while(iPos + iNameLen <= iStrLen)
  {
    if( iPos + iNameLen == iStrLen) 
    {
      if(_tcsncmp(tmpStr+iPos,szName,iNameLen) == 0) //is the tail item
      {
        //iPos=0:is the only one item; iPos!=0:has more than one items
        if(iPos != 0) 
          _tcsncpy(szNewStr,tmpStr,iPos-1);
        bFound=TRUE;
        break;
      }
    }
    else
    {
      pSplitChr=_tcschr(tmpStr+iPos,_T(';'));
      if(pSplitChr == NULL)
        break;
      if( ((pSplitChr-(tmpStr+iPos)) == iNameLen) && 
        (_tcsncmp(tmpStr+iPos,szName,iNameLen) == 0) )
      {
        _tcsncpy(szNewStr,tmpStr,iPos);
        _tcscat(szNewStr,pSplitChr+1);
        bFound=TRUE;
        break;
      }
      else
      {
        iPos = (INT)(pSplitChr - (TCHAR*)tmpStr[0] + 1);
      }
    }
  }
  if(bFound == FALSE)
  {
    MessageBox(NULL,_T("DeleteItemInCfgFile: pidl ready to delete can't be find in current folder!"),_T("Error"),MB_OK);
    return E_FAIL;
  }

  //6. delete the old keyvalue and insert the new keyvalue
  if( iItemType == NWS_FOLDER )
  {
    if(_tcslen(szNewStr)!=0)
      dwCheck = WritePrivateProfileString( szSection,_T("dir"),szNewStr,szCfgFile);
    else
      dwCheck = WritePrivateProfileString( szSection,_T("dir"),NULL,szCfgFile);


    //Delete the deleted folder's corresponding section from cfg file
    //Notes:
    //To make this sample project perfect,indeed,we need to
    //recursively delete all the sub folders corresponding sections
    //from configuration file, to do this will spend lots.
    //
    //However, for our purpose is to describe how to delete/create folder,
    //for simplicity, we only delete the section which directly
    //referred by the deleted folder object from configuration file.

    if(_tcscmp(szSection,_T("ROOT"))==0)
    {
      _tcsnset(szSection,0,MAX_PATH);
      _tcscpy(szSection,szName);
    }
    else
    {
      _tcscat(szSection,_T("\\"));
      _tcscat(szSection,szName);
    }
    WritePrivateProfileString(szSection,NULL,NULL,szCfgFile);
  }
  else if( iItemType == NWS_FILE )
  {
    if(_tcslen(szNewStr)!=0)
      dwCheck = WritePrivateProfileString( szSection,_T("file"),szNewStr,szCfgFile);
    else
      dwCheck = WritePrivateProfileString( szSection,_T("file"),NULL,szCfgFile);
  }
  return Hr;
}