INT_PTR CMergeFilesDialog::OnInitDialog()
{
    m_hDialogIcon = LoadIcon(GetModuleHandle(0),MAKEINTRESOURCE(IDI_MAIN_SMALL));
    SetClassLongPtr(m_hDlg,GCLP_HICONSM,reinterpret_cast<LONG_PTR>(m_hDialogIcon));

    std::wregex rxPattern;
    bool bAllMatchPattern = true;

    rxPattern.assign(_T(".*[\\.]?part[0-9]+"),std::regex_constants::icase);

    /* If the files all match the pattern .*[\\.]?part[0-9]+
    (e.g. document.txt.part1), order them alphabetically. */
    for each(auto strFullFilename in m_FullFilenameList)
    {
        if(!std::tr1::regex_match(strFullFilename,rxPattern))
        {
            bAllMatchPattern = false;
            break;
        }
    }

    std::wstring strOutputFilename;

    if(bAllMatchPattern)
    {
        m_FullFilenameList.sort(CompareFilenames);

        /* Since the filenames all match the
        pattern, construct the output filename
        from the first files name. */
        rxPattern.assign(_T("[\\.]?part[0-9]+"),std::regex_constants::icase);
        strOutputFilename = std::tr1::regex_replace(m_FullFilenameList.front(),
                            rxPattern,std::wstring(_T("")));
    }
    else
    {
        /* TODO: Improve output name. */
        strOutputFilename = _T("output");
    }

    TCHAR szOutputFile[MAX_PATH];
    PathCombine(szOutputFile,m_strOutputDirectory.c_str(),strOutputFilename.c_str());
    SetDlgItemText(m_hDlg,IDC_MERGE_EDIT_FILENAME,szOutputFile);

    HWND hListView = GetDlgItem(m_hDlg,IDC_MERGE_LISTVIEW);

    HIMAGELIST himlSmall;
    Shell_GetImageLists(NULL,&himlSmall);
    ListView_SetImageList(hListView,himlSmall,LVSIL_SMALL);

    SetWindowTheme(hListView,L"Explorer",NULL);

    ListView_SetExtendedListViewStyleEx(hListView,
                                        LVS_EX_DOUBLEBUFFER|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES,
                                        LVS_EX_DOUBLEBUFFER|LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);

    LVCOLUMN lvColumn;
    TCHAR szTemp[32];

    LoadString(GetInstance(),IDS_MERGE_FILES_COLUMN_FILE,
               szTemp,SIZEOF_ARRAY(szTemp));
    lvColumn.mask		= LVCF_TEXT;
    lvColumn.pszText	= szTemp;
    ListView_InsertColumn(hListView,0,&lvColumn);

    LoadString(GetInstance(),IDS_MERGE_FILES_COLUMN_TYPE,
               szTemp,SIZEOF_ARRAY(szTemp));
    lvColumn.mask		= LVCF_TEXT;
    lvColumn.pszText	= szTemp;
    ListView_InsertColumn(hListView,1,&lvColumn);

    LoadString(GetInstance(),IDS_MERGE_FILES_COLUMN_SIZE,
               szTemp,SIZEOF_ARRAY(szTemp));
    lvColumn.mask		= LVCF_TEXT;
    lvColumn.pszText	= szTemp;
    ListView_InsertColumn(hListView,2,&lvColumn);

    LoadString(GetInstance(),IDS_MERGE_FILES_COLUMN_DATE_MODIFIED,
               szTemp,SIZEOF_ARRAY(szTemp));
    lvColumn.mask		= LVCF_TEXT;
    lvColumn.pszText	= szTemp;
    ListView_InsertColumn(hListView,3,&lvColumn);

    int iItem = 0;

    for each(auto strFullFilename in m_FullFilenameList)
    {
        TCHAR szFullFilename[MAX_PATH];

        StringCchCopy(szFullFilename,SIZEOF_ARRAY(szFullFilename),
                      strFullFilename.c_str());

        /* TODO: Perform in background thread. */
        SHFILEINFO shfi;
        SHGetFileInfo(szFullFilename,0,&shfi,sizeof(SHFILEINFO),
                      SHGFI_SYSICONINDEX|SHGFI_TYPENAME);

        LVITEM lvItem;
        lvItem.mask		= LVIF_TEXT|LVIF_IMAGE;
        lvItem.iItem	= iItem;
        lvItem.iSubItem	= 0;
        lvItem.pszText	= szFullFilename;
        lvItem.iImage	= shfi.iIcon;
        ListView_InsertItem(hListView,&lvItem);

        ListView_SetItemText(hListView,iItem,1,shfi.szTypeName);

        WIN32_FILE_ATTRIBUTE_DATA wfad;
        GetFileAttributesEx(szFullFilename,GetFileExInfoStandard,&wfad);

        TCHAR szFileSize[32];
        ULARGE_INTEGER lFileSize = {wfad.nFileSizeLow,wfad.nFileSizeHigh};
        FormatSizeString(lFileSize,szFileSize,SIZEOF_ARRAY(szFileSize));
        ListView_SetItemText(hListView,iItem,2,szFileSize);

        TCHAR szDateModified[32];
        CreateFileTimeString(&wfad.ftLastWriteTime,szDateModified,
                             SIZEOF_ARRAY(szDateModified),m_bShowFriendlyDates);
        ListView_SetItemText(hListView,iItem,3,szDateModified);

        iItem++;
    }
Exemplo n.º 2
0
int CTSExecutorLIB::nParseTestSuite(xmlNodePtr pXmlNode, sTestSuiteConfigInfo& sConfigInfo)
{
    xmlXPathObjectPtr pObjectPtr = NULL;
    xmlNodePtr pTempNode;
    int nRetValue = S_OK;

    //Test Setup File Path
    pObjectPtr = xmlUtils::pGetChildNodes(pXmlNode, (xmlChar*)"File_Path");
    if( NULL != pObjectPtr)
    {
        pTempNode = pObjectPtr->nodesetval->nodeTab[0];
        char* key = (char*)xmlNodeListGetString(pTempNode->doc, pTempNode->children, 1);

        if( NULL != key)
        {
            if(PathIsRelative((char*)key) == TRUE)
            {
                string omStrConfigFolder;
                string omPath;
                char configPath[MAX_PATH];
                AfxGetMainWnd()->SendMessage(MSG_GET_CONFIGPATH, (WPARAM)configPath, 0);
                CUtilFunctions::nGetBaseFolder(configPath, omStrConfigFolder );
                char chAbsPath[MAX_PATH];
                PathCombine(chAbsPath, omStrConfigFolder.c_str(), (char*)key);
                sConfigInfo.m_strFileName = chAbsPath;
            }
            else
            {
                sConfigInfo.m_strFileName = (char*)key;
            }
            xmlFree(key);
        }

        xmlXPathFreeObject(pObjectPtr);
        pObjectPtr = NULL;
    }
    else
    {
        nRetValue = S_FALSE;
    }

    //Test Setup File Enable
    if( S_OK == nRetValue )
    {
        pObjectPtr = xmlUtils::pGetChildNodes(pXmlNode, (xmlChar*)"IsEnable");
        sConfigInfo.m_bEnable = TRUE;
        if( NULL != pObjectPtr)
        {
            pTempNode = pObjectPtr->nodesetval->nodeTab[0];
            sConfigInfo.m_bEnable = xmlUtils::bGetBooleanValue((char*)xmlNodeListGetString(pTempNode->doc, pTempNode->children, 1));
            xmlXPathFreeObject(pObjectPtr);
            pObjectPtr = NULL;
        }

        pObjectPtr = xmlUtils::pGetChildNodes(pXmlNode, (xmlChar*)"Testcases_Selected/Index");
        if( NULL != pObjectPtr)
        {
            int nSelectedCount = pObjectPtr->nodesetval->nodeNr;
            for( int i =0; i < nSelectedCount; i++ )
            {
                char* pchKey = (char*)xmlNodeListGetString( pXmlNode->doc, pObjectPtr->nodesetval->nodeTab[i]->children, 1);
                int nValue = strtol(pchKey, NULL, 10);
                xmlFree(pchKey);
                sConfigInfo.m_nListSelctedCases.push_back(nValue);
            }
            xmlXPathFreeObject(pObjectPtr);
            pObjectPtr = NULL;
        }

    }
    return nRetValue;
}
Exemplo n.º 3
0
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void EffectImplemented::ReloadResources( const EFK_CHAR* materialPath )
{
	UnloadResources();

	const EFK_CHAR* matPath = materialPath != NULL ? materialPath : m_materialPath.c_str();
	
	Setting* loader = GetSetting();

	{
		TextureLoader* textureLoader = loader->GetTextureLoader();
		if( textureLoader != NULL )
		{
			for( int32_t ind = 0; ind < m_ImageCount; ind++ )
			{
				EFK_CHAR fullPath[512];
				PathCombine( fullPath, matPath, m_ImagePaths[ ind ] );
				m_pImages[ind] = textureLoader->Load( fullPath, TextureType::Color );
			}
		}
	}

	{
		TextureLoader* textureLoader = loader->GetTextureLoader();
		if (textureLoader != NULL)
		{
			for (int32_t ind = 0; ind < m_normalImageCount; ind++)
			{
				EFK_CHAR fullPath[512];
				PathCombine(fullPath, matPath, m_normalImagePaths[ind]);
				m_normalImages[ind] = textureLoader->Load(fullPath, TextureType::Normal);
			}
		}

	}
		{
			TextureLoader* textureLoader = loader->GetTextureLoader();
			if (textureLoader != NULL)
			{
				for (int32_t ind = 0; ind < m_distortionImageCount; ind++)
				{
					EFK_CHAR fullPath[512];
					PathCombine(fullPath, matPath, m_distortionImagePaths[ind]);
					m_distortionImages[ind] = textureLoader->Load(fullPath, TextureType::Distortion);
				}
			}
		}

	

	{
		SoundLoader* soundLoader = loader->GetSoundLoader();
		if( soundLoader != NULL )
		{
			for( int32_t ind = 0; ind < m_WaveCount; ind++ )
			{
				EFK_CHAR fullPath[512];
				PathCombine( fullPath, matPath, m_WavePaths[ ind ] );
				m_pWaves[ind] = soundLoader->Load( fullPath );
			}
		}
	}

	{
		ModelLoader* modelLoader = loader->GetModelLoader();
		
		if( modelLoader != NULL )
		{
			for( int32_t ind = 0; ind < m_modelCount; ind++ )
			{
				EFK_CHAR fullPath[512];
				PathCombine( fullPath, matPath, m_modelPaths[ ind ] );
				m_pModels[ind] = modelLoader->Load( fullPath );
			}
		}
	}
}
Exemplo n.º 4
0
int CReplayFile::nLoadXMLConfig(xmlNodePtr pNodePtr)
{
    int nRetValue = S_OK;
    xmlNodePtr pTempNode = pNodePtr;
    CStringArray omStrFilters;
    while( NULL != pNodePtr )
    {
        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Log_File_Path")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                if(PathIsRelative((char*)key) == TRUE)
                {
                    std::string omStrConfigFolder;
                    std::string omPath;
                    char configPath[MAX_PATH];
                    AfxGetMainWnd()->SendMessage(MSG_GET_CONFIGPATH, (WPARAM)configPath, 0);
                    CUtilFunctions::nGetBaseFolder(configPath, omStrConfigFolder );
                    char chAbsPath[MAX_PATH];
                    PathCombine(chAbsPath, omStrConfigFolder.c_str(), (char*)key);
                    m_omStrFileName = chAbsPath;
                }
                else
                {
                    m_omStrFileName = (char*)key;
                }
                xmlFree(key);
            }
        }

        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"IsEnabled")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_bEnabled = xmlUtils::getBooleanValue((char*)key);
                xmlFree(key);
            }
        }


        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Retain_Recored_Time")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_nTimeMode = xmlUtils::getBooleanValue((char*)key);
                xmlFree(key);
            }
        }
        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Message_Delay")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_unMsgTimeDelay = atoi((char*)key);
                xmlFree(key);
            }
        }

        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Is_Cyclic_Mode")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_nReplayMode = (int)xmlUtils::getBooleanValue((char*)key);
                xmlFree(key);
            }
        }


        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Cyclic_Delay")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_unCycleTimeDelay = atoi((char*)key);
                xmlFree(key);
            }
        }
        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"IsInteractive")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                m_bInteractive = (int)xmlUtils::getBooleanValue((char*)key);
                xmlFree(key);
            }
        }
        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Replay_Message_Direction")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                this->m_ouReplayMsgType = xmlUtils::bGetDirection((char*)key);
                xmlFree(key);
            }
        }

        if ((!xmlStrcmp(pNodePtr->name, (const xmlChar*)"Filter")))
        {
            xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
            if(NULL != key)
            {
                omStrFilters.Add((char*)key);
                xmlFree(key);
            }
        }
        pNodePtr = pNodePtr->next;
    }
    //Filters

    if( omStrFilters.GetSize() > 0 && pTempNode != NULL)
    {
        SFILTERAPPLIED_CAN sFilterApplied;
        if( sFilterApplied.nSetXMLConfigData(pTempNode->doc) == S_OK)
        {
            sFilterApplied.nGetFiltersFromName(m_sFilterApplied, omStrFilters);
            /*
            int nRealFilters = 0;
            for(int i = 0; i < omStrFilters.GetSize(); i++)
            {
                int nIndex = GetFilterNameIndex((LPCSTR)omStrFilters.GetAt(i), sFilterApplied);
                if(nIndex >= 0)
                {
                    nRealFilters++;
                }
                else
                {
                    omStrFilters.RemoveAt(i);
                }
            }
            m_sFilterApplied.m_bEnabled = sFilterApplied.m_bEnabled;
            m_sFilterApplied.m_ushTotal = omStrFilters.GetSize();
            m_sFilterApplied.m_psFilters = new SFILTERSET[m_sFilterApplied.m_ushTotal];

            for(int i = 0; i < omStrFilters.GetSize(); i++)
            {
                int nIndex = GetFilterNameIndex((LPCSTR)omStrFilters.GetAt(i), sFilterApplied);
                if(nIndex >= 0)
                {
                    m_sFilterApplied.m_psFilters[i].bClone(sFilterApplied.m_psFilters[nIndex]);
                }
            }*/
        }

    }
    return nRetValue;
}
Exemplo n.º 5
0
TEST(USystemTest,PathCombineWorks)
{
	ASSERT_EQ(L"C:\\Temp\\Test.txt",PathCombine(L"C:",L"Temp\\Test.txt"));
}
Exemplo n.º 6
0
InstanceList::InstListError InstanceList::loadList()
{
	// load the instance groups
	QMap<QString, QString> groupMap;
	loadGroupList(groupMap);
	
	beginResetModel();
	
	m_instances.clear();
	QDir dir(m_instDir);
	QDirIterator iter(dir);
	while (iter.hasNext())
	{
		QString subDir = iter.next();
		if (!QFileInfo(PathCombine(subDir, "instance.cfg")).exists())
			continue;
		
		BaseInstance *instPtr = NULL;
		auto &loader = InstanceFactory::get();
		auto error = loader.loadInstance(instPtr, subDir);
		
		switch(error)
		{
			case InstanceFactory::NoLoadError:
				break;
			case InstanceFactory::NotAnInstance:
				break;
		}
		
		if (error != InstanceFactory::NoLoadError &&
			error != InstanceFactory::NotAnInstance)
		{
			QString errorMsg = QString("Failed to load instance %1: ").
					arg(QFileInfo(subDir).baseName()).toUtf8();
			
			switch (error)
			{
			default:
				errorMsg += QString("Unknown instance loader error %1").
						arg(error);
				break;
			}
			qDebug(errorMsg.toUtf8());
		}
		else if (!instPtr)
		{
			qDebug(QString("Error loading instance %1. Instance loader returned null.").
					arg(QFileInfo(subDir).baseName()).toUtf8());
		}
		else
		{
			QSharedPointer<BaseInstance> inst(instPtr);
			auto iter = groupMap.find(inst->id());
			if(iter != groupMap.end())
			{
				inst->setGroupInitial((*iter));
			}
			qDebug(QString("Loaded instance %1").arg(inst->name()).toUtf8());
			inst->setParent(this);
			m_instances.append(inst);
			connect(instPtr, SIGNAL(propertiesChanged(BaseInstance*)),this, SLOT(propertiesChanged(BaseInstance*)));
			connect(instPtr, SIGNAL(groupChanged()),this, SLOT(groupChanged()));
			connect(instPtr, SIGNAL(nuked(BaseInstance*)), this, SLOT(instanceNuked(BaseInstance*)));
		}
	}
	endResetModel();
	emit dataIsInvalid();
	return NoError;
}
Exemplo n.º 7
0
BOOL CBuildProgram::bBuildProgram(PSNODEINFO psNodeInfo, BOOL bLoadDLL, BOOL bDisplaySuccessful)
{
    BOOL bReturn            = FALSE;
    CString omStrFilePath   = "";
    CString omStrErrorMsg   = "";
    int iMajorVer = 0;
    int iMinorVer = 0;
    BOOL bVersion = FALSE ;
    CString omFileName=psNodeInfo->m_omStrCFileName;
    //psNodeInfo->m_eNodeState = NODE_NOT_BUILT;
    CString omLongFileName=omFileName;
    PROCESS_INFORMATION sProcessInfo;
    STARTUPINFO         sStartInfo;
    SECURITY_ATTRIBUTES sSecurityAttr;
    CWaitCursor omWait;
    DWORD makeResult = 1;		//non-zero initialisation

    // Check if file name passed as parameter is not empty
    if(omFileName.IsEmpty()==FALSE)
    {
        UpdatedDbCheckSumInfo(psNodeInfo);
        //CFileFind omFileFind;
        /*If the .dll file is already exists delete the .dll files
        so that on checking creation of .dll file we say build is
        success or failure*/

        // Remove all items in this string array before adding.
        m_omStrArray.RemoveAll();
        m_omStrArray.Add(" ");
        m_omStrArray.Add(omFileName);
        m_omStrSourceFilename = omFileName;

        CString omStrDllFile = omFileName;
        omStrDllFile.Replace(".cpp",".dll");
        /*if(omFileFind.FindFile(omStrDllFile) != 0)
        {
            if(DeleteFile(omStrDllFile) == 0)
            {
                omStrErrorMsg.Format(defERROR_DELETE_DLL,
                                     omStrDllFile);
                m_omStrArray.Add(omStrErrorMsg);
                bAddString(m_omStrArray);
                return FALSE;
            }
        }*/

        LONG lError = 0;
        //HKEY sKey;
        BYTE acGCCPath[1024];

        // Get the installation path for FRAME
        lError = ERROR_SUCCESS;
        /*lError = RegOpenKeyEx(  HKEY_LOCAL_MACHINE,
                 defREGISTRY_LOCATION,
                 0,
                 KEY_READ,
                 &sKey);*/
        // If the registry key open successfully, get the value in "path"
        // sub key
        if(lError==ERROR_SUCCESS)
        {
            HANDLE hStdInput        = nullptr; // Standard input handle of the child process.
            HANDLE hStdOutput       = nullptr; // - Standard output handle of the child process.
            HANDLE hStdError        = nullptr; //- Standard error handle of the child process.

            lError = ERROR_SUCCESS;
            /*lError = RegQueryValueEx(sKey,_T("path"),0, &ulType, acGCCPath,&dwSize);
            RegCloseKey(sKey);*/
            // Check if value is read successfully.
            if(lError !=ERROR_SUCCESS)
            {
                m_omStrArray.Add(defERROR_IN_REGISTRY);
                // Add string to list box attached to output window after
                // displaying it if not displayed already.
                bAddString(m_omStrArray);

                bReturn = FALSE;
                return bReturn;
            }
            // create an output file will be used by create process to send
            // output of process.
            sSecurityAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
            sSecurityAttr.bInheritHandle = TRUE;
            sSecurityAttr.lpSecurityDescriptor = nullptr;

            omStrFilePath   = omFileName.Left(omFileName.ReverseFind('\\'));
            omStrFilePath  += "\\output.txt";

            hStdOutput =  CreateFile(LPCTSTR(omStrFilePath) ,
                                     GENERIC_WRITE|GENERIC_READ, // access mode
                                     FILE_SHARE_WRITE  |FILE_SHARE_WRITE,
                                     &sSecurityAttr,
                                     CREATE_ALWAYS,
                                     FILE_ATTRIBUTE_NORMAL,
                                     nullptr ) ;

            // check if file is open successfully
            if(hStdOutput== INVALID_HANDLE_VALUE)
            {
                DWORD dwError = GetLastError();
                omStrErrorMsg.Format("%s: %d",
                                     "Error in opening output file",
                                     dwError);
                m_omStrArray.Add(omStrErrorMsg);
                // Add string to list box attached to output window after
                // displaying it if not displayed already.
                bAddString(m_omStrArray);

                bReturn = FALSE;
                return bReturn;
            }

            // Create an error file which will be used by create process to put
            // all error message generated.
            sSecurityAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
            sSecurityAttr.bInheritHandle = TRUE;
            sSecurityAttr.lpSecurityDescriptor = nullptr;

            omStrFilePath   = omFileName.Left(omFileName.ReverseFind('\\'));
            omStrFilePath  += "\\error.txt";

            hStdError =  CreateFile(LPCTSTR(omStrFilePath),
                                    GENERIC_WRITE|GENERIC_READ, // access mode
                                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                                    &sSecurityAttr,
                                    CREATE_ALWAYS,
                                    FILE_ATTRIBUTE_NORMAL,
                                    nullptr );

            // check if error file is created successfully
            if(hStdError == INVALID_HANDLE_VALUE)
            {
                DWORD dwError =   GetLastError();
                omStrErrorMsg.Format("%s: %d",
                                     "Error in opening error file",
                                     dwError);
                m_omStrArray.Add(omStrErrorMsg);
                // Add string to list box attached to output window after
                // displaying it if not displayed already.
                bAddString(m_omStrArray);

                bReturn = FALSE;
                // close output if error file is not created
                // successfully
                CloseHandle(hStdOutput);
                return bReturn;
            }

            // create input file which will be used by create process
            sSecurityAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
            sSecurityAttr.bInheritHandle = TRUE;
            sSecurityAttr.lpSecurityDescriptor = nullptr;

            omStrFilePath   = omFileName.Left(omFileName.ReverseFind('\\'));
            omStrFilePath  += "\\input.txt";

            hStdInput =  CreateFile(LPCTSTR(omStrFilePath),
                                    GENERIC_WRITE|GENERIC_READ,    // access mode
                                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                                    &sSecurityAttr,
                                    CREATE_ALWAYS,
                                    FILE_ATTRIBUTE_NORMAL,
                                    nullptr );

            // Check if input file created successfully
            if(hStdInput == INVALID_HANDLE_VALUE)
            {
                DWORD dwError =   GetLastError();
                omStrErrorMsg.Format("%s: %d",
                                     "Error in opening input file",
                                     dwError);
                m_omStrArray.Add(omStrErrorMsg);
                // Add string to list box attached to output window after
                // displaying it if not displayed already.
                bAddString(m_omStrArray);

                // close output and error files if input file is not created
                // successfully
                CloseHandle(hStdError);
                CloseHandle(hStdOutput);
                bReturn = FALSE;
                return bReturn;
            }

            // Create process using input, output and error file handle.
            // Set up the start up info struct.
            ZeroMemory(&sProcessInfo, sizeof(sProcessInfo) );
            ZeroMemory(&sStartInfo,sizeof(STARTUPINFO));
            sStartInfo.cb           = sizeof(STARTUPINFO);
            //to use the specified handles
            sStartInfo.dwFlags      = STARTF_USESTDHANDLES;
            sStartInfo.hStdOutput   = hStdOutput;
            sStartInfo.hStdInput    = hStdInput;
            sStartInfo.hStdError    = hStdError;
            // Use this if you want to hide the child:
            sStartInfo.wShowWindow  = SW_HIDE;

            // Get the make file template path.
            CString omStrMakeFileTemplateName;
            omStrMakeFileTemplateName  = acGCCPath;
            CString omTempGccFile = m_pGlobalObj->m_omAppDirectory;
            /*kadoor*/
            omStrMakeFileTemplateName = omTempGccFile;
            CString omGccMakeFileName = "\\GCCDLLMakeTemplate";


            omStrMakeFileTemplateName += omGccMakeFileName;

            // Create make file in the path where source file to by compiled is
            // Located
            CString omStrTemp          = omFileName.Left(
                                             omFileName.ReverseFind('\\'));
            CString omStrMakeFileName  = omStrTemp;
            omStrMakeFileName         += "\\DLLMake";
            bReturn = bCreateMakeFile(psNodeInfo, omStrMakeFileTemplateName,
                                      omStrMakeFileName);
            char acStrShortPath[1024];
            dwConvertShortPathName(omStrMakeFileName,acStrShortPath);

            // check if make file is created successfully.
            if(bReturn == TRUE)
            {
                CString omStrGccMakeFile = "";
                CString omStrGccParamter = "";
                CString omStrGCCPath     = "";
                // Create process after giving the command line input
                omStrGccMakeFile  = acGCCPath;

                /*kadoor*/
                omStrGccMakeFile = omTempGccFile;
                /*omStrGccMakeFile += "\\MinGW\\bin";
                omStrGCCPath      = omStrGccMakeFile;*/
                omStrGccMakeFile = "mingw32-make.exe";
                omStrGccParamter  =  "--silent --file=";
                omStrGccParamter += acStrShortPath;

                char* pucGccMakeFile  = (TCHAR*)omStrGccMakeFile.GetBuffer(
                                            omStrGccMakeFile.GetLength());
                char* pucGccParameter = (TCHAR*)omStrGccParamter.GetBuffer(
                                            omStrGccParamter.GetLength());
                char* pucGCCPath      = (TCHAR*)omStrGCCPath.GetBuffer(
                                            omStrGCCPath.GetLength());
                CString omStrCommandParam = pucGccMakeFile ;
                omStrCommandParam += " ";
                omStrCommandParam += pucGccParameter;

                char path_buffer[_MAX_PATH];
                char drive[_MAX_DRIVE];
                char dir[_MAX_DIR];
                char fname[_MAX_FNAME];
                char ext[_MAX_EXT];

                _splitpath( omLongFileName, drive, dir, fname, ext );
                PathCombine(path_buffer, drive, dir );

                SetCurrentDirectory(path_buffer);

                if ( psNodeInfo->m_eNodeState == NODE_REQ_CLEAN_BUILT)
                {
                    CString StrCleanCommandPram = omStrCommandParam + " clean";
                    INT nSuccess = CreateProcess( nullptr, StrCleanCommandPram.GetBuffer(MAX_PATH),
                                                  nullptr, nullptr,
                                                  true, CREATE_NO_WINDOW,
                                                  nullptr, nullptr,
                                                  &sStartInfo, &sProcessInfo);
                    if (nSuccess!=0)
                    {
                        WaitForSingleObject(sProcessInfo.hProcess, INFINITE );
                    }
                }
                psNodeInfo->m_eNodeState = NODE_NOT_BUILT;//Whether success or not move to next build step

                INT nSuccess = CreateProcess( nullptr, omStrCommandParam.GetBuffer(MAX_PATH),
                                              nullptr, nullptr,
                                              true, CREATE_NO_WINDOW,
                                              nullptr, nullptr,
                                              &sStartInfo, &sProcessInfo);

                // check if process is not created successfully else
                // wait for the process to to complete with time out value
                if (nSuccess==0)
                {
                    DWORD dwError =   GetLastError();
                    LPTSTR pcMessageBuffer;
                    DWORD dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                          FORMAT_MESSAGE_IGNORE_INSERTS |
                                          FORMAT_MESSAGE_FROM_SYSTEM ;

                    FormatMessage(
                        dwFormatFlags,
                        nullptr, // module to get message from (nullptr == system)
                        dwError,
                        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // default language
                        (LPTSTR) &pcMessageBuffer,
                        0,
                        nullptr
                    );

                    omStrErrorMsg.Format("%s: %s",
                                         "Invoking MinGW gcc compiler Failed",
                                         pcMessageBuffer);
                    LocalFree(pcMessageBuffer);
                    m_omStrArray.Add(omStrErrorMsg);
                    omStrErrorMsg = "Refer \"MinGW Installation\" Section in BUSMASTER Help File for Further Information";
                    m_omStrArray.Add(omStrErrorMsg);
                    // Add string to list box attached to output window after
                    // displaying it if not displayed already.
                    bAddString(m_omStrArray);

                    omStrGccParamter.ReleaseBuffer(omStrGccParamter.GetLength());
                    omStrGccMakeFile.ReleaseBuffer(omStrGccMakeFile.GetLength());
                    omStrGCCPath.ReleaseBuffer(omStrGCCPath.GetLength());

                    // close all three files if create process is not successfull
                    CloseHandle(hStdError);
                    CloseHandle(hStdOutput);
                    CloseHandle(hStdInput);
                    bReturn = FALSE;
                    return bReturn;
                }
                else
                {

                    if (nSuccess!=0)
                    {
                        WaitForSingleObject(sProcessInfo.hProcess, INFINITE );
                        GetExitCodeProcess(sProcessInfo.hProcess, &makeResult);
                    }
                }
                omStrGccParamter.ReleaseBuffer(omStrGccParamter.GetLength());
                omStrGccMakeFile.ReleaseBuffer(omStrGccMakeFile.GetLength());
                omStrGCCPath.ReleaseBuffer(omStrGCCPath.GetLength());
                // close the created files
                CloseHandle(hStdError);
                CloseHandle(hStdOutput);
                CloseHandle(hStdInput);

                // Get the output or error message from the corresponding file
                // and add it to CStringArray
                omStrFilePath   = omFileName.Left(omFileName.ReverseFind('\\'));
                omStrFilePath  += "\\error.txt";
                bAddStrToArrayFromFile(omStrFilePath,m_omStrArray);
                // to generate a message that dll is created successfully.
                // If there is no message in error file -> DLL created
                // successfully

                omStrFilePath.Replace("error.txt","output.txt");
                bAddStrToArrayFromFile(omStrFilePath,m_omStrArray);

                CString omStrDLLFile = "";
                //compiled properly
                if(makeResult == 0)								
                {
                    CString omStrFileNameInSDLLFile="";
                    CString omStrFileNameInLongFileName="";
                    CString omStrDLLFile   = "";
                    char acStrShortPath[1000];
                    dwConvertShortPathName(omFileName,acStrShortPath);
                    omFileName    = acStrShortPath;
                    omStrDLLFile  = omFileName.Left(omFileName.ReverseFind('.'));
                    omStrDLLFile += defDOT_DLL;
                    int nLength=omStrDLLFile.GetLength();
                    nLength-=omStrDLLFile.ReverseFind('\\');
                    nLength--;
                    omStrFileNameInSDLLFile=omStrDLLFile.
                                            Right(nLength);
                    int nLastDotPlace=omLongFileName.ReverseFind('.');
                    omLongFileName=omLongFileName.Left(nLastDotPlace);
                    omLongFileName+= defDOT_DLL;
                    nLength=omLongFileName.GetLength();
                    nLength-=omLongFileName.ReverseFind('\\');
                    nLength--;
                    omStrFileNameInLongFileName=omLongFileName.
                                                Right(nLength);
                    if(omStrFileNameInLongFileName.
                            CompareNoCase(omStrFileNameInSDLLFile))
                    {
                        BOOL bCopyFileStatus=COPYFILE(omStrDLLFile,omLongFileName);
                        if(bCopyFileStatus!=FALSE)
                        {
                            DeleteFile(omStrDLLFile);
                        }
                    }
                    psNodeInfo->m_omStrDllName=omLongFileName;
                    omLongFileName +=" created successfully";



                    if(bDisplaySuccessful)
                    {
                        m_omStrArray.Add(omLongFileName);
                        bAddString(m_omStrArray);
                    }
                }
                else
                {
                    // Error in building DLL
                    omStrDLLFile  ="Error in creating ";
                    omStrDLLFile += omLongFileName.Left(omLongFileName.ReverseFind('.'));
                    omStrDLLFile += defDOT_DLL;
                    m_omStrArray.Add(omStrDLLFile);
                    bReturn = FALSE;
                    bAddString(m_omStrArray);
                }
                // Add all items in CStringArray to list box attached to
                // output window.after displaying it if not displayed

            }
            else
            {
                // close the created files
                CloseHandle(hStdError);
                CloseHandle(hStdOutput);
                CloseHandle(hStdInput);
                bReturn = FALSE;
            }

        }
        else
        {
            m_omStrArray.Add(defERROR_OPEN_REGISTRY);
            // Add string to list box attached to output window
            // after displaying it if not displayed already.
            bAddString(m_omStrArray);
            bReturn = FALSE;
        }
        // Load the DLL if the flag passed as parameter is set
        // Unloading of already loaded library is done in CMainFrame.
        if(bLoadDLL==TRUE && bReturn == TRUE)
        {
            int n=omLongFileName.ReverseFind('.');
            omLongFileName=omLongFileName.Left(n);
            omLongFileName+= defDOT_DLL;
            HMODULE hModuleHandle  = nullptr;

            hModuleHandle = LoadLibrary(omLongFileName);
            if(hModuleHandle!=nullptr)
            {
                //check for the version number
                PFGET_PRG_VER pFGetPrgVer = (PFGET_PRG_VER)
                                            GetProcAddress( hModuleHandle,
                                                    defNAME_FUNC_GET_PRG_VER );
                if( pFGetPrgVer != nullptr )
                {
                    bVersion = pFGetPrgVer(&iMajorVer,&iMinorVer,hModuleHandle);
                    if( bVersion == TRUE )
                    {
                        if( iMajorVer != defMAJOR_VERSION &&
                                iMinorVer != defMINOR_VERSION )
                        {
                            CString omStrErrMsg ;
                            omStrErrMsg.Format( defUNSUPPORTED_VER,
                                                iMajorVer,iMinorVer );
                            bReturn = FALSE ;
                            if( FreeLibrary(hModuleHandle) != 0 )
                            {
                                hModuleHandle = nullptr;
                            }
                            // Remove Key Panel entry
                            /*if (CGlobalObj::g_podNodeToDllMap != nullptr)
                            {
                                CGlobalObj::g_podNodeToDllMap->RemoveKey(psNodeInfo->m_omStrDllName);
                            }*/
                            //AfxMessageBox(omStrErrMsg);
                            m_omStrArray.Add(omStrErrMsg);
                            bAddString(m_omStrArray);
                        }
                        else
                        {
                            /*if (CGlobalObj::g_podNodeToDllMap != nullptr)
                            {
                                CGlobalObj::g_podNodeToDllMap->operator [](psNodeInfo->m_omStrDllName) = hModuleHandle;
                                ::PostMessage(CGlobalObj::hWmdMDIParentFrame,WM_LOAD_UNLOAD, 1, 0);
                            }*/
                        }
                    }
                }
                else
                {
                    CString omStrErrMsg ;
                    omStrErrMsg.Format( defOLD_VER, omLongFileName );
                    bReturn = FALSE ;
                    if( FreeLibrary(hModuleHandle) != 0 )
                    {
                        hModuleHandle = nullptr;
                    }
                    //AfxMessageBox(omStrErrMsg);
                    m_omStrArray.Add(omStrErrMsg);
                    bAddString(m_omStrArray);
                }

                if(bReturn)
                {
                    psNodeInfo->m_omStrDllName=omLongFileName;
                    psNodeInfo->m_hModuleHandle=hModuleHandle;
                    //Local array so that only loading message will be
                    //added to the COutWnd list
                    CStringArray m_omStrArray;
                    if(bDisplaySuccessful)
                    {
                        m_omStrArray.Add(omLongFileName+ " loaded successfully");
                        // Add string to list box attached to output window
                        // after displaying it if not displayed already.
                        bAddString(m_omStrArray);
                    }
                }
            }

        }
    }
    if(bReturn)
    {
        psNodeInfo->m_eNodeState = NODE_BUILD_SUCCESS;
    }
    else
    {
        psNodeInfo->m_eNodeState = NODE_BUILD_FAIL;
    }
    return bReturn;
}
Exemplo n.º 8
0
QString LegacyInstance::coreModsDir() const
{
	return PathCombine(minecraftRoot(), "coremods");
}
Exemplo n.º 9
0
QString LegacyInstance::resourceDir() const
{
	return PathCombine(minecraftRoot(), "resources");
}
Exemplo n.º 10
0
QString LegacyInstance::savesDir() const
{
	return PathCombine(minecraftRoot(), "saves");
}
Exemplo n.º 11
0
QString LegacyInstance::loaderModsDir() const
{
	return PathCombine(minecraftRoot(), "mods");
}
Exemplo n.º 12
0
QString LegacyInstance::binDir() const
{
	return PathCombine(minecraftRoot(), "bin");
}
Exemplo n.º 13
0
/**
 * @param pszMapPdbFolder - folder with MAP/PDB files.
 * @param pszModuleName - base module name.
 * @param pszFileExt - requested file extension.
 * @param pszFileName - combined file name.
 * @return true if requested file exist.
 */
bool CExpressModeDlg::FindFileByPattern(PCTSTR pszMapPdbFolder, PCTSTR pszModuleName, PCTSTR pszFileExt, PTSTR pszFileName)
{
	PathCombine(pszFileName, pszMapPdbFolder, pszModuleName);
	PathRenameExtension(pszFileName, pszFileExt);
	return (GetFileAttributes(pszFileName) != INVALID_FILE_ATTRIBUTES);
}
Exemplo n.º 14
0
void CFileInfo::DirtoryInfoExtraction(const wstring& wstrPath, list<MESHPATH*>& rPathInfolist)
{
	CFileFind		Find;
	Find.FindFile(wstrPath.c_str());

	int		iContinue = 1;
	while(iContinue)
	{
		iContinue = Find.FindNextFile();

		if(Find.IsDots())
			continue;

		if(Find.IsDirectory())
			DirtoryInfoExtraction(wstring(Find.GetFilePath() + L"\\*.*"), rPathInfolist);
		else
		{
			if(Find.IsSystem())
				continue;

			MESHPATH*   pFilePath = new MESHPATH;
			ZeroMemory(pFilePath, sizeof(MESHPATH));

			TCHAR   szPathBuf[MAX_PATH] = L"";
			lstrcpy(szPathBuf, wstrPath.c_str());														//szPathBuf = 0x0013dd98 "C:\Users\Administrator.JUSIN-20150429V\Desktop\Export\Bush\Bush1\*.*"
			PathRemoveFileSpec(szPathBuf);		    													// szPathBuf = 0x0013dd98 "C:\Users\Administrator.JUSIN-20150429V\Desktop\Export\Bush\Bush1\*.*"
		

			wstring      wstrFileName = szPathBuf;														//szPathBuf = 0x0013dd98 "C:\Users\Administrator.JUSIN-20150429V\Desktop\Export\Bush\Bush1"
			wstrFileName = PathFindFileName(wstrFileName.c_str());										//wstrFileName = "Bush1"
			pFilePath->wstrObjTag = wstrFileName.c_str();         									// pFilePath = 0x11c5ff50 {wstrFileName="Bush1" wstrFilePath="" wstrFullPath="" ...}

			// 파일 이름 다시 정한다.
			while(true)
			{
				wstrFileName = Find.GetFilePath().operator LPCWSTR();									//wstrFileName = "C:\Users\Administrator.JUSIN-20150429V\Desktop\Export\Bush\Bush1\Bush1.X"

				wstring      wstrFileTag = wstrFileName.substr( wstrPath.find_last_of(L"\\") + 1 );		//wstrFileTag = "Bush1.X"
				wstrFileTag = wstrFileTag.substr(wstrFileTag.length() - 2, wstrFileTag.length());		//wstrFileTag = ".X"
				if(wstrFileTag == L".X" ||
					wstrFileTag == L".x")      // 대 소문자 구분하니까, 구분해서 찾아주기
				{
					wstrFileName = wstrFileName.substr( wstrPath.find_last_of(L"\\") + 1 );				//wstrFileName = "Bush1.X"
					pFilePath->wstrFileTag = wstrFileName.c_str();      // 파일이름						//pFilePath->wstrType = "Bush1.X"
					break;
				}
				Find.FindNextFile();
			}
			//          wstrFileName = wstrFileName + L".X";
			//          lstrcpy(pFilePath->szFileTag, wstrFileName.c_str());      // 파일이름

			TCHAR   szBuf[MAX_PATH] = L"";
			lstrcpy(szBuf, (LPWSTR)Find.GetFilePath().operator LPCWSTR());								//szBuf = 0x0013db38 "C:\Users\Administrator.JUSIN-20150429V\Desktop\Export\Bush\Bush1\Bush1.X"
			PathRemoveFileSpec(szBuf);																	//szBuf = 0x0013db38 "C:\Users\Administrator.JUSIN-20150429V\Desktop\Export\Bush\Bush1"

			PathCombine(szBuf, szBuf, (LPWSTR)wstrFileName.c_str());									//szBuf = 0x0013db38 "C:\Users\Administrator.JUSIN-20150429V\Desktop\Export\Bush\Bush1\Bush1.X"
			PathRemoveFileSpec(szBuf);																	//szBuf = 0x0013db38 "C:\Users\Administrator.JUSIN-20150429V\Desktop\Export\Bush\Bush1"
			//PathRemoveFileSpec(szBuf);
			pFilePath->wstrFullPath = ConvertRelativePath(szBuf).c_str();								//pFilePath->wstrFullPath = "..\..\..\..\Export\Bush\Bush1"
			// 마지막 파일 이름 없애야 함

			PathRemoveFileSpec(szBuf);																	//szBuf = 0x0013db38 "C:\Users\Administrator.JUSIN-20150429V\Desktop\Export\Bush"
			pFilePath->wstrGroupTag = PathFindFileName(szBuf);											//pFilePath->wstrFilePath = "Bush"


			pFilePath->wstrFullPath += L"\\";      // 마지막에 하나 붙여주자							//pFilePath->wstrFullPath = "..\..\..\..\Export\Bush\Bush1\"
			rPathInfolist.push_back(pFilePath);															//pFilePath = 0x11c5ff50 {wstrFileName="Bush1" wstrFilePath="Bush" wstrFullPath="..\..\..\..\Export\Bush\Bush1\" ...}

			Find.FindFile(Find.GetFilePath());
			Find.FindNextFile();
		}
	}
}
int InstallMissingPrerequisites(const WCHAR* BaseDirectory)
{
	// Look for missing prerequisites
	WCHAR MissingPrerequisites[1024] = { 0, };
	if(LoadLibrary(L"MSVCP120.DLL") == NULL || LoadLibrary(L"MSVCR120.DLL") == NULL)
	{
		wcscat_s(MissingPrerequisites, TEXT("Microsoft Visual C++ 2013 Runtime\n"));
	}
	if(LoadLibrary(L"MSVCP140.DLL") == NULL || LoadLibrary(L"ucrtbase.dll") == NULL)
	{
		wcscat_s(MissingPrerequisites, TEXT("Microsoft Visual C++ 2015 Runtime\n"));
	}
	if(LoadLibrary(L"XINPUT1_3.DLL") == NULL)
	{
		wcscat_s(MissingPrerequisites, TEXT("DirectX Runtime\n"));
	}

	// Check if there's anything missing
	if(MissingPrerequisites[0] != 0)
	{
		WCHAR MissingPrerequisitesMsg[1024];
		wsprintf(MissingPrerequisitesMsg, L"The following component(s) are required to run this program:\n\n%s", MissingPrerequisites);

		// If we don't have the installer, just notify the user and quit
		WCHAR PrereqInstaller[MAX_PATH];
#ifdef _M_X64
		PathCombine(PrereqInstaller, BaseDirectory, L"Engine\\Extras\\Redist\\en-us\\UE4PrereqSetup_x64.exe");
#else
		PathCombine(PrereqInstaller, BaseDirectory, L"Engine\\Extras\\Redist\\en-us\\UE4PrereqSetup_x86.exe");
#endif
		if(GetFileAttributes(PrereqInstaller) == INVALID_FILE_ATTRIBUTES)
		{
			MessageBox(NULL, MissingPrerequisitesMsg, NULL, MB_OK);
			return 9001;
		}

		// Otherwise ask them if they want to install them
		wcscat_s(MissingPrerequisitesMsg, L"\nWould you like to install them now?");
		if(MessageBox(NULL, MissingPrerequisitesMsg, NULL, MB_YESNO) == IDNO)
		{
			return 9002;
		}

		// Start the installer
		SHELLEXECUTEINFO ShellExecuteInfo;
		ZeroMemory(&ShellExecuteInfo, sizeof(ShellExecuteInfo));
		ShellExecuteInfo.cbSize = sizeof(ShellExecuteInfo);
		ShellExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
		ShellExecuteInfo.nShow = SW_SHOWNORMAL;
		ShellExecuteInfo.lpFile = PrereqInstaller;
		if(!ShellExecuteExW(&ShellExecuteInfo))
		{
			return 9003;
		}

		// Wait for the process to complete, then get its exit code
		DWORD ExitCode = 0;
		WaitForSingleObject(ShellExecuteInfo.hProcess, INFINITE);
		GetExitCodeProcess(ShellExecuteInfo.hProcess, &ExitCode);
		CloseHandle(ShellExecuteInfo.hProcess);
		if(ExitCode != 0)
		{
			return 9004;
		}
	}
	return 0;
}
Exemplo n.º 16
0
QString LegacyInstance::texturePacksDir() const
{
	return PathCombine(minecraftRoot(), "texturepacks");
}
Exemplo n.º 17
0
void CmdService::Run() {
	CLog* log=LogManager::OpenLog(m_szLogFile,CLog::LL_INFO);
	int i;

	DWORD nBufferSize=GetFileSize(m_szConfigFile);

	if(!nBufferSize) {
		nBufferSize = 32767;
	}

	PEXECPARAM tmpExecParam=NULL,ptrExecParam;
	PTCHAR pBuffer= (PTCHAR)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(TCHAR)*nBufferSize),ptrBuffer,tmpBuffer;
	DWORD ret = GetPrivateProfileSection("Command", pBuffer, nBufferSize, m_szConfigFile);

	// ¶ÁÈ¡ËùÓÐÅäÖõÄÃüÁî
	if(ret>0) {
		TCHAR *p;
		TCHAR tmpDirectory[MAX_PATH]={0};
		TCHAR configFileDirectory[MAX_PATH]={0};
		strncpy(configFileDirectory,m_szConfigFile,strrchr(m_szConfigFile,'\\')-m_szConfigFile+1);

		for(ptrBuffer=pBuffer;*ptrBuffer;ptrBuffer+=strlen(ptrBuffer)+1) {
			ptrExecParam = (PEXECPARAM)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(EXECPARAM));
			tmpBuffer=strchr(ptrBuffer,'=');
			strcpy(ptrExecParam->cmdLine,tmpBuffer+1);

			*tmpBuffer='\0';
			strcpy(ptrExecParam->keyName,ptrBuffer);

			sprintf(ptrExecParam->logFile, "%s-%s", m_szLogFile, ptrExecParam->keyName);

			GetPrivateProfileString("Directory", ptrExecParam->keyName, ".\\", tmpDirectory, MAX_PATH-1,m_szConfigFile);
			p=tmpDirectory;
			while(*p) {
				if(*p == '/') {
					*p='\\';
				}
				p++;
			}
			PathCombine(ptrExecParam->curDirectory,configFileDirectory, tmpDirectory);
#ifdef _DEBUG
			log->WriteLog(CLog::LL_INFO,"keyName(%s), curDirectory(%s), cmdLine(%s), logFile(%s)", ptrExecParam->keyName, ptrExecParam->curDirectory, ptrExecParam->cmdLine, ptrExecParam->logFile);
#endif
			ptrExecParam->next = NULL;
			if(tmpExecParam) {
				tmpExecParam->next = ptrExecParam;
			} else {
				pHeadExecParam = ptrExecParam;
			}
			tmpExecParam = ptrExecParam;

			nCmdSize++;

			ptrBuffer=strchr(tmpBuffer+1,'\0');
		}
	} else {
		log->WriteLog("Not found [Command] section in config file.");
		log->CloseLogFile();
		return;
	}

	TCHAR domain[100], userName[100], passWord[100];
	HANDLE hToken = NULL;

	GetPrivateProfileString("Account", "Domain", ".", domain, sizeof(domain)-1, m_szConfigFile);
	GetPrivateProfileString("Account", "User", "Administrator", userName, sizeof(userName)-1, m_szConfigFile);
	GetPrivateProfileString("Account", "Password", "", passWord, sizeof(passWord)-1, m_szConfigFile);
	ret = LogonUser(userName, domain, passWord, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &hToken);
	if(ret) {
		log->WriteLog(CLog::LL_INFO, "Login success(Domain=%s, User=%s, Password=%s)", domain, userName, passWord);
	} else {
		log->WriteLog(CLog::LL_WARN, "Login fail(Domain=%s, User=%s, Password=%s)", domain, userName, passWord);
	}

	dwThreadId = (PDWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(DWORD)*nCmdSize);
	hThread = (PHANDLE)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(HANDLE)*nCmdSize);
	m_bRunning = true;
	while (m_bRunning) {
		if (m_bPaused) {
			Sleep(200);
			continue;
		}

		ptrExecParam=pHeadExecParam;
		i=0;
		while(ptrExecParam) {
			ptrExecParam->hToken = hToken;
			hThread[i]=CreateThread(NULL, 0, ThreadProc, ptrExecParam, 0, &dwThreadId[i]);
			if(hThread[i]==NULL) {
				log->WriteLog(CLog::LL_ERROR, "[%s] create thread fail", ptrExecParam->keyName);
			} else {
#ifdef _DEBUG
				log->WriteLog(CLog::LL_INFO, "[%d] = %s", i, ptrExecParam->keyName);
#endif
				i++;
			}
			ptrExecParam = ptrExecParam->next;
		}

		WaitForMultipleObjects(i, hThread, TRUE, INFINITE);

		ptrExecParam=pHeadExecParam;
		i = 0;
		while(ptrExecParam) {
			CloseHandle(hThread[i]);
			i++;
			ptrExecParam = ptrExecParam->next;
		}

		Sleep(1000);
	}
	log->CloseLogFile();
}
Exemplo n.º 18
0
QString LegacyInstance::runnableJar() const
{
	return PathCombine(binDir(), "minecraft.jar");
}
Exemplo n.º 19
0
void StartCmder(std::wstring path, bool is_single_mode)
{
#if USE_TASKBAR_API
	wchar_t appId[MAX_PATH] = { 0 };
#endif
	wchar_t exeDir[MAX_PATH] = { 0 };
	wchar_t icoPath[MAX_PATH] = { 0 };
	wchar_t cfgPath[MAX_PATH] = { 0 };
	wchar_t oldCfgPath[MAX_PATH] = { 0 };
	wchar_t conEmuPath[MAX_PATH] = { 0 };
	wchar_t args[MAX_PATH * 2 + 256] = { 0 };

	GetModuleFileName(NULL, exeDir, sizeof(exeDir));

#if USE_TASKBAR_API
	wcscpy_s(appId, exeDir);
#endif

	PathRemoveFileSpec(exeDir);

	PathCombine(icoPath, exeDir, L"icons\\cmder.ico");

	// Check for machine-specific config file.
	PathCombine(oldCfgPath, exeDir, L"config\\ConEmu-%COMPUTERNAME%.xml");
	ExpandEnvironmentStrings(oldCfgPath, oldCfgPath, sizeof(oldCfgPath) / sizeof(oldCfgPath[0]));
	if (!PathFileExists(oldCfgPath)) {
		PathCombine(oldCfgPath, exeDir, L"config\\ConEmu.xml");
	}

	// Check for machine-specific config file.
	PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu-%COMPUTERNAME%.xml");
	ExpandEnvironmentStrings(cfgPath, cfgPath, sizeof(cfgPath) / sizeof(cfgPath[0]));
	if (!PathFileExists(cfgPath)) {
		PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.xml");
	}

	PathCombine(conEmuPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.exe");

	if (FileExists(oldCfgPath) && !FileExists(cfgPath))
	{
		if (!CopyFile(oldCfgPath, cfgPath, FALSE))
		{
			MessageBox(NULL,
				(GetLastError() == ERROR_ACCESS_DENIED)
				? L"Failed to copy ConEmu.xml file to new location! Restart cmder as administrator."
				: L"Failed to copy ConEmu.xml file to new location!", MB_TITLE, MB_ICONSTOP);
			exit(1);
		}
	}

	if (is_single_mode)
	{
		swprintf_s(args, L"/single /Icon \"%s\" /Title Cmder", icoPath);
	}
	else
	{
		swprintf_s(args, L"/Icon \"%s\" /Title Cmder", icoPath);
	}

	SetEnvironmentVariable(L"CMDER_ROOT", exeDir);
	if (!streqi(path.c_str(), L""))
	{
		if (!SetEnvironmentVariable(L"CMDER_START", path.c_str())) {
			MessageBox(NULL, _T("Error trying to set CMDER_START to given path!"), _T("Error"), MB_OK);
		}
	}
	// Ensure EnvironmentVariables are propagated.
	SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_ABORTIFHUNG, 5000, NULL);
	SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) L"Environment", SMTO_ABORTIFHUNG, 5000, NULL); // For Windows >= 8

	STARTUPINFO si = { 0 };
	si.cb = sizeof(STARTUPINFO);
#if USE_TASKBAR_API
	si.lpTitle = appId;
	si.dwFlags = STARTF_TITLEISAPPID;
#endif

	PROCESS_INFORMATION pi;
	if (!CreateProcess(conEmuPath, args, NULL, NULL, false, 0, NULL, NULL, &si, &pi)) {
		MessageBox(NULL, _T("Unable to create the ConEmu Process!"), _T("Error"), MB_OK);
		return;
	}
}
Exemplo n.º 20
0
QString LegacyInstance::modListFile() const
{
	return PathCombine(instanceRoot(), "modlist");
}
Exemplo n.º 21
0
void LegacyUpdate::extractLwjgl()
{
	// make sure the directories are there

	bool success = ensureFolderPathExists(lwjglNativesPath);

	if (!success)
	{
		emitFailed("Failed to extract the lwjgl libs - error when creating required folders.");
		return;
	}

	QuaZip zip("lwjgl.zip");
	if (!zip.open(QuaZip::mdUnzip))
	{
		emitFailed("Failed to extract the lwjgl libs - not a valid archive.");
		return;
	}

	// and now we are going to access files inside it
	QuaZipFile file(&zip);
	const QString jarNames[] = {"jinput.jar", "lwjgl_util.jar", "lwjgl.jar"};
	for (bool more = zip.goToFirstFile(); more; more = zip.goToNextFile())
	{
		if (!file.open(QIODevice::ReadOnly))
		{
			zip.close();
			emitFailed("Failed to extract the lwjgl libs - error while reading archive.");
			return;
		}
		QuaZipFileInfo info;
		QString name = file.getActualFileName();
		if (name.endsWith('/'))
		{
			file.close();
			continue;
		}
		QString destFileName;
		// Look for the jars
		for (int i = 0; i < 3; i++)
		{
			if (name.endsWith(jarNames[i]))
			{
				destFileName = PathCombine(lwjglTargetPath, jarNames[i]);
			}
		}
		// Not found? look for the natives
		if (destFileName.isEmpty())
		{
#ifdef Q_OS_WIN32
			QString nativesDir = "windows";
#else
#ifdef Q_OS_MAC
			QString nativesDir = "macosx";
#else
			QString nativesDir = "linux";
#endif
#endif
			if (name.contains(nativesDir))
			{
				int lastSlash = name.lastIndexOf('/');
				int lastBackSlash = name.lastIndexOf('\\');
				if (lastSlash != -1)
					name = name.mid(lastSlash + 1);
				else if (lastBackSlash != -1)
					name = name.mid(lastBackSlash + 1);
				destFileName = PathCombine(lwjglNativesPath, name);
			}
		}
		// Now if destFileName is still empty, go to the next file.
		if (!destFileName.isEmpty())
		{
			setStatus(tr("Installing new LWJGL - extracting ") + name + "...");
			QFile output(destFileName);
			output.open(QIODevice::WriteOnly);
			output.write(file.readAll()); // FIXME: wste of memory!?
			output.close();
		}
		file.close(); // do not forget to close!
	}
	zip.close();
	m_reply.reset();
	QFile doneFile(PathCombine(lwjglTargetPath, "done"));
	doneFile.open(QIODevice::WriteOnly);
	doneFile.write("done.");
	doneFile.close();
}
Exemplo n.º 22
0
QString LegacyInstance::instanceConfigFolder() const
{
	return PathCombine(minecraftRoot(), "config");
}
Exemplo n.º 23
0
HRESULT CDropHandler::CopyDIBV5Data(IDataObject *pDataObject,
	list<PastedFile_t> *pPastedFileList)
{
	STGMEDIUM stg;
	HRESULT hr;

	hr = pDataObject->GetData(&m_ftcDIBV5,&stg);

	if(hr == S_OK)
	{
		BITMAPINFO *pbmp = static_cast<BITMAPINFO *>(GlobalLock(stg.hGlobal));

		if(pbmp != NULL)
		{
			SYSTEMTIME st;
			FILETIME ft;
			FILETIME lft;
			TCHAR szTime[512];

			GetLocalTime(&st);
			SystemTimeToFileTime(&st,&ft);
			LocalFileTimeToFileTime(&ft,&lft);
			CreateFileTimeString(&lft,szTime,SIZEOF_ARRAY(szTime),FALSE);

			for(int i = 0;i < lstrlen(szTime);i++)
			{
				if(szTime[i] == '/')
				{
					szTime[i] = '-';
				}
				else if(szTime[i] == ':')
				{
					szTime[i] = '.';
				}
			}

			TCHAR szFullFileName[MAX_PATH];
			TCHAR szFileName[MAX_PATH];

			/* TODO: Move text into string table. */
			StringCchPrintf(szFileName,SIZEOF_ARRAY(szFileName),
				_T("Clipboard Image (%s).bmp"),szTime);

			PathCombine(szFullFileName,m_szDestDirectory,
				szFileName);

			HANDLE hFile = CreateFile(szFullFileName,
				GENERIC_WRITE,0,NULL,CREATE_NEW,
				FILE_ATTRIBUTE_NORMAL,NULL);

			if(hFile != INVALID_HANDLE_VALUE)
			{
				DWORD dwSize = static_cast<DWORD>(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (GlobalSize(stg.hGlobal) - sizeof(BITMAPINFOHEADER)));

				LPBYTE pData = new BYTE[dwSize];

				BITMAPFILEHEADER *pbfh = (BITMAPFILEHEADER *)pData;

				/* 'BM'. */
				pbfh->bfType		= 0x4D42;

				pbfh->bfSize		= pbmp->bmiHeader.biSize;
				pbfh->bfReserved1	= 0;
				pbfh->bfReserved2	= 0;
				pbfh->bfOffBits		= sizeof(BITMAPFILEHEADER);

				BITMAPINFOHEADER *pb5h = (BITMAPINFOHEADER *)(pData + sizeof(BITMAPFILEHEADER));

				memcpy(pb5h,&pbmp->bmiHeader,sizeof(BITMAPINFOHEADER));

				RGBQUAD *prgb = (RGBQUAD *)(pData + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER));

				memcpy(prgb,pbmp->bmiColors,GlobalSize(stg.hGlobal) - sizeof(BITMAPINFOHEADER));

				DWORD nBytesWritten;

				WriteFile(hFile,(LPCVOID)pData,
					dwSize,
					&nBytesWritten,NULL);

				CloseHandle(hFile);

				delete[] pData;

				PastedFile_t pf;

				StringCchCopy(pf.szFileName,SIZEOF_ARRAY(pf.szFileName),szFullFileName);
				PathStripPath(pf.szFileName);

				pPastedFileList->push_back(pf);
			}

			GlobalUnlock(stg.hGlobal);
		}

		/* Must release the storage medium. */
		ReleaseStgMedium(&stg);
	}

	return hr;
}
Exemplo n.º 24
0
QString LegacyInstance::defaultCustomBaseJar() const
{
	return PathCombine(binDir(), "mcbackup.jar");
}
Exemplo n.º 25
0
void MainWindow::on_actionAddInstance_triggered()
{
	if (!MMC->minecraftlist()->isLoaded() && m_versionLoadTask &&
		m_versionLoadTask->isRunning())
	{
		QEventLoop waitLoop;
		waitLoop.connect(m_versionLoadTask, SIGNAL(failed(QString)), SLOT(quit()));
		waitLoop.connect(m_versionLoadTask, SIGNAL(succeeded()), SLOT(quit()));
		waitLoop.exec();
	}

	NewInstanceDialog newInstDlg(this);
	if (!newInstDlg.exec())
		return;

	BaseInstance *newInstance = NULL;

	QString instancesDir = MMC->settings()->get("InstanceDir").toString();
	QString instDirName = DirNameFromString(newInstDlg.instName(), instancesDir);
	QString instDir = PathCombine(instancesDir, instDirName);

	auto &loader = InstanceFactory::get();

	auto error = loader.createInstance(newInstance, newInstDlg.selectedVersion(), instDir);
	QString errorMsg = QString("Failed to create instance %1: ").arg(instDirName);
	switch (error)
	{
	case InstanceFactory::NoCreateError:
		newInstance->setName(newInstDlg.instName());
		newInstance->setIconKey(newInstDlg.iconKey());
		MMC->instances()->add(InstancePtr(newInstance));
		break;

	case InstanceFactory::InstExists:
	{
		errorMsg += "An instance with the given directory name already exists.";
		CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show();
		return;
	}

	case InstanceFactory::CantCreateDir:
	{
		errorMsg += "Failed to create the instance directory.";
		CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show();
		return;
	}

	default:
	{
		errorMsg += QString("Unknown instance loader error %1").arg(error);
		CustomMessageBox::selectable(this, tr("Error"), errorMsg, QMessageBox::Warning)->show();
		return;
	}
	}

	if (MMC->accounts()->anyAccountIsValid())
	{
		ProgressDialog loadDialog(this);
		auto update = newInstance->doUpdate(false);
		connect(update.get(), &Task::failed, [this](QString reason)
		{
			QString error = QString("Instance load failed: %1").arg(reason);
			CustomMessageBox::selectable(this, tr("Error"), error, QMessageBox::Warning)
				->show();
		});
		loadDialog.exec(update.get());
	}
	else
	{
		CustomMessageBox::selectable(
			this, tr("Error"),
			tr("MultiMC cannot download Minecraft or update instances unless you have at least "
			   "one account added.\nPlease add your Mojang or Minecraft account."),
			QMessageBox::Warning)->show();
	}
}
Exemplo n.º 26
0
MinecraftProcess *LegacyInstance::prepareForLaunch(MojangAccountPtr account)
{
	MinecraftProcess *proc = new MinecraftProcess(this);

	QIcon icon = MMC->icons()->getIcon(iconKey());
	auto pixmap = icon.pixmap(128, 128);
	pixmap.save(PathCombine(minecraftRoot(), "icon.png"), "PNG");

	// extract the legacy launcher
	QFile(":/java/launcher.jar").copy(PathCombine(minecraftRoot(), LAUNCHER_FILE));

	// set the process arguments
	{
		QStringList args;

		// window size
		QString windowSize;
		if (settings().get("LaunchMaximized").toBool())
			windowSize = "max";
		else
			windowSize = QString("%1x%2").arg(settings().get("MinecraftWinWidth").toInt()).arg(
				settings().get("MinecraftWinHeight").toInt());

		// window title
		QString windowTitle;
		windowTitle.append("MultiMC: ").append(name());

		// Java arguments
		args.append(Util::Commandline::splitArgs(settings().get("JvmArgs").toString()));

#ifdef OSX
		// OSX dock icon and name
		args << "-Xdock:icon=icon.png";
		args << QString("-Xdock:name=\"%1\"").arg(windowTitle);
#endif

		QString lwjgl = QDir(MMC->settings()->get("LWJGLDir").toString() + "/" + lwjglVersion())
							.absolutePath();

		// launcher arguments
		args << QString("-Xms%1m").arg(settings().get("MinMemAlloc").toInt());
		args << QString("-Xmx%1m").arg(settings().get("MaxMemAlloc").toInt());
		args << QString("-XX:PermSize=%1m").arg(settings().get("PermGen").toInt());
/**
* HACK: Stupid hack for Intel drivers.
* See: https://mojang.atlassian.net/browse/MCL-767
*/
#ifdef Q_OS_WIN32
		args << QString("-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_"
						"minecraft.exe.heapdump");
#endif

		args << "-jar" << LAUNCHER_FILE;
		args << account->currentProfile()->name();
		args << account->sessionId();
		args << windowTitle;
		args << windowSize;
		args << lwjgl;
		proc->setArguments(args);
	}

	// set the process work path
	proc->setWorkdir(minecraftRoot());

	return proc;
}
Exemplo n.º 27
0
INT tagLogInfo::nSetConfigData(xmlNodePtr pNodePtr)
{
    //pNodePtr = pNodePtr->xmlChildrenNode;
    vClear();   //To give Initial Values
    INT nRetValue = S_OK;
    m_sLogTrigger.startId = -1;
    m_sLogTrigger.stopId = -1;

    while (pNodePtr != NULL)
    {
        if ( pNodePtr->xmlChildrenNode != NULL )
        {
            if ((!xmlStrcmp((const xmlChar*)pNodePtr->name, (const xmlChar*)"IsEnabled")))
            {
                xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
                if(NULL != key)
                {
                    m_bEnabled = xmlUtils::getBooleanValue((char*)key);
                    xmlFree(key);
                }
            }
            else if ((!xmlStrcmp((const xmlChar*)pNodePtr->name, (const xmlChar*)"Time_Mode")))
            {
                xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
                if(NULL != key)
                {
                    m_eLogTimerMode =  xmlUtils::eGetTimerMode((char*)key);
                    xmlFree(key);
                }
            }
            else if ((!xmlStrcmp((const xmlChar*)pNodePtr->name, (const xmlChar*)"Numeric_Mode")))
            {
                xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
                if(NULL != key)
                {
                    m_eNumFormat = xmlUtils::eGetNumericMode((char*)key);
                    xmlFree(key);
                }
            }

            else if ((!xmlStrcmp((const xmlChar*)pNodePtr->name, (const xmlChar*)"IsAppendLog_Enabled")))
            {
                xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
                if(NULL != key)
                {
                    BOOL bValue = xmlUtils::getBooleanValue((char*)key);
                    m_eFileMode = OVERWRITE_MODE;
                    if(bValue == TRUE)
                    {
                        m_eFileMode = APPEND_MODE;
                    }
                    xmlFree(key);
                }
            }


            else if ((!xmlStrcmp((const xmlChar*)pNodePtr->name, (const xmlChar*)"Reset_Absolute_Time")))
            {
                xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
                if(NULL != key)
                {
                    m_bResetAbsTimeStamp = xmlUtils::getBooleanValue((char*)key);
                    xmlFree(key);
                }
            }



            else if ((!xmlStrcmp((const xmlChar*)pNodePtr->name, (const xmlChar*)"Channel")))
            {
                xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
                if(NULL != key)
                {
                    m_ChannelSelected = atoi((char*)key);
                    if(m_ChannelSelected < 0 || m_ChannelSelected > CHANNEL_ALLOWED )
                    {
                        m_ChannelSelected = CAN_CHANNEL_ALL;
                    }
                    xmlFree(key);
                }
            }

            else if ((!xmlStrcmp((const xmlChar*)pNodePtr->name, (const xmlChar*)"File_Path")))
            {
                xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
                if(NULL != key)
                {
                    if(PathIsRelative((char*)key) == TRUE)
                    {
                        std::string omStrConfigFolder;
                        std::string omPath;
                        char configPath[MAX_PATH];
                        AfxGetMainWnd()->SendMessage(MSG_GET_CONFIGPATH, (WPARAM)configPath, 0);
                        CUtilFunctions::nGetBaseFolder(configPath, omStrConfigFolder );
                        char chAbsPath[MAX_PATH];
                        PathCombine(chAbsPath, omStrConfigFolder.c_str(), (char*)key);
                        strcpy_s(m_sLogFileName, MAX_PATH, chAbsPath);
                    }
                    else
                    {
                        strcpy_s(m_sLogFileName, _MAX_PATH, (char*)key);
                    }
                    xmlFree(key);
                    nRetValue = S_OK;
                }
                else
                {
                    nRetValue = S_FALSE;
                }
            }

            else if ((!xmlStrcmp((const xmlChar*)pNodePtr->name, (const xmlChar*)"Trigger_Start_ID")))
            {
                xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
                if(NULL != key)
                {
                    m_sLogTrigger.startId = atoi((char*)key);
                    xmlFree(key);
                }
            }
            else if ((!xmlStrcmp((const xmlChar*)pNodePtr->name, (const xmlChar*)"Trigger_Stop_ID")))
            {
                xmlChar* key = xmlNodeListGetString(pNodePtr->doc, pNodePtr->xmlChildrenNode, 1);
                if(NULL != key)
                {
                    m_sLogTrigger.stopId = atoi((char*)key);
                    xmlFree(key);
                }
            }
        }//if Conditions
        pNodePtr = pNodePtr->next;
    }//While
    if (strlen(m_sLogFileName) == 0)
    {
        nRetValue = S_FALSE;
    }
    //0 - None, 1 - Start, 2 - Stop, 3 - Both
    m_sLogTrigger.triggerType = NONE;
    int nStartID = m_sLogTrigger.startId;
    int nStopID = m_sLogTrigger.stopId;

    if( nStartID >= 0 && nStopID < 0 )
    {
        m_sLogTrigger.triggerType = START;
    }
    else if( nStartID < 0 && nStopID >= 0 )
    {
        m_sLogTrigger.triggerType = STOP;
    }
    else if( nStartID < 0 && nStopID < 0 )
    {
        m_sLogTrigger.triggerType = NONE;
    }
    else if( nStartID >= 0 && nStopID >= 0 )
    {
        m_sLogTrigger.triggerType = BOTH;
    }

    return nRetValue;
}
Exemplo n.º 28
0
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
	DWORD tick = GetTickCount();
	(void)tick;

	unsigned cmd_line_flags = 0;
	int argc;
	LPWSTR *argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	for (int i = 1; i < argc; ++i)
	{
		const FlagsName *f;
		for (f = g_flags_names; f->name; ++f)
		{
			if (_wcsicmp(argv[i], f->wname) == 0)
			{
				cmd_line_flags |= f->flags;
				break;
			}
		}

		if (!f->name)
		{
			Help(argv[i]);
			return 1;
		}
	}

	GTC;

	char exe[MAX_PATH];
	GetModuleFileName(GetModuleHandle(0), exe, sizeof exe);
	PathRemoveFileSpec(exe);
	PathCombine(g_ini_path, exe, g_ini_file_name);
	ODS(strprintf("dispswitch: %s: INI path is \"%s\".\n", __FUNCTION__, g_ini_path));

	// 	STARTUPINFO si;
	// 	GetStartupInfo(&si);

	GTC;

	std::vector<MonitorInfo> monitors;
	EnumDisplayMonitors(0, 0, &GetAllMonitorsMonitorEnumProc, LPARAM(&monitors));
	if (monitors.size() <= 1)
		return 0;

	std::sort(monitors.begin(), monitors.end(), [](const MonitorInfo &a, const MonitorInfo &b) { return a.info.rcWork.left < b.info.rcWork.left; });

	for (unsigned i = 0; i < monitors.size(); ++i)
	{
		const MonitorInfo *mi = &monitors[i];
		(void)mi;

		ODS(strprintf("dispswitch: monitor %u/%u:\n", 1 + i, monitors.size()));
		ODS(strprintf("    Original index: %u\n", (unsigned)mi->original_index));
		ODS(strprintf("    Device=\"%s\"\n", mi->info.szDevice));
		ODS(strprintf("    MonitorRect=(%ld,%ld)-(%ld,%ld)\n",
			mi->info.rcMonitor.left, mi->info.rcMonitor.top, mi->info.rcMonitor.right, mi->info.rcMonitor.bottom));
		ODS(strprintf("    WorkRect=(%ld,%ld)-(%ld,%ld)\n",
			mi->info.rcWork.left, mi->info.rcWork.top, mi->info.rcWork.right, mi->info.rcWork.bottom));
	}

	//
	std::vector<PROCESSENTRY32> processes;
	EnumProcesses(&processes);

	GTC;

	// 
	HWND fg = GetForegroundWindow();
	WindowDetails fg_details;
	GetWindowDetails(processes, fg, &fg_details);

	ODS(strprintf("exe=%s\n", fg_details.exe_file));

	std::vector<HWND> hwnds;
	if (fg_details.flags&F_TAKE_EXE)
	{
		EnumWindows(&GetAllVisibleWindowsWindowEnumProc, LPARAM(&hwnds));
		ODS(strprintf("%u hwnds.\n", hwnds.size()));
		std::vector<HWND>::iterator hwnd = hwnds.begin();
		while (hwnd != hwnds.end())
		{
			char exe_file[MAX_PATH];
			GetExeFileForWindow(processes, *hwnd, exe_file);
			if (strcmp(exe_file, fg_details.exe_file) == 0)
				++hwnd;
			else
				hwnd = hwnds.erase(hwnd);
		}
	}
	else
	{
		HWND h = fg;
		do
		{
			hwnds.push_back(h);
			h = GetParent(h);
		} while (h && (fg_details.flags&F_TAKE_PARENT));
	}

	GTC;

	ODS(strprintf("%u hwnds.\n", hwnds.size()));

	for (unsigned i = 0; i < hwnds.size(); ++i)
	{
		HWND fg_wnd = hwnds[i];

		bool was_zoomed = false;
		if (IsZoomed(fg_wnd))
		{
			was_zoomed = true;
			ShowWindow(fg_wnd, SW_RESTORE);
		}

		RECT fg_rect;
		GetWindowRect(fg_wnd, &fg_rect);

		ODS(strprintf("dispswitch: old rect=(%ld,%ld)->(%ld,%ld).\n", fg_rect.left, fg_rect.top, fg_rect.right,
			fg_rect.bottom));

		HMONITOR fg_monitor = MonitorFromRect(&fg_rect, MONITOR_DEFAULTTOPRIMARY);

		size_t monitor_idx;
		for (monitor_idx = 0; monitor_idx < monitors.size(); ++monitor_idx)
		{
			if (monitors[monitor_idx].hmonitor == fg_monitor)
				break;
		}

		if (monitor_idx >= monitors.size())
		{
			// Oh dear.
			continue;
		}

		const MONITORINFOEX *old_info = &monitors[monitor_idx].info;

		++monitor_idx;
		monitor_idx %= monitors.size();

		const MONITORINFOEX *new_info = &monitors[monitor_idx].info;

		//
		RECT dr;
		dr.left = fg_rect.left - old_info->rcWork.left;
		dr.top = fg_rect.top - old_info->rcWork.top;
		dr.right = fg_rect.right - old_info->rcWork.right;
		dr.bottom = fg_rect.bottom - old_info->rcWork.bottom;

		if (fg_details.flags&F_DONT_RESIZE)
		{
			LONG cx = (fg_rect.left + fg_rect.right) / 2 - old_info->rcWork.left;
			LONG cy = (fg_rect.top + fg_rect.bottom) / 2 - old_info->rcWork.top;

			float tcx = cx / (float)GetRectWidth(old_info->rcWork);
			float tcy = cy / (float)GetRectHeight(old_info->rcWork);

			LONG fg_w = GetRectWidth(fg_rect);
			LONG fg_h = GetRectHeight(fg_rect);

			fg_rect.left = new_info->rcWork.left + LONG(tcx*GetRectWidth(new_info->rcWork) + .5f) - fg_w / 2;
			fg_rect.top = new_info->rcWork.top + LONG(tcy*GetRectHeight(new_info->rcWork) + .5f) - fg_h / 2;

			fg_rect.right = fg_rect.left + fg_w;
			fg_rect.bottom = fg_rect.top + fg_h;

			// don't let it go outside the work rect.
			LONG dx = new_info->rcWork.left - fg_rect.left;
			if (dx < 0)
				dx = 0;

			LONG dy = new_info->rcWork.top - fg_rect.top;
			if (dy < 0)
				dy = 0;

			OffsetRect(&fg_rect, dx, dy);
		}
		else
		{
			float left_frac, top_frac, right_frac, bottom_frac;
			{
				RECT local_rect = fg_rect;
				OffsetRect(&local_rect, -old_info->rcWork.left, -old_info->rcWork.top);

				left_frac = local_rect.left / float(GetRectWidth(old_info->rcWork));
				top_frac = local_rect.top / float(GetRectHeight(old_info->rcWork));
				right_frac = local_rect.right / float(GetRectWidth(old_info->rcWork));
				bottom_frac = local_rect.bottom / float(GetRectHeight(old_info->rcWork));
			}

			if (fg_details.flags&F_SIDE_RELATIVE)
			{
				fg_rect.left = new_info->rcWork.left + dr.left;
				fg_rect.top = new_info->rcWork.top + dr.top;
				fg_rect.right = new_info->rcWork.right + dr.right;
				fg_rect.bottom = new_info->rcWork.bottom + dr.bottom;
			}
			else
			{
				// round to nearest instead of round to zero, prevents window
				// floating towards the origin with repeated invocations (or at
				// least it did with the test window).
				fg_rect.left = new_info->rcWork.left + LONG(left_frac*GetRectWidth(new_info->rcWork) + .5f);
				fg_rect.top = new_info->rcWork.top + LONG(top_frac*GetRectHeight(new_info->rcWork) + .5f);
				fg_rect.right = new_info->rcWork.left + LONG(right_frac*GetRectWidth(new_info->rcWork) + .5f);
				fg_rect.bottom = new_info->rcWork.top + LONG(bottom_frac*GetRectHeight(new_info->rcWork) + .5f);
			}

			// Work out a minimum size for this window.
			LONG min_width, min_height;
			{
				// Include a small client area
				RECT rect = { 0, 0, 100, 100 };
				DWORD style = GetWindowLong(fg_wnd, GWL_STYLE);
				DWORD ex_style = GetWindowLong(fg_wnd, GWL_EXSTYLE);
				BOOL menu = !!GetMenu(fg_wnd);
				AdjustWindowRectEx(&rect, style, menu, ex_style);

				min_width = GetRectWidth(rect);
				min_height = GetRectHeight(rect);

				ODS(strprintf("dispswitch: min size=%ldx%ld\n", min_width, min_height));
			}

			// Clamp size, rather crudely.
			if (GetRectWidth(fg_rect) < min_width)
				fg_rect.right = fg_rect.left + min_width;

			if (GetRectHeight(fg_rect) < min_height)
				fg_rect.bottom = fg_rect.top + min_height;
		}

		ODS(strprintf("dispswitch: new rect=(%ld,%ld)->(%ld,%ld).\n", fg_rect.left, fg_rect.top, fg_rect.right,
			fg_rect.bottom));

		// 		BOOL ok=MoveWindow(fg_wnd,fg_rect.left,fg_rect.top,fg_rect.right-fg_rect.left,
		// 			fg_rect.bottom-fg_rect.top,TRUE);
		BOOL ok = SetWindowPos(fg_wnd, 0, fg_rect.left, fg_rect.top, fg_rect.right - fg_rect.left,
			fg_rect.bottom - fg_rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOCOPYBITS);
		if (!ok)
		{
			DWORD err = GetLastError();
			(void)err;
			ODS(strprintf("dispswitch:     move failed. Error: 0x%08lX\n", err));
		}

		if (was_zoomed)
			ShowWindow(fg_wnd, SW_MAXIMIZE);
	}

	return 0;
}
Exemplo n.º 29
0
QString LegacyInstance::jarModsDir() const
{
	return PathCombine(instanceRoot(), "instMods");
}
Exemplo n.º 30
0
InstanceList::InstListError InstanceList::loadList()
{
	QDir dir(m_instDir);
	QDirIterator iter(dir);
	
	QString groupFileName = m_instDir + "/instgroups.json";
	// temporary map from instance ID to group name
	QMap<QString, QString> groupMap;
	
	// HACK: this is really an if. breaks after one iteration.
	while (QFileInfo(groupFileName).exists())
	{
		QFile groupFile(groupFileName);
		
		if (!groupFile.open(QIODevice::ReadOnly))
		{
			// An error occurred. Ignore it.
			qDebug("Failed to read instance group file.");
			break;
		}
		
		QTextStream in(&groupFile);
		QString jsonStr = in.readAll();
		groupFile.close();
		
		QJsonParseError error;
		QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8(), &error);
		
		if (error.error != QJsonParseError::NoError)
		{
			qWarning(QString("Failed to parse instance group file: %1 at offset %2").
					 arg(error.errorString(), QString::number(error.offset)).toUtf8());
			break;
		}
		
		if (!jsonDoc.isObject())
		{
			qWarning("Invalid group file. Root entry should be an object.");
			break;
		}
		
		QJsonObject rootObj = jsonDoc.object();
		
		// Make sure the format version matches.
		if (rootObj.value("formatVersion").toVariant().toInt() == GROUP_FILE_FORMAT_VERSION)
		{
			// Get the group list.
			if (!rootObj.value("groups").isObject())
			{
				qWarning("Invalid group list JSON: 'groups' should be an object.");
				break;
			}
			
			// Iterate through the list.
			QJsonObject groupList = rootObj.value("groups").toObject();
			
			for (QJsonObject::iterator iter = groupList.begin(); 
				 iter != groupList.end(); iter++)
			{
				QString groupName = iter.key();
				
				// If not an object, complain and skip to the next one.
				if (!iter.value().isObject())
				{
					qWarning(QString("Group '%1' in the group list should "
									 "be an object.").arg(groupName).toUtf8());
					continue;
				}
				
				QJsonObject groupObj = iter.value().toObject();
				/*
				// Create the group object.
				InstanceGroup *group = new InstanceGroup(groupName, this);
				groups.push_back(group);
				
				// If 'hidden' isn't a bool value, just assume it's false.
				if (groupObj.value("hidden").isBool() && groupObj.value("hidden").toBool())
				{
					group->setHidden(groupObj.value("hidden").toBool());
				}
				*/
				
				if (!groupObj.value("instances").isArray())
				{
					qWarning(QString("Group '%1' in the group list is invalid. "
									 "It should contain an array "
									 "called 'instances'.").arg(groupName).toUtf8());
					continue;
				}
				
				// Iterate through the list of instances in the group.
				QJsonArray instancesArray = groupObj.value("instances").toArray();
				
				for (QJsonArray::iterator iter2 = instancesArray.begin(); 
					 iter2 != instancesArray.end(); iter2++)
				{
					groupMap[(*iter2).toString()] = groupName;
				}
			}
		}
		break;
	}
	m_instances.clear();
	while (iter.hasNext())
	{
		QString subDir = iter.next();
		if (QFileInfo(PathCombine(subDir, "instance.cfg")).exists())
		{
			Instance *instPtr = NULL;
			
			InstanceLoader::InstTypeError error = InstanceLoader::get().
					loadInstance(instPtr, subDir);
			
			if (error != InstanceLoader::NoError &&
					 error != InstanceLoader::NotAnInstance)
			{
				QString errorMsg = QString("Failed to load instance %1: ").
						arg(QFileInfo(subDir).baseName()).toUtf8();
				
				switch (error)
				{
				case InstanceLoader::TypeNotRegistered:
					errorMsg += "Instance type not found.";
					break;
					
				default:
					errorMsg += QString("Unknown instance loader error %1").
							arg(error);
					break;
				}
				qDebug(errorMsg.toUtf8());
			}
			else if (!instPtr)
			{
				qDebug(QString("Error loading instance %1. Instance loader returned null.").
					   arg(QFileInfo(subDir).baseName()).toUtf8());
			}
			else
			{
				QSharedPointer<Instance> inst(instPtr);
				auto iter = groupMap.find(inst->id());
				if(iter != groupMap.end())
				{
					inst->setGroup((*iter));
				}
				qDebug(QString("Loaded instance %1").arg(inst->name()).toUtf8());
				inst->setParent(this);
				m_instances.append(inst);
				connect(instPtr, SIGNAL(propertiesChanged(Instance*)),this, SLOT(propertiesChanged(Instance*)));
			}
		}
	}