Esempio n. 1
1
bool WDL_ChooseFileForSave(HWND parent, 
                                      const char *text, 
                                      const char *initialdir, 
                                      const char *initialfile, 
                                      const char *extlist,
                                      const char *defext,
                                      bool preservecwd,
                                      char *fn, 
                                      int fnsize,
                                      const char *dlgid,
                                      void *dlgProc,
#ifdef _WIN32
                                      HINSTANCE hInstance
#else
                                      struct SWELL_DialogResourceIndex *reshead
#endif
                                      )
{
  char cwd[2048];
  GetCurrentDirectory(sizeof(cwd),cwd);

#ifdef _WIN32
  char temp[4096];
  memset(temp,0,sizeof(temp));
  if (initialfile) lstrcpyn_safe(temp,initialfile,sizeof(temp));
  WDL_fixfnforopenfn(temp);

#ifdef WDL_FILEBROWSE_WIN7VISTAMODE
  {
    Win7FileDialog fd(text, 1);
    if(fd.inited())
    {
      fd.addOptions(FOS_DONTADDTORECENT);
      //vista+ file open dialog
      char olddir[2048];
      GetCurrentDirectory(sizeof(olddir),olddir);

      fd.setFilterList(extlist);
      if (defext) 
      {
        fd.setDefaultExtension(defext);

        int i = 0;
        const char *p = extlist;
        while(*p)
        {
          if(*p) p+=strlen(p)+1;
          if(!*p) break;
          if(stristr(p, defext)) 
          {
            fd.setFileTypeIndex(i+1);
            break;
          }
          i++;
          p+=strlen(p)+1;
        }
      }
      fd.setFolder(initialdir?initialdir:olddir, 0);
      if(initialfile) 
      {
        //check for folder name
        if (WDL_remove_filepart(temp))
        {
          //folder found
          fd.setFolder(temp, 0);
          fd.setFilename(temp + strlen(temp) + 1);
        }
        else
          fd.setFilename(*temp ? temp : initialfile);
      }
      fd.setTemplate(hInstance, dlgid, (LPOFNHOOKPROC)dlgProc);
      
      if(fd.show(parent))
      {
        //ifilesavedialog saves the last folder automatically
        fd.getResult(fn, fnsize);
        
        if (preservecwd) SetCurrentDirectory(olddir);
        return true;
      }
      
      if (preservecwd) SetCurrentDirectory(olddir);
      return NULL;
    }
  }
#endif


  OPENFILENAME l={sizeof(l),parent, hInstance, extlist, NULL,0, 0, temp, sizeof(temp)-1, NULL, 0, initialdir&&initialdir[0] ? initialdir : cwd, text, 
                  OFN_HIDEREADONLY|OFN_EXPLORER|OFN_OVERWRITEPROMPT,0,0,defext, 0, (LPOFNHOOKPROC)dlgProc, dlgid};

  if (hInstance&&dlgProc&&dlgid) l.Flags |= OFN_ENABLEHOOK|OFN_ENABLETEMPLATE|OFN_ENABLESIZING;
  if (preservecwd) l.Flags |= OFN_NOCHANGEDIR;

  if (!GetSaveFileName(&l)||!temp[0]) 
  {
    if (preservecwd) SetCurrentDirectory(cwd);
    return false;
  }
  if (preservecwd) SetCurrentDirectory(cwd);
  lstrcpyn_safe(fn,temp,fnsize);
  return true;

#else
  BrowseFile_SetTemplate(dlgid,(DLGPROC)dlgProc,reshead);
  char if_temp[4096];
  if (initialfile && *initialfile) 
  {
    lstrcpyn_safe(if_temp,initialfile,sizeof(if_temp));
    WDL_fixfnforopenfn(if_temp);
    initialfile = if_temp;
  }
  else
  {
    if (defext && *defext == '.') initialfile = defext; // SWELL supports default extension in filename field
  }

  bool r = BrowseForSaveFile(text,initialdir,initialfile,extlist,fn,fnsize);

  if (preservecwd) SetCurrentDirectory(cwd);

  return r;
#endif
}
Esempio n. 2
0
//初始化函数
BOOL CDlgRegister::OnInitDialog()
{
	__super::OnInitDialog();

	//设置标题
	SetWindowText(TEXT("帐号注册"));

	//限制输入
	((CComboBox *)(GetDlgItem(IDC_ACCOUNTS)))->LimitText(NAME_LEN-1);
	((CEdit *)(GetDlgItem(IDC_PASSWORD)))->LimitText(PASS_LEN-1);
	((CEdit *)(GetDlgItem(IDC_PASSWORD2)))->LimitText(PASS_LEN-1);
	m_LineRegWeb.SetHyperLinkUrl(TEXT("http://www.dc173.com"));
	m_LineMainPage.SetHyperLinkUrl(TEXT("http://www.dc173.com"));
	m_LinePassWord.SetHyperLinkUrl(TEXT("http://www.dc173.com"));

	//加载头像
	g_GlobalUnits.m_UserFaceRes->FillImageList(m_ImageList);
	m_FaceSelect.SetImageList(&m_ImageList);

	//插入头像
	COMBOBOXEXITEM Item;
	ZeroMemory(&Item,sizeof(Item));
	Item.mask=CBEIF_IMAGE|CBEIF_SELECTEDIMAGE;
	for (int i=g_GlobalUnits.m_UserFaceRes->GetFaceCount()-1;i>=0;i--) 
	{
		Item.lParam=i;
		Item.iImage=i;
		Item.iSelectedImage=i;
		m_FaceSelect.InsertItem(&Item);
	}

	//用户性别
	BYTE cbGender[]={/*GENDER_NULL,*/GENDER_BOY,GENDER_GIRL};
	LPCTSTR pszGender[]={/*TEXT("保密"),*/TEXT("男性"),TEXT("女性")};
	CComboBox * pComboBox=(CComboBox *)GetDlgItem(IDC_GENDER);

	//用户性别
	for (int i=0;i<CountArray(cbGender);i++)
	{
		int nItem=pComboBox->InsertString(i,pszGender[i]);
		pComboBox->SetItemData(nItem,cbGender[i]);
	}
	pComboBox->SetCurSel(0);

	//设置头像
	m_wFaceID=rand()%g_GlobalUnits.m_UserFaceRes->GetFaceCount();
	m_FaceSelect.SetCurSel(m_wFaceID);

	//获取目录
	TCHAR szPath[MAX_PATH]=TEXT("");
	GetCurrentDirectory(sizeof(szPath),szPath);

	//读取配置
	TCHAR szFileName[MAX_PATH]=TEXT("");
	_snprintf(szFileName,sizeof(szFileName),TEXT("%s\\Spreader.ini"),szPath);

	//读取推荐人
	TCHAR szSpreader[NAME_LEN]=TEXT("");
	GetPrivateProfileString(TEXT("SpreaderInfo"),TEXT("SpreaderName"),TEXT(""),szSpreader,CountArray(szSpreader),szFileName);

	//设置名字
	if (szSpreader[0]!=0)
	{
		SetDlgItemText(IDC_SPREADER,szSpreader);
		((CEdit *)GetDlgItem(IDC_SPREADER))->SetReadOnly();
	}

	return TRUE;
}
Esempio n. 3
0
void  ReadVOIPConfig(void)
{
    int   i;
    DJ_S8 sep[] = {","};
    char  buf[MAX_PREFIX][256] = {(0,0)};
    char  *p = NULL;
    char  *pBuf = NULL;
    char  chTmp[MAX_SEC]= {0};
    char  strTmp[256]= {0};

    /*read sysconfig from PBXGetWay.ini*/

    GetCurrentDirectory(MAX_FILE_NAME_LEN-32, cfg_IniName);
    strcat(cfg_IniName, cfg_IniShortName);

    GetPrivateProfileString("XMSCONFIG", "XMSIP", "192.168.10.132", cfg_ServerID.m_s8ServerIp, sizeof(cfg_ServerID.m_s8ServerIp), cfg_IniName);

    cfg_ServerID.m_u32ServerPort = GetPrivateProfileInt("XMSCONFIG", "XMSPORT", 9000, cfg_IniName);

    GetPrivateProfileString("XMSCONFIG","XMSUSER","",cfg_ServerID.m_s8UserName,sizeof(cfg_ServerID.m_s8UserName),cfg_IniName);
    GetPrivateProfileString("XMSCONFIG","XMSPASSWORD","",cfg_ServerID.m_s8UserPwd,sizeof(cfg_ServerID.m_s8UserPwd),cfg_IniName);
    g_u8UnitID = GetPrivateProfileInt("XMSCONFIG", "UNITID", 40, cfg_IniName);
    /*read work moduleID form PBXGetWay.ini*/
    GetPrivateProfileString("XMSCONFIG", "VOIPWORK","",cfg_chPartWorkModuleID, sizeof(cfg_chPartWorkModuleID), cfg_IniName);
    strncpy(strTmp, cfg_chPartWorkModuleID, sizeof(strTmp));
    SplitStr2Int(strTmp, ",", cfg_iVoipWorkMod);

    GetPrivateProfileString("XMSCONFIG", "DIGTRKWORK","",cfg_chPartWorkModuleID, sizeof(cfg_chPartWorkModuleID), cfg_IniName);
    strncpy(strTmp, cfg_chPartWorkModuleID, sizeof(strTmp));
    SplitStr2Int(strTmp, ",", cfg_iDTrkWorkMod);


    /*read ip pool from PBXGetWay.ini*/
    cfg_IpPool = GetPrivateProfileInt("IPPOOL", "ITEMCNT", 1, cfg_IniName);
    My_IpPoolItem(cfg_IpPool);
    My_IpPool(cfg_IpPool);

    for (i = 0; i < cfg_IpPool; i++)
    {
        if (pIpPool[i] != NULL)
            GetPrivateProfileString("IPPOOL",pIpPoolItem[i] , "", (LPTSTR )pIpPool[i], 20, cfg_IniName);
    }

    pubSendRTPDTMFType = GetPrivateProfileInt("RTPDTMF","SENDTYPE",1,cfg_IniName);
    pubDebug = GetPrivateProfileInt("XMSCONFIG","DEBUGON",0,cfg_IniName);

    GetPrivateProfileString("OUTBONDVOIP","VOIP_ADDRESS","",pubOutVoipAddress,sizeof(pubOutVoipAddress),cfg_IniName);
    pubOutVoipPort=GetPrivateProfileInt("OUTBONDVOIP","VOIP_PORT",5060,cfg_IniName);

    //VOIP输出规则
    pubVoipRule=GetPrivateProfileInt("VOIPRULE","OUTRULE",0,cfg_IniName);

    //日志开关
    bLog = GetPrivateProfileInt("LOG", "LOG", 0, cfg_IniName);

//	GetPrivateProfileString("DIALRULE", "DIALRULE", "", CodeRule, sizeof(CodeRule), cfg_IniName);

    cfg_routCnt = GetPrivateProfileInt("OUTBOUNDROUT", "ROUTCNT", 1, cfg_IniName);
    if (cfg_routCnt > 0)
    {

        outRout = new OutBoundRout[cfg_routCnt+1];
        memset(outRout, 0, sizeof(OutBoundRout) * (cfg_routCnt+1));
        if (outRout != NULL)
        {
            char routStr[10] = {0};
            char outRoutStr[512] = {0};
            for (i = 1; i <= cfg_routCnt; i++)
            {
                sprintf(routStr, "ROUT[%d]", i);
                GetPrivateProfileString("OUTBOUNDROUT", routStr ,"",outRoutStr,sizeof(OutBoundRout),cfg_IniName);
                assignmentOutBoundRout(outRoutStr, &outRout[i]);
            }
        }
    }

    cfg_FaxMode = GetPrivateProfileInt("FAXMODE", "FaxMode", 0, cfg_IniName);

    CreateDailRule(&pDailRuleHead);


    return ;
}
Esempio n. 4
0
int init(int argc, char *argv[]) {

#if WIN32
    char currentDirectory[MAX_PATH];
#endif

    srand(time(0));

    conInit();
    loadDefaults();
    timerInit();

    if (!commandLineRead(argc, argv))
        return 0;

    if (view.quit)
        return 0;

    if (!state.dontExecuteDefaultScript)
        configRead(findFile(CONFIG_FILE), 0);

#ifndef NO_GUI

    if (!gfxInit())
        return 1;

#endif

    if (state.historyFrames % 2)
        state.historyFrames--;

    fpsInit();

#ifdef WIN32
    // if we've gone this far, lets set the registry key even if it exists...
    GetCurrentDirectory(MAX_PATH, currentDirectory);
    setRegistryString(REGISTRY_NAME_PATH, currentDirectory);
#endif

#ifdef _OPENMP
    conAdd(LHELP, "multi-threaded rendering: max threads = %d.    Found %d processors.", 
                  state.processFrameThreads, omp_get_num_procs());
#endif

#ifndef NO_STDIO_REDIRECT
    // say hi (and keep stdout.txt alive on windows...)
    if(!view.useStdout && !view.screenSaver)
      printf("Welcome to %s.\n", GRAVIT_VERSION);
#endif

#ifdef WITHOUT_AGAR
    conAdd(LHELP, "Welcome to Gravit!");

#ifndef NO_GUI

    conAdd(LHELP, "Quick Start: Hit SPACE to start a new simulation!");
    conAdd(LHELP, "Hold down a mouse button and move it around. Use A and Z keys, or the scroll wheel to zoom in and out.");

#endif
#endif

    return 0;

}
Esempio n. 5
0
int VSRM_GetPath(char *filepath, unsigned int size)
{
#ifdef _WIN32
	int nSize = 0, i=0;
	char szPath[MAX_PATH] = {0,};
	GetModuleFileName(NULL, szPath, sizeof(szPath));
	nSize = (int)strlen(szPath);

	i=nSize;
	for (i=nSize; i>0; i--)
	{
		if (szPath[i]=='\\')
		{
			szPath[i] = '\0';
			break;
		}
		szPath[i] = '\0';
	}

	if (i < 1)
	{
		GetCurrentDirectory(MAX_PATH, szPath);
		nSize = (int)strlen(szPath);
		if ((unsigned int)nSize > size)
		{
			printf("VSRM_GetPath::  传入路径长度太小. 无法复制当前路径.");
		}
		else
		{
			strncpy(filepath, szPath, nSize);
		}
	}
	else
	{
		strncpy(filepath, szPath, nSize);
	}

	return 0;
#else
	char path[260] = {0,};
	int cnt = readlink("/proc/self/exe", path, sizeof(path));
	if (cnt < 0 || cnt>=sizeof(path))
	{
		printf("readlink error..\n");
		return -1;
	}
	
	int i=0;
	for (i=cnt; i>=0; --i)
	{
		if (path[i] == '/')
		{
			path[i+1] = '\0';
			break;
		}
	}

	int nSize = (int)strlen(path);
	if ((unsigned int)nSize > size)
	{
		_TRACE_ERR("VSRM_GetPath::  传入路径长度太小. 无法复制当前路径.");
	}
	else
	{
		strncpy(filepath, path, nSize);
		return 0;
	}
	return -1;
#endif
}
Esempio n. 6
0
// Вызывается для инициализации из Settings::LoadSettings()
HWND CConEmuInside::InsideFindParent()
{
	bool bFirstStep = true;
	DWORD nParentPID = 0;

	if (!m_InsideIntegration)
	{
		return NULL;
	}

	if (mh_InsideParentWND)
	{
		if (IsWindow(mh_InsideParentWND))
		{
			if (m_InsideIntegration == ii_Simple)
			{
				if (mh_InsideParentRoot == NULL)
				{
					// Если еще не искали "корневое" окно
					HWND hParent = mh_InsideParentWND;
					while (hParent)
					{
						mh_InsideParentRoot = hParent;
						hParent = GetParent(hParent);
					}
				}
				// В этом режиме занимаем всю клиентскую область
				_ASSERTE(mh_InsideParentRel==NULL);
				mh_InsideParentRel = NULL;
			}

			_ASSERTE(mh_InsideParentWND!=NULL);
			goto wrap;
		}
		else
		{
			if (m_InsideIntegration == ii_Simple)
			{
				DisplayLastError(L"Specified window not found");
				mh_InsideParentWND = NULL;
				goto wrap;
			}
			_ASSERTE(IsWindow(mh_InsideParentWND));
			mh_InsideParentRoot = mh_InsideParentWND = mh_InsideParentRel = NULL;
		}
	}

	_ASSERTE(m_InsideIntegration!=ii_Simple);

	if (mn_InsideParentPID)
	{
		PROCESSENTRY32 pi = {sizeof(pi)};
		if ((mn_InsideParentPID == GetCurrentProcessId())
			|| !GetProcessInfo(mn_InsideParentPID, &pi))
		{
			DisplayLastError(L"Invalid parent process specified");
			m_InsideIntegration = ii_None;
			mh_InsideParentWND = NULL;
			goto wrap;
		}
		nParentPID = mn_InsideParentPID;
	}
	else
	{
		PROCESSENTRY32 pi = {sizeof(pi)};
		if (!GetProcessInfo(GetCurrentProcessId(), &pi) || !pi.th32ParentProcessID)
		{
			DisplayLastError(L"GetProcessInfo(GetCurrentProcessId()) failed");
			m_InsideIntegration = ii_None;
			mh_InsideParentWND = NULL;
			goto wrap;
		}
		nParentPID = pi.th32ParentProcessID;
	}

	EnumWindows(EnumInsideFindParent, nParentPID);
	if (!mh_InsideParentRoot)
	{
		int nBtn = MsgBox(L"Can't find appropriate parent window!\n\nContinue in normal mode?", MB_ICONSTOP|MB_YESNO|MB_DEFBUTTON2);
		if (nBtn != IDYES)
		{
			mh_InsideParentWND = INSIDE_PARENT_NOT_FOUND;
			return mh_InsideParentWND; // Закрыться!
		}
		// Продолжить в обычном режиме
		m_InsideIntegration = ii_None;
		mh_InsideParentWND = NULL;
		goto wrap;
	}


    HWND hExistConEmu;
    if ((hExistConEmu = InsideFindConEmu(mh_InsideParentRoot)) != NULL)
    {
    	_ASSERTE(FALSE && "Continue to create tab in existing instance");
    	// Если в проводнике уже есть ConEmu - открыть в нем новую вкладку
    	gpSetCls->SingleInstanceShowHide = sih_None;
    	LPCWSTR pszCmdLine = GetCommandLine();
    	LPCWSTR pszCmd = StrStrI(pszCmdLine, L" /cmd ");
    	gpConEmu->RunSingleInstance(hExistConEmu, pszCmd ? (pszCmd + 6) : NULL);

		mh_InsideParentWND = INSIDE_PARENT_NOT_FOUND;
		return mh_InsideParentWND; // Закрыться!
    }

	// Теперь нужно найти дочерние окна
	// 1. в которое будем внедряться
	// 2. по которому будем позиционироваться
	// 3. для синхронизации текущего пути
	InsideFindShellView(mh_InsideParentRoot);

RepeatCheck:
	if (!mh_InsideParentWND || (!mh_InsideParentRel && (m_InsideIntegration == ii_Explorer)))
	{
		wchar_t szAddMsg[128] = L"", szMsg[1024];
		if (bFirstStep)
		{
			bFirstStep = false;

			if (TurnExplorerTipPane(szAddMsg))
			{
				goto RepeatCheck;
			}
		}

		//MessageBox(L"Can't find appropriate shell window!", MB_ICONSTOP);
		_wsprintf(szMsg, SKIPLEN(countof(szMsg)) L"%sCan't find appropriate shell window!\nUnrecognized layout of the Explorer.\n\nContinue in normal mode?", szAddMsg);
		int nBtn = MsgBox(szMsg, MB_ICONSTOP|MB_YESNO|MB_DEFBUTTON2);

		if (nBtn != IDYES)
		{
			mh_InsideParentWND = INSIDE_PARENT_NOT_FOUND;
			return mh_InsideParentWND; // Закрыться!
		}
		m_InsideIntegration = ii_None;
		mh_InsideParentRoot = NULL;
		mh_InsideParentWND = NULL;
		goto wrap;
	}

wrap:
	if (!mh_InsideParentWND)
	{
		m_InsideIntegration = ii_None;
		mh_InsideParentRoot = NULL;
	}
	else
	{
		GetWindowThreadProcessId(mh_InsideParentWND, &mn_InsideParentPID);
		// Для мониторинга папки
		GetCurrentDirectory(countof(ms_InsideParentPath), ms_InsideParentPath);
		int nLen = lstrlen(ms_InsideParentPath);
		if ((nLen > 3) && (ms_InsideParentPath[nLen-1] == L'\\'))
		{
			ms_InsideParentPath[nLen-1] = 0;
		}
	}

	return mh_InsideParentWND;
}
Esempio n. 7
0
BOOLEAN
SetupDriverName(
    _Inout_updates_bytes_all_(BufferLength) PCHAR DriverLocation,
    _In_ ULONG BufferLength
    )
{
    HANDLE fileHandle;
    DWORD driverLocLen = 0;

    //
    // Get the current directory.
    //

    driverLocLen = GetCurrentDirectory(BufferLength,
                                       DriverLocation
                                       );

    if (driverLocLen == 0 || driverLocLen < BufferLength) {

        printf("GetCurrentDirectory failed!  Error = %d \n", (int)GetLastError());

        return FALSE;
    }

    DriverLocation[ driverLocLen - 1 ] = '\0';

    //
    // Setup path name to driver file.
    //
    if (FAILED( StringCbCat(DriverLocation, BufferLength, "\\"DRIVER_NAME".sys") )) {
void getCurrentDirectory(char* buffer, int buffer_size)
{
	GetCurrentDirectory(buffer_size, buffer);
}
HRESULT AnimaApplication::CreateInstance( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	assert( AnimaApplication::mInstance == 0 );

	HWND	   hWnd;
	WNDCLASSEX winClass;
	memset( &winClass, 0x0, sizeof(WNDCLASSEX) );
	
	winClass.lpszClassName = "MY_WINDOWS_CLASS";
	winClass.cbSize        = sizeof(WNDCLASSEX);
	winClass.style         = CS_HREDRAW | CS_VREDRAW;
	winClass.lpfnWndProc   = WindowProc;
	winClass.hInstance     = hInstance;
	winClass.hIcon	       = LoadIcon(hInstance, (LPCTSTR)IDI_DIRECTX_ICON);
    winClass.hIconSm	   = LoadIcon(hInstance, (LPCTSTR)IDI_DIRECTX_ICON);
	winClass.hCursor       = LoadCursor(NULL, IDC_ARROW);
	winClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	winClass.lpszMenuName  = NULL;
	winClass.cbClsExtra    = 0;
	winClass.cbWndExtra    = 0;

	if( !RegisterClassEx(&winClass) )
		return E_FAIL;

	hWnd = CreateWindowEx( NULL, "MY_WINDOWS_CLASS", 
                             "DX9 Skinning Sample",
						     WS_OVERLAPPEDWINDOW | WS_VISIBLE,
					         0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT, NULL, NULL, hInstance, NULL );

	if( hWnd == NULL )
		return E_FAIL;

	// register raw input device
	RAWINPUTDEVICE Rid[2];
    Rid[0].usUsagePage = HID_USAGE_PAGE_GENERIC; 
    Rid[0].usUsage = HID_USAGE_GENERIC_MOUSE; 
    Rid[0].dwFlags = RIDEV_INPUTSINK;   
    Rid[0].hwndTarget = hWnd;
 
	// Keyboard
	Rid[1].usUsagePage = HID_USAGE_PAGE_GENERIC;
	Rid[1].usUsage = 6;
	Rid[1].dwFlags = 0;
	Rid[1].hwndTarget=hWnd;

	RegisterRawInputDevices( Rid, 2, sizeof(Rid[0]) );


	ShowWindow( hWnd, nCmdShow );
    UpdateWindow( hWnd );

	LPWSTR *szArglist;
	int nArgs;
	
	szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
	TestEnvironment* testEnvironment = new TestEnvironment( nArgs, szArglist );
	Math::Random::Init( testEnvironment->GetRandomSeed() );

	AnimaApplication::mInstance = new AnimaApplication( winClass, hWnd );

	char szCurrentDir[2048];
	GetCurrentDirectory( sizeof(szCurrentDir), szCurrentDir );
	strcat_s(szCurrentDir, "/../Shaders");
	Instance()->mShadersWatcher = FindFirstChangeNotification( szCurrentDir, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE);
	if (Instance()->mShadersWatcher  == INVALID_HANDLE_VALUE) 
		DXTRACE_ERR("Unable to monitor shaders directory. Live shaders editing will not work", E_FAIL );

	Instance()->mTestEnvironment = testEnvironment;
	Instance()->mRenderContext = new RenderContext( hWnd, DISPLAY_WIDTH, DISPLAY_HEIGHT );
	Instance()->mFramerateCounter = new FramerateCounter;

	Instance()->mUserInterface = new UserInterface( mInstance->mRenderContext, mInstance->mFramerateCounter );
	Instance()->mUserInterface->AcquireResources( Instance()->mRenderContext );

	Instance()->mInput = new Input();
	Instance()->mCamera = new Camera( *Instance()->mInput, *Instance()->mRenderContext );
	// set up renderer 

	Instance()->mModel = new SkeletalModel( "..\\Models\\frank.dae" );
	Instance()->mModel->Load( Instance()->mRenderContext );
	Instance()->mModel->SetNext( Instance()->mUserInterface );
	Instance()->mModel->PlayAnimation( 0, 0.25f );

	Instance()->mModelRotationAngle = 0.f;
	Instance()->mRotateModel = true;
	Instance()->mFrameCounter = 0;

	return S_OK;
}
Esempio n. 10
0
BOOL CTortoiseGitBlameApp::InitInstance()
{
	{
		DWORD len = GetCurrentDirectory(0, NULL);
		if (len)
		{
			std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]);
			if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
			{
				sOrigCWD = originalCurrentDirectory.get();
				sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
			}
		}
	}

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

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

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

	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinAppEx::InitInstance();

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL);

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

	SetRegistryKey(_T("TortoiseGit"));
	LoadStdProfileSettings(4);  // Load standard INI file options (including MRU)

	InitContextMenuManager();

	InitKeyboardManager();

	InitTooltipManager();
	CMFCToolTipInfo ttParams;
	ttParams.m_bVislManagerTheme = TRUE;
	theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL,
		RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams);

	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views
	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_TORTOISE_GIT_BLAME_MAINFRAME,
		RUNTIME_CLASS(CTortoiseGitBlameDoc),
		RUNTIME_CLASS(CMainFrame),       // main SDI frame window
		RUNTIME_CLASS(CTortoiseGitBlameView));
	if (!pDocTemplate)
		return FALSE;
	AddDocTemplate(pDocTemplate);

	CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine);
	g_sGroupingUUID = parser.GetVal(L"groupuuid");

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// Dispatch commands specified on the command line.  Will return FALSE if
	// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	// The one and only window has been initialized, so show and update it
	m_pMainWnd->ShowWindow(SW_SHOW);
	m_pMainWnd->UpdateWindow();
	// call DragAcceptFiles only if there's a suffix
	//  In an SDI app, this should occur after ProcessShellCommand
	return TRUE;
}
Esempio n. 11
0
// Open function modified by Donald Graft as part of fix for dropped frames and random frame access.
int CMPEG2Decoder::Open(const char *path)
{
	char buf[2048], *buf_p;

	Choose_Prediction(this->fastMC);

	char ID[80], PASS[80] = "DGIndexProjectFile16";
	DWORD i, j, size, code, type, tff, rff, film, ntsc, gop, top, bottom, mapping;
	int repeat_on, repeat_off, repeat_init;
	int vob_id, cell_id;
	__int64 position;
    int HadI;

	CMPEG2Decoder* out = this;

	out->VF_File = fopen(path, "r");
	if (fgets(ID, 79, out->VF_File)==NULL)
		return 1;
	if (strstr(ID, "DGIndexProjectFile") == NULL)
		return 5;
	if (strncmp(ID, PASS, 20))
		return 2;

	fscanf(out->VF_File, "%d\n", &File_Limit);
	i = File_Limit;
	while (i)
	{
		Infilename[File_Limit-i] = (char*)aligned_malloc(_MAX_PATH, 16);
		fgets(Infilename[File_Limit-i], _MAX_PATH - 1, out->VF_File);
		// Strip newline.
		Infilename[File_Limit-i][strlen(Infilename[File_Limit-i])-1] = 0;
		if (PathIsRelative(Infilename[File_Limit-i]))
		{
			char *p, d2v_stem[_MAX_PATH], open_path[_MAX_PATH];

			if (PathIsRelative(path))
			{
				GetCurrentDirectory(_MAX_PATH, d2v_stem);
				if (*(d2v_stem + strlen(d2v_stem) - 1) != '\\')
					strcat(d2v_stem, "\\");
				strcat(d2v_stem, path);
			}
			else
			{
				strcpy(d2v_stem, path);
			}
			p = d2v_stem + strlen(d2v_stem);
			while (*p != '\\' && p != d2v_stem) p--;
			if (p != d2v_stem)
			{
				p[1] = 0;
				strcat(d2v_stem, Infilename[File_Limit-i]);
				PathCanonicalize(open_path, d2v_stem);
				if ((Infile[File_Limit-i] = _open(open_path, _O_RDONLY | _O_BINARY))==-1)
					return 3;
			}
			else
			{
				// This should never happen because the code should guarantee that d2v_stem has a '\' character.
				return 3;
			}
		}
		else
		{
			if ((Infile[File_Limit-i] = _open(Infilename[File_Limit-i], _O_RDONLY | _O_BINARY))==-1)
				return 3;
		}
		i--;
	}

	fscanf(out->VF_File, "\nStream_Type=%d\n", &SystemStream_Flag);
	if (SystemStream_Flag == 2)
	{
		fscanf(out->VF_File, "MPEG2_Transport_PID=%x,%x,%x\n",
			   &MPEG2_Transport_VideoPID, &MPEG2_Transport_AudioPID, &MPEG2_Transport_PCRPID);
		fscanf(out->VF_File, "Transport_Packet_Size=%d\n", &TransportPacketSize);
	}
	fscanf(out->VF_File, "MPEG_Type=%d\n", &mpeg_type);
	fscanf(out->VF_File, "iDCT_Algorithm=%d\n", &IDCT_Flag);

	switch (IDCT_Flag)
	{
		case IDCT_MMX:
			idctFunc = MMX_IDCT;
			break;

		case IDCT_SSEMMX:
			idctFunc = SSEMMX_IDCT;
			if (!cpu.ssemmx)
			{
				IDCT_Flag = IDCT_MMX;
				idctFunc = MMX_IDCT;
			}
			break;

		case IDCT_FPU:
			if (!fpuinit) 
			{
				Initialize_FPU_IDCT();
				fpuinit = true;
			}
			idctFunc = FPU_IDCT;
			break;

		case IDCT_REF:
			if (!refinit) 
			{
				refinit = true;
			}
			idctFunc = REF_IDCT;
			break;

		case IDCT_SSE2MMX:
			idctFunc = SSE2MMX_IDCT;
			if (!cpu.sse2mmx)
			{
				IDCT_Flag = IDCT_SSEMMX;
				idctFunc = SSEMMX_IDCT;
				if (!cpu.ssemmx)
				{
					IDCT_Flag = IDCT_MMX;
					idctFunc = MMX_IDCT;
				}
			}
			break;
		
		case IDCT_SKALSSE:
			idctFunc = Skl_IDct16_Sparse_SSE; //Skl_IDct16_SSE;
			if (!cpu.ssemmx)
			{
				IDCT_Flag = IDCT_MMX;
				idctFunc = MMX_IDCT;
			}
			break;

		case IDCT_SIMPLEIDCT:
			idctFunc = simple_idct_mmx;
			if (!cpu.ssemmx)
			{
				IDCT_Flag = IDCT_MMX;
				idctFunc = MMX_IDCT;
			}
			break;
	}

	File_Flag = 0;
	_lseeki64(Infile[0], 0, SEEK_SET);
	Initialize_Buffer();

	do
	{
		if (Fault_Flag == OUT_OF_BITS) return 4;
		next_start_code();
		code = Get_Bits(32);
	}
	while (code!=SEQUENCE_HEADER_CODE);

	sequence_header();

	mb_width = (horizontal_size+15)/16;
	mb_height = progressive_sequence ? (vertical_size+15)/16 : 2*((vertical_size+31)/32);

	QP = (int*)aligned_malloc(sizeof(int)*mb_width*mb_height, 32);
	backwardQP = (int*)aligned_malloc(sizeof(int)*mb_width*mb_height, 32);
	auxQP = (int*)aligned_malloc(sizeof(int)*mb_width*mb_height, 32);

	Coded_Picture_Width = 16 * mb_width;
	Coded_Picture_Height = 16 * mb_height;

	Chroma_Width = (chroma_format==CHROMA444) ? Coded_Picture_Width : Coded_Picture_Width>>1;
	Chroma_Height = (chroma_format!=CHROMA420) ? Coded_Picture_Height : Coded_Picture_Height>>1;

	block_count = ChromaFormat[chroma_format];

	for (i=0; i<8; i++)
	{
		p_block[i] = (short *)aligned_malloc(sizeof(short)*64 + 64, 32);
		block[i]   = (short *)((long)p_block[i] + 64 - (long)p_block[i]%64);
	}

	for (i=0; i<3; i++)
	{
		if (i==0)
			size = Coded_Picture_Width * Coded_Picture_Height;
		else
			size = Chroma_Width * Chroma_Height;

		backward_reference_frame[i] = (unsigned char*)aligned_malloc(2*size+4096, 32);  //>>> cheap safety bump
		forward_reference_frame[i] = (unsigned char*)aligned_malloc(2*size+4096, 32);
		auxframe[i] = (unsigned char*)aligned_malloc(2*size+4096, 32);
	}

	fscanf(out->VF_File, "YUVRGB_Scale=%d\n", &pc_scale);

	fscanf(out->VF_File, "Luminance_Filter=%d,%d\n", &i, &j);
	if (i==0 && j==0)
		Luminance_Flag = 0;
	else
	{
		Luminance_Flag = 1;
		InitializeLuminanceFilter(i, j);
	}

	fscanf(out->VF_File, "Clipping=%d,%d,%d,%d\n", 
		   &Clip_Left, &Clip_Right, &Clip_Top, &Clip_Bottom);
	fscanf(out->VF_File, "Aspect_Ratio=%s\n", Aspect_Ratio);
	fscanf(out->VF_File, "Picture_Size=%dx%d\n", &D2V_Width, &D2V_Height);

	Clip_Width = Coded_Picture_Width;
	Clip_Height = Coded_Picture_Height;

	if (upConv > 0 && chroma_format == 1)
	{
		// these are labeled u422 and v422, but I'm only using them as a temporary
		// storage place for YV12 chroma before upsampling to 4:2:2 so that's why its
		// /4 and not /2  --  (tritical - 1/05/2005)
		int tpitch = (((Chroma_Width+15)>>4)<<4); // mod 16 chroma pitch needed to work with YV12PICTs
		u422 = (unsigned char*)aligned_malloc((tpitch * Coded_Picture_Height / 2)+2048, 32);
		v422 = (unsigned char*)aligned_malloc((tpitch * Coded_Picture_Height / 2)+2048, 32);
		auxFrame1 = create_YV12PICT(Coded_Picture_Height,Coded_Picture_Width,chroma_format+1);
		auxFrame2 = create_YV12PICT(Coded_Picture_Height,Coded_Picture_Width,chroma_format+1);
	}
/*
	ANT_DIRECTORY_ITERATOR_RECURSIVE::FIRST()
	-----------------------------------------
*/
ANT_directory_iterator_object *ANT_directory_iterator_recursive::first(ANT_directory_iterator_object *object)
{
file_list = handle_stack;

#ifdef _MSC_VER
	file_list->first_time = TRUE;
	GetCurrentDirectory(sizeof(file_list->path), file_list->path);
	strcat(file_list->path, "/*.*");

	return next(object);
#else
	/* the modification below would not affected the original way of reading files */
	long last_slash_idx = strlen(wildcard) - 1;
	char *last_char = wildcard + last_slash_idx; // searching backward
	char *slash = last_char;
	char *got;

	if (ANT_disk::is_directory(wildcard))
		{
		strcpy(path_buffer, wildcard);
		strcpy(this->wildcard, "*");
		}
	else
		{
		while (slash != wildcard)
			{
			if(*slash == '/')
				break;
			slash--;
			last_slash_idx--;
			}

		if (last_slash_idx <= 0) 		// the wildcard will be wildcard itself
			{
			if (getcwd(path_buffer, sizeof(path_buffer)) == NULL)
				return NULL;

			sprintf(path_buffer, "%s/", path_buffer); /* As we will later use this to mark dirs */
			}
		else // the wildcard will be after slash
			{
			strncpy(path_buffer, wildcard, last_slash_idx + 1);
			path_buffer[last_slash_idx+1] = '\0';
			if (last_char == slash)
				strcpy(this->wildcard, "*");
			else
				{
				char *wildcard_start = slash;
				wildcard_start++;
				long wildcard_len = last_char - wildcard_start + 1;
				// trim the wildcard path string to contain only the wildcard characters
				strncpy(this->wildcard, wildcard_start, wildcard_len);
				this->wildcard[wildcard_len] = '\0';
				}
			}
		}

	if ((got = first_match_wildcard(path_buffer)) == NULL)
		return NULL;

	object->filename = strnew(got);

	if (get_file)
		object->file = ANT_disk::read_entire_file(object->filename, &object->length);
	else
		{
		object->file = NULL;
		object->length = 0;
		}

	return object;
#endif
}
Esempio n. 13
0
std::string GetWorkingFolder()
{
	char sCurrentPath[MAX_PATH]={0};
	GetCurrentDirectory(MAX_PATH,sCurrentPath);
	return sCurrentPath;
}
Esempio n. 14
0
char *WDL_ChooseFileForOpen2(HWND parent,
                                        const char *text, 
                                        const char *initialdir,  
                                        const char *initialfile, 
                                        const char *extlist,
                                        const char *defext,

                                        bool preservecwd,
                                        int allowmul, 

                                        const char *dlgid, 
                                        void *dlgProc, 
#ifdef _WIN32
                                        HINSTANCE hInstance
#else
                                        struct SWELL_DialogResourceIndex *reshead
#endif
                                        )
{
  char olddir[2048];
  GetCurrentDirectory(sizeof(olddir),olddir);

#ifdef _WIN32

#ifdef WDL_FILEBROWSE_WIN7VISTAMODE
  if (allowmul!=1)
  {
    Win7FileDialog fd(text);
    if(fd.inited())
    {
      //vista+ file open dialog
      fd.addOptions(FOS_FILEMUSTEXIST|(allowmul?FOS_ALLOWMULTISELECT:0));
      fd.setFilterList(extlist);
      if (defext) 
      {
        fd.setDefaultExtension(defext);
        
        int i = 0;
        const char *p = extlist;
        while(*p)
        {
          if(*p) p+=strlen(p)+1;
          if(!*p) break;
          if(stristr(p, defext)) 
          {
            fd.setFileTypeIndex(i+1);
            break;
          }
          i++;
          p+=strlen(p)+1;
        }
      }
      fd.setFolder(initialdir?initialdir:olddir, 0);
      fd.setTemplate(hInstance, dlgid, (LPOFNHOOKPROC)dlgProc);
      if(initialfile) 
      {
        char temp[4096];
        lstrcpyn_safe(temp,initialfile,sizeof(temp));
        //check for folder name
        if (WDL_remove_filepart(temp))
        {
          //folder found
          fd.setFolder(temp, 0);
          fd.setFilename(temp + strlen(temp) + 1);
        }
        else
          fd.setFilename(temp);
      }

      if(fd.show(parent))
      {
        char *ret=NULL;
        char temp[4096];
        temp[0]=0;

        //ifileopendialog saves the last folder automatically
        if (!allowmul)
        {
          fd.getResult(temp, sizeof(temp)-1);
          ret= temp[0] ? strdup(temp) : NULL;
        }
        else
        {
          char* p=NULL;
          int totallen=0, cnt=fd.getResultCount();
          if (cnt>1)
          {
            // sets an empty path as 1st returned string for multipath support
            // (when selecting files among search results for ex.)
            ret = strdup("");
            totallen=1;
          }

          int i;
          for (i=0; i<cnt; i++)
          {
            int len = fd.getResult(i, temp, sizeof(temp)-1);
            p = len ? (char*)realloc(ret, totallen + len + ((i==cnt-1)?1:0)) : NULL;
            if (p)
            {
              ret=p;
              memcpy(ret+totallen, temp, len);
              totallen+=len;
            }
            else
            {
              free(ret);
              ret=NULL;
              break;
            }
          }
          if (ret) p[totallen]=0;
        }

        if (preservecwd) SetCurrentDirectory(olddir);
        return ret;
      }

      if (preservecwd) SetCurrentDirectory(olddir);
      return NULL;
    }
  }
#endif

  int temp_size = allowmul ? 256*1024-1 : 4096-1;
  char *temp = (char *)calloc(temp_size+1,1);

  OPENFILENAME l={sizeof(l), parent, hInstance, extlist, NULL, 0, 0, temp, temp_size, NULL, 0, initialdir, text,
    OFN_HIDEREADONLY|OFN_EXPLORER|OFN_FILEMUSTEXIST,0,0, (char *)(defext ? defext : ""), 0, (LPOFNHOOKPROC)dlgProc, dlgid};

  if (hInstance&&dlgProc&&dlgid) l.Flags |= OFN_ENABLEHOOK|OFN_ENABLETEMPLATE|OFN_ENABLESIZING;
  if (allowmul) l.Flags|=OFN_ALLOWMULTISELECT;
  if (preservecwd) l.Flags|=OFN_NOCHANGEDIR;

  if (initialfile) lstrcpyn_safe(temp,initialfile,temp_size);

  WDL_fixfnforopenfn(temp);

  if (!l.lpstrInitialDir||!l.lpstrInitialDir[0]) l.lpstrInitialDir=olddir;

  int r = GetOpenFileName(&l);
  if (preservecwd) SetCurrentDirectory(olddir);

  if (!r) free(temp);
  return r?temp:NULL;

#else  
  char if_temp[4096];
  if (initialfile) 
  {
    lstrcpyn_safe(if_temp,initialfile,sizeof(if_temp));
    WDL_fixfnforopenfn(if_temp);
    initialfile = if_temp;
  }
  
  // defext support?
  BrowseFile_SetTemplate(dlgid,(DLGPROC)dlgProc,reshead);
  char *ret = BrowseForFiles(text,initialdir,initialfile,allowmul,extlist);
  if (preservecwd) SetCurrentDirectory(olddir);

  return ret;
#endif
}
Esempio n. 15
0
	virtual BOOL InitInstance()
	{
		try{
			SetRegistryKey(G_softwarename());

			//boost process priority
			SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS);

			AfxInitRichEdit();
	//		AfxEnableControlContainer();
	//		AfxOleInit();

			{//create documents folder
				QString dir;
				GetDocumentsDir(dir);dir+=_qstr("\\");dir+=G_softwarename();
				CreateDirectory(dir,NULL);
			}


			CWinApp::InitInstance();

			//for 3D Connexion
			if (!AfxOleInit())
			{
				AfxMessageBox(L"OLE Init failed");
				return FALSE;
			}
			AfxEnableControlContainer();


			StrChar locstartupdir[600];
			GetCurrentDirectory(599,locstartupdir);
			startupdir=locstartupdir;
			datadir=startupdir+_qstr("/Data");
			{
				QString storeddatadir;
				QParamRead(PARAMLOCATION_REGISTRY,_qstr("DataDirectory"),storeddatadir);
				if (qstrlen(storeddatadir)>0)
					datadir=storeddatadir;
			}

			initlog();
			addlog(TFormatString(_text("Data directory: ^1"),datadir));

			scriptsdir=datadir;scriptsdir+=_qstr("\\Scripts");
			texturesdir=datadir;texturesdir+=_qstr("\\textures");

			addlog(_text("Fetching MAC address"));
			GetMACaddress(MACaddr);
			addlog(MACaddr);

			G_3DCosmos().LoadSettings();
			G_3DCosmos().init();


			loadstockcyclorbits();

			G_QXSys().startup();

			addlog(_text("Loading languages"),+1);
			QTranslate::Get().loadlanguages();
			addlog(_text("Loaded languages"),-1);

			addlog(_text("Creating source code window"),+1);
			mainwin= new Tmainwin();
			mainwin->createwindow(NULL,QString("Source code window"));
			addlog(_text("Source code window created"),-1);
			addlog(_text(""));
			addlog(_text(""));
			mainwin->ShowWindow(m_nCmdShow);
			m_pMainWnd=mainwin;

		}
		catch(QError &err)
		{
			reporterror(err.G_content());
		}

		return TRUE;
	}
Esempio n. 16
0
int _stdcall StartBurn (DWORD whichone,DWORD priority,DWORD mem_size)
{

command_line_string="\0";
dir_name_len=GetCurrentDirectory(100,(char*)current_dir);

_asm{
	lea		edi,current_dir
	mov		edx,dir_name_len
	add		edi,edx
	mov		ebx,whichone
	mov		eax,dword ptr[ebx]
	push	eax
	dec		eax
	shl		eax,3
	mov		esi,const_names
	add		esi,eax
	mov		ecx,7
	rep	movsb
	add		ecx,5
	mov		esi,exe
	rep movsb
	mov		ecx,edx
	add		ecx,11
	lea		esi,current_dir
	lea		edi,burn_exe_name
	rep movsb

		mov		byte ptr [edi],32
		inc		edi
		pop		ebx
		cmp		ebx,4
		jl		skip_cls
		cmp		ebx,5
		jg		skip_cls
		//mov		edi,command_line_string
		mov		edx,mem_size	
		mov		eax,[edx]
		add		eax,65
		mov		byte ptr[edi],al
		mov		byte ptr[edi+1],0
skip_cls:	
}


startup_info.cb=sizeof(STARTUPINFO);
startup_info.lpReserved=NULL;
startup_info.lpDesktop="";
startup_info.lpTitle="Burning!";
startup_info.lpReserved2=NULL;
startup_info.cbReserved2=0;
startup_info.dwFlags=STARTF_USESHOWWINDOW;
startup_info.wShowWindow=SW_MINIMIZE;

_asm{
	mov		ebx,priority
	mov		cl,byte ptr[ebx]
	mov		edx,0x20
	dec		ecx
	shl		edx,cl
	mov		eax,edx
	and		eax,0x100
	shr		eax,1
	or		edx,eax
	mov		flags,dl


}
/*
HIGH_PRIORITY_CLASS = 0x80
IDLE_PRIORITY_CLASS = 0x40
NORMAL_PRIORITY_CLASS = 0x20
REALTIME_PRIORITY_CLASS = 0x00
*/

CreateProcess(NULL,burn_exe_name,NULL,NULL,TRUE,flags,
			  NULL,NULL,&startup_info,&proc_info);


return(0);
}


int _stdcall IsStillBurning ()
{


return(0);
}


int _stdcall Kill_me ()
{

TerminateProcess(proc_info.hProcess,0);

return(0);
}
Esempio n. 17
0
LRESULT CMainFrame::EnterStation(WPARAM wPanel,LPARAM Mylparamp)
{
	MI_SETTING* wMI =  (MI_SETTING*)wPanel;
	PROCESS_INFORMATION *pi = &(wMI->m_pi);
	HANDLE  hProcess = OpenProcess(PROCESS_QUERY_INFORMATION , FALSE, pi->dwProcessId);
	if(hProcess == NULL)
	{
		//创建新的进程
		//AfxMessageBox(_T("This Chanel is Close."));
		int ret = MessageBox(_T("This Chanel is Close.ReCreate it."),_T("Chanel Error"),MB_YESNO);
		if (ret ==IDYES)
		{
			wchar_t m_sCurrentPath[MAX_PATH];
			GetCurrentDirectory(MAX_PATH,m_sCurrentPath);
			CString ApplicationName;
			ApplicationName=m_sCurrentPath;
			ApplicationName+=_T("\\AOIEDIT.EXE");
			STARTUPINFO si;
			ZeroMemory(&si,sizeof(si)); 
			si.cb   =   sizeof   STARTUPINFO; 
			si.lpReserved=NULL;    
			si.lpDesktop=NULL;    
			si.lpTitle=NULL;    
			si.dwX=0;    
			si.dwY=0;    
			si.dwXSize=0;    
			si.dwYSize=0;    
			si.dwXCountChars=500;    
			si.dwYCountChars=500;    
			si.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;    
			si.wShowWindow=SW_HIDE;    
			//说明进程将以隐藏的方式在后台执行    
			si.cbReserved2=0;    
			si.lpReserved2=NULL;    
			si.hStdInput=stdin;    
			si.hStdOutput=stdout;    
			si.hStdError=stderr;  

			//C:\\WINDOWS\\SYSTEM32\\NOTEPAD.EXE")

			CString cmd;
			cmd.Format(_T("%s$%s$%d$"),wMI->szStationID,wMI->szProgramName,wMI->ch);
			BOOL fRet=CreateProcess(ApplicationName,cmd.GetBuffer(),NULL,NULL,TRUE,NULL ,NULL,NULL,&si,&(wMI->m_pi));
			if(fRet==false)   
			{   
				AfxMessageBox(_T("CreateProcess    failed"));   
				//exit(1);
			}   
			else   
			{   
				WaitForInputIdle(wMI->m_pi.hProcess,0);   
				CloseHandle(wMI->m_pi.hThread);   
				CloseHandle(wMI->m_pi.hProcess);   
			}  
			EnumThreadWindows(pi->dwThreadId,EnumThreadWndProc,MI_SHOW);
		}
		return 0;

	}
	EnumThreadWindows(pi->dwThreadId,EnumThreadWndProc,MI_SHOW);
	::CloseHandle(hProcess);

	return 0;
}
Esempio n. 18
0
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	// Init any globals not in "struct g" that need it:
	g_hInstance = hInstance;
	InitializeCriticalSection(&g_CriticalRegExCache); // v1.0.45.04: Must be done early so that it's unconditional, so that DeleteCriticalSection() in the script destructor can also be unconditional (deleting when never initialized can crash, at least on Win 9x).

	if (!GetCurrentDirectory(sizeof(g_WorkingDir), g_WorkingDir)) // Needed for the FileSelectFile() workaround.
		*g_WorkingDir = '\0';
	// Unlike the below, the above must not be Malloc'd because the contents can later change to something
	// as large as MAX_PATH by means of the SetWorkingDir command.
	g_WorkingDirOrig = SimpleHeap::Malloc(g_WorkingDir); // Needed by the Reload command.

	// Set defaults, to be overridden by command line args we receive:
	bool restart_mode = false;

#ifndef AUTOHOTKEYSC
	#ifdef _DEBUG
		//char *script_filespec = "C:\\Util\\AutoHotkey.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\GUI Demo.ahk";
		char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\MAIN.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\Expressions.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\Line Continuation.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\DllCall.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\RegExMatch & RegExReplace.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\Win commands, all cases.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\GUI Date.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\GUI ListView.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\OnMessage.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\TEST SUITES\\Send command.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Ref\\ImageSearch\\TEST SUITE\\MAIN.ahk";
		//char *script_filespec = "C:\\A-Source\\AutoHotkey\\Test\\New Text Document.ahk";
	#else
		char *script_filespec = NULL; // Set default as "unspecified/omitted".
	#endif
#endif

	// The problem of some command line parameters such as /r being "reserved" is a design flaw (one that
	// can't be fixed without breaking existing scripts).  Fortunately, I think it affects only compiled
	// scripts because running a script via AutoHotkey.exe should avoid treating anything after the
	// filename as switches. This flaw probably occurred because when this part of the program was designed,
	// there was no plan to have compiled scripts.
	//
	// Examine command line args.  Rules:
	// Any special flags (e.g. /force and /restart) must appear prior to the script filespec.
	// The script filespec (if present) must be the first non-backslash arg.
	// All args that appear after the filespec are considered to be parameters for the script
	// and will be added as variables %1% %2% etc.
	// The above rules effectively make it impossible to autostart AutoHotkey.ini with parameters
	// unless the filename is explicitly given (shouldn't be an issue for 99.9% of people).
	char var_name[32], *param; // Small size since only numbers will be used (e.g. %1%, %2%).
	Var *var;
	bool switch_processing_is_complete = false;
	int script_param_num = 1;

	for (int i = 1; i < __argc; ++i) // Start at 1 because 0 contains the program name.
	{
		param = __argv[i]; // For performance and convenience.
		if (switch_processing_is_complete) // All args are now considered to be input parameters for the script.
		{
			if (   !(var = g_script.FindOrAddVar(var_name, sprintf(var_name, "%d", script_param_num)))   )
				return CRITICAL_ERROR;  // Realistically should never happen.
			var->Assign(param);
			++script_param_num;
		}
		// Insist that switches be an exact match for the allowed values to cut down on ambiguity.
		// For example, if the user runs "CompiledScript.exe /find", we want /find to be considered
		// an input parameter for the script rather than a switch:
		else if (!stricmp(param, "/R") || !stricmp(param, "/restart"))
			restart_mode = true;
		else if (!stricmp(param, "/F") || !stricmp(param, "/force"))
			g_ForceLaunch = true;
		else if (!stricmp(param, "/ErrorStdOut"))
			g_script.mErrorStdOut = true;
#ifndef AUTOHOTKEYSC // i.e. the following switch is recognized only by AutoHotkey.exe (especially since recognizing new switches in compiled scripts can break them, unlike AutoHotkey.exe).
		else if (!stricmp(param, "/iLib")) // v1.0.47: Build an include-file so that ahk2exe can include library functions called by the script.
		{
			++i; // Consume the next parameter too, because it's associated with this one.
			if (i >= __argc) // Missing the expected filename parameter.
				return CRITICAL_ERROR;
			// For performance and simplicity, open/crease the file unconditionally and keep it open until exit.
			if (   !(g_script.mIncludeLibraryFunctionsThenExit = fopen(__argv[i], "w"))   ) // Can't open the temp file.
				return CRITICAL_ERROR;
		}
#endif
		else // since this is not a recognized switch, the end of the [Switches] section has been reached (by design).
		{
			switch_processing_is_complete = true;  // No more switches allowed after this point.
#ifdef AUTOHOTKEYSC
			--i; // Make the loop process this item again so that it will be treated as a script param.
#else
			script_filespec = param;  // The first unrecognized switch must be the script filespec, by design.
#endif
		}
	}

#ifndef AUTOHOTKEYSC
	if (script_filespec)// Script filename was explicitly specified, so check if it has the special conversion flag.
	{
		size_t filespec_length = strlen(script_filespec);
		if (filespec_length >= CONVERSION_FLAG_LENGTH)
		{
			char *cp = script_filespec + filespec_length - CONVERSION_FLAG_LENGTH;
			// Now cp points to the first dot in the CONVERSION_FLAG of script_filespec (if it has one).
			if (!stricmp(cp, CONVERSION_FLAG))
				return Line::ConvertEscapeChar(script_filespec);
		}
	}
#endif

	// Like AutoIt2, store the number of script parameters in the script variable %0%, even if it's zero:
	if (   !(var = g_script.FindOrAddVar("0"))   )
		return CRITICAL_ERROR;  // Realistically should never happen.
	var->Assign(script_param_num - 1);

	global_init(g);  // Set defaults prior to the below, since below might override them for AutoIt2 scripts.

// Set up the basics of the script:
#ifdef AUTOHOTKEYSC
	if (g_script.Init("", restart_mode) != OK)
#else
	if (g_script.Init(script_filespec, restart_mode) != OK)  // Set up the basics of the script, using the above.
#endif
		return CRITICAL_ERROR;

	// Set g_default now, reflecting any changes made to "g" above, in case AutoExecSection(), below,
	// never returns, perhaps because it contains an infinite loop (intentional or not):
	CopyMemory(&g_default, &g, sizeof(global_struct));

	// Could use CreateMutex() but that seems pointless because we have to discover the
	// hWnd of the existing process so that we can close or restart it, so we would have
	// to do this check anyway, which serves both purposes.  Alt method is this:
	// Even if a 2nd instance is run with the /force switch and then a 3rd instance
	// is run without it, that 3rd instance should still be blocked because the
	// second created a 2nd handle to the mutex that won't be closed until the 2nd
	// instance terminates, so it should work ok:
	//CreateMutex(NULL, FALSE, script_filespec); // script_filespec seems a good choice for uniqueness.
	//if (!g_ForceLaunch && !restart_mode && GetLastError() == ERROR_ALREADY_EXISTS)

#ifdef AUTOHOTKEYSC
	LineNumberType load_result = g_script.LoadFromFile();
#else
	LineNumberType load_result = g_script.LoadFromFile(script_filespec == NULL);
#endif
	if (load_result == LOADING_FAILED) // Error during load (was already displayed by the function call).
		return CRITICAL_ERROR;  // Should return this value because PostQuitMessage() also uses it.
	if (!load_result) // LoadFromFile() relies upon us to do this check.  No lines were loaded, so we're done.
		return 0;

	// Unless explicitly set to be non-SingleInstance via SINGLE_INSTANCE_OFF or a special kind of
	// SingleInstance such as SINGLE_INSTANCE_REPLACE and SINGLE_INSTANCE_IGNORE, persistent scripts
	// and those that contain hotkeys/hotstrings are automatically SINGLE_INSTANCE_PROMPT as of v1.0.16:
	if (g_AllowOnlyOneInstance == ALLOW_MULTI_INSTANCE && IS_PERSISTENT)
		g_AllowOnlyOneInstance = SINGLE_INSTANCE_PROMPT;

	HWND w_existing = NULL;
	UserMessages reason_to_close_prior = (UserMessages)0;
	if (g_AllowOnlyOneInstance && g_AllowOnlyOneInstance != SINGLE_INSTANCE_OFF && !restart_mode && !g_ForceLaunch)
	{
		// Note: the title below must be constructed the same was as is done by our
		// CreateWindows(), which is why it's standardized in g_script.mMainWindowTitle:
		if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
		{
			if (g_AllowOnlyOneInstance == SINGLE_INSTANCE_IGNORE)
				return 0;
			if (g_AllowOnlyOneInstance != SINGLE_INSTANCE_REPLACE)
				if (MsgBox("An older instance of this script is already running.  Replace it with this"
					" instance?\nNote: To avoid this message, see #SingleInstance in the help file."
					, MB_YESNO, g_script.mFileName) == IDNO)
					return 0;
			// Otherwise:
			reason_to_close_prior = AHK_EXIT_BY_SINGLEINSTANCE;
		}
	}
	if (!reason_to_close_prior && restart_mode)
		if (w_existing = FindWindow(WINDOW_CLASS_MAIN, g_script.mMainWindowTitle))
			reason_to_close_prior = AHK_EXIT_BY_RELOAD;
	if (reason_to_close_prior)
	{
		// Now that the script has been validated and is ready to run, close the prior instance.
		// We wait until now to do this so that the prior instance's "restart" hotkey will still
		// be available to use again after the user has fixed the script.  UPDATE: We now inform
		// the prior instance of why it is being asked to close so that it can make that reason
		// available to the OnExit subroutine via a built-in variable:
		ASK_INSTANCE_TO_CLOSE(w_existing, reason_to_close_prior);
		//PostMessage(w_existing, WM_CLOSE, 0, 0);

		// Wait for it to close before we continue, so that it will deinstall any
		// hooks and unregister any hotkeys it has:
		int interval_count;
		for (interval_count = 0; ; ++interval_count)
		{
			Sleep(20);  // No need to use MsgSleep() in this case.
			if (!IsWindow(w_existing))
				break;  // done waiting.
			if (interval_count == 100)
			{
				// This can happen if the previous instance has an OnExit subroutine that takes a long
				// time to finish, or if it's waiting for a network drive to timeout or some other
				// operation in which it's thread is occupied.
				if (MsgBox("Could not close the previous instance of this script.  Keep waiting?", 4) == IDNO)
					return CRITICAL_ERROR;
				interval_count = 0;
			}
		}
		// Give it a small amount of additional time to completely terminate, even though
		// its main window has already been destroyed:
		Sleep(100);
	}

	// Call this only after closing any existing instance of the program,
	// because otherwise the change to the "focus stealing" setting would never be undone:
	SetForegroundLockTimeout();

	// Create all our windows and the tray icon.  This is done after all other chances
	// to return early due to an error have passed, above.
	if (g_script.CreateWindows() != OK)
		return CRITICAL_ERROR;

	// At this point, it is nearly certain that the script will be executed.

	if (g_MaxHistoryKeys && (g_KeyHistory = (KeyHistoryItem *)malloc(g_MaxHistoryKeys * sizeof(KeyHistoryItem))))
		ZeroMemory(g_KeyHistory, g_MaxHistoryKeys * sizeof(KeyHistoryItem)); // Must be zeroed.
	//else leave it NULL as it was initialized in globaldata.

	// MSDN: "Windows XP: If a manifest is used, InitCommonControlsEx is not required."
	// Therefore, in case it's a high overhead call, it's not done on XP or later:
	if (!g_os.IsWinXPorLater())
	{
		// Since InitCommonControls() is apparently incapable of initializing DateTime and MonthCal
		// controls, InitCommonControlsEx() must be called.  But since Ex() requires comctl32.dll
		// 4.70+, must get the function's address dynamically in case the program is running on
		// Windows 95/NT without the updated DLL (otherwise the program would not launch at all).
		typedef BOOL (WINAPI *MyInitCommonControlsExType)(LPINITCOMMONCONTROLSEX);
		MyInitCommonControlsExType MyInitCommonControlsEx = (MyInitCommonControlsExType)
			GetProcAddress(GetModuleHandle("comctl32"), "InitCommonControlsEx"); // LoadLibrary shouldn't be necessary because comctl32 in linked by compiler.
		if (MyInitCommonControlsEx)
		{
			INITCOMMONCONTROLSEX icce;
			icce.dwSize = sizeof(INITCOMMONCONTROLSEX);
			icce.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES; // ICC_WIN95_CLASSES is equivalent to calling InitCommonControls().
			MyInitCommonControlsEx(&icce);
		}
		else // InitCommonControlsEx not available, so must revert to non-Ex() to make controls work on Win95/NT4.
			InitCommonControls();
	}

	// Activate the hotkeys, hotstrings, and any hooks that are required prior to executing the
	// top part (the auto-execute part) of the script so that they will be in effect even if the
	// top part is something that's very involved and requires user interaction:
	Hotkey::ManifestAllHotkeysHotstringsHooks(); // We want these active now in case auto-execute never returns (e.g. loop)
	g_script.mIsReadyToExecute = true; // This is done only now for error reporting purposes in Hotkey.cpp.

	// Run the auto-execute part at the top of the script (this call might never return):
	ResultType result = g_script.AutoExecSection();
	// If no hotkeys are in effect, the user hasn't requested a hook to be activated, and the script
	// doesn't contain the #Persistent directive we're done unless the OnExit subroutine doesn't exit:
	if (!IS_PERSISTENT) // Resolve macro again in case any of its components changed since the last time.
		g_script.ExitApp(result == FAIL ? EXIT_ERROR : EXIT_EXIT);

	// The below is done even if AutoExecSectionTimeout() already set the values once.
	// This is because when the AutoExecute section finally does finish, by definition it's
	// supposed to store the global settings that are currently in effect as the default values.
	// In other words, the only purpose of AutoExecSectionTimeout() is to handle cases where
	// the AutoExecute section takes a long time to complete, or never completes (perhaps because
	// it is being used by the script as a "backround thread" of sorts):
	// Save the values of KeyDelay, WinDelay etc. in case they were changed by the auto-execute part
	// of the script.  These new defaults will be put into effect whenever a new hotkey subroutine
	// is launched.  Each launched subroutine may then change the values for its own purposes without
	// affecting the settings for other subroutines:
	global_clear_state(g);  // Start with a "clean slate" in both g and g_default.
	CopyMemory(&g_default, &g, sizeof(global_struct)); // Above has set g.IsPaused==false in case it's ever possible that it's true as a result of AutoExecSection().
	// After this point, the values in g_default should never be changed.

	// It seems best to set ErrorLevel to NONE after the auto-execute part of the script is done.
	// However, we do not set it to NONE right before launching each new hotkey subroutine because
	// it's more flexible that way (i.e. the user may want one hotkey subroutine to use the value of
	// ErrorLevel set by another).  This reset was also done by LoadFromFile(), but we do it again
	// here in case the auto-exectute section changed it:
	g_ErrorLevel->Assign(ERRORLEVEL_NONE);

	// Since we're about to enter the script's idle state, set the "idle thread" to
	// be minimum priority so that it can always be "interrupted" (though technically,
	// there is no actual idle quasi-thread, so it can't really be interrupted):
	g.Priority = PRIORITY_MINIMUM;
	g.ThreadIsCritical = false;            // v1.0.38.04: Prevent the idle thread from being seen as uninterruptible.
	g.AllowTimers = true;                  // v1.0.40.01: Similar to above.
	g.AllowThreadToBeInterrupted = true;   // This is the primary line, the one above is not strictly necessary (just for maintainability).

	// Call it in this special mode to kick off the main event loop.
	// Be sure to pass something >0 for the first param or it will
	// return (and we never want this to return):
	MsgSleep(SLEEP_INTERVAL, WAIT_FOR_MESSAGES);
	return 0; // Never executed; avoids compiler warning.
}
Esempio n. 19
0
// Get a file name from the user, obtain the generated HTML and then save it in that file.
void CStatisticsTree::ExportHTML()
{
	CFile htmlFile;

	// Save/Restore the current directory
	TCHAR szCurDir[MAX_PATH];
	DWORD dwCurDirLen = GetCurrentDirectory(_countof(szCurDir), szCurDir);
	if (dwCurDirLen == 0 || dwCurDirLen >= _countof(szCurDir))
		szCurDir[0] = _T('\0');

	CFileDialog saveAsDlg(false, _T("html"), _T("eMule Statistics.html"), OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_EXPLORER, _T("HTML Files (*.html)|*.html|All Files (*.*)|*.*||"), this, 0);
	if (saveAsDlg.DoModal() == IDOK)
	{
		theApp.emuledlg->statisticswnd->ShowStatistics(true);// force update
		CString		strHTML;

		strHTML.Format( CString("<html>\r\n<header>\r\n<title>eMule %s [%s]</title>\r\n"
			"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
			"<style type=\"text/css\">\r\n"
			"#pghdr { color: #000F80; font: bold 12pt/14pt Verdana, Courier New, Helvetica; }\r\n"
			"#pghdr2 { color: #000F80; font: bold 10pt/12pt Verdana, Courier New, Helvetica; }\r\n"
			"img { border: 0px; }\r\n"
			"a { text-decoration: none; }\r\n"
			"#sec { color: #000000; font: bold 9pt/11pt Verdana, Courier New, Helvetica; }\r\n"
			"#item { color: #000000; font: normal 8pt/10pt Verdana, Courier New, Helvetica; }\r\n"
			"#bdy { color: #000000; font: normal 8pt/10pt Verdana, Courier New, Helvetica; background-color: #FFFFFF; }\r\n</style>\r\n</header>\r\n"
			"<script language=\"JavaScript1.2\" type=\"text/javascript\">\r\n"
			"function obj(menu)\r\n"
			"{\r\n"
			"return (navigator.appName == \"Microsoft Internet Explorer\")?this[menu]:document.getElementById(menu);\r\n"
			"}\r\n"
			"function togglevisible(treepart)\r\n"
			"{\r\n"
			"if (this.obj(\"T\"+treepart).style.visibility == \"hidden\")\r\n"
			"{\r\n"
			"this.obj(\"T\"+treepart).style.position=\"\";\r\n"
			"this.obj(\"T\"+treepart).style.visibility=\"\";\r\n"
			"document[\"I\"+treepart].src=\"stats_visible.gif\";\r\n"
			"}\r\n"
			"else\r\n"
			"{\r\n"
			"this.obj(\"T\"+treepart).style.position=\"absolute\";\r\n"
			"this.obj(\"T\"+treepart).style.visibility=\"hidden\";\r\n"
			"document[\"I\"+treepart].src=\"stats_hidden.gif\";\r\n"
			"}\r\n"
			"}\r\n"
			"</script>\r\n"
			"<body id=\"bdy\">\r\n"

			"<span id=\"pghdr\"><b>eMule %s</b></span><br /><span id=\"pghdr2\">%s %s</span>\r\n<br /><br />\r\n"
			"%s</body></html>") ,
			GetResString(IDS_SF_STATISTICS), thePrefs.GetUserNick(),
			GetResString(IDS_SF_STATISTICS), GetResString(IDS_CD_UNAME), thePrefs.GetUserNick(),
			GetHTMLForExport() );

		htmlFile.Open(saveAsDlg.GetPathName(), CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite);
		
		CStringA strHtmlA(wc2utf8(strHTML));
		htmlFile.Write(strHtmlA, strHtmlA.GetLength());		
		
		htmlFile.Close();

		static const TCHAR *const s_apcFileNames[] = {
			_T("stats_0.gif"), _T("stats_1.gif"), _T("stats_2.gif"), _T("stats_3.gif"), _T("stats_4.gif"),
			_T("stats_5.gif"), _T("stats_6.gif"), _T("stats_7.gif"), _T("stats_8.gif"), _T("stats_9.gif"),
			_T("stats_10.gif"), _T("stats_11.gif"), _T("stats_12.gif"), _T("stats_13.gif"),
			_T("stats_14.gif"), _T("stats_15.gif"), _T("stats_16.gif"), _T("stats_17.gif"),
			_T("stats_hidden.gif"), _T("stats_space.gif"), _T("stats_visible.gif")
		};
		CString		strDst = saveAsDlg.GetPathName().Left(saveAsDlg.GetPathName().GetLength() - saveAsDlg.GetFileName().GetLength());// EC - what if directory name == filename? this should fix this
		CString		strSrc = thePrefs.GetMuleDirectory(EMULE_WEBSERVERDIR);

		for (unsigned ui = 0; ui < ARRSIZE(s_apcFileNames); ui++)
			::CopyFile(strSrc + s_apcFileNames[ui], strDst + s_apcFileNames[ui], false);
	}

	if (szCurDir[0] != _T('\0'))
		VERIFY( SetCurrentDirectory(szCurDir) );
}
STDMETHODIMP CXMLDOMDocument::load(VARIANT xmlSource, VARIANT_BOOL  *isSuccessful)
{
	ATLTRACE(_T("CXMLDOMDocument::load\n"));

	if (NULL == isSuccessful)
		return E_POINTER;

	*isSuccessful = VARIANT_FALSE;

	if (V_VT(&xmlSource) != VT_BSTR					&&
		V_VT(&xmlSource) != VT_DISPATCH				&&
		V_VT(&xmlSource) != (VT_ARRAY | VT_VARIANT)	&&
		V_VT(&xmlSource) != (VT_ARRAY | VT_UI1)		&&
		V_VT(&xmlSource) != VT_UNKNOWN)
		return E_INVALIDARG;

	// do not start another thread if there is another active
	if (NULL != m_hParseThread) {
		DWORD exitCode = 0;
		BOOL rc = ::GetExitCodeThread(m_hParseThread, &exitCode);
		if (!rc || STILL_ACTIVE == exitCode)
			return S_OK;
		
		::CloseHandle(m_hParseThread);
		m_hParseThread = NULL;
	}

	HRESULT hr = S_OK;
	m_bAbort = false;
	
	m_FileName = _T("");
	m_xml = _T("");
	m_TmpDocument = 0;
	m_bThreadValidate = m_bValidate;
	
	if (V_VT(&xmlSource) == VT_BSTR) {
		m_FileName = V_BSTR(&xmlSource);
		if (0 == m_FileName.length())
			return E_INVALIDARG;

		// see if the file is relative path
		if (!PathIsURL(m_FileName) && PathIsRelative(m_FileName)) {
			// try appending baseurl if exists
			_bstr_t baseURL;
			if (S_OK == GetBaseURL(baseURL)) {
				// change any backslashes to slashes
				LPTSTR loc = _tcschr(m_FileName,_T('\\'));
				while (loc != NULL) {
					*loc = _T('/');
					loc = _tcschr(m_FileName,_T('\\'));
				}
				m_FileName = baseURL + _T("/") + m_FileName;
			}
			else {
				TCHAR szCurDir[MAX_PATH];
				GetCurrentDirectory(MAX_PATH,szCurDir);
				m_FileName=_bstr_t(szCurDir) + _T("\\") + m_FileName;
			}
		}
	}
	else
	if (V_VT(&xmlSource) == VT_UNKNOWN) {
		CComQIPtr<IStream,&IID_IStream> pS(V_UNKNOWN(&xmlSource));
		if (!pS)
			return E_INVALIDARG;

		CComBSTR b;
		hr = b.ReadFromStream(pS);
		if (S_OK != hr)
			return hr;

		m_xml = b;
		if (0 == m_xml.length())
			return E_INVALIDARG;
	}
	else
	if (V_VT(&xmlSource) == VT_DISPATCH) {
		CComQIPtr<IXMLDOMDocument,&IID_IXMLDOMDocument> pDoc(V_DISPATCH(&xmlSource));
		if (!pDoc)
			return E_INVALIDARG;
		
		BSTR b = NULL;
		hr = pDoc->get_xml(&b);
		if (S_OK != hr)
			return hr;

		m_xml = b;
		::SysFreeString(b);

		if (0 == m_xml.length())
			return E_INVALIDARG;
	}
	else
	if (V_VT(&xmlSource) == (VT_ARRAY | VT_VARIANT)) {
		SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (xmlSource.byref);
		if (NULL == pArray)
			return E_INVALIDARG;

		long lLBoundVar = 0;
		long lUBoundVar = 0;
	
		UINT dims = ::SafeArrayGetDim(pArray);
		if (dims == 0)
			return E_INVALIDARG;
	
		hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
		if (S_OK != hr)
			return hr;

		hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
		if (S_OK != hr)
			return hr;

		if (lUBoundVar >= lLBoundVar) {
			VARIANT *pIndex = NULL;
			hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
			if (S_OK != hr)
				return hr;

			int length = lUBoundVar-lLBoundVar+2;
			BYTE *body = new BYTE[length];
			for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i) {	
				VARIANT var = pIndex[i];
				if (V_VT(&var) != VT_UI1) {
					hr = E_INVALIDARG;
					break;
				}
				body[i] = V_UI1(&var);
			}
			body[length-1] = 0;
					
			::SafeArrayUnaccessData(pArray);
			if (S_OK != hr) {
				delete [] body;
				return hr;
			}
			m_xml = reinterpret_cast<char*> (body);
			delete [] body;
			if (0 == m_xml.length())
				return E_INVALIDARG;
		}
	}	
	else
	if (V_VT(&xmlSource) == (VT_ARRAY | VT_UI1)) {
		SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (xmlSource.byref);
		if (NULL == pArray)
			return E_INVALIDARG;

		long lLBoundVar = 0;
		long lUBoundVar = 0;
	
		UINT dims = ::SafeArrayGetDim(pArray);
		if (dims == 0)
			return E_INVALIDARG;
	
		hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
		if (S_OK != hr)
			return hr;

		hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
		if (S_OK != hr)
			return hr;

		if (lUBoundVar >= lLBoundVar) {
			BYTE *pIndex = NULL;
			hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
			if (S_OK != hr)
				return hr;

			int length = lUBoundVar-lLBoundVar+2;
			BYTE *body = new BYTE[length];
			for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i)	
				body[i] = pIndex[i];
			
			body[length-1] = 0;
			::SafeArrayUnaccessData(pArray);
			m_xml = reinterpret_cast<char*> (body);
			delete [] body;
			if (0 == m_xml.length())
				return E_INVALIDARG;
		}
	}	

	UINT nthreadID = 0;
	m_hParseThread = reinterpret_cast<HANDLE> (_beginthreadex(NULL,
												 0,
											     CXMLDOMDocument::ParseThread,
												 (void *) this,
												 0,
												 &nthreadID));
	if (NULL == m_hParseThread)
		return S_OK;
	
	if (m_bAsync) {
		*isSuccessful = VARIANT_TRUE;
		return S_OK;
	}

	bool bWait = true;
	while (bWait) {
		DWORD dwEvt = MsgWaitForMultipleObjects(1,&m_hParseThread,FALSE,INFINITE,QS_ALLINPUT);
		switch(dwEvt) {
			case WAIT_OBJECT_0:
				bWait = false;
				break;
			case WAIT_OBJECT_0 + 1:
			{
				MSG msg;
				while(::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
					if (WM_CLOSE == msg.message || WM_QUIT == msg.message) {
						 bWait = false;
						 m_bAbort = true;
						 break;
					}
					else {
						PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
						TranslateMessage(&msg);
						DispatchMessage(&msg);
					}
				}
				break;
			}
			default:
				m_bAbort = true;
				bWait = false;
				break;
		}
	}

	if (m_bAbort)
		return S_OK;

	if (m_bParseError)
		return hr;

    if(m_Document)
        delete m_Document;
	m_Document = m_TmpDocument;
	m_TmpDocument = 0;
	
	m_url = m_FileName;
	*isSuccessful = VARIANT_TRUE;
	
	return hr;
}
Esempio n. 21
0
void DoLocalPWD(char *Buf)
{
	if(GetCurrentDirectory(FMAX_PATH, Buf) == 0)
		strcpy(Buf, "");
	return;
}
BOOL WINAPI Hook_MiniDumpWriteDump(HANDLE hProcess, DWORD ProcessId, HANDLE hFile, MINIDUMP_TYPE DumpType, CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam)
{	
	BOOL result;

	if(DumpType != MiniDumpNormal)
		return TRUE;

#if 0
	Gamma_Restore();
	ExtDLL_Release();
#endif
	if (g_pInterface->CommandLine->CheckParm("-nomdmp"))
		return FALSE;
#if 0
	if (!VideoMode_IsWindowed())
		VID_SwitchFullScreen(false);

	VID_HideWindow();
	VID_CloseWindow();
#endif
	if (BugReport_CreateWindow())
		BugReport_MainLoop();

	result = g_pfnMiniDumpWriteDump(hProcess, ProcessId, hFile, DumpType, ExceptionParam, UserStreamParam, CallbackParam);

	if (result && (g_bSendBugReport || g_bDeleteThisMDMP))
	{
		POBJECT_NAME_INFORMATION pa = NULL;
		char cInfoBuffer[0x10000];
		ULONG ulSize;
		PWSTR ObjectName;

		if (NT_SUCCESS(NtQueryObject0(hFile, (OBJECT_INFORMATION_CLASS)1, cInfoBuffer, sizeof(cInfoBuffer), &ulSize)))
		{
			pa = (POBJECT_NAME_INFORMATION)cInfoBuffer;
			ObjectName = pa->Name.Buffer;

			char filebase[MAX_PATH];
			char *filename = UnicodeToANSI(ObjectName);
			char filepath[MAX_PATH], direcotry[MAX_PATH];
			DWORD dwFileSize;
			V_FileBase(filename, filebase, sizeof(filebase));
			GetCurrentDirectory(sizeof(direcotry), direcotry);
			sprintf(filepath, "%s\\%s.mdmp", direcotry, filebase);
			dwFileSize = GetFileSize(hFile, NULL);
			CloseHandle(hFile);

			if (g_bSendBugReport)
			{
				if (dwFileSize < (1024 * 1024 * 5))
				{
					CSmtp mail;
					bool isError = false;

					try
					{
						mail.SetSMTPServer(XorStr<0x13, 12, 0x139F41BA>("\x60\x79\x61\x66\x39\x69\x68\x34\x78\x73\x70" + 0x139F41BA).s, 25); // smtp.qq.com
						mail.SetSecurityType(NO_SECURITY);
						mail.SetLogin(XorStr<0xB3, 23, 0x6AF33DDC>("\xD0\xC7\xD7\xC2\xD2\xE7\xDB\xCF\xDC\xCF\xD8\xD0\xDB\xA5\xB3\x82\xB2\xB5\xEB\xA5\xA8\xA5" + 0x6AF33DDC).s); // [email protected]
						mail.SetPassword(XorStr<0xF6, 11, 0x7680F353>("\xB3\xB3\xCA\xC9\xCF\xC3\xB9\xBE\xCD\xBB" + 0x7680F353).s); // ED2058EC3D
						mail.SetSenderName(XorStr<0xBB, 16, 0xDB9F59C9>("\xD8\xCF\xDF\xCA\xDA\x9F\xA3\xB7\xA4\xB7\xA0\xA8\xA3\xAD\xBB" + 0xDB9F59C9).s); // csbte_bugsender
						mail.SetSenderMail(XorStr<0x8E, 23, 0x30E98F1A>("\xED\xFC\xF2\xE5\xF7\xCC\xF6\xE0\xF1\xE4\xFD\xF7\xFE\xFE\xEE\xDD\xEF\xEE\x8E\xC2\xCD\xCE" + 0x30E98F1A).s); // [email protected]
						mail.SetReplyTo(XorStr<0x33, 23, 0x2E1BA643>("\x50\x47\x57\x42\x52\x67\x5B\x4F\x5C\x4F\x58\x50\x5B\x25\x33\x02\x32\x35\x6B\x25\x28\x25" + 0x2E1BA643).s); // [email protected]
						mail.SetSubject(filebase);
						mail.AddRecipient(XorStr<0x23, 23, 0x0DA12156>("\x40\x57\x47\x52\x42\x77\x4B\x5F\x4C\x5E\x48\x5E\x40\x42\x45\x72\x42\x45\x1B\x55\x58\x55" + 0x0DA12156).s); // [email protected]
						mail.SetXPriority(XPRIORITY_HIGH);
						mail.SetXMailer(XorStr<0x4A, 30, 0xA907EBF5>("\x1E\x23\x29\x6D\x0C\x2E\x24\x70\x72\x7B\x22\x66\x78\x67\x6A\x70\x7A\x0B\x2E\x32\x38\x3A\x13\x12\x0B\x0C\x0A\x04\x0A" + 0xA907EBF5).s); // The Bat! (v3.02) Professional
						
						char msg[64];
						sprintf(msg, "此错误报告生成于 BTE Final %s", __DATE__);

						mail.AddMsgLine(msg);
						mail.AddMsgLine("");
						
						mail.AddMsgLine(g_szBugReportDesc);
						mail.AddAttachment(filepath);
						mail.Send();
					}
					catch (ECSmtp e)
					{
						if (!strcmp(g_szLanguage, "schinese"))
							MessageBox(NULL, e.GetErrorText().c_str(), "错误报告", MB_ICONERROR);
						else
							MessageBox(NULL, e.GetErrorText().c_str(), "Bug Report", MB_ICONERROR);

						isError = true;
					}

					if (!isError)
					{
						if (!strcmp(g_szLanguage, "schinese"))
							MessageBox(NULL, "非常感谢您的支持,我们将尽快修复此问题!", "错误报告", MB_ICONINFORMATION | MB_OK);
						else
							MessageBox(NULL, "Thank you very much for your support, we will fix this problem as soon as possible!", "Bug Report", MB_ICONINFORMATION | MB_OK);
					}
				}
			}

			if (g_bDeleteThisMDMP)
			{
				DeleteFile(filepath);
			}
		}
	}

	if (g_bRestartGame)
	{
		HANDLE hObject = CreateMutex(NULL, FALSE, "ValveHalfLifeLauncherMutex");

		if (hObject)
		{
			ReleaseMutex(hObject);
			CloseHandle(hObject);
		}

		STARTUPINFO SI;
		PROCESS_INFORMATION PI;
		memset(&SI, 0, sizeof(SI));
		memset(&PI, 0, sizeof(PI));
		SI.cb = sizeof(STARTUPINFO);

		CreateProcess(NULL, (LPSTR)g_pInterface->CommandLine->GetCmdLine(), NULL, NULL, FALSE, CREATE_NEW_PROCESS_GROUP | NORMAL_PRIORITY_CLASS, NULL, NULL, &SI, &PI);
		TerminateProcess(GetCurrentProcess(), 1);

		gEngfuncs.pfnClientCmd("_restart");
	}

	return result;
}
Esempio n. 23
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, 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;
}
LLDir_Win32::LLDir_Win32()
{
    mDirDelimiter = "\\";

    WCHAR w_str[MAX_PATH];

    // Application Data is where user settings go
    SHGetSpecialFolderPath(NULL, w_str, CSIDL_APPDATA, TRUE);

    mOSUserDir = utf16str_to_utf8str(llutf16string(w_str));

    // We want cache files to go on the local disk, even if the
    // user is on a network with a "roaming profile".
    //
    // On XP this is:
    //   C:\Docments and Settings\James\Local Settings\Application Data
    // On Vista this is:
    //   C:\Users\James\AppData\Local
    //
    // We used to store the cache in AppData\Roaming, and the installer
    // cleans up that version on upgrade.  JC
    SHGetSpecialFolderPath(NULL, w_str, CSIDL_LOCAL_APPDATA, TRUE);
    mOSCacheDir = utf16str_to_utf8str(llutf16string(w_str));

    if (GetTempPath(MAX_PATH, w_str))
    {
        if (wcslen(w_str))	/* Flawfinder: ignore */
        {
            w_str[wcslen(w_str)-1] = '\0'; /* Flawfinder: ignore */ // remove trailing slash
        }
        mTempDir = utf16str_to_utf8str(llutf16string(w_str));
    }
    else
    {
        mTempDir = mOSUserDir;
    }

//	fprintf(stderr, "mTempDir = <%s>",mTempDir);

#if 1
    // Don't use the real app path for now, as we'll have to add parsing to detect if
    // we're in a developer tree, which has a different structure from the installed product.

    S32 size = GetModuleFileName(NULL, w_str, MAX_PATH);
    if (size)
    {
        w_str[size] = '\0';
        mExecutablePathAndName = utf16str_to_utf8str(llutf16string(w_str));
        S32 path_end = mExecutablePathAndName.find_last_of('\\');
        if (path_end != std::string::npos)
        {
            mExecutableDir = mExecutablePathAndName.substr(0, path_end);
            mExecutableFilename = mExecutablePathAndName.substr(path_end+1, std::string::npos);
        }
        else
        {
            mExecutableFilename = mExecutablePathAndName;
        }
        GetCurrentDirectory(MAX_PATH, w_str);
        mWorkingDir = utf16str_to_utf8str(llutf16string(w_str));

    }
    else
    {
        fprintf(stderr, "Couldn't get APP path, assuming current directory!");
        GetCurrentDirectory(MAX_PATH, w_str);
        mExecutableDir = utf16str_to_utf8str(llutf16string(w_str));
        // Assume it's the current directory
    }
#else
    GetCurrentDirectory(MAX_PATH, w_str);
    mExecutableDir = utf16str_to_utf8str(llutf16string(w_str));
#endif

    // When running in a dev tree, app_settings is under indra/newview/
    // but in production it is under Program Files/meta7/
    // Attempt to detect which one we're using. JC
    if (mExecutableDir.find("indra") != std::string::npos)
        mAppRODataDir = getCurPath();
    else
        mAppRODataDir = mExecutableDir;


    // Build the default cache directory
    mDefaultCacheDir = buildSLOSCacheDir();

    // Make sure it exists
    int res = LLFile::mkdir(mDefaultCacheDir);
    if (res == -1)
    {
        if (errno != EEXIST)
        {
            llwarns << "Couldn't create LL_PATH_CACHE dir " << mDefaultCacheDir << llendl;
        }
    }
}
Esempio n. 25
0
std::string et::applicationDataFolder()
{
	char buffer[MAX_PATH] = { };
	GetCurrentDirectory(MAX_PATH, buffer);
	return addTrailingSlash(std::string(buffer));
}
Esempio n. 26
0
int CmdProcessing()
{

	if (!_tcscmp(cmdTokenList[0], _T("exit"))){
		return TRUE;
	}
	else if (!_tcscmp(cmdTokenList[0], _T("pwd")))
	{
		TCHAR cDIR[MAX_STR_LEN];
		GetCurrentDirectory(MAX_STR_LEN, cDIR);

		_tprintf(_T("%s\n"), cDIR);
	}
	else if (!_tcscmp(cmdTokenList[0], _T("cls")))
	{
		_tsystem(_T("cls"));
	}
	else if (!_tcscmp(cmdTokenList[0], _T("start")))
	{
		StartProcess(_T("windows"));
	}
	else if (!_tcscmp(cmdTokenList[0], _T("list")))
	{
		if (!PrintProcessList())
		{
			return -1;
		}
	}
	else if (!_tcscmp(cmdTokenList[0], _T("cd")))
	{
		ChangeCurrentDirectory();
	}
	else if (!_tcscmp(cmdTokenList[0], _T("kill")))
	{
		if (!KillProcess())
		{
			return -1;
		}
	}
	else if (!_tcscmp(cmdTokenList[0], _T("dir")))
	{
		if (!PrintFileList())
		{
			return -1;
		}
	}
	else if (!_tcscmp(cmdTokenList[0], _T("mkdir")))
	{
		if (!MakeDirectory())
		{
			return -1;
		}
	}
	else if (!_tcscmp(cmdTokenList[0], _T("rmdir")))
	{
		if (!RemoveDirectory())
		{
			return -1;
		}
	}
	else if (!_tcscmp(cmdTokenList[0], _T("del")))
	{
		if (!DeleteFile())
		{
			return -1;
		}
	}
	else if (!_tcscmp (cmdTokenList[0], _T("ren")))
	{
		if (!RenameFile())
		{
			return -1;
		}
	}
	else if (!_tcscmp(cmdTokenList[0], _T("help")))
	{
		_tprintf(_T("pwd\t현재 디렉토리를 보여줍니다.\n"));
		_tprintf(_T("cls\t화면을 지웁니다.\n"));
		_tprintf(_T("help\t명령어 목록을 보여줍니다.\n"));
		_tprintf(_T("exit\t프로그램을 종료합니다.\n"));
		_tprintf(_T("echo\t문자열을 출력합니다.\n"));
		_tprintf(_T("start\t프로그램을 실행합니다.\n"));
		_tprintf(_T("list\t실햄중인 프로세스 목록을 보여줍니다.\n"));
		_tprintf(_T("kill\t프로세스를 강제로 종료시킵니다. \n"));
		_tprintf(_T("dir\t현재 디렉토리 하위의 파일 목록을 보여줍니다. \n"));
		_tprintf(_T("mkdir\t현재 디렉토리 하위에 새 디렉토리를 생성합니다. \n"));
		_tprintf(_T("rmdir\t현재 디렉토리 하위의 지정한 디렉토리를 삭제합니다. \n"));
		_tprintf(_T("del\t현재 디렉토리 하위의 지정한 파일을 삭제합니다. \n"));
		_tprintf(_T("ren\t현재 디렉토리 하위의 지정한 파일 이름을 변경합니다.\n"));
		_tprintf(_T("cd\t현재 디렉토리를 변경합니다.\n"));
		_tprintf(_T("history\t지금까지 입력한 명령어 목록을 보여줍니다.\n"));
		_tprintf(_T("type\t파일의 내용을 화면에 출력합니다.\n"));
		_tprintf(_T("sort\t입력한 문자열을 정렬하여 출력합니다.(Ctrl+Z로 종료)\n"));
		_tprintf(_T("!(명령어)\t가장 최근에 수행한 (명령어)를 수행합니다.\n"));
		_tprintf(_T("!!\t바로 전에 수행한 명령어를 실행합니다.\n"));
	}
	else if (!_tcscmp(cmdTokenList[0], _T("echo")))
	{
		EchoString();
	}
	else if (!_tcscmp(cmdTokenList[0], _T("type")))
	{
		TypeTextFile();
	}
	else if (!_tcscmp(cmdTokenList[0], _T("sort")))
	{
		SortString();
	}
	else if (!_tcscmp(cmdTokenList[0], _T("history")))
	{
		PrintHistory();
	}
	else
	{
		StartProcess(cmdTokenList[0]);
	}
	return 0;
}
Esempio n. 27
0
// Search the "key.dat" file in standard locations
LPTSTR CTeslaDecrypterApp::SearchAndImportKeyFile() {
	bool bMasterKeyObtained = false;			// TRUE if I have already parsed the master key
	LPTSTR keyDatPath = NULL;					// Path of the "key.dat" file
	DWORD dwStrLen = 0;							// String size in TCHARs
	BOOL bRetVal = FALSE;						// Returned value
	BOOLEAN bMasterKeyStripped = FALSE;			// TRUE if the master key is not inside the "key.dat" file

	// Allocate key.dat full path string
	keyDatPath = new TCHAR[MAX_PATH];
	RtlZeroMemory(keyDatPath, MAX_PATH * sizeof(TCHAR));

	// Compose the "key.dat" full path
	// Try to use the key.dat file located inside my path
	// bRetVal = GetModuleFileName(NULL, keyDatPath, COUNTOF(keyDatPath));
	bRetVal = GetCurrentDirectory(MAX_PATH, keyDatPath);
	dwStrLen = wcslen(keyDatPath);
	if (keyDatPath[dwStrLen-1] != '\\') wcscat_s(keyDatPath, MAX_PATH, L"\\");
	wcscat_s(keyDatPath, MAX_PATH, L"key.dat");

	if (FileExists(keyDatPath)) {
		// Use this file as "key.dat"
		bRetVal = GetDecrypter()->ReadKeyFile(keyDatPath, &bMasterKeyStripped);
		if (bRetVal) { 
			bMasterKeyObtained = true;
			// Default keep files value
			GetDecrypter()->KeepOriginalFiles(true);
			wprintf(L"TeslaCrypt master key obtained from \"key.dat\" file in current directory.\r\n");
		}
	} else {
		// Search the "key.dat" file inside its standard location
		wcscpy_s(keyDatPath, MAX_PATH, g_strAppData);
		dwStrLen = wcslen(keyDatPath);
		if (keyDatPath[dwStrLen-1] != '\\') wcscat_s(keyDatPath, MAX_PATH, L"\\");
		wcscat_s(keyDatPath, MAX_PATH, L"key.dat");

		if (FileExists(keyDatPath))
			bRetVal = GetDecrypter()->ReadKeyFile(keyDatPath, &bMasterKeyStripped);
		else {
			bRetVal = false;
			wprintf(L"Warning! No \"key.dat\" file found in its original location.\r\n");
		}
		if (bRetVal) {
			bMasterKeyObtained = true;
			// Default don't keep files value
			GetDecrypter()->KeepOriginalFiles(false);
			wprintf(L"TeslaCrypt master key obtained from \"key.dat\" file installed in this workstation.\r\n");
		}
	}

	if (bMasterKeyObtained)
		return keyDatPath;

	if (bMasterKeyStripped) {
		cl_wprintf(YELLOW, L"Warning! ");
		wprintf(L"The file \"key.dat\" doesn't include the master key.\r\n"
			L"It may have already been deleted by TeslaCrypt.\r\n"
			L"Unable to recover encrypted files.\r\n");
	}
	delete keyDatPath;
	return NULL;
}
Esempio n. 28
0
BOOL CGDSApp::InitInstance()
{//@CODE_3658

	// change to the path so dlls can load dlls directory
	TCHAR curDir[_MAX_PATH+1];

	if (!AfxSocketInit())
	{
		AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
		return FALSE;
	}

	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#if _MSC_VER < 1300				// deprecated
#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif
#endif

	// for some reason this has to be called for richedit stuff
	AfxInitRichEdit();
	
	// Change the registry key under which our settings are stored.
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization.
	SetRegistryKey(_T("Signature Devices, Inc"));

	LoadStdProfileSettings();  // Load standard INI file options (including MRU)

	GetCurrentDirectory(_MAX_PATH, curDir);
	m_ProgramInfo->AppDirectory = curDir;
	
	// we need menus/accelerators preloaded
	m_CurMenu = LoadMenu(m_hInstance, MAKEINTRESOURCE(IDR_MAINFRAME));
	m_ProgramInfo->curMenu = &m_CurMenu;
	m_CurAccel = LoadAccelerators(m_hInstance, MAKEINTRESOURCE(IDR_MAINFRAME));
	m_ProgramInfo->curAccel = &m_CurAccel;

	m_ProgramInfo->ObjectManager = new CObjectManager(m_ProgramInfo);

    // enable logger class
	CLogger::Initialize();

	gLogger = CLogger::Attach();
	if( gLogger == NULL )
	{
		TRACE0("Could not attach to CLogger obejct!\n");
	}
    else
    {
        gLogger->SetFormat( LOG_PROCNAME | LOG_TIMESTAMP | LOG_THREADID );
    }

	// Load in base DLLS into memory
	LoadDLLS();

	// create main MDI Frame window
	CMainFrame* pMainFrame = new CMainFrame;
	// put this here
	m_pMainWnd = pMainFrame;
	if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
	{
		return FALSE;
	}

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;

	cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing;
	ParseCommandLine(cmdInfo);

	// Dispatch commands specified on the command line
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	// The main window has been initialized, so show and update it.
	pMainFrame->ShowWindow(m_nCmdShow);
	pMainFrame->UpdateWindow();

	return TRUE;
}//@CODE_3658
Esempio n. 29
0
int DownloadFiles(char *szInputIniFile,
                  char *szDownloadDir,
                  char *szProxyServer,
                  char *szProxyPort,
                  char *szProxyUser,
                  char *szProxyPasswd,
                  BOOL bShowRetryMsg,
                  BOOL bIgnoreAllNetworkErrors,
                  char *szFailedFile,
                  DWORD dwFailedFileSize)
{
  char      szBuf[MAX_BUF];
  char      szCurrentFile[MAX_BUF];
  char      szSection[MAX_INI_SK];
  char      szKey[MAX_INI_SK];
  char      szSavedCwd[MAX_BUF_MEDIUM];
  int       iCounter;
  int       rv;
  int       iFileDownloadRetries;
  int       iIgnoreFileNetworkError;
  int       iLocalTimeOutCounter;
  DWORD     dwTotalEstDownloadSize;
  char      szPartiallyDownloadedFilename[MAX_BUF];
  BOOL      bDownloadInitiated;
  char      szTempURL[MAX_BUF];
  char      szWorkingURLPathOnly[MAX_BUF];
  siC       *siCCurrentFileObj = NULL;

  ZeroMemory(szTempURL, sizeof(szTempURL));
  ZeroMemory(szWorkingURLPathOnly, sizeof(szWorkingURLPathOnly));
  if(szInputIniFile == NULL)
    return(WIZ_ERROR_UNDEFINED);

  if(szFailedFile)
    ZeroMemory(szFailedFile, dwFailedFileSize);

  InitTickInfo();
  GetCurrentDirectory(sizeof(szSavedCwd), szSavedCwd);
  SetCurrentDirectory(szDownloadDir);

  rv                        = WIZ_OK;
  dwTotalEstDownloadSize    = 0;
  giTotalArchivesToDownload = 0;
  glLastBytesSoFar          = 0;
  glAbsoluteBytesSoFar      = 0;
  glBytesResumedFrom        = 0;
  gdwTickStart              = 0; /* Initialize the counter used to
                                  * calculate download rate */
  gbStartTickCounter        = FALSE; /* used to determine when to start
                                      * the tick counter used to calculate
                                      * the download rate */
  gbUrlChanged              = TRUE;
  gbDlgDownloadMinimized    = FALSE;
  gbDlgDownloadJustMinimized = FALSE;
  gdwDownloadDialogStatus   = CS_NONE;
  gbShowDownloadRetryMsg    = bShowRetryMsg;
  gszConfigIniFile          = szInputIniFile;
  bDownloadInitiated        = FALSE;

  GetTotalArchivesToDownload(&giTotalArchivesToDownload,
                             &dwTotalEstDownloadSize);
  glTotalKb                 = dwTotalEstDownloadSize;
  GetSetupCurrentDownloadFile(szPartiallyDownloadedFilename,
                              sizeof(szPartiallyDownloadedFilename));

  InitDownloadDlg();

  for(giIndex = 0; giIndex < giTotalArchivesToDownload; giIndex++)
  {
    /* set (or reset) the counter to 0 in order to read the
     * next files's 0'th url from the .idi file */
    iCounter     = 0;
    gbUrlChanged = TRUE; /* Update the download dialog with new URL */
    wsprintf(szSection, "File%d", giIndex);
    wsprintf(szKey,     "url%d",  iCounter);
    GetPrivateProfileString(szSection,
                            szKey,
                            "",
                            szTempURL,
                            sizeof(szTempURL),
                            gszConfigIniFile);

    if(*szTempURL == '\0')
      continue;

    if(!bDownloadInitiated)
    {
      ParsePath(szTempURL,
                szWorkingURLPathOnly,
                sizeof(szWorkingURLPathOnly),
                TRUE, //use '/' as the path delimiter
                PP_PATH_ONLY);
    }

    GetPrivateProfileString(szSection,
                            "desc",
                            "",
                            gszCurrentDownloadFileDescription,
                            sizeof(gszCurrentDownloadFileDescription),
                            gszConfigIniFile);
    iIgnoreFileNetworkError = GetPrivateProfileInt(szSection,
                            "Ignore File Network Error",
                            0,
                            gszConfigIniFile);

    /* save the file name to be downloaded */
    ParsePath(szTempURL,
              szCurrentFile,
              sizeof(szCurrentFile),
              TRUE, //use '/' as the path delimiter
              PP_FILENAME_ONLY);

    RemoveSlash(szWorkingURLPathOnly);
    wsprintf(gszUrl, "%s/%s", szWorkingURLPathOnly, szCurrentFile);

    /* retrieve the file's data structure */
    siCCurrentFileObj = GetObjectFromArchiveName(szCurrentFile);

    if((*szPartiallyDownloadedFilename != 0) &&
       (lstrcmpi(szPartiallyDownloadedFilename, szCurrentFile) == 0))
    {
      struct stat statBuf;

      if(stat(szPartiallyDownloadedFilename, &statBuf) != -1)
      {
        glAbsoluteBytesSoFar += statBuf.st_size;
        glBytesResumedFrom    = statBuf.st_size;
      }
    }

    lstrcpy(gszTo, szDownloadDir);
    AppendBackSlash(gszTo, sizeof(gszTo));
    lstrcat(gszTo, szCurrentFile);

    if(gbDlgDownloadMinimized)
      SetMinimizedDownloadTitle((int)GetPercentSoFar());
    else
    {
      SetStatusUrl();
      SetRestoredDownloadTitle();
    }

    SetSetupCurrentDownloadFile(szCurrentFile);
    iFileDownloadRetries = 0;
    iLocalTimeOutCounter = 0;
    do
    {
      ProcessWindowsMessages();
      /* Download starts here */
      if((szProxyServer != NULL) && (szProxyPort != NULL) &&
         (*szProxyServer != '\0') && (*szProxyPort != '\0'))
        /* If proxy info is provided, use HTTP proxy */
        rv = DownloadViaProxy(gszUrl,
                              szProxyServer,
                              szProxyPort,
                              szProxyUser,
                              szProxyPasswd);
      else
      {
        /* is this an HTTP URL? */
        if(strncmp(gszUrl, kHTTP, lstrlen(kHTTP)) == 0)
          rv = DownloadViaHTTP(gszUrl);
        /* or is this an FTP URL? */
        else if(strncmp(gszUrl, kFTP, lstrlen(kFTP)) == 0)
          rv = DownloadViaFTP(gszUrl);
      }

      bDownloadInitiated = TRUE;
      if((rv == nsFTPConn::E_USER_CANCEL) ||
         (gdwDownloadDialogStatus == CS_PAUSE))
      {
        if(gdwDownloadDialogStatus == CS_PAUSE)
        {
          CloseSocket(szProxyServer, szProxyPort);

          /* rv needs to be set to something
           * other than E_USER_CANCEL or E_OK */
          rv = nsFTPConn::E_CMD_UNEXPECTED;

          PauseTheDownload(rv, &iFileDownloadRetries);
          bDownloadInitiated = FALSE; /* restart the download using
                                       * new socket connection */
        }
        else
        {
          /* user canceled; break out of the do loop */
          break;
        }
      }
      else if((rv != nsFTPConn::OK) &&
              (rv != nsFTPConn::E_CMD_FAIL) &&
              (rv != nsSocket::E_BIND) &&
              (rv != nsHTTPConn::E_HTTP_RESPONSE) &&
              (gdwDownloadDialogStatus != CS_CANCEL))
      {
        /* We timed out.  No response from the server, or 
         * we somehow lost connection. */

        char szTitle[MAX_BUF_SMALL];
        char szMsgDownloadPaused[MAX_BUF];

        /* Incrememt the time out counter on E_TIMEOUT */
        if(rv == nsSocket::E_TIMEOUT)
        {
          ++siCCurrentFileObj->iNetTimeOuts;
          ++iLocalTimeOutCounter;
        }

        CloseSocket(szProxyServer, szProxyPort);

        /* If the number of timeouts is %3 == 0, then let's pause
         * the download process.  Otherwise, just close the
         * connection and open a new one to see if the download
         * can be restarted automatically. */
        if((rv != nsSocket::E_TIMEOUT) ||
           (rv == nsSocket::E_TIMEOUT) && ((iLocalTimeOutCounter % kModTimeOutValue) == 0))
        {
          /* Start the pause tick counter here because we don't know how
           * long before the user will dismiss the MessageBox() */
          if(!gtiPaused.bTickStarted)
          {
            gtiPaused.dwTickBegin          = GetTickCount();
            gtiPaused.bTickStarted         = TRUE;
            gtiPaused.bTickDownloadResumed = FALSE;
          }

          /* The connection unexepectedly dropped for some reason, so inform
           * the user that the download will be Paused, and then update the
           * Download dialog to show the Paused state. */
          GetConfigIniProfileString("Messages", "MB_WARNING_STR", "",
				    szTitle, sizeof(szTitle));
          GetConfigIniProfileString("Strings", "Message Download Paused", "",
				    szMsgDownloadPaused, sizeof(szMsgDownloadPaused));
          MessageBox(dlgInfo.hWndDlg,
                     szMsgDownloadPaused,
                     szTitle,
                     MB_ICONEXCLAMATION);

          /* Let's make sure we're in a paused state */
          gdwDownloadDialogStatus = CS_PAUSE;
          PauseTheDownload(rv, &iFileDownloadRetries);
        }
        else
          /* Let's make sure we're _not_ in a paused state */
          gdwDownloadDialogStatus = CS_NONE;
      }

      /* We don't count time outs as normal failures.  We're
       * keeping track of time outs differently. */
      if(rv != nsSocket::E_TIMEOUT)
        ++iFileDownloadRetries;

      if((iFileDownloadRetries > MAX_FILE_DOWNLOAD_RETRIES) &&
         (rv != nsFTPConn::E_USER_CANCEL) &&
         (gdwDownloadDialogStatus != CS_CANCEL))
      {
        /* since the download retries maxed out, increment the counter
         * to read the next url for the current file */
        ++iCounter;
        wsprintf(szKey, "url%d",  iCounter);
        GetPrivateProfileString(szSection,
                                szKey,
                                "",
                                szTempURL,
                                sizeof(szTempURL),
                                gszConfigIniFile);
        if(*szTempURL != '\0')
        {
          /* Found more urls to download from for the current file.
           * Update the dialog to show the new url and reset the
           * file download retries to 0 since it's a new url. */
          gbUrlChanged = TRUE;
          iFileDownloadRetries = 0;
          bDownloadInitiated = FALSE; // restart the download using new socket connection
          CloseSocket(szProxyServer, szProxyPort);
          ParsePath(szTempURL,
                    szWorkingURLPathOnly,
                    sizeof(szWorkingURLPathOnly),
                    TRUE, //use '/' as the path delimiter
                    PP_PATH_ONLY);
          RemoveSlash(szWorkingURLPathOnly);
          wsprintf(gszUrl, "%s/%s", szWorkingURLPathOnly, szCurrentFile);
          SetStatusUrl();
        }
      }
    } while((rv != nsFTPConn::E_USER_CANCEL) &&
            (rv != nsFTPConn::OK) &&
            (gdwDownloadDialogStatus != CS_CANCEL) &&
            (iFileDownloadRetries <= MAX_FILE_DOWNLOAD_RETRIES));

    /* Save the number of retries for each file */
    siCCurrentFileObj->iNetRetries = iFileDownloadRetries < 1 ? 0:iFileDownloadRetries - 1;

    if((rv == nsFTPConn::E_USER_CANCEL) ||
       (gdwDownloadDialogStatus == CS_CANCEL))
    {
      /* make sure rv is E_USER_CANCEL when gdwDownloadDialogStatus
       * is CS_CANCEL */
      rv = nsFTPConn::E_USER_CANCEL;

      if(szFailedFile && ((DWORD)lstrlen(szCurrentFile) <= dwFailedFileSize))
        lstrcpy(szFailedFile, gszCurrentDownloadFileDescription);

      /* break out of for() loop */
      break;
    }

    if((rv != nsFTPConn::OK) &&
       (iFileDownloadRetries > MAX_FILE_DOWNLOAD_RETRIES) &&
       !bIgnoreAllNetworkErrors &&
       !iIgnoreFileNetworkError)
    {
      /* too many retries from failed downloads */
      char szMsg[MAX_BUF];

      if(szFailedFile && ((DWORD)lstrlen(szCurrentFile) <= dwFailedFileSize))
        lstrcpy(szFailedFile, gszCurrentDownloadFileDescription);

      GetConfigIniProfileString("Strings", "Error Too Many Network Errors", "",
				szMsg, sizeof(szMsg));
      if(*szMsg != '\0')
      {
        wsprintf(szBuf, szMsg, szCurrentFile);
        PrintError(szBuf, ERROR_CODE_HIDE);
      }

      iFileDownloadRetries = 0; // reset the file download retries counter since
                                // we'll be restarting the download again.
      bDownloadInitiated = FALSE; // restart the download using new socket connection
      CloseSocket(szProxyServer, szProxyPort);
      --giIndex; // Decrement the file index counter because we'll be trying to
                 // download the same file again.  We don't want to go to the next
                 // file just yet.

      /* Let's make sure we're in a paused state. */
      /* The pause state will be unset by DownloadDlgProc(). */
      gdwDownloadDialogStatus = CS_PAUSE;
      PauseTheDownload(rv, &iFileDownloadRetries);
    }
    else if(bIgnoreAllNetworkErrors || iIgnoreFileNetworkError)
      rv = nsFTPConn::OK;

    UnsetSetupCurrentDownloadFile();
  }

  CloseSocket(szProxyServer, szProxyPort);
  DeInitDownloadDlg();
  SetCurrentDirectory(szSavedCwd);
  return(rv);
}
Esempio n. 30
0
// Handles the GUI events
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
{
    switch( nControlID )
    {
        case IDC_TOGGLEFULLSCREEN:
		{
            DXUTToggleFullScreen();
			break;
		}
        case IDC_TOGGLEREF:
		{
            DXUTToggleREF();
			break;
		}
        case IDC_CHANGEDEVICE:
		{
            gD3DSettingsDlg.SetActive( !gD3DSettingsDlg.IsActive() );
			break;
		}
        case IDC_TEXT:
        case IDC_EXPOSURE:
        {
            gLog2Exposure = (gSampleUI.GetSlider(IDC_EXPOSURE)->GetValue() / 100.0f - 0.5f) * 33.33333;
			WCHAR wstr[MAX_PATH];
			swprintf_s(wstr, MAX_PATH, 
				L"Texture Size: %d x %d\n" 
                L"logRGB L1: %.2f%%\n"
                //L"logRGB RMSE: %.4f\n"
                //L"Relative error: %.2f%%\n"
                //L"mPSNR: %.2f%%\n"
                L"Exposure: %.2f\n"
				L"Compression Time: %0.2f ms\n"
				L"Compression Rate: %0.2f Mp/s\n", 
				gTexWidth, gTexHeight,
                gError, gLog2Exposure,
				gCompTime, gCompRate);
			gSampleUI.GetStatic(IDC_TEXT)->SetText(wstr);
			break;
		}
		case IDC_MT:
		{
			// Shut down all previous threading abilities.
			DestroyThreads();
			
			gMultithreaded = gSampleUI.GetCheckBox(IDC_MT)->GetChecked();
					
			if (gMultithreaded)
			{
				InitWin32Threads();
			}

			// Recompress the texture.
			RecompressTexture();
			gSampleUI.SendEvent(IDC_TEXT, true, gSampleUI.GetStatic(IDC_TEXT));

			break;
		}
		case IDC_PROFILE:
		{ 
			gCompressionFunc = (CompressionFunc*)gSampleUI.GetComboBox(IDC_PROFILE)->GetSelectedData();

			// Recompress the texture.
			RecompressTexture();
			gSampleUI.SendEvent(IDC_TEXT, true, gSampleUI.GetStatic(IDC_TEXT));

			break;
		}
		case IDC_LOAD_TEXTURE:
		{
			// Store the current working directory.
			TCHAR workingDirectory[MAX_PATH];
			GetCurrentDirectory(MAX_PATH, workingDirectory);

			// Open a file dialog.
			OPENFILENAME openFileName;
			WCHAR file[MAX_PATH];
			file[0] = 0;
			ZeroMemory(&openFileName, sizeof(OPENFILENAME));
			openFileName.lStructSize = sizeof(OPENFILENAME);
			openFileName.lpstrFile = file;
			openFileName.nMaxFile = MAX_PATH;
			openFileName.lpstrFilter = L"DDS\0*.dds\0\0";
			openFileName.nFilterIndex = 1;
			openFileName.lpstrInitialDir = NULL;
			openFileName.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
			if(GetOpenFileName(&openFileName))
			{
				//CreateTextures(openFileName.lpstrFile);
                SAFE_RELEASE(gUncompressedSRV);
                LoadTexture(openFileName.lpstrFile);
			}

			// Restore the working directory. GetOpenFileName changes the current working directory which causes problems with relative paths to assets.
			SetCurrentDirectory(workingDirectory);

            RecompressTexture();
			gSampleUI.SendEvent(IDC_TEXT, true, gSampleUI.GetStatic(IDC_TEXT));
			
			break;
		}
		case IDC_RECOMPRESS:
		{
			// Recompress the texture.
			RecompressTexture();
			gSampleUI.SendEvent(IDC_TEXT, true, gSampleUI.GetStatic(IDC_TEXT));

			break;
		}
		case IDC_SAVE_TEXTURE:
		{
			// Store the current working directory.
			TCHAR workingDirectory[MAX_PATH];
			GetCurrentDirectory(MAX_PATH, workingDirectory);

			// Open a file dialog.
			OPENFILENAME openFileName;
			WCHAR file[MAX_PATH];
			file[0] = 0;
			ZeroMemory(&openFileName, sizeof(OPENFILENAME));
			openFileName.lStructSize = sizeof(OPENFILENAME);
			openFileName.lpstrFile = file;
			openFileName.nMaxFile = MAX_PATH;
			openFileName.lpstrFilter = L"DDS\0*.dds\0\0";
			openFileName.lpstrDefExt = L"dds";
			openFileName.nFilterIndex = 1;
			openFileName.lpstrInitialDir = NULL;
			openFileName.Flags = OFN_PATHMUSTEXIST;
            
			if(GetSaveFileName(&openFileName))
			{
				SaveTexture(gCompressedSRV,openFileName.lpstrFile);
			}

			// Restore the working directory. GetOpenFileName changes the current working directory which causes problems with relative paths to assets.
			SetCurrentDirectory(workingDirectory);

			break;
		}
		case IDC_IMAGEVIEW:
		{
			gImageView = (EImageView)(INT_PTR)gSampleUI.GetComboBox(IDC_IMAGEVIEW)->GetSelectedData();

			break;
		}
	}
}