示例#1
0
BOOL ResolveSupersede(siC *siCObject, greInfo *aGre)
{
  DWORD dwIndex;
  char  szFilePath[MAX_BUF];
  char  szSupersedeFile[MAX_BUF];
  char  szSupersedeVersion[MAX_BUF];
  char  szType[MAX_BUF_TINY];
  char  szKey[MAX_BUF_TINY];
  verBlock  vbVersionNew;
  verBlock  vbFileVersion;

  siCObject->bSupersede = FALSE;
  if(siCObject->dwAttributes & SIC_SUPERSEDE)
  {
    dwIndex = 0;
    GetConfigIniProfileString(siCObject->szReferenceName, "SupersedeType", "", szType, sizeof(szType));
    if(*szType !='\0')
    {
      if(lstrcmpi(szType, "File Exists") == 0)
      {
        wsprintf(szKey, "SupersedeFile%d", dwIndex);        
        GetConfigIniProfileString(siCObject->szReferenceName, szKey, "", szSupersedeFile, sizeof(szSupersedeFile));
        while(*szSupersedeFile != '\0')
        {
          DecryptString(szFilePath, szSupersedeFile);
          if(FileExists(szFilePath))
          {
            wsprintf(szKey, "SupersedeMinVersion%d",dwIndex);
            GetConfigIniProfileString(siCObject->szReferenceName, szKey, "", szSupersedeVersion, sizeof(szSupersedeVersion));
            if(*szSupersedeVersion != '\0')
            {
              if(GetFileVersion(szFilePath,&vbFileVersion))
              {
                /* If we can get the version, and it is greater than or equal to the SupersedeVersion
                 * set supersede.  If we cannot get the version, do not supersede the file. */
                TranslateVersionStr(szSupersedeVersion, &vbVersionNew);
                if(CompareVersion(vbFileVersion,vbVersionNew) >= 0)
                {  
                  siCObject->bSupersede = TRUE;
                  break;  /* Found at least one file, so break out of while loop */
                }
              }
            }
            else
            { /* The file exists, and there's no version to check.  set Supersede */
              siCObject->bSupersede = TRUE;
              break;  /* Found at least one file, so break out of while loop */
            }
          }
          wsprintf(szKey, "SupersedeFile%d", ++dwIndex);        
          GetConfigIniProfileString(siCObject->szReferenceName, szKey, "", szSupersedeFile, sizeof(szSupersedeFile));
        }
      }
      else if(lstrcmpi(szType, "GRE") == 0)
      {
        /* save the GRE component */
        aGre->siCGreComponent = siCObject;

        /* If -fgre is passed in, and the current product to install is !GRE,
         * and the current component is 'Component GRE' then select and
         * disable it to force it to be installed regardless of supersede
         * rules.
         *
         * If the product is GRE, then it won't have a 'Component GRE', but
         * rather a 'Component XPCOM', in which case it will always get
         * installed */
        if((gbForceInstallGre) && (lstrcmpi(sgProduct.szProductNameInternal, "GRE") != 0))
        {
          siCObject->dwAttributes |= SIC_SELECTED;
          siCObject->dwAttributes |= SIC_DISABLED;
        }
        else
          ResolveSupersedeGre(siCObject, aGre);
      }
    }

    if(siCObject->bSupersede)
    {
      siCObject->dwAttributes &= ~SIC_SELECTED;
      siCObject->dwAttributes |= SIC_DISABLED;
      siCObject->dwAttributes |= SIC_INVISIBLE;
    }
    else
      /* Make sure to unset the DISABLED bit.  If the Setup Type is other than
       * Custom, then we don't care if it's DISABLED or not because this flag
       * is only used in the Custom dialogs.
       *
       * If the Setup Type is Custom and this component is DISABLED by default
       * via the config.ini, it's default value will be restored in the
       * SiCNodeSetItemsSelected() function that called ResolveSupersede(). */
      siCObject->dwAttributes &= ~SIC_DISABLED;
  }
  return(siCObject->bSupersede);
}
示例#2
0
void CDlgSelCritDB::OnOK() 
{
	CString	strCurCodeName;
	CString	strCurDBName;
	CString strTmp;
	UpdateData();
	m_ctlMaterCodeName.GetWindowText( EDIBgbl::sCur_MaterialCodeName );

	int row = m_ctrlShowCODE.GetSelectionMark();
	if( row == -1 )
	{
		AfxMessageBox("请选择一个行业的规范数据库!");
		return;
	}
	char c[256];
	//规范数据库
	m_ctrlShowCODE.GetItemText(row, 1, c, 256);
	strCurDBName = c;

	//当前规范
	memset(c,'\0',256);
	m_ctrlShowCODE.GetItemText(row, 0, c, 256);
	strCurCodeName = c;

	//当前规范代号
	memset(c,'\0',256);
	m_ctrlShowCODE.GetItemText(row, 2, c, 256);
	EDIBgbl::sCur_CodeNO = c;

	try
	{
		if ( !FileExists( EDIBgbl::sCritPath + strCurDBName ) )
		{
			strTmp.Format(IDS_NOT_EXISTS_FILE, EDIBgbl::sCritPath + strCurDBName);
			AfxMessageBox( strTmp );
			return;
		}
		CString strCon;
		//重新连接标准库
		strCon = CONNECTSTRING + EDIBgbl::sCritPath + strCurDBName;
		if( theApp.m_pConnectionCODE->State == adStateOpen )
		{
			theApp.m_pConnectionCODE->Close();
		}
		theApp.m_pConnectionCODE->Open(_bstr_t(strCon), "", "", -1);
	}
	catch(_com_error &e)
	{
		AfxMessageBox(e.Description()+"\n\n选择的规范数据库("+strCurCodeName+")被破坏, 请重新安装 AutoIPED !");
		CDialog::OnCancel();
		return;
	}
	EDIBgbl::sCur_CritDbName = strCurDBName;
	EDIBgbl::sCur_CodeName = strCurCodeName;
	EDIBgbl::iCur_CodeKey=row+1;

	EDIBgbl::SetCurDBName();
	//显示当前的工程名(加上行业标准)
	((CMainFrame*)theApp.m_pMainWnd)->ShowCurrentProjectName();
	
	CDialog::OnOK();
}
示例#3
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;
	}
}
示例#4
0
文件: Sequence.cpp 项目: jcochran/fpp
int Sequence::OpenSequenceFile(const char *filename, int startSeconds) {
	LogDebug(VB_SEQUENCE, "OpenSequenceFile(%s, %d)\n", filename, startSeconds);

	if (!filename || !filename[0])
	{
		LogErr(VB_SEQUENCE, "Empty Sequence Filename!\n", filename);
		return 0;
	}

	size_t bytesRead = 0;

	m_seqFileSize = 0;

	if (IsSequenceRunning())
		CloseSequenceFile();

	m_seqStarting = 1;
	m_seqPaused   = 0;
	m_seqDuration = 0;
	m_seqSecondsElapsed = 0;
	m_seqSecondsRemaining = 0;

	strcpy(m_seqFilename, filename);

	char tmpFilename[2048];
	unsigned char tmpData[2048];
	strcpy(tmpFilename,(const char *)getSequenceDirectory());
	strcat(tmpFilename,"/");
	strcat(tmpFilename, filename);

	if (getFPPmode() == REMOTE_MODE)
		CheckForHostSpecificFile(getSetting("HostName"), tmpFilename);

	if (!FileExists(tmpFilename))
	{
		LogErr(VB_SEQUENCE, "Sequence file %s does not exist\n", tmpFilename);
		m_seqStarting = 0;
		return 0;
	}

	m_seqFile = fopen((const char *)tmpFilename, "r");
	if (m_seqFile == NULL) 
	{
		LogErr(VB_SEQUENCE, "Error opening sequence file: %s. fopen returned NULL\n",
			tmpFilename);
		m_seqStarting = 0;
		return 0;
	}

	if (getFPPmode() == MASTER_MODE)
	{
		SendSeqSyncStartPacket(filename);

		// Give the remotes a head start spining up so they are ready
		usleep(100000);
	}

	///////////////////////////////////////////////////////////////////////
	// Check 4-byte File format identifier
	char seqFormatID[5];
	strcpy(seqFormatID, "    ");
	bytesRead = fread(seqFormatID, 1, 4, m_seqFile);
	seqFormatID[4] = 0;
	if ((bytesRead != 4) || (strcmp(seqFormatID, "PSEQ") && strcmp(seqFormatID, "FSEQ")))
	{
		LogErr(VB_SEQUENCE, "Error opening sequence file: %s. Incorrect File Format header: '%s', bytesRead: %d\n",
			filename, seqFormatID, bytesRead);

		fseek(m_seqFile, 0L, SEEK_SET);
		bytesRead = fread(tmpData, 1, DATA_DUMP_SIZE, m_seqFile);
		HexDump("Sequence File head:", tmpData, bytesRead);

		fclose(m_seqFile);
		m_seqFile = NULL;
		m_seqStarting = 0;
		return 0;
	}

	///////////////////////////////////////////////////////////////////////
	// Get Channel Data Offset
	bytesRead = fread(tmpData, 1, 2, m_seqFile);
	if (bytesRead != 2)
	{
		LogErr(VB_SEQUENCE, "Sequence file %s too short, unable to read channel data offset value\n", filename);

		fseek(m_seqFile, 0L, SEEK_SET);
		bytesRead = fread(tmpData, 1, DATA_DUMP_SIZE, m_seqFile);
		HexDump("Sequence File head:", tmpData, bytesRead);

		fclose(m_seqFile);
		m_seqFile = NULL;
		m_seqStarting = 0;
		return 0;
	}
	m_seqChanDataOffset = tmpData[0] + (tmpData[1] << 8);

	///////////////////////////////////////////////////////////////////////
	// Now that we know the header size, read the whole header in one shot
	fseek(m_seqFile, 0L, SEEK_SET);
	bytesRead = fread(tmpData, 1, m_seqChanDataOffset, m_seqFile);
	if (bytesRead != m_seqChanDataOffset)
	{
		LogErr(VB_SEQUENCE, "Sequence file %s too short, unable to read fixed header size value\n", filename);

		fseek(m_seqFile, 0L, SEEK_SET);
		bytesRead = fread(tmpData, 1, DATA_DUMP_SIZE, m_seqFile);
		HexDump("Sequence File head:", tmpData, bytesRead);

		fclose(m_seqFile);
		m_seqFile = NULL;
		m_seqStarting = 0;
		return 0;
	}

	m_seqVersionMinor = tmpData[6];
	m_seqVersionMajor = tmpData[7];
	m_seqVersion      = (m_seqVersionMajor * 256) + m_seqVersionMinor;

	m_seqFixedHeaderSize =
		(tmpData[8])        + (tmpData[9] << 8);

	m_seqStepSize =
		(tmpData[10])       + (tmpData[11] << 8) +
		(tmpData[12] << 16) + (tmpData[13] << 24);

	m_seqNumPeriods =
		(tmpData[14])       + (tmpData[15] << 8) +
		(tmpData[16] << 16) + (tmpData[17] << 24);

	m_seqStepTime =
		(tmpData[18])       + (tmpData[19] << 8);

	m_seqNumUniverses = 
		(tmpData[20])       + (tmpData[21] << 8);

	m_seqUniverseSize = 
		(tmpData[22])       + (tmpData[23] << 8);

	m_seqGamma         = tmpData[24];
	m_seqColorEncoding = tmpData[25];

	// End of v1.0 fields
	if (m_seqVersion > 0x0100)
	{
	}

	m_seqRefreshRate = 1000 / m_seqStepTime;

	fseek(m_seqFile, 0L, SEEK_END);
	m_seqFileSize = ftell(m_seqFile);
	m_seqDuration = (int)((float)(m_seqFileSize - m_seqChanDataOffset)
		/ ((float)m_seqStepSize * (float)m_seqRefreshRate));
	m_seqSecondsRemaining = m_seqDuration;
	fseek(m_seqFile, m_seqChanDataOffset, SEEK_SET);
	m_seqFilePosition = m_seqChanDataOffset;

	LogDebug(VB_SEQUENCE, "Sequence File Information\n");
	LogDebug(VB_SEQUENCE, "seqFilename           : %s\n", m_seqFilename);
	LogDebug(VB_SEQUENCE, "seqVersion            : %d.%d\n",
		m_seqVersionMajor, m_seqVersionMinor);
	LogDebug(VB_SEQUENCE, "seqFormatID           : %s\n", seqFormatID);
	LogDebug(VB_SEQUENCE, "seqChanDataOffset     : %d\n", m_seqChanDataOffset);
	LogDebug(VB_SEQUENCE, "seqFixedHeaderSize    : %d\n", m_seqFixedHeaderSize);
	LogDebug(VB_SEQUENCE, "seqStepSize           : %d\n", m_seqStepSize);
	LogDebug(VB_SEQUENCE, "seqNumPeriods         : %d\n", m_seqNumPeriods);
	LogDebug(VB_SEQUENCE, "seqStepTime           : %dms\n", m_seqStepTime);
	LogDebug(VB_SEQUENCE, "seqNumUniverses       : %d *\n", m_seqNumUniverses);
	LogDebug(VB_SEQUENCE, "seqUniverseSize       : %d *\n", m_seqUniverseSize);
	LogDebug(VB_SEQUENCE, "seqGamma              : %d *\n", m_seqGamma);
	LogDebug(VB_SEQUENCE, "seqColorEncoding      : %d *\n", m_seqColorEncoding);
	LogDebug(VB_SEQUENCE, "seqRefreshRate        : %d\n", m_seqRefreshRate);
	LogDebug(VB_SEQUENCE, "seqFileSize           : %lu\n", m_seqFileSize);
	LogDebug(VB_SEQUENCE, "seqDuration           : %d\n", m_seqDuration);
	LogDebug(VB_SEQUENCE, "'*' denotes field is currently ignored by FPP\n");

	m_seqPaused = 0;
	m_seqSingleStep = 0;
	m_seqSingleStepBack = 0;

	int frameNumber = 0;

	if (startSeconds)
	{
		int frameNumber = startSeconds * m_seqRefreshRate;
		int newPos = m_seqChanDataOffset + (frameNumber * m_seqStepSize);
		LogDebug(VB_SEQUENCE, "Seeking to byte %d in %s\n", newPos, m_seqFilename);

		fseek(m_seqFile, newPos, SEEK_SET);
	}

	ReadSequenceData();

	SetChannelOutputFrameNumber(frameNumber);

	SetChannelOutputRefreshRate(m_seqRefreshRate);
	StartChannelOutputThread();

	m_seqStarting = 0;

	return m_seqFileSize;
}
int
main(int argc, char *argv[])
{
  char         **av, surf_fname[STRLEN], *template_fname, *hemi, *sphere_name,
  *cp, *subject, fname[STRLEN] ;
  int          ac, nargs, ino, sno, nbad = 0, failed, n,nfields;
  VERTEX *v;
  VALS_VP *vp;
  MRI_SURFACE  *mris ;
  MRI_SP       *mrisp, /* *mrisp_aligned,*/ *mrisp_template ;
  INTEGRATION_PARMS parms ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mris_make_template.c,v 1.27 2011/03/02 00:04:33 nicks Exp $",
           "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  memset(&parms, 0, sizeof(parms)) ;
  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;
  /* setting default values for vectorial registration */
  setParms(&parms);

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv,&parms) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 5) usage_exit() ;

  /* multiframe registration */
  if (multiframes) parms.flags |= IP_USE_MULTIFRAMES;

  if (!strlen(subjects_dir))  /* not specified on command line*/
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM,
                "%s: SUBJECTS_DIR not defined in environment.\n",
                Progname) ;
    strcpy(subjects_dir, cp) ;
  }
  hemi = argv[1] ;
  sphere_name = argv[2] ;
  template_fname = argv[argc-1] ;
  if (1 || !FileExists(template_fname))  /* first time - create it */
  {
    fprintf(stderr, "creating new parameterization...\n") ;
    if (multiframes)
    {
      mrisp_template = MRISPalloc(scale, atlas_size * IMAGES_PER_SURFACE );
      /*    if (no_rot)  /\* don't do rigid alignment *\/ */
      /*     mrisp_aligned = NULL ; */
      /*    else */
      /*     mrisp_aligned = MRISPalloc(scale, PARAM_FRAMES);  */
    }
    else
    {
      mrisp_template = MRISPalloc(scale, PARAM_IMAGES);
      /*    if (no_rot)  /\* don't do rigid alignment *\/ */
      /*     mrisp_aligned = NULL ; */
      /*    else */
      /*     mrisp_aligned = MRISPalloc(scale, PARAM_IMAGES);  */
    }

  }
  else
  {
    fprintf(stderr, "reading template parameterization from %s...\n",
            template_fname) ;
    /* mrisp_aligned = NULL ; */
    mrisp_template = MRISPread(template_fname) ;
    if (!mrisp_template)
      ErrorExit(ERROR_NOFILE, "%s: could not open template file %s",
                Progname, template_fname) ;
  }

  argv += 3 ;
  argc -= 3 ;
  for (ino = 0 ; ino < argc-1 ; ino++)
  {
    failed = 0 ;
    subject = argv[ino] ;
    fprintf(stderr, "\nprocessing subject %s (%d of %d)\n", subject,
            ino+1, argc-1) ;
    sprintf(surf_fname, "%s/%s/surf/%s.%s",
            subjects_dir, subject, hemi, sphere_name) ;
    fprintf(stderr, "reading spherical surface %s...\n", surf_fname) ;
    mris = MRISread(surf_fname) ;
    if (!mris)
    {
      nbad++ ;
      ErrorPrintf(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, surf_fname) ;
      exit(1) ;
    }
    if (annot_name)
    {
      if (MRISreadAnnotation(mris, annot_name) != NO_ERROR)
        ErrorExit(ERROR_BADPARM,
                  "%s: could not read annot file %s",
                  Progname, annot_name) ;
      MRISripMedialWall(mris) ;
    }

    MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;
    MRISstoreMetricProperties(mris) ;

    if (Gdiag & DIAG_WRITE)
    {
      char *cp1 ;

      FileNameOnly(template_fname, fname) ;
      cp = strchr(fname, '.') ;
      if (cp)
      {
        cp1 = strrchr(fname, '.') ;
        if (cp1 && cp1 != cp)
          strncpy(parms.base_name, cp+1, cp1-cp-1) ;
        else
          strcpy(parms.base_name, cp+1) ;
      }
      else
        strcpy(parms.base_name, "template") ;
      sprintf(fname, "%s.%s.out", hemi, parms.base_name);
      parms.fp = fopen(fname, "w") ;
      printf("writing output to '%s'\n", fname) ;
    }

    /* multiframe registration */
    if (multiframes)
    {
      nfields=parms.nfields;

      for ( n = 0; n < mris->nvertices ; n++) /* allocate the VALS_VP
                                                                 structure */
      {
        v=&mris->vertices[n];
        vp=calloc(1,sizeof(VALS_VP));
        vp->nvals=nfields;
        vp->orig_vals=(float*)malloc(nfields*sizeof(float)); /* before
                                                                blurring */
        vp->vals=(float*)malloc(nfields*sizeof(float));     /* values used by
                                                               MRISintegrate */
        v->vp=(void*)vp;
      }

      /* load the different fields */
      for (n = 0 ; n < parms.nfields ; n++)
      {
        if (parms.fields[n].name != NULL)
        {
          sprintf(surf_fname, "%s/%s/%s/%s.%s", subjects_dir,
                  subject, overlay_dir, hemi, parms.fields[n].name) ;
          printf("reading overlay file %s...\n", surf_fname) ;
          if (MRISreadValues(mris, surf_fname) != NO_ERROR)
            ErrorExit(ERROR_BADPARM, "%s: could not read overlay file %s",
                      Progname, surf_fname) ;
          MRIScopyValuesToCurvature(mris) ;
        }
        else if (ReturnFieldName(parms.fields[n].field))
        {
          /* read in precomputed curvature file */
          sprintf(surf_fname, "%s/%s/surf/%s.%s", subjects_dir,
                  subject, hemi, ReturnFieldName(parms.fields[n].field)) ;
          // fprintf(stderr,"\nreading field %d from %s(type=%d,frame=%d)\n",parms.fields[n].field,surf_fname,parms.fields[n].type,parms.fields[n].frame);
          if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
          {
            fprintf(stderr,"\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
            fprintf(stderr, "%s: could not read curvature file '%s'\n",
                    Progname, surf_fname) ;
            failed = 1;
            break;
          }
        }
        else
        {                       /* compute curvature of surface */
          sprintf(surf_fname, "%s/%s/surf/%s.%s", subjects_dir,
                  subject, hemi, surface_names[parms.fields[n].field]) ;
          /*if(parms.fields[n].field==0)
           sprintf(fname, "inflated") ;
           else
           sprintf(fname, "smoothwm") ;*/
          //fprintf(stderr,"\ngenerating field %d(type=%d,frame=%d) (from %s)\n",parms.fields[n].field,parms.fields[n].type,parms.fields[n].frame,surf_fname);
          //     MRISsaveVertexPositions(mris, TMP_VERTICES) ;
          if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
          {
            fprintf(stderr,"\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
            ErrorPrintf(ERROR_NOFILE, "%s: could not read surface file %s",
                        Progname, surf_fname) ;
            fprintf(stderr,"setting up correlation coefficient to zero\n");
            parms.fields[n].l_corr=parms.fields[n].l_pcorr=0.0;
            failed=1;
            break;
          }

          if (nbrs > 1) MRISsetNeighborhoodSize(mris, nbrs) ;
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRISuseMeanCurvature(mris) ;
          MRISaverageCurvatures(mris, navgs) ;
          MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
        }
        /*    if(parms.fields[n].field!=SULC_CORR_FRAME)*/
        MRISnormalizeField(mris,parms.fields[n].type,
                           parms.fields[n].which_norm); /* normalize values */
        MRISsetCurvaturesToOrigValues(mris,n);
        MRISsetCurvaturesToValues(mris,n);
      }

      if (failed)
      {
        fprintf(stderr,"\n\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
        fprintf(stderr,"Subject %s Failed",subject);
        fprintf(stderr,"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\n");
        /* free cal structure*/
        for ( n = 0; n < mris->nvertices ; n++)
        {
          v=&mris->vertices[n];
          vp=(VALS_VP*)v->vp;
          free(vp->orig_vals);
          free(vp->vals);
          free(vp);
          v->vp=NULL;
        }
        /* free surface */
        MRISfree(&mris);
        /* go onto the next subject */
        continue;
      }
    }

    if (multiframes && (!no_rot))
    { /* rigid body alignment */
      parms.frame_no = 3 ;  /* don't use single field correlation functions */
      parms.l_corr = parms.l_pcorr = 0.0f ;

      parms.mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
      parms.mrisp_template = mrisp_template ;

      MRISrigidBodyAlignVectorGlobal(mris, &parms, 1.0, 64.0, 8) ;
      if (Gdiag & DIAG_WRITE) MRISwrite(mris, "sphere.rot.global") ;
      MRISrigidBodyAlignVectorLocal(mris, &parms) ;
      if (Gdiag & DIAG_WRITE) MRISwrite(mris, "sphere.rot.local") ;
      MRISPfree(&parms.mrisp) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    };
    if ((!multiframes) && (!no_rot) && ino > 0)
    { /* rigid body alignment */
      sprintf(surf_fname, "%s/%s/surf/%s.%s",
              subjects_dir, subject, hemi, "sulc") ;
      if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
      {
        ErrorPrintf(Gerror, "%s: could not read curvature file '%s'\n",
                    Progname, surf_fname) ;
        nbad++ ;
        MRISfree(&mris) ;
        continue ;
      }
      parms.frame_no = 3 ; /* use sulc for rigid registration */
      parms.mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
      parms.mrisp_template = mrisp_template ;
      parms.l_corr = 1.0f ;

      MRISrigidBodyAlignGlobal(mris, &parms, 1.0, 64.0, 8) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.global") ;
      MRISrigidBodyAlignLocal(mris, &parms) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.local") ;
      MRISPfree(&parms.mrisp) ;
      MRISsaveVertexPositions(mris, CANONICAL_VERTICES) ;
    }

    if (multiframes)
    {
      for (n = 0; n < parms.nfields ; n++)
      {
        MRISsetOrigValuesToCurvatures(mris,n);
        MRISaverageCurvatures(mris, parms.fields[n].navgs) ;
        mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
        MRISPcombine(mrisp,
                     mrisp_template,
                     parms.fields[n].frame * IMAGES_PER_SURFACE) ;
        MRISPfree(&mrisp) ;
      }
      /* free the VALS_VP structure */
      for ( n = 0; n < mris->nvertices ; n++)
      {
        v=&mris->vertices[n];
        vp=(VALS_VP*)v->vp;
        free(vp->orig_vals);
        free(vp->vals);
        free(vp);
        v->vp=NULL;
      }
      MRISfree(&mris) ;
    }
    else
    {
      for (sno = 0; sno < SURFACES ; sno++)
      {
        if (curvature_names[sno])  /* read in precomputed curvature file */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, curvature_names[sno]) ;
          if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
          {
            nbad++ ;
            ErrorPrintf(Gerror, "%s: could not read curvature file '%s'\n",
                        Progname, surf_fname) ;
            failed = 1 ;
            break ;
          }
          /* the two next lines were not in the original code */
          MRISaverageCurvatures(mris, navgs) ;
          MRISnormalizeCurvature(mris, which_norm) ;
        } else                       /* compute curvature of surface */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, surface_names[sno]) ;
          if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
          {
            ErrorPrintf(ERROR_NOFILE, "%s: could not read surface file %s",
                        Progname, surf_fname) ;
            nbad++ ;
            failed = 1 ;
            break ;
          }

          if (nbrs > 1)
            MRISsetNeighborhoodSize(mris, nbrs) ;
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRISuseMeanCurvature(mris) ;
          MRISaverageCurvatures(mris, navgs) ;
          MRISrestoreVertexPositions(mris, CANONICAL_VERTICES) ;
          MRISnormalizeCurvature(mris, which_norm) ;
        }
        fprintf(stderr, "computing parameterization for surface %s...\n",
                surf_fname);
        if (failed)
        {
          continue ;
          MRISfree(&mris) ;
        }
        mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
        MRISPcombine(mrisp, mrisp_template, sno*3) ;
        MRISPfree(&mrisp) ;
      }
      MRISfree(&mris) ;
    }
  }

#if 0
  if (mrisp_aligned)  /* new parameterization - use rigid alignment */
  {
    MRI_SP *mrisp_tmp ;

    if (Gdiag & DIAG_WRITE)
    {
      char *cp1 ;

      FileNameOnly(template_fname, fname) ;
      cp = strchr(fname, '.') ;
      if (cp)
      {
        cp1 = strrchr(fname, '.') ;
        if (cp1 && cp1 != cp)
          strncpy(parms.base_name, cp+1, cp1-cp-1) ;
        else
          strcpy(parms.base_name, cp+1) ;
      }
      else
        strcpy(parms.base_name, "template") ;
      sprintf(fname, "%s.%s.out", hemi, parms.base_name);
      parms.fp = fopen(fname, "w") ;
      printf("writing output to '%s'\n", fname) ;
    }
    for (ino = 0 ; ino < argc-1 ; ino++)
    {
      subject = argv[ino] ;
      if (Gdiag & DIAG_WRITE)
        fprintf(parms.fp, "processing subject %s\n", subject) ;
      fprintf(stderr, "processing subject %s\n", subject) ;
      sprintf(surf_fname, "%s/%s/surf/%s.%s",
              subjects_dir, subject, hemi, sphere_name) ;
      fprintf(stderr, "reading spherical surface %s...\n", surf_fname) ;
      mris = MRISread(surf_fname) ;
      if (!mris)
        ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                  Progname, surf_fname) ;
      MRIScomputeMetricProperties(mris) ;
      MRISstoreMetricProperties(mris) ;
      MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
      sprintf(surf_fname, "%s/%s/surf/%s.%s",
              subjects_dir, subject, hemi, "sulc") ;
      if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
        ErrorExit(Gerror, "%s: could not read curvature file '%s'\n",
                  Progname, surf_fname) ;
      parms.frame_no = 3 ;
      parms.mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
      parms.mrisp_template = mrisp_template ;
      parms.l_corr = 1.0f ;

      MRISrigidBodyAlignGlobal(mris, &parms, 1.0, 32.0, 8) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.global") ;
      MRISrigidBodyAlignLocal(mris, &parms) ;
      if (Gdiag & DIAG_WRITE)
        MRISwrite(mris, "sphere.rot.local") ;
      MRISPfree(&parms.mrisp) ;

#if 0
      /* write out rotated surface */
      sprintf(surf_fname, "%s.rot", mris->fname) ;
      fprintf(stderr, "writing out rigidly aligned surface to '%s'\n",
              surf_fname) ;
      MRISwrite(mris, surf_fname) ;
#endif

      /* now generate new parameterization using the optimal alignment */
      for (sno = 0; sno < SURFACES ; sno++)
      {
        if (curvature_names[sno])  /* read in precomputed curvature file */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, curvature_names[sno]) ;
          if (MRISreadCurvatureFile(mris, surf_fname) != NO_ERROR)
            ErrorExit(Gerror, "%s: could not read curvature file '%s'\n",
                      Progname, surf_fname) ;
        } else                       /* compute curvature of surface */
        {
          sprintf(surf_fname, "%s/%s/surf/%s.%s",
                  subjects_dir, subject, hemi, surface_names[sno]) ;
          if (MRISreadVertexPositions(mris, surf_fname) != NO_ERROR)
            ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                      Progname, surf_fname) ;

          if (nbrs > 1)
            MRISsetNeighborhoodSize(mris, nbrs) ;
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRISuseMeanCurvature(mris) ;
          MRISaverageCurvatures(mris, navgs) ;
          MRISrestoreVertexPositions(mris, ORIGINAL_VERTICES) ;
          MRISnormalizeCurvature(mris) ;
        }
        fprintf(stderr, "computing parameterization for surface %s...\n",
                surf_fname);
        mrisp = MRIStoParameterization(mris, NULL, scale, 0) ;
        MRISPcombine(mrisp, mrisp_aligned, sno*3) ;
        MRISPfree(&mrisp) ;
      }
      MRISfree(&mris) ;
    }

    if (Gdiag & DIAG_WRITE)
      fclose(parms.fp) ;

    mrisp_tmp = mrisp_aligned ;
    mrisp_aligned = mrisp_template ;
    mrisp_template = mrisp_tmp ;
    MRISPfree(&mrisp_aligned) ;
  }
#endif
  fprintf(stderr,
          "writing updated template with %d subjects to %s...\n",
          argc-1-nbad, template_fname) ;
  MRISPwrite(mrisp_template, template_fname) ;
  MRISPfree(&mrisp_template) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
void __fastcall TForm1::TabControl1Change(TObject *Sender)
{
	
	switch( TabControl1 -> TabIndex )
	{
		
		case 0:
		{
			
			if( !FileExists( "MeanFile.txt" ) || !FileExists( "standardDeviation.txt" ) )
			{
				
				char filename[ 150 ];
				
				MacroBlock MeanBlock[ imageHeight / 16 ][ imageWidth / 16 ];
				
				MacroBlock block[ imageHeight / 16 ][ imageWidth / 16 ];
				
				for( int n = 0; n < FileListBox1 -> Items -> Count; n ++ )
				{
					
					memset( block, 0, sizeof( block ) );
					memset( MeanBlock, 0, sizeof( MeanBlock ) );
					
					sprintf( filename, "%s%s", ExtractFilePath( FileListBox1 -> FileName ), FileListBox1 -> Items -> Strings[ n ].c_str() );
					
					ReadBMPData( filename );
					
					double LSum = 0;
					
					for( int i = 0; i < imageHeight / 16; i ++ )
						for( int j = 0; j < imageWidth / 16; LSum = 0, j ++ )
						{
							for( int k = i * 16; k <= ( i * 16 + 15 ); k ++ )
								for( int m = j * 16 * 3; m <= ( j * 16 + 15 ) * 3; m += 3 )
								{
									RGB2Lab( ImageDataBlock[ k ][ m + 0 ], ImageDataBlock[ k ][ m + 1 ], ImageDataBlock[ k ][ m + 2 ],
										&Lab_buf[ k ][ m + 0 ], &Lab_buf[ k ][ m + 1 ], &Lab_buf[ k ][ m + 2 ] );
									
									LSum += Lab_buf[ k ][ m + 0 ];
									
								}
							
							block[ i ][ j ].DCL = LSum / 256.0;
							
							MeanBlock[ i ][ j ].DCL += block[ i ][ j ].DCL;
							
							AllDCL[ n ][ i ][ j ] = block[ i ][ j ].DCL;
							
						}
					
				}
				
				for( int i = 0; i < imageHeight / 16; i ++ )
					for( int j = 0; j < imageWidth / 16; j ++ )
						MeanBlock[ i ][ j ].DCL /= FileListBox1 -> Items -> Count;
				
				FILE *MeanFile = fopen( "MeanFile.txt", "w" );
				
				for( int i = 0; i < imageHeight / 16; i ++ )
				{
					for( int j = 0; j < imageWidth / 16; j ++ )
						fprintf( MeanFile, "%f ", MeanBlock[ i ][ j ].DCL );
					
					fprintf( MeanFile, "\n" );
				}
				
				fclose( MeanFile );
				
				for( int i = 0; i < 100; i ++ )
					for( int j = 0; j < imageHeight / 16; j ++ )
						for( int k = 0; k < imageWidth / 16; k ++ )
							stddev[ j ][ k ] += pow( AllDCL[ i ][ j ][ k ] - MeanBlock[ j ][ k ].DCL, 2 );
				
				for( int i = 0; i < imageHeight / 16; i ++ )
					for( int j = 0; j < imageWidth / 16; j ++ )
						stddev[ i ][ j ] = pow( stddev[ i ][ j ] / ( FileListBox1 -> Items -> Count - 1 ), 0.5 );
				
				FILE *StandardDeviation = fopen( "standardDeviation.txt", "w" );
				
				for( int i = 0; i < imageHeight / 16; i ++ )
				{
					for( int j = 0; j < imageWidth / 16; j ++ )
						fprintf( StandardDeviation, "%f ", stddev[ i ][ j ] );
					
					fprintf( StandardDeviation, "\n" );
				}
				
				fclose( StandardDeviation );
				
			}
			
			break;
		}
		
	}
}
示例#7
0
/************************************************************************************
 *    batch use of mkmat:   open file, save to another file.... T6spectra.root
 *
 ************************************************************************************
 */
void batchmat(int run,  int  det=6, const char* VOL="V" ){

  //  TChain *c=new TChain("nanot");
  TString s;
  char fname[180];
  char fnamespe[180];
  char namespe[180];

  char telename[30];// T6
  char telename1D[30];// T61D - original name
  char telenamed[33];// T6d
  char telenamep[30];// T6p
  char telenamede[30];// T6de

  char cutdname[30];// cutt6d
  char cutpname[30];// cutt6p

  // accept  both 003 or 0003......
  sprintf( fname, "RUN%03d_%s.root", run,  VOL );
  if (  FileExists( fname,1000 )  ){
    printf("File %s exists\n", fname);   
  }else{
    sprintf( fname, "RUN%04d_%s.root", run,  VOL );
  }


  sprintf( namespe, "T%d_run%03d_%s", det, run, VOL  );//spectrum name
  sprintf( fnamespe, "T%d%sspectra.root", det, VOL );       //filename

  // these names must correspond to mkmat    T2V  T2V1D
  sprintf( telename, "T%d%s", det, VOL );       //telename
  sprintf( telename1D, "T%d%s1D", det, VOL );      //telename 1D
  sprintf( telenamed, "T%d_d_run%03d_%s", det, run, VOL);       //telename d
  sprintf( telenamep, "T%d_p_run%03d_%s", det, run, VOL );       //telename p
  sprintf( telenamede, "T%d_de_run%03d_%s", det, run, VOL );       //telename de

  sprintf( cutdname, "cutt%dd%s", det, VOL );       //cutname d 
  sprintf( cutpname, "cutt%dp%s", det, VOL );       //cutname p



  /*
   *        READ THE FOLLOWING  ROOT  FILE-----------------------------------------
   */
  if ( ! FileExists( fname,1000 )  ){//  FILE root DOES EXIST..................
       printf("file %s doesnot exist or is zombie\n", fname  );
 }else{
       printf("file %s exists OK\n", fname  );


  TFile *f=new TFile( fname ,"READ");  //   read from
  TTree *t=(TTree*)f->Get("nanot");
  /*
   *    CREATE  MATRIX   (and  d  and p spectra as well?)
   */
  mkmat( det, VOL  );
  TH2F* t6bi=(TH2F*)gDirectory->Get(  telename  );

   /*
    *    CREATE  1DIM   (and  d  and p spectra as well?)
    */
  printf( "searching for TCutG : %s, %s\n", cutdname, cutpname );
  TCutG *mycutd=(TCutG*)gROOT->GetListOfSpecials()->FindObject( cutdname );
  TCutG *mycutp=(TCutG*)gROOT->GetListOfSpecials()->FindObject( cutpname );

  TH1F* t61d_d;
  TH1F* t61d_p;
  TH1F* t61d_de;
  /*
   *  if there are cuts  ==>>  create 1D
   */
  if (mycutd!=NULL){
    mkmat1( det, VOL, mycutd ); // create 1D
    t61d_d=(TH1F*)gDirectory->Get(  telename1D  );
    t61d_d->SetName( telenamed );
  }//cutd
  if (mycutp!=NULL){
    mkmat1( det,  VOL, mycutp ); // create 1D
    t61d_p=(TH1F*)gDirectory->Get(  telename1D  );
    t61d_p->SetName( telenamep );
  }//cutd
  // Run with a condition:
  // MAKE 1D   dE  ONLY SPECTRUM

  mkmat1( -det , VOL, "e<10" );  // and now see....  only dE plotted; reverse
  t61d_de=(TH1F*)gDirectory->Get(  telename1D  );
  t61d_de->SetName( telenamede );




  // SAVE .................................................
  TDirectory *dir=gDirectory;  
  TFile *f2=new TFile( fnamespe ,"UPDATE");   //  save to ...fnamespe...Tispectra.root
    t6bi->SetName( namespe );
    t6bi->Write();

    if (t61d_d!=NULL){t61d_d->Write();}
    if (t61d_p!=NULL){t61d_p->Write();}
    t61d_de->Write();

    f2->ls();
    printf("closing %s\n",  fnamespe );
  f2->Close();
  dir->cd();
  
  //  t->Show(2);
    printf("closing %s\n",  fname );
    f->Close();
  }//FILE root DOES EXIST
  
    
}//  batchmat
示例#8
0
int main(int argc, char * arg[])
{
    printf("DBC/Map Extractor\n");
    printf("===================\n\n");

    bool extractDBC = true;
    bool extractMap = true;

    for (int i = 0; i < argc; ++i)
    {
        if (strcmp(arg[i], ARG_MAP) == 0)
            extractMap = true;
        if (strcmp(arg[i], ARG_NOMAP) == 0)
            extractMap = false;
        if (strcmp(arg[i], ARG_DBC) == 0)
            extractDBC = true;
        if (strcmp(arg[i], ARG_NODBC) == 0)
            extractDBC = false;
    }

    int FirstLocale = -1;
    int build = 0;

    for (int i = 0; i < LANG_COUNT; i++)
    {
        char tmp1[512];
        sprintf(tmp1, "%s/Data/%s/locale-%s.MPQ", input_path, langs[i], langs[i]);
        if (FileExists(tmp1))
        {
            printf("Detected locale: %s\n", langs[i]);

            //Open MPQs
            LoadLocaleMPQFiles(i);

            //Extract DBC files
            if (FirstLocale < 0)
            {
                FirstLocale = i;
                build = ReadBuild(FirstLocale);
                printf("Detected base client build: %u\n", build);
                if (build != CLIENT_BUILD)
                {
                    printf("ERROR: your client is not up-to-date. Client build should be %u", CLIENT_BUILD);
                    return 0;
                }
                if (extractDBC)
                    ExtractDBCFiles(i, true);
            }
            else if (extractDBC)
                ExtractDBCFiles(i, false);
        }
    }

    if (FirstLocale < 0)
    {
        printf("No locales detected\n");
        return 0;
    }

    if (extractMap)
        ExtractMapsFromMpq(build);

    return 0;
}
示例#9
0
void __fastcall TReportForm::ToolButton3Click(TObject *Sender)
{

  Variant WordApp, WordSel, WordDoc, EmptyParam, table, cell, range;
  TDateTime dtReport = Date();
  UnicodeString s=ExtractFileDir(Application->ExeName)+"\\template.doc";

  if (!FileExists(s)) {
	ShowMessage("Файл шаблона не найден");
	return;
  }

  TVirtualNode *t_root=VirtualStringTree1->RootNode->FirstChild;
  TVirtualNode *t_child;
  TReportData *data_root, *data_child;

  try {
	WordApp=GetActiveOleObject("Word.Application");
  } catch (...) {
	try {
	  WordApp=CreateOleObject("Word.Application");

	} catch (...) {
	  ShowMessage("Microsoft Word не установлен");
	  return;
	}
  }



  try {
	WordApp.OlePropertySet("Visible", false);
	WordDoc=WordApp.OlePropertyGet("Documents").OleFunction("Add", s.t_str());


//	if (WordDoc.OlePropertyGet("Bookmarks").OleFunction("Exists", "date"))
//	  ShowMessage("!");

//	WordDoc.OleFunction("GoTo", 0xFFFFFFFF, EmptyParam, EmptyParam, "date").OleFunction("Select");
	WordApp.OlePropertyGet("Selection").OleFunction("goto", 0xFFFFFFFF, EmptyParam, EmptyParam, "date");
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", dtReport.FormatString("dd.mm.yyyy").t_str());
	WordApp.OlePropertyGet("Selection").OleFunction("goto", 0xFFFFFFFF, EmptyParam, EmptyParam, "img");
	MainForm->Chart5->CopyToClipboardMetafile(true);
	WordApp.OlePropertyGet("Selection").OleFunction("Paste");


	WordApp.OlePropertyGet("Selection").OleFunction("goto", 0xFFFFFFFF, EmptyParam, EmptyParam, "table");

//	table=WordDoc.OlePropertyGet("Tables").OleFunction("Item", 1);
//	cell=table.OleFunction("Cell", 1, 1);
//	range=cell.OlePropertyGet("Range");
//	range.OlePropertySet("Text", "Fuck");
	for (size_t i=0; i < VirtualStringTree1->RootNodeCount; i++) {
	  if (!(t_root == NULL)) {
		data_root=(TReportData *)ReportForm->VirtualStringTree1->GetNodeData(t_root);
		if (!(data_root == NULL)) {
		  s=data_root->Name;
		  WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", s.t_str());
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		}
		else
		  continue;

		t_child=t_root->FirstChild;
		while (!(t_child == NULL))
		{
		  data_child=(TReportData *)ReportForm->VirtualStringTree1->GetNodeData(t_child);
		  if (!(data_child == NULL) && (t_child->CheckState == csCheckedNormal)) {
			s=data_child->Name;
			WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", s.t_str());
			WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
			WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  FloatToStrF(data_child->pcs, ffFixed, 5, 2).t_str());
			WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
			WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  FloatToStrF(data_child->pi, ffFixed, 5, 2).t_str());
			WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
			WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  FloatToStr(data_child->angle).t_str());
			WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  }
		  t_child=t_child->NextSibling;
		}
		WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", true);
		WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 0);
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "Средний диаметр");
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", false);
		WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 1);
		s=FloatToStrF(data_root->pcs, ffFixed, 5, 2)+" нм.";
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  s.t_str());
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "Средний ППД");
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  FloatToStrF(data_root->pi, ffFixed, 5, 2).t_str());
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "СКО");
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		s=FloatToStrF(data_root->rms, ffFixed, 5, 2)+" нм.";
		WordApp.OlePropertyGet("Selection").OleProcedure("TypeText",  s.t_str());
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		if (!(i == (VirtualStringTree1->RootNodeCount-1))) {
		  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
		  WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", false);
		  WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 1);
		}
	  }
	  t_root=t_root->NextSibling;
	}




	/*

	for (int i=0; i < 100; i++) {
	  WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "Fuck");
	  WordApp.OlePropertyGet("Selection").OleFunction("MoveRight", 12);
	}
	  */

	/*WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 1);
	WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", true);
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", "Протокол измерений");
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeParagraph");
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeParagraph");
	WordApp.OlePropertyGet("Selection").OlePropertyGet("ParagraphFormat").OlePropertySet("Alignment", 0);
	WordApp.OlePropertyGet("Selection").OlePropertyGet("Font").OlePropertySet("Bold", false);
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeText", dtReport.FormatString("dd.mm.yyyy").t_str());
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeParagraph");
	WordApp.OlePropertyGet("Selection").OleProcedure("TypeParagraph");
	WordApp.OlePropertyGet("Tables").OlePropertySet("Add", 3, 3);
	 */
  }
  __finally{
    WordApp.OlePropertySet("Visible", true);
	WordApp=Unassigned();
  }

}
示例#10
0
int InjectRemote(DWORD nRemotePID, bool abDefTermOnly /*= false */)
{
	int iRc = -1;
	bool lbWin64 = WIN3264TEST((IsWindows64()!=0),true);
	bool is32bit;
	DWORD nWrapperWait = (DWORD)-1, nWrapperResult = (DWORD)-1;
	HANDLE hProc = NULL;
	wchar_t szSelf[MAX_PATH+16], szHooks[MAX_PATH+16];
	wchar_t *pszNamePtr, szArgs[32];

	if (!GetModuleFileName(NULL, szSelf, MAX_PATH))
	{
		iRc = -200;
		goto wrap;
	}
	wcscpy_c(szHooks, szSelf);
	pszNamePtr = (wchar_t*)PointToName(szHooks);
	if (!pszNamePtr)
	{
		iRc = -200;
		goto wrap;
	}

	hProc = OpenProcess(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ, FALSE, nRemotePID);
	if (hProc == NULL)
	{
		iRc = -201;
		goto wrap;
	}

	// Определить битность процесса, Если он 32битный, а текущий - ConEmuC64.exe
	// Перезапустить 32битную версию ConEmuC.exe
	if (!lbWin64)
	{
		is32bit = true; // x86 OS!
	}
	else
	{
		is32bit = false; // x64 OS!

		// Проверяем, кто такой nRemotePID
		HMODULE hKernel = GetModuleHandleW(L"kernel32.dll");

		if (hKernel)
		{
			typedef BOOL (WINAPI* IsWow64Process_t)(HANDLE hProcess, PBOOL Wow64Process);
			IsWow64Process_t IsWow64Process_f = (IsWow64Process_t)GetProcAddress(hKernel, "IsWow64Process");

			if (IsWow64Process_f)
			{
				BOOL bWow64 = FALSE;

				if (IsWow64Process_f(hProc, &bWow64) && bWow64)
				{
					// По идее, такого быть не должно. ConEmu должен был запустить 32битный conemuC.exe
					#ifdef _WIN64
					_ASSERTE(bWow64==FALSE);
					#endif
					is32bit = true;
				}
			}
		}
	}

	if (is32bit != WIN3264TEST(true,false))
	{
		// По идее, такого быть не должно. ConEmu должен был запустить соответствующий conemuC*.exe
		_ASSERTE(is32bit == WIN3264TEST(true,false));
		PROCESS_INFORMATION pi = {};
		STARTUPINFO si = {sizeof(si)};

		_wcscpy_c(pszNamePtr, 16, is32bit ? L"ConEmuC.exe" : L"ConEmuC64.exe");
		_wsprintf(szArgs, SKIPLEN(countof(szArgs)) L" /INJECT=%u", nRemotePID);

		if (!CreateProcess(szHooks, szArgs, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi))
		{
			iRc = -202;
			goto wrap;
		}
		nWrapperWait = WaitForSingleObject(pi.hProcess, INFINITE);
		GetExitCodeProcess(pi.hProcess, &nWrapperResult);
		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
		if ((nWrapperResult != CERR_HOOKS_WAS_SET) && (nWrapperResult != CERR_HOOKS_WAS_ALREADY_SET))
		{
			iRc = -203;
			SetLastError(nWrapperResult);
			goto wrap;
		}
		// Значит всю работу сделал враппер
		iRc = 0;
		goto wrap;
	}

	// Поехали
	_wcscpy_c(pszNamePtr, 16, is32bit ? L"ConEmuHk.dll" : L"ConEmuHk64.dll");
	if (!FileExists(szHooks))
	{
		iRc = -250;
		goto wrap;
	}

	if (abDefTermOnly)
	{
		int iFRc = PrepareHookModule(szHooks);
		if (iFRc != 0)
		{
			iRc = iFRc;
			goto wrap;
		}
	}

	iRc = InfiltrateDll(hProc, szHooks);

	// Если создавали временную копию - запланировать ее удаление
	if (abDefTermOnly && (lstrcmpi(szHooks, szSelf) != 0))
	{
		MoveFileEx(szHooks, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
	}
wrap:
	if (hProc != NULL)
		CloseHandle(hProc);
	return iRc;
}
/** check that parameter settings make sense */
bool Parameter::Validate()
{
  bool noErrorFlag = true;

  PARAM_MAP::const_iterator iterParams;
  for (iterParams = m_setting.begin(); iterParams != m_setting.end(); ++iterParams) {
    const std::string &key = iterParams->first;
    
    if (m_valid.find(key) == m_valid.end())
    {
      UserMessage::Add("Unknown parameter " + key);
      noErrorFlag = false;
    }
  }
  

  // required parameters
  if (m_setting["ttable-file"].size() == 0) {
    UserMessage::Add("No phrase translation table (ttable-file)");
    noErrorFlag = false;
  }

  if (m_setting["lmodel-dub"].size() > 0) {
    if (m_setting["lmodel-file"].size() != m_setting["lmodel-dub"].size()) {
      stringstream errorMsg("");
      errorMsg << "Config and parameters specify "
               << static_cast<int>(m_setting["lmodel-file"].size())
               << " language model files (lmodel-file), but "
               << static_cast<int>(m_setting["lmodel-dub"].size())
               << " LM upperbounds (lmodel-dub)"
               << endl;
      UserMessage::Add(errorMsg.str());
      noErrorFlag = false;
    }
  }

  if (m_setting["lmodel-file"].size() * (m_setting.find("lmodel-oov-feature") != m_setting.end() ? 2 : 1)
         != m_setting["weight-l"].size()) {
    stringstream errorMsg("");
    errorMsg << "Config and parameters specify "
             << static_cast<int>(m_setting["lmodel-file"].size())
             << " language model files (lmodel-file), but "
             << static_cast<int>(m_setting["weight-l"].size())
             << " weights (weight-l)";
    errorMsg << endl << "You might be giving '-lmodel-file TYPE FACTOR ORDER FILENAME' but you should be giving these four as a single argument, i.e. '-lmodel-file \"TYPE FACTOR ORDER FILENAME\"'";
    errorMsg << endl << "You should also remember that each language model requires 2 weights, if and only if lmodel-oov-feature is on.";
    UserMessage::Add(errorMsg.str());
    noErrorFlag = false;
  }

  // do files exist?

  // input file
  if (noErrorFlag && m_setting["input-file"].size() == 1) {
    noErrorFlag = FileExists(m_setting["input-file"][0]);
  }
  // generation tables
  if (noErrorFlag) {
    std::vector<std::string> ext;
    //raw tables in either un compressed or compressed form
    ext.push_back("");
    ext.push_back(".gz");
    noErrorFlag = FilesExist("generation-file", 3, ext);
  }
  // distortion
  if (noErrorFlag) {
    std::vector<std::string> ext;
    //raw tables in either un compressed or compressed form
    ext.push_back("");
    ext.push_back(".gz");
    //prefix tree format
    ext.push_back(".binlexr.idx");
    noErrorFlag = FilesExist("distortion-file", 3, ext);
  }
  return noErrorFlag;
}
示例#12
0
int PrepareHookModule(wchar_t (&szModule)[MAX_PATH+16])
{
	int iRc = -251;
	wchar_t szNewPath[MAX_PATH+16] = {}, szAddName[32] = {}, szVer[2] = {};
	INT_PTR nLen = 0;
	bool bAlreadyExists = false;

	// Copy szModule to CSIDL_LOCAL_APPDATA and return new path
	HRESULT hr = SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, szNewPath);
	if ((hr != S_OK) || !*szNewPath)
	{
		iRc = -251;
		goto wrap;
	}

	szVer[0] = MVV_4a[0];
	_wsprintf(szAddName, SKIPLEN(countof(szAddName))
		L"\\" CEDEFTERMDLLFORMAT /*L"ConEmuHk%s.%02u%02u%02u%s.dll"*/,
		WIN3264TEST(L"",L"64"), MVV_1, MVV_2, MVV_3, szVer);

	nLen = lstrlen(szNewPath);
	if (szNewPath[nLen-1] != L'\\')
	{
		szNewPath[nLen++] = L'\\'; szNewPath[nLen] = 0;
	}

	if ((nLen + lstrlen(szAddName) + 8) >= countof(szNewPath))
	{
		iRc = -252;
		goto wrap;
	}

	wcscat_c(szNewPath, L"ConEmu");
	if (!DirectoryExists(szNewPath))
	{
		if (!CreateDirectory(szNewPath, NULL))
		{
			iRc = -253;
			goto wrap;
		}
	}

	wcscat_c(szNewPath, szAddName);

	if ((bAlreadyExists = FileExists(szNewPath)) && FileCompare(szNewPath, szModule))
	{
		// OK, file exists and match the required
	}
	else
	{
		if (bAlreadyExists)
		{
			_ASSERTE(FALSE && "Continue to overwrite existing ConEmuHk in AppLocal");

			// Try to delete or rename old version
			if (!DeleteFile(szNewPath))
			{
				//SYSTEMTIME st; GetLocalTime(&st);
				wchar_t szBakPath[MAX_PATH+32]; wcscpy_c(szBakPath, szNewPath);
				wchar_t* pszExt = (wchar_t*)PointToExt(szBakPath);
				msprintf(pszExt, 16, L".%u.dll", GetTickCount());
				DeleteFile(szBakPath);
				MoveFile(szNewPath, szBakPath);
			}
		}

		if (!CopyFile(szModule, szNewPath, FALSE))
		{
			iRc = -254;
			goto wrap;
		}
	}

	wcscpy_c(szModule, szNewPath);
	iRc = 0;
wrap:
	return iRc;
}
示例#13
0
/*****************************************************************************
static DWORD CreateChecksumFiles_OnePerDir(CONST UINT uiMode,CONST TCHAR szChkSumFilename[MAX_PATH_EX], list<FILEINFO*> *finalList)
	uiMode			: (IN) create MD5 or SFV files
	szChkSumFilename: (IN) filename without path
	finalList		: (IN) pointer to list of fileinfo pointers on which the action is to be performed

Return Value:
returns NOERROR or GetLastError()

Notes:
- handles the situation if the user want one sfv/md5 file per directory. In every directory
  a file with the name szChkSumFilename is created
*****************************************************************************/
static DWORD CreateChecksumFiles_OnePerDir(CONST UINT uiMode,CONST TCHAR szChkSumFilename[MAX_PATH_EX], list<FILEINFO*> *finalList)
{
	DWORD dwResult;
	TCHAR szCurrentDir[MAX_PATH_EX];
	TCHAR szCurChecksumFilename[MAX_PATH_EX];
	TCHAR szPreviousDir[MAX_PATH_EX] = TEXT("?:><");	// some symbols that are not allowed in filenames to force
													// the checksum file creation in the for loop
	HANDLE hFile = NULL;


	for(list<FILEINFO*>::iterator it=finalList->begin();it!=finalList->end();it++) {
		if( (*it)->dwError == NO_ERROR ){
			StringCchCopy(szCurrentDir, MAX_PATH_EX, (*it)->szFilename);
			ReduceToPath(szCurrentDir);
			if(lstrcmpi(szPreviousDir, szCurrentDir) != 0){
                if(hFile) {
				    CloseHandle(hFile);
                    hFile = NULL;
                }
				StringCchCopy(szPreviousDir, MAX_PATH_EX, szCurrentDir);
				StringCchPrintf(szCurChecksumFilename, MAX_PATH_EX, TEXT("%s%s"), szCurrentDir, szChkSumFilename);
                if(g_program_options.bNoHashFileOverride && FileExists(szCurChecksumFilename)) {
                    continue;
                }
				hFile = CreateFile(szCurChecksumFilename, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, NULL);
				if(hFile == INVALID_HANDLE_VALUE){
					return GetLastError();
				}
#ifdef UNICODE
				// we need a BOM if we are writing unicode
				if(!WriteCurrentBOM(hFile))
					return GetLastError();
#endif
				if( (uiMode == MODE_SFV) && g_program_options.bWinsfvComp){
					dwResult = WriteSfvHeader(hFile);
					if(dwResult != NOERROR){
						CloseHandle(hFile);
						return dwResult;
					}
				}
                if(g_program_options.bIncludeFileComments) {
                    list<FILEINFO*>::iterator commentIt = it;
                    do
                    {
                        if((*commentIt)->dwError == NO_ERROR) {
                            WriteFileComment(hFile, (*commentIt), (UINT)(GetFilenameWithoutPathPointer((*commentIt)->szFilenameShort) - (*commentIt)->szFilename));
                        }
                        commentIt++;
                        if(commentIt == finalList->end())
                            break;
                        StringCchCopy(szCurrentDir, MAX_PATH_EX, (*commentIt)->szFilename);
			            ReduceToPath(szCurrentDir);
                    }
                    while(lstrcmpi(szPreviousDir, szCurrentDir) == 0);
                }
			}

            if(hFile) {
                dwResult = WriteHashLine(hFile, GetFilenameWithoutPathPointer((*it)->szFilenameShort),
                    (*it)->hashInfo[uiMode].szResult, uiMode == MODE_SFV);

			    if(dwResult != NOERROR){
				    CloseHandle(hFile);
				    return dwResult;
			    }
            }
		}
	}
	CloseHandle(hFile);

	return NOERROR;
}
示例#14
0
///////////////////////////////////////////////////////////////
//
// DoInstallFiles
//
// Copy directory tree at current dirctory to GetMTASAPath ()
//
///////////////////////////////////////////////////////////////
bool DoInstallFiles ( void )
{
    SString strCurrentDir = PathConform ( GetSystemCurrentDirectory () );

    const SString strMTASAPath = PathConform ( GetMTASAPath () );

    SString path1, path2;
    strCurrentDir.Split ( "\\", &path1, &path2, -1 );

    SString strDestRoot = strMTASAPath;
    SString strSrcRoot = strCurrentDir;
    SString strBakRoot = MakeUniquePath ( strCurrentDir + "_bak_" );

    // Clean backup dir
    if ( !MkDir ( strBakRoot ) )
    {
        AddReportLog ( 5020, SString ( "InstallFiles: Couldn't make dir '%s'", strBakRoot.c_str () ) );
        return false;
    }

    // Get list of files to install
    std::vector < SFileItem > itemList;
    {
        std::vector < SString > fileList;
        FindFilesRecursive ( PathJoin ( strCurrentDir, "*" ), fileList );
        for ( unsigned int i = 0 ; i < fileList.size () ; i++ )
        {
            SFileItem item;
            item.strSrcPathFilename = PathConform ( fileList[i] );
            item.strDestPathFilename = PathConform ( fileList[i].Replace ( strSrcRoot, strDestRoot ) );
            item.strBackupPathFilename = PathConform ( fileList[i].Replace ( strSrcRoot, strBakRoot ) );
            itemList.push_back ( item );
        }
    }

    // See if any files to be updated are running.
    // If so, terminate them
    for ( unsigned int i = 0 ; i < itemList.size () ; i++ )
    {
        SString strFile = itemList[i].strDestPathFilename;
        if ( strFile.EndsWithI( ".exe" ) )
            TerminateProcessFromPathFilename ( strFile );
    }

    // Copy current(old) files into backup location
    for ( unsigned int i = 0 ; i < itemList.size () ; i++ )
    {
        const SFileItem& item = itemList[i];
        if ( !FileCopy ( item.strDestPathFilename, item.strBackupPathFilename ) )
        {
            if ( FileExists ( item.strDestPathFilename ) )
            {
                AddReportLog ( 5021, SString ( "InstallFiles: Couldn't backup '%s' to '%s'", *item.strDestPathFilename, *item.strBackupPathFilename ) );
                return false;
            }
            AddReportLog ( 4023, SString ( "InstallFiles: Couldn't backup '%s' as it does not exist", *item.strDestPathFilename ) );
        }
    }

    // Try copy new files
    bool bOk = true;
    std::vector < SFileItem > fileListSuccess;
    for (  unsigned int i = 0 ; i < itemList.size () ; i++ )
    {
        const SFileItem& item = itemList[i];
        if ( !FileCopy ( item.strSrcPathFilename, item.strDestPathFilename ) )
        {
            // If copy failed, check if we really need to copy the file
            if ( GenerateSha256HexStringFromFile( item.strSrcPathFilename ) != GenerateSha256HexStringFromFile( item.strDestPathFilename ) )
            {
                AddReportLog ( 5022, SString ( "InstallFiles: Couldn't copy '%s' to '%s'", *item.strSrcPathFilename, *item.strDestPathFilename ) );
                bOk = false;
                break;
            }
        }
        fileListSuccess.push_back ( item );
    }

    // If fail, copy back old files
    if ( !bOk )
    {
        bool bPossibleDisaster = false;
        for ( unsigned int i = 0 ; i < fileListSuccess.size () ; i++ )
        {
            const SFileItem& item = fileListSuccess[i];
            int iRetryCount = 3;
            while ( true )
            {
                if ( FileCopy ( item.strBackupPathFilename, item.strDestPathFilename ) )
                    break;

                // If copy failed, check if we really need to copy the file
                if ( GenerateSha256HexStringFromFile( item.strBackupPathFilename ) != GenerateSha256HexStringFromFile( item.strDestPathFilename ) )
                    break;

                if ( !--iRetryCount )
                {
                    AddReportLog ( 5023, SString ( "InstallFiles: Possible disaster restoring '%s' to '%s'", *item.strBackupPathFilename, *item.strDestPathFilename ) );
                    bPossibleDisaster = true;
                    break;
                }
            }
        }

        //if ( bPossibleDisaster )
        //    MessageBox ( NULL, _("Installation may be corrupt. Please redownload from www.mtasa.com"), _("Error"), MB_OK | MB_ICONERROR );
        //else 
        //    MessageBox ( NULL, _("Could not update due to file conflicts."), _("Error"), MB_OK | MB_ICONERROR );
    }

    // Launch MTA_EXE_NAME
    return bOk;
}
int Handle_Get(Dictionary* dictHttpRequest, SOCKET scClientSocket)
{
	int nReturnValue = 0;
	char* szURI = 0;
	int nHttpVersion = 0;
	int bFoundFile = 0;
	char* szQueryString = 0;
	char* szPathOfFile = 0;
	char szIndex = "index.html";
	char szPathAfterAdding[260] = { '\0' };
	//TODO: Yet to handle this type of method

	LogMessage(LOG_DEBUG, "Going to handle the Get type of method");

	szURI = GetValueFromDictionary(dictHttpRequest, "URI");
	if (szURI != NULL)
	{
		//Check if the uri has query string. If so then it needs to be handled by cgi.

		//Based on the URI - search in the local path for the file. If found then send 200 else send 404 not found error
		LogMessage(LOG_DEBUG, "Got the URI from the request");
		LogMessage(LOG_DEBUG, szURI);
		szQueryString = szURI;
		while ((*szQueryString) != '?' && (*szQueryString) != '\0')
		{
			szQueryString++;
		}
		if ((*szQueryString) == '?')
		{
			//This is a query string so handle it in a different way.
			LogMessage(LOG_DEBUG, "Got a query string in uri");

			szQueryString++;
			LogMessage(LOG_DEBUG, szQueryString);
		}
		else
		{
			LogMessage(LOG_DEBUG, "Query string not found");
			bFoundFile = FindFileInLocalPath(szURI, strMappedLocalPath);
			if (bFoundFile == 0)
			{
				//printf_s("\nBHS:ERROR:Cound not find the file in the local path:%s\n", szURI);
				LogMessage(LOG_ERROR, "Could not find the file in the local path");
				nReturnValue = HandleFileNotFound(dictHttpRequest, scClientSocket);
			}
			else
			{
				//printf_s("\nBHS:INFO:Able to find the file in the local path:%s\n", szURI);
				LogMessage(LOG_DEBUG, "Able to find the file in local path");
				szPathOfFile = GetFilePathFromURI(szURI, strMappedLocalPath);
				LogMessage(LOG_DEBUG, szPathOfFile);
				if (szPathOfFile[strnlen_s(szPathOfFile, 260) - 1] == '/')
				{
					//Add index.html file
					LogMessage(LOG_DEBUG, "Its a folder so adding index.html by default");
					stringcopy(szPathAfterAdding, strlen(szPathOfFile), szPathOfFile);
					strcat_s(szPathAfterAdding, 260, szIndex);
					free(szPathOfFile);
					if (FileExists(szPathAfterAdding) == 1)
					{
						szPathOfFile = (char*)malloc(sizeof(char)*strlen(szPathAfterAdding) + 1);
						memset(szPathOfFile, '\0', strlen(szPathAfterAdding)+1);
						stringcopy(szPathOfFile, strlen(szPathAfterAdding), szPathAfterAdding);
						LogMessage(LOG_DEBUG, "Going to send a http response now");
						LogMessage(LOG_DEBUG, szPathOfFile);
						nReturnValue = HandleGetFileResponse(dictHttpRequest, scClientSocket, szPathOfFile);

						free(szPathOfFile);
						szPathOfFile = 0;
					}
					else
					{
						LogMessage(LOG_DEBUG, "Could not find the index.html file inside the folder");
						LogMessage(LOG_DEBUG, szPathAfterAdding);
						nReturnValue = HandleFileNotFound(dictHttpRequest, scClientSocket);
					}

				}
				else
				{
					LogMessage(LOG_DEBUG, "About to handle the Get request of file");
					LogMessage(LOG_DEBUG, szPathOfFile);
					nReturnValue = HandleGetFileResponse(dictHttpRequest, scClientSocket, szPathOfFile);

					free(szPathOfFile);
					szPathOfFile = 0;
				}

			}
		}

		
			
	}
	else
	{
		//ERROR handle it
		LogMessage(LOG_ERROR, "URI was empty");
	}

	LogMessage(LOG_DEBUG, "Returning after handling GET request");
	return nReturnValue;
}
示例#16
0
void __fastcall TReportForm::ToolButton6Click(TObject *Sender)
{
	Variant ExcelApp, ExcelBooks, Book, WorkSheet, Cells, EmptyParam;
	TDateTime dtReport = Date();
	UnicodeString s=ExtractFileDir(Application->ExeName)+"\\template.xls";

	if (!FileExists(s))
	{
		ShowMessage("Файл шаблона не найден");
		return;
	}

	TVirtualNode *t_root=VirtualStringTree1->RootNode->FirstChild;
	TVirtualNode *t_child;
	TReportData *data_root, *data_child;

	try
	{
		ExcelApp = GetActiveOleObject("Excel.Application");
		ExcelBooks = ExcelApp.OlePropertyGet("WorkBooks");
	}
	catch (...)
	{
		try
		{
			ExcelApp = CreateOleObject("Excel.Application");
			ExcelBooks = ExcelApp.OlePropertyGet("WorkBooks");

		}
		catch (...)
		{
		  ShowMessage("Microsoft Excel не установлен");
		return;
		}
	}

	int i = 27;
	int j = 2;
	TFormatSettings format_settings;
	GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, format_settings);
	format_settings.DecimalSeparator = ',';

	try
	{
    	ExcelApp.OlePropertySet("Visible", false);
		Book = ExcelBooks.OleFunction("Add", s.t_str());
		WorkSheet = Book.OlePropertyGet("Worksheets").OlePropertyGet("Item", 1);
		Cells = WorkSheet.OlePropertyGet("Cells");
		Cells.OlePropertyGet("Item",4,3).OlePropertySet("Value", dtReport.FormatString("dd.mm.yyyy").t_str());
		Cells.OlePropertyGet("Item",8,1).OleProcedure("Select");
		MainForm->Chart5->CopyToClipboardMetafile(true);
		WorkSheet.OleProcedure("Paste");
		Variant shapes = WorkSheet.OlePropertyGet("Shapes").OleFunction("Item", 1);
		shapes.OleFunction("ScaleWidth", 0.9, EmptyParam, EmptyParam);
		shapes.OleFunction("ScaleHeight", 0.9, EmptyParam, EmptyParam);


		for (size_t k=0; k < VirtualStringTree1->RootNodeCount; k++)
		{
			if (t_root)
			{
				data_root = (TReportData *)ReportForm->VirtualStringTree1->GetNodeData(t_root);
				if (data_root)
				{
					s=data_root->Name;
					Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", s.t_str());
					i++;
				}


				t_child=t_root->FirstChild;
				while (t_child)
				{
					data_child=(TReportData *)ReportForm->VirtualStringTree1->GetNodeData(t_child);
					if (data_root)
					{
						s=data_child->Name;
						Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", s.t_str());
						Cells.OlePropertyGet("Item",i,j+1).OlePropertySet("Value", FloatToStrF(data_child->pcs, ffFixed, 5, 2, format_settings).t_str());
						Cells.OlePropertyGet("Item",i,j+2).OlePropertySet("Value", FloatToStrF(data_child->pi, ffFixed, 5, 2, format_settings).t_str());
						Cells.OlePropertyGet("Item",i,j+3).OlePropertySet("Value", FloatToStrF(data_child->angle, ffFixed, 5, 2,format_settings).t_str());
						i++;

					}
					t_child = t_child->NextSibling;
				}

				Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", "Средний диаметр");
				Cells.OlePropertyGet("Item",i,j).OlePropertyGet("Font").OlePropertySet("Bold", true);
				Cells.OlePropertyGet("Item",i,j+1).OlePropertySet("Value", FloatToStrF(data_root->pcs, ffFixed, 5, 2, format_settings).t_str());
				i++;
				Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", "Средний ПДД");
				Cells.OlePropertyGet("Item",i,j).OlePropertyGet("Font").OlePropertySet("Bold", true);
				Cells.OlePropertyGet("Item",i,j+1).OlePropertySet("Value", FloatToStrF(data_root->pi, ffFixed, 5, 2, format_settings).t_str());
				i++;
				Cells.OlePropertyGet("Item",i,j).OlePropertySet("Value", "СКО");
				Cells.OlePropertyGet("Item",i,j).OlePropertyGet("Font").OlePropertySet("Bold", true);
				Cells.OlePropertyGet("Item",i,j+1).OlePropertySet("Value", FloatToStrF(data_root->rms, ffFixed, 5, 2, format_settings).t_str());
				i++;
			}

			t_root=t_root->NextSibling;
		}
	}
	__finally
	{
		ExcelApp.OlePropertySet("Visible", true);
		ExcelApp=Unassigned();
	}

}
int Handle_Head(Dictionary *dictHttpRequest, SOCKET scClientSocket)
{
	int nReturnValue = 0;
	char *szURI = 0;
	char *szQueryString = 0;
	char* szPathOfFile = 0;
	char szIndex = "index.html";
	char szPathAfterAdding[260] = { '\0' };
	int bFoundFile = 0;
	
	LogMessage(LOG_DEBUG, "Started to hanlde head http request");

	szURI = GetValueFromDictionary(dictHttpRequest, "URI");
	if (NULL != szURI)
	{
		//Check if the uri has query string. If so then it needs to be handled by cgi.

		//Based on the URI - search in the local path for the file. If found then send 200 else send 404 not found error

		LogMessage(LOG_DEBUG, "Got URI of request");
		LogMessage(LOG_DEBUG, szURI);

		szQueryString = szURI;
		while ((*szQueryString) != '?' && (*szQueryString) != '\0')
		{
			szQueryString++;
		}
		if ((*szQueryString) == '?')
		{
			//This is a query string so handle it in a different way.
			szQueryString++;
			LogMessage(LOG_DEBUG, "URI has a query string in it");
			LogMessage(LOG_DEBUG, szQueryString);
		}
		else
		{
			LogMessage(LOG_DEBUG, "request does not have query string");
			bFoundFile = FindFileInLocalPath(szURI, strMappedLocalPath);
			if (bFoundFile == 0)
			{
				LogMessage(LOG_ERROR, "Could not find the file in the local path");
				nReturnValue = HandleFileNotFound(dictHttpRequest, scClientSocket);
			}
			else
			{
				//printf_s("\nBHS:INFO:Able to find the file in the local path:%s\n", szURI);
				LogMessage(LOG_DEBUG, "Able to find the file in the local path");
				szPathOfFile = GetFilePathFromURI(szURI, strMappedLocalPath);
				LogMessage(LOG_DEBUG, szPathOfFile);
				if (szPathOfFile[strnlen_s(szPathOfFile, 260) - 1] == '/')
				{
					//Add index.html file
					stringcopy(szPathAfterAdding, strlen(szPathOfFile), szPathOfFile);
					strcat_s(szPathAfterAdding, 260, szIndex);
					free(szPathOfFile);
					if (FileExists(szPathAfterAdding) == 1)
					{
						LogMessage(LOG_DEBUG, "Path is directory, so added index.html to path");
						
						szPathOfFile = (char*)malloc(sizeof(char)*strlen(szPathAfterAdding) + 1);
						memset(szPathOfFile, '\0', strlen(szPathAfterAdding) + 1);
						stringcopy(szPathOfFile, strlen(szPathAfterAdding), szPathAfterAdding);
						LogMessage(LOG_DEBUG, szPathOfFile);
						nReturnValue = HandleHeadFileResponse(dictHttpRequest, scClientSocket);

						free(szPathOfFile);
						szPathOfFile = 0;
					}
					else
					{
						LogMessage(LOG_DEBUG, "Found to be directory, so added index.html, But file not in local path");
						LogMessage(LOG_DEBUG, szPathOfFile);
						nReturnValue = HandleHeadFileNotFound(dictHttpRequest, scClientSocket);
					}

				}
				else
				{
					LogMessage(LOG_DEBUG, "Going to send the head response");
					nReturnValue = HandleHeadFileResponse(dictHttpRequest, scClientSocket);

					free(szPathOfFile);
					szPathOfFile = 0;
				}

			}
		}
	}

	LogMessage(LOG_DEBUG, "Returning after handling head request");
	return nReturnValue;
}
示例#18
0
LPCWSTR GetComspecFromEnvVar(wchar_t* pszComspec, DWORD cchMax, ComSpecBits Bits/* = csb_SameOS*/)
{
	if (!pszComspec || (cchMax < MAX_PATH))
	{
		_ASSERTE(pszComspec && (cchMax >= MAX_PATH));
		return NULL;
	}

	*pszComspec = 0;
	BOOL bWin64 = IsWindows64();

	if (!((Bits == csb_x32) || (Bits == csb_x64)))
	{
		if (GetEnvironmentVariable(L"ComSpec", pszComspec, cchMax))
		{
			// Не должен быть (даже случайно) ConEmuC.exe
			const wchar_t* pszName = PointToName(pszComspec);
			if (!pszName || !lstrcmpi(pszName, L"ConEmuC.exe") || !lstrcmpi(pszName, L"ConEmuC64.exe")
				|| !FileExists(pszComspec)) // ну и существовать должен
			{
				pszComspec[0] = 0;
			}
		}
	}

	// Если не удалось определить через переменную окружения - пробуем обычный "cmd.exe" из System32
	if (pszComspec[0] == 0)
	{
		int n = GetWindowsDirectory(pszComspec, cchMax - 20);
		if (n > 0 && (((DWORD)n) < (cchMax - 20)))
		{
			// Добавить \System32\cmd.exe

			// Warning! 'c:\Windows\SysNative\cmd.exe' не прокатит, т.к. доступен
			// только для 32битных приложений. А нам нужно в общем виде.
			// Если из 32битного нужно запустить 64битный cmd.exe - нужно выключать редиректор.

			if (!bWin64 || (Bits != csb_x32))
			{
				_wcscat_c(pszComspec, cchMax, (pszComspec[n-1] == L'\\') ? L"System32\\cmd.exe" : L"\\System32\\cmd.exe");
			}
			else
			{
				_wcscat_c(pszComspec, cchMax, (pszComspec[n-1] == L'\\') ? L"SysWOW64\\cmd.exe" : L"\\SysWOW64\\cmd.exe");
			}
		}
	}

	if (pszComspec[0] && !FileExists(pszComspec))
	{
		_ASSERTE("Comspec not found! File not exists!");
		pszComspec[0] = 0;
	}

	// Last chance
	if (pszComspec[0] == 0)
	{
		_ASSERTE(pszComspec[0] != 0); // Уже должен был быть определен
		//lstrcpyn(pszComspec, L"cmd.exe", cchMax);
		wchar_t *psFilePart;
		DWORD n = SearchPathW(NULL, L"cmd.exe", NULL, cchMax, pszComspec, &psFilePart);
		if (!n || (n >= cchMax))
			_wcscpy_c(pszComspec, cchMax, L"cmd.exe");
	}

	return pszComspec;
}
示例#19
0
/*
 *
 *  MAIN  LINE
 *
 *   1/coef
 *   2/ de[0]  e[0]   jsou kanaly od detektoru
 *   tele <0   ==>   dE + 1/f*E
 *
 */
void mkmat(int teleIN, int count=-1, int bins=4, TCutG *cut=NULL, int dimen=2 , 
	   const char* VOL="V", const char* CONDITION="" ,double coefover=-0.1 ){

  int reverse=0;
  int tele=teleIN;


  if (tele<0){ printf("1D PLOTTING IN REVERSE (dE + 1/f*E)\n",""); reverse=1; tele=-1*tele;}

   printf(" making matrix for telescope T%d%s, #%d, 5000/bins :%d [email protected]%d %dDIM\n", 
	 tele,VOL, count, bins, (int)cut, dimen );


  /*
   * ONCE THIS COEF is set,  you cannot change again because of !cuts!
   *  coenficients for de:de + 0.49*e. By default I put 0.5...
   *  then I need best resolution == finetune...
   *
   *  POZOR NA re-bin artefakty
   */
  //               1     2     3      4     5             6      7     8
  double coef[8]={0.5, 0.525 , 0.510, 0.465, 0.465     ,   0.505, 0.455, 0.425 };
  int de[8], e[8];
  char cmd[500];
  char cmdcond[500];
  char sde[10];
  char se[10];
  char telename[10];  // T1
  char spename[10];  // T1V  or  T1V1D
  char randomization[50];// rand()

  // ----------------------------------------------------VME--------------------
  if ( strcmp(VOL,"V")==0){
  for (int i=0;i<8;i++){// DEFINICE KANALU JE 1-8(E)  17-24(dE)
    de[i]=17+i;
    e[i]=i+1;
  }
  //  sprintf( sde,"V%03d", de[tele-1] );
  //  sprintf(  se,"V%03d",  e[tele-1] );
  //  sprintf(  telename,"T%d",  tele );
  //  //  sprintf(   spename,"T%d",  tele );// LATER ON...!
  }//V
  // ----------------------------------------------------ORT--------------------
  if ( strcmp(VOL,"O")==0){
  for (int i=0;i<8;i++){// DEFINICE KANALU
    de[i]=0;    e[i]=0;
  }
  de[0]=2;e[0]=1;
  de[5]=6;e[5]=5;
  de[1]=10;e[1]=9;
  de[7]=14;e[7]=13;
  //  sprintf( sde,"O%03d", de[tele-1] );
  //  sprintf(  se,"O%03d",  e[tele-1] );
  //  sprintf(  telename,"T%dO",  tele );
  }//O 
  // ----------------------------------------------------LEC--------------------

  

  if (  FileExists("mkmat.xml",33) ){  //minimum size 
    
    xmlreadfile_init("mkmat.xml");

    for (int i=1;i<=8;i++){
     coef[i-1]=xmlread_addwith(i, VOL );
     de[i-1]=  xmlread_dechan( i, VOL );
     e[i-1]=   xmlread_echan( i, VOL );
    }
    xmlreadfile_fini();
  }//  XML FILE EXISTS------------------------------
  
  if (coefover>0.0){ coef[tele-1]=coefover;printf("ceoficient override\n\n%s","");}

  sprintf( sde,"%s%03d",    VOL, de[tele-1] );
  sprintf(  se,"%s%03d",    VOL, e[tele-1] );
  sprintf(  telename,"T%d%s",  tele,  VOL );// T1V
  sprintf(  spename,"T%d%s",  tele,  VOL );//  (T1V or T1V1D)SPECTRUM NAME (redefine later if 1D)

  // if I do V017+0.5-rand(0,1) => spe is shifted!
  //         V017+rand(0,1)     =>  is correct...
  //  sprintf(randomization,"+0.5-1e-3*(rand()%%1e3)","" );//  0.456*(  V001 R )
  sprintf(randomization,"+1e-3*(rand()%%1e3)","" );//  0.456*(  V001 R)  R="" or "+x"


  //COMMAND  - 1D   or  2D ..................
  char option[20]=""; //"col" for bidim

  if (dimen==2){
  sprintf( cmd,    "%s:%s+%s*%.4f>>%s( %d,0,5000,%d,0,5000 )",
	   sde,se,sde,   coef[tele-1],  spename , 5000/bins , 5000/bins );
  sprintf( option,"%s","col" );
  }//dim==2


  if (dimen==1){
  sprintf(  spename,"T%d%s1D",  tele,  VOL );//  SPECTRUM NAME REDEFINE
  //
  // with rand: 25sec
  // wo   rand: 24sec
  //  sprintf( cmd,    "%s+(%s)*%.4f>>%s( 5000,0,5000 )",   // SIMPLE BUT WITH SPIKES
  //  sprintf( cmd,    "%s+(%s+1e-3*(rand()%%1e3))*%.4f>>%s( 5000,0,5000 )",
  //	    se,sde,   coef[tele-1],  spename  );// better automaticaly:
  /*
   *   dE * factor + E   ===>>>  This is how normaly we plot the matrix.
   */
  if (reverse==0){
  sprintf( cmd,    "%s+(%s %s)*%.4f>>%s( 5000,0,5000 )",
	   se,sde, randomization,  coef[tele-1],  spename  );
  }
  /*   reverse
   *   dE  +  factor *E   ???  10000 bins! ==>> consistent with dE...
   */
  if (reverse==1){
  sprintf( cmd,    "1./%.4f*(%s %s)+%s>>%s( 10000,0,10000 )",
	   coef[tele-1], se, randomization, sde,  spename  );
  }
  //	   se,sde, randomization,  coef[tele-1],  spename  );
  sprintf( option,"%s","" );
 }//dim==1



  // CUT - IF ANY - AND dE>0
  if (cut!=NULL){
    sprintf( cmdcond,"%s>0 && %s",   sde , cut->GetName()   );// USE CUT
  }else{
    sprintf( cmdcond,"%s>0",   sde );     //  at least dE >0 !!!!!1
  }
 
  //problem....         V001 V002.........
  // I solve it by replacing     de->  V001
  //                             e->   V017
  // simply - another fine interpreter.
  if (strlen(CONDITION)>1){
    //sprintf( cmdcond,"%s && %s",  cmdcond, CONDITION  );     //  at least dE >0 !!!!!1
    TString cono=CONDITION;
    cono.ReplaceAll("de", sde );
    cono.ReplaceAll("e", se );

    cono.ReplaceAll("dE", sde );
    cono.ReplaceAll("E", se );
    sprintf( cmdcond,"%s && %s",  cmdcond, cono.Data()  );     //  at least dE >0 !!!!!1

  } // if condition:  reinterpret it

  // GRAPHICS OFF
  //  sprintf( option,"%s%s",option, "goff" );


  printf("\"%s\"  , \"%s\" ,  \"%s\"   \n", cmd, cmdcond,  option );


  
  if (count>0){   nanot->Draw(cmd, cmdcond,  option  , count );}
  if (count<=0){  nanot->Draw(cmd, cmdcond,  option          );}


  //  gDirectory->ls();
  printf("searching <%s>\n", spename );
  TH1* h2;
  //  TH2F* h2=(TH2F*)gDirectory->Get( telename );
  //  sleep(1);
  h2=(TH1*)gDirectory->FindObject( spename ); 
  //  if ( dimen==2){  h2=(TH1*)gDirectory->FindObject( telename );  }
  //  if ( dimen==1){  h2=(TH1*)gDirectory->FindObject( telename );  }

  h2->Print();
  TString hname=h2->GetTitle(  );
  hname.Append(" made in ");
  hname.Append( gFile->GetName() );
  h2->SetTitle( hname.Data()  );

  //"nanot->Draw(\"V022:V006+V022*0.535>>h6a(200,2500,2700,200,750,950)\",\"V022>0\",\"col\" )
  //goff  gPad->Modified();  gPad->Update();
}//mkmat
示例#20
0
void Ide::SerializeWorkspace(Stream& s) {
	int i;
	int version = 14;
	s / version;
	s.Magic(0x12354);
	if(s.IsStoring()) {
		for(i = 0; i < filedata.GetCount(); i++) {
			String fn = filedata.GetKey(i);
			if(!fn.IsEmpty() && FileExists(fn)) {
				s % fn;
				s % filedata[i].editpos;
				if(version >= 1)
					s % filedata[i].columnline;
			}
		}
		String h;
		s % h;
	}
	else {
		String fn;
		filedata.Clear();
		for(;;) {
			s % fn;
			if(fn.IsEmpty()) break;
			FileData& fd = filedata.GetAdd(fn);
			fd.Clear();
			s % fd.editpos;
			if(version >= 1)
				s % fd.columnline;
		}
	}
	String pk = GetActivePackage();
	s % pk;
	package.FindSetCursor(pk);
	s % tablru;
	s % mainconfigname;
	s % mainconfigparam;
	s % console.verbosebuild;
	s % stoponerrors;
	byte dummy;
	s % dummy;
	s % runarg;
	s % recent_runarg;
	s % rundir;
	s % stdout_file % recent_stdout_file / runmode;
	if(version >= 1)
		s % runexternal;
	if(version >= 11) {
		bool dummy;
		s % dummy;
	}
	if(version >= 13)
		s % consolemode;
	if(version >= 14)
		s % console_utf8;
	s % editfile;
	for(i = 0; i < 10; i++)
		s % bookmark[i];
	editor.Serialize(s);
	if(version >= 5)
		s % editorsplit;
	if(version == 6) {
		String n;
		int v;
		s / v;
		for(int i = 0; i < 10; i++) {
			s % n;
			s / v;
		}
	}
	if(version >= 8) {
		bool dummyb;
		String dummy;
		s % dummyb;
		s % dummy;
	}
	SerializeFindInFiles(s);
	String om;
	s % om;
	s % recentoutput;
	s % recentflags;
	s / editortabsize / indent_amount % indent_spaces;
	for(int j = 0; j < GetIdeModuleCount(); j++)
		GetIdeModule(j).Serialize(s); // -> Workspace
	SerializeWorkspaceConfigs(s);
	SerializeOutputMode(s);
	SerializeClosed(s);
	if(version >= 10) {
		if(tabs_serialize) {
			s % tabs;
		}
	}
	if(version >= 11) {
		s % find_file_search_string;
	}
	if(version >= 12)
		SerializePlacement(s);

}
示例#21
0
void PluginCallbackManager::init()
{
	DIR *dp;
	struct dirent *ep;

	dp = opendir(getPluginDirectory());
	if (dp != NULL)
	{
		while (ep = readdir(dp))
		{
			int location = strstr(ep->d_name,".") - ep->d_name;
			// We're one of ".", "..", or hidden, so let's skip
			if ( location == 0 )
				continue;

			LogDebug(VB_PLUGIN, "Found Plugin: (%s)\n", ep->d_name);

			std::string filename = std::string(getPluginDirectory()) + "/" + ep->d_name + "/callbacks";
			bool found = false;

			if ( FileExists(filename.c_str()) )
			{
				printf("Found callback with no extension");
				found = true;
			}
			else
			{
				std::vector<std::string> extensions;
				extensions.push_back(std::string(".sh"));
				extensions.push_back(std::string(".pl"));
				extensions.push_back(std::string(".php"));
				extensions.push_back(std::string(".py"));

				for ( std::vector<std::string>::iterator i = extensions.begin(); i != extensions.end(); ++i)
				{
					std::string tmpFilename = filename + *i;
					if ( FileExists( tmpFilename.c_str() ) )
					{
						filename += *i;
						found = true;
					}
				}
			}
			std::string eventScript = std::string(getFPPDirectory()) + "/scripts/eventScript";

			if ( !found )
			{
				LogExcess(VB_PLUGIN, "No callbacks supported by plugin: '%s'\n", ep->d_name);
				continue;
			}

			LogDebug(VB_PLUGIN, "Processing Callbacks (%s) for plugin: '%s'\n", filename.c_str(), ep->d_name);

			int output_pipe[2], pid, bytes_read;
			char readbuffer[128];
			std::string callback_list = "";

			if (pipe(output_pipe) == -1)
			{
				LogErr(VB_PLUGIN, "Failed to make pipe\n");
				exit(EXIT_FAILURE);
			}

			if ((pid = fork()) == -1 )
			{
				LogErr(VB_PLUGIN, "Failed to fork\n");
				exit(EXIT_FAILURE);
			}

			if ( pid == 0 )
			{
				dup2(output_pipe[1], STDOUT_FILENO);
				close(output_pipe[1]);
				execl(eventScript.c_str(), "eventScript", filename.c_str(), "--list", NULL);

				LogErr(VB_PLUGIN, "We failed to exec our callbacks query!\n");
				exit(EXIT_FAILURE);
			}
			else
			{
				close(output_pipe[1]);

				while (true)
				{
					bytes_read = read(output_pipe[0], readbuffer, sizeof(readbuffer)-1);

					if (bytes_read <= 0)
						break;

					readbuffer[bytes_read] = '\0';
					callback_list += readbuffer;
				}

				boost::trim(callback_list);

				LogExcess(VB_PLUGIN, "Callback output: (%s)\n", callback_list.c_str());

				wait(NULL);
			}

			boost::char_separator<char> sep(",");
			boost::tokenizer< boost::char_separator<char> > tokens(callback_list, sep);
		    BOOST_FOREACH (const std::string& type, tokens)
			{
				if (type == "media")
				{
					LogDebug(VB_PLUGIN, "Plugin %s supports media callback.\n", ep->d_name);
					MediaCallback *media = new MediaCallback(std::string(ep->d_name), filename);
					mCallbacks.push_back(media);
				}
				else if (type == "playlist")
				{
					LogDebug(VB_PLUGIN, "Plugin %s supports playlist callback.\n", ep->d_name);
					PlaylistCallback *playlist = new PlaylistCallback(std::string(ep->d_name), filename);
					mCallbacks.push_back(playlist);
				}
				else if (type == "nextplaylist")
				{
					LogDebug(VB_PLUGIN, "Plugin %s supports nextplaylist callback.\n", ep->d_name);
					NextPlaylistEntryCallback *nextplaylistentry = new NextPlaylistEntryCallback(std::string(ep->d_name), filename);
					mCallbacks.push_back(nextplaylistentry);
				}
				else if (type == "event")
				{
					LogDebug(VB_PLUGIN, "Plugin %s supports event callback.\n", ep->d_name);
					EventCallback *eventcallback = new EventCallback(std::string(ep->d_name), filename);
					mCallbacks.push_back(eventcallback);
				}
			}

			plugin_count += 1;
		}
		closedir(dp);
	}
	else
	{
示例#22
0
//  27-Aug-2004 SFK		Created
void CopyLogsMenuOption()
{                                 

    static char szDfltRootPath[PATH_LEN+1] = "";
    static char szDfltCurrentDbPath[PATH_LEN+1] = "";                   
    static BOOL bFirst = TRUE;
    
	char szCurrentDbPath[PATH_LEN+1] = "";    
	char szMainCurrentDbPath[PATH_LEN+1] = "";    
    char szRootBackupPath[PATH_LEN+1] = "";
	char szMainBackupPath[PATH_LEN+1] = "";
    unsigned long ulDirSize, ulDiskSize, ulDiskAvailable;
    BOOL bRoom;     
    int status;
    char *pStr;

    
    GUI_ACTION DlgReturn;         
    CGFmtStr msg;

	SetCurrentDrive();    
    GetDbName(szCurrentDbPath);
    
   /* ------------------------------------------------------------------
    *	First time or when change databases, get the default values
    *	from the .ini file else use the last successful values.
    * ------------------------------------------------------------------*/
    if ((bFirst == TRUE) || (!SameDb(szDfltCurrentDbPath))) {
    	pStr = pRAD_Init->Get_LogCopy_To_Path(); 
		MyStrnCpy(szDfltRootPath, pStr, PATH_LEN); 
   		bFirst = FALSE;
    	strcpy(szDfltCurrentDbPath, szCurrentDbPath);
	}
	
	strcpy(szRootBackupPath, szDfltRootPath);

   /* ------------------------------------------------------------------
    *	Define the buttons and actions in the dialog box
    * ----------------------------------------------------------------*/
    CGUI_Dlg BackupDbDlg(IDD_FILE_COPY_LOGS, NULL, DLG_POSN_NO_SAVE);
    if (BackupDbDlg.IsValid()) {
		BackupDbDlg.DefinePushBtn(IDCANCEL, GUI_CANCEL);
		BackupDbDlg.DefinePushBtn(IDOK, GUI_OK);
		BackupDbDlg.DefinePushBtn(IDUPDATE, GUI_NONE, UpdateINI_Parms);              
			                                               
		BackupDbDlg.DefineFldTxt(IDC_CLOG_EDIT_NEW_PATH, szRootBackupPath, PATH_LEN);
			
		BackupDbDlg.SetFocus(IDOK);
		
	    DlgReturn = BackupDbDlg.Go();
		    
	    if (DlgReturn == GUI_OK) {  
		    	
	    	BackupDbDlg.RetrieveAllControlValues();

		   /* ------------------------------------------------------------------
		    *	Remove spaces, check length
		    * ----------------------------------------------------------------*/
	    	if (PathCopy(szMainBackupPath, szRootBackupPath) != TRUE) return;
	    	strcat(szMainBackupPath, "logs\\rad\\");

	    	if (PathCopy(szMainCurrentDbPath, szCurrentDbPath) != TRUE) return;
	    	strcat(szMainCurrentDbPath, "logs\\rad\\");

		   /* ------------------------------------------------------------------
		    *	See if the new path exists, if not make it.  If can't make it give
		    *	reason why.
		    * ----------------------------------------------------------------*/
		    status = PathExists(szMainBackupPath); // returns TRUE, uiPATH_TOO_LONG_ERR, uiDRIVE_DOES_NOT_EXIST_ERR oruiPATH_DOES_NOT_EXIST_ERR
		    if ( status == uiPATH_DOES_NOT_EXIST_ERR) {
		    	status = AskAndMakePath(szMainBackupPath);
		    	if (status != TRUE) return;
		    }	
		    if ( status != TRUE) {
		    	RadReviewMsg(status, (const char *)szMainBackupPath);
				return;
			}	

		   /* ------------------------------------------------------------------
		    *	See if a log file exists at the location specified.  If yes,
		    *	see if they want to overwrite it.
		    * ----------------------------------------------------------------*/
		    if (FileExists(szMainBackupPath, "RadReviewLog.txt") == TRUE) {
		    	status = AskOverwriteQuestion(szMainBackupPath);
		    	if (status == FALSE) return;
		    }	
		    
		   /* ------------------------------------------------------------------
		    *	Figure out how many bytes will need to be copied and if there
		    *	is room on the destination drive.  (Destination drive must have
		    *	directory size + 10000 to allow for directory entries, etc.)
		    * ----------------------------------------------------------------*/
		    if (GetDirSize(szMainCurrentDbPath, "*.*", &ulDirSize) != TRUE) return;	/* check number of bytes filled in szCurrentDbPath */
			
			// Customize for COMs, if don't write to this log directory

		    if (GetDriveSize(szMainBackupPath, &ulDiskSize, &ulDiskAvailable) != TRUE) return;	/* check number of bytes available on drive */
			
			bRoom = TRUE;
			if ((ulDirSize + 10000) > ulDiskAvailable) bRoom = FALSE;	    
		    	    
		    if (bRoom == FALSE) {
		    	if (AskNotEnoughRoomQuestion(ulDirSize, ulDiskAvailable, szMainBackupPath) == FALSE) return;
		    }
		    
		   /* ------------------------------------------------------------------
		    *	Close the current database in case are trying to copy it.
		    *	Copy the data and show progress. Inform of the results of the copy.	
		    * ----------------------------------------------------------------*/
		    GetDbName(szCurrentDbPath);
			_flushall();
			    
		    status = CopyDirectory(szMainCurrentDbPath, szMainBackupPath);

			// Customize for COMs, if don't write to this log directory

		    if (status != TRUE) { 
		    	RadReviewMsg(uiCOPY_DB_ERR, (const char *)szCurrentDbPath, (const char *)szRootBackupPath);
		    }
		    else {	
		    	MyStrnCpy(szDfltRootPath,szRootBackupPath, PATH_LEN);	// remember the default for next time
				msg.Printf("Logs copied to %s.", szRootBackupPath);	
			    GUI_MsgBox(msg, GUI_ICON_INFO);
		    }	

	    }	
	}    
}   		                                 
void frControlPanel::BuildContent(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size)
{
    wxLongLong t1 = wxGetUTCTimeMillis();
    Freeze();
	//(*Initialize(frControlPanel)
	wxFlexGridSizer* FlexGridSizer1;

	Create(parent, wxID_ANY, _("Control panel"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE|wxSTATIC_BORDER, _T("wxID_ANY"));
	SetMinSize(wxSize(1000,600));
	FlexGridSizer1 = new wxFlexGridSizer(2, 1, 0, 0);
	FlexGridSizer1->AddGrowableCol(0);
	FlexGridSizer1->AddGrowableRow(0);
	pcSPIS = new wxNotebook(this, ID_NOTEBOOK1, wxDefaultPosition, wxSize(900,500), wxNO_FULL_REPAINT_ON_RESIZE, _T("ID_NOTEBOOK1"));
	m_Customer = new pnlCustomer(pcSPIS, ID_PANEL2, wxDefaultPosition, wxSize(621,263), wxTAB_TRAVERSAL, _T("ID_PANEL2"));
	m_top = new pnlTop(pcSPIS, ID_PANEL3, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL3"));
	m_TxPLL = new pnlTxPLL(pcSPIS, ID_PANEL4, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL4"));
	m_RxPLL = new pnlRxPLL(pcSPIS, ID_PANEL5, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL5"));
	m_TxLPF = new pnlTxLPF(pcSPIS, ID_PANEL6, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL6"));
	m_TxRF = new pnlTxRF(pcSPIS, ID_PANEL7, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL7"));
	m_RxLPF = new pnlRxLPF(pcSPIS, ID_PANEL8, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL8"));
	m_RxVGA2 = new pnlRxVGA2(pcSPIS, ID_PANEL9, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL9"));
	m_RxFE = new pnlRxFE(pcSPIS, ID_PANEL10, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL10"));
	m_ADDC = new pnlADDC(pcSPIS, ID_PANEL11, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL11"));
	m_Board = new pnlBoard(pcSPIS, ID_PANEL13, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL13"));
	m_ADF = new pnlADF(pcSPIS, ID_PANEL1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL1"));
	pcSPIS->AddPage(m_Customer, _("System"), false);
	pcSPIS->AddPage(m_top, _("Top"), false);
	pcSPIS->AddPage(m_TxPLL, _("Tx PLL + DSM"), false);
	pcSPIS->AddPage(m_RxPLL, _("Rx PLL + DSM"), false);
	pcSPIS->AddPage(m_TxLPF, _("Tx LPF"), false);
	pcSPIS->AddPage(m_TxRF, _("Tx RF"), false);
	pcSPIS->AddPage(m_RxLPF, _("Rx LPF"), false);
	pcSPIS->AddPage(m_RxVGA2, _("Rx VGA2"), false);
	pcSPIS->AddPage(m_RxFE, _("Rx FE"), false);
	pcSPIS->AddPage(m_ADDC, _("ADC / DAC"), false);
	pcSPIS->AddPage(m_Board, _("Board"), false);
	pcSPIS->AddPage(m_ADF, _("ADF4002"), false);
	FlexGridSizer1->Add(pcSPIS, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	lbMsgs = new wxRichTextCtrl(this, ID_RICHTEXTCTRL1, _("Text"), wxDefaultPosition, wxDefaultSize, wxRE_MULTILINE, wxDefaultValidator, _T("ID_RICHTEXTCTRL1"));
		wxRichTextAttr rchtxtAttr_1;
	lbMsgs->SetMinSize(wxSize(-1,100));
	FlexGridSizer1->Add(lbMsgs, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5);
	SetSizer(FlexGridSizer1);
	MenuBar1 = new wxMenuBar();
	Menu1 = new wxMenu();
	mnuNew = new wxMenuItem(Menu1, ID_MENUITEM1, _("New project"), wxEmptyString, wxITEM_NORMAL);
	Menu1->Append(mnuNew);
	mnuOpen = new wxMenuItem(Menu1, ID_MENUITEM2, _("Open project"), wxEmptyString, wxITEM_NORMAL);
	Menu1->Append(mnuOpen);
	mnuSave = new wxMenuItem(Menu1, ID_MENUITEM3, _("Save"), wxEmptyString, wxITEM_NORMAL);
	Menu1->Append(mnuSave);
	mnuSaveAs = new wxMenuItem(Menu1, ID_MENUITEM4, _("Save as"), wxEmptyString, wxITEM_NORMAL);
	Menu1->Append(mnuSaveAs);
	Menu1->AppendSeparator();
	mnuReadRVF_rfif = new wxMenuItem(Menu1, ID_MENUITEM9, _("Save to HEX"), wxEmptyString, wxITEM_NORMAL);
	Menu1->Append(mnuReadRVF_rfif);
	Menu1->AppendSeparator();
	mnuChipToGUI = new wxMenuItem(Menu1, ID_MENUITEM10, _("Chip --> GUI"), wxEmptyString, wxITEM_NORMAL);
	Menu1->Append(mnuChipToGUI);
	MenuBar1->Append(Menu1, _("File"));
	Menu2 = new wxMenu();
	mnuAutoDwnld = new wxMenuItem(Menu2, ID_MENUITEM5, _("Auto Download"), wxEmptyString, wxITEM_CHECK);
	Menu2->Append(mnuAutoDwnld);
	mnuAutoDwnld->Check(true);
	mnuRefClk = new wxMenuItem(Menu2, ID_MENUITEM6, _("Reference Clock"), wxEmptyString, wxITEM_NORMAL);
	Menu2->Append(mnuRefClk);
	CommunicationSettings1 = new wxMenuItem(Menu2, ID_MENUITEM7, _("Communication Settings"), wxEmptyString, wxITEM_NORMAL);
	Menu2->Append(CommunicationSettings1);
	MenuBar1->Append(Menu2, _("Options"));
	Menu3 = new wxMenu();
	RegisterTest1 = new wxMenuItem(Menu3, ID_MENUITEM8, _("Registers test"), wxEmptyString, wxITEM_NORMAL);
	Menu3->Append(RegisterTest1);
	MenuBar1->Append(Menu3, _("Tools"));
	Menu4 = new wxMenu();
	mnuAbout = new wxMenuItem(Menu4, ID_MENUITEM11, _("About..."), wxEmptyString, wxITEM_NORMAL);
	Menu4->Append(mnuAbout);
	MenuBar1->Append(Menu4, _("Help"));
	SetMenuBar(MenuBar1);
	ToolBar1 = new wxToolBar(this, ID_TOOLBAR1, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL|wxTB_HORZ_TEXT|wxNO_BORDER, _T("ID_TOOLBAR1"));
	ToolBarItem1 = ToolBar1->AddTool(ID_TOOLBARITEM1, _("New"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_NEW")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);
	ToolBarItem2 = ToolBar1->AddTool(ID_TOOLBARITEM2, _("Open"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_FILE_OPEN")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);
	ToolBarItem3 = ToolBar1->AddTool(ID_TOOLBARITEM3, _("Save"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_FILE_SAVE")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, wxEmptyString, wxEmptyString);
	ToolBar1->AddSeparator();
	tbtnDownload = ToolBar1->AddTool(ID_TOOLBARITEM4, _("Send configuration"), wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_HELP_SIDE_PANEL")),wxART_TOOLBAR), wxNullBitmap, wxITEM_NORMAL, _("Send all configuration"), wxEmptyString);
	ToolBar1->Realize();
	SetToolBar(ToolBar1);
	dlgOpen = new wxFileDialog(this, _("Select file"), wxEmptyString, wxEmptyString, wxFileSelectorDefaultWildcardStr, wxFD_DEFAULT_STYLE, wxDefaultPosition, wxDefaultSize, _T("wxFileDialog"));
	sbMain = new wxStatusBar(this, ID_STATUSBAR1, 0, _T("ID_STATUSBAR1"));
	int __wxStatusBarWidths_1[3] = { 10, -10, -10 };
	int __wxStatusBarStyles_1[3] = { wxSB_NORMAL, wxSB_NORMAL, wxSB_NORMAL };
	sbMain->SetFieldsCount(3,__wxStatusBarWidths_1);
	sbMain->SetStatusStyles(3,__wxStatusBarStyles_1);
	SetStatusBar(sbMain);
	FlexGridSizer1->Fit(this);
	FlexGridSizer1->SetSizeHints(this);

	Connect(ID_MENUITEM1,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnmnuNewSelected);
	Connect(ID_MENUITEM2,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnmnuOpenSelected);
	Connect(ID_MENUITEM3,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnmnuSaveSelected);
	Connect(ID_MENUITEM4,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnmnuSaveAsSelected);
	Connect(ID_MENUITEM9,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnmnuReadRVF_rfifSelected);
	Connect(ID_MENUITEM10,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnmnuChipToGUISelected);
	Connect(ID_MENUITEM5,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnmnuAutoDwnldSelected1);
	Connect(ID_MENUITEM6,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnmnuRefClkSelected1);
	Connect(ID_MENUITEM7,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnCommunicationSettings1Selected1);
	Connect(ID_MENUITEM8,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnRegisterTest1Selected);
	Connect(ID_MENUITEM11,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&frControlPanel::OnmnuAboutSelected);
	Connect(ID_TOOLBARITEM1,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&frControlPanel::OnmnuNewSelected);
	Connect(ID_TOOLBARITEM2,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&frControlPanel::OnmnuOpenSelected);
	Connect(ID_TOOLBARITEM3,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&frControlPanel::OnmnuSaveSelected);
	Connect(ID_TOOLBARITEM4,wxEVT_COMMAND_TOOL_CLICKED,(wxObjectEventFunction)&frControlPanel::OntbtnDownloadClicked);
	Connect(wxID_ANY,wxEVT_CLOSE_WINDOW,(wxObjectEventFunction)&frControlPanel::OnClose);
	//*)

	//Set image for download all tool button
	//ToolBar1->SetToolNormalBitmap(ID_TOOLBARITEM4, wxBitmap(*Image1));

	//SetTitle("ctr_6002dr2 - ZIPPER EDITION");

	t1 = wxGetUTCTimeMillis();
	// Clear Messages
	lbMsgs->Clear();
	m_top->Initialize();
	m_RxLPF->Initialize(m_ADDC);
	m_TxLPF->Initialize(NULL);
	m_TxRF->Initialize();
	m_RxVGA2->Initialize();
	m_RxFE->Initialize();
	m_TxPLL->Initialize();
	m_RxPLL->Initialize();
	m_ADDC->Initialize();
	m_Customer->Initialize();
	t1 = wxGetUTCTimeMillis();
	// m_frmBoard->Initialize();

	// Project by default
	Thaw();
	setCurrentFileName("untitled.prj");

#ifndef CUSTOMER_MODE
	//double Freq = ReadRefClkFromReg();
	//ShowReferenceClk(Freq);
#endif

#ifdef CUSTOMER_MODE
	if (FileExists(ChangeFileExt(Application->ExeName, ".prj")))
	{
		if (!FileIsNotEmpty(ChangeFileExt(Application->ExeName, ".prj")))
		{
			ShowMessage("Configuration file is corrupt.\n\n\
        Contact Lime Microsystems\n\
        Unit 57 Surrey Tech Centre Occam Road\n\
        The Surrey Research Park Guildford Surrey\n\
        GU2 7YG\n\n\
        Tel: +44 (0)1483 684801, +44(0)142 8653335\n\
        Fax: +44(0) 1428656662\n\n\
		[email protected]");
			Application->Terminate();
		};

		setCurrentFileName(ChangeFileExt(Application->ExeName, ".prj"));
		LoadConfiguration(m_sFileName);
		tbtnDownload->Click();
	}
示例#24
0
文件: WUser.cpp 项目: davgit/ConEmu
// используется в GUI при загрузке настроек
void FindComspec(ConEmuComspec* pOpt, bool bCmdAlso /*= true*/)
{
	if (!pOpt)
		return;

	pOpt->Comspec32[0] = 0;
	pOpt->Comspec64[0] = 0;

	// Ищем tcc.exe
	if (pOpt->csType == cst_AutoTccCmd)
	{
		HKEY hk;
		BOOL bWin64 = IsWindows64();
		wchar_t szPath[MAX_PATH+1];

		// If tcc.exe can be found near to ConEmu location
		LPCWSTR ppszPredefined[] = {
			L"%ConEmuBaseDir%\\tcc.exe",
			L"%ConEmuDir%\\tcc.exe",
			// Sort of PortableApps locations
			L"%ConEmuDir%\\..\\tcc\\tcc.exe",
			L"%ConEmuDir%\\..\\..\\tcc\\tcc.exe",
			// End of predefined list
			NULL};
		for (INT_PTR i = 0; ppszPredefined[i]; i++)
		{
			DWORD nExpand = ExpandEnvironmentStrings(ppszPredefined[i], szPath, countof(szPath));
			if (nExpand && (nExpand < countof(szPath)))
			{
				if (FileExists(szPath))
				{
					wcscpy_c(pOpt->Comspec32, szPath);
					wcscpy_c(pOpt->Comspec64, szPath);
					break;
				}
			}
		}

		// On this step - check "Take Command"!
		if (!*pOpt->Comspec32 || !*pOpt->Comspec64)
		{
			// [HKEY_LOCAL_MACHINE\SOFTWARE\JP Software\Take Command 13.0]
			// @="\"C:\\Program Files\\JPSoft\\TCMD13\\tcmd.exe\""
			for (int b = 0; b <= 1; b++)
			{
				// b==0 - 32bit, b==1 - 64bit
				if (b && !bWin64)
					continue;
				bool bFound = false;
				DWORD nOpt = (b == 0) ? (bWin64 ? KEY_WOW64_32KEY : 0) : (bWin64 ? KEY_WOW64_64KEY : 0);
				if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\JP Software", 0, KEY_READ|nOpt, &hk))
				{
					wchar_t szName[MAX_PATH+1]; DWORD nLen;
					for (DWORD k = 0; !bFound && !RegEnumKeyEx(hk, k, szName, &(nLen = countof(szName)-1), 0,0,0,0); k++)
					{
						HKEY hk2;
						if (!RegOpenKeyEx(hk, szName, 0, KEY_READ|nOpt, &hk2))
						{
							// Just in case, check "Path" too
							LPCWSTR rsNames[] = {NULL, L"Path"};

							for (size_t n = 0; n < countof(rsNames); n++)
							{
								ZeroStruct(szPath); DWORD nSize = (countof(szPath)-1)*sizeof(szPath[0]);
								if (!RegQueryValueExW(hk2, rsNames[n], NULL, NULL, (LPBYTE)szPath, &nSize) && *szPath)
								{
									wchar_t* psz, *pszEnd;
									psz = (wchar_t*)Unquote(szPath, true);
									pszEnd = wcsrchr(psz, L'\\');
									if (!pszEnd || lstrcmpi(pszEnd, L"\\tcmd.exe") || !FileExists(psz))
										continue;
									lstrcpyn(pszEnd+1, L"tcc.exe", 8);
									if (FileExists(psz))
									{
										bFound = true;
										if (b == 0)
											wcscpy_c(pOpt->Comspec32, psz);
										else
											wcscpy_c(pOpt->Comspec64, psz);
									}
								}
							} // for (size_t n = 0; n < countof(rsNames); n++)
							RegCloseKey(hk2);
						}
					} //  for, подключи
					RegCloseKey(hk);
				} // L"SOFTWARE\\JP Software"
			} // for (int b = 0; b <= 1; b++)

			// Если установлен TCMD - предпочтительно использовать именно его, независимо от битности
			if (*pOpt->Comspec32 && !*pOpt->Comspec64)
				wcscpy_c(pOpt->Comspec64, pOpt->Comspec32);
			else if (*pOpt->Comspec64 && !*pOpt->Comspec32)
				wcscpy_c(pOpt->Comspec32, pOpt->Comspec64);
		}

		// If "Take Command" not installed - try "TCC/LE"
		if (!*pOpt->Comspec32 || !*pOpt->Comspec64)
		{
			// [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{16A21882-4138-4ADA-A390-F62DC27E4504}]
			// "DisplayVersion"="13.04.60"
			// "Publisher"="JP Software"
			// "DisplayName"="Take Command 13.0"
			// или
			// "DisplayName"="TCC/LE 13.0"
			// и наконец
			// "InstallLocation"="C:\\Program Files\\JPSoft\\TCMD13\\"
			for (int b = 0; b <= 1; b++)
			{
				// b==0 - 32bit, b==1 - 64bit
				if (b && !bWin64)
					continue;
				if (((b == 0) ? *pOpt->Comspec32 : *pOpt->Comspec64))
					continue; // этот уже нашелся в TCMD

				bool bFound = false;
				DWORD nOpt = (b == 0) ? (bWin64 ? KEY_WOW64_32KEY : 0) : (bWin64 ? KEY_WOW64_64KEY : 0);
				if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", 0, KEY_READ|nOpt, &hk))
				{
					wchar_t szName[MAX_PATH+1]; DWORD nLen;
					for (DWORD n = 0; !bFound && !RegEnumKeyEx(hk, n, szName, &(nLen = countof(szName)-1), 0,0,0,0); n++)
					{
						if (*szName != L'{')
							continue;
						HKEY hk2;
						if (!RegOpenKeyEx(hk, szName, 0, KEY_READ|nOpt, &hk2))
						{
							ZeroStruct(szPath); DWORD nSize = (countof(szPath) - 1)*sizeof(szPath[0]);
							if (!RegQueryValueExW(hk2, L"Publisher", NULL, NULL, (LPBYTE)szPath, &nSize)
								&& !lstrcmpi(szPath, L"JP Software"))
							{
								nSize = (countof(szPath)-12)*sizeof(szPath[0]);
								if (!RegQueryValueExW(hk2, L"InstallLocation", NULL, NULL, (LPBYTE)szPath, &nSize)
									&& *szPath)
								{
									wchar_t* psz, *pszEnd;
									if (szPath[0] == L'"')
									{
										psz = szPath + 1;
										pszEnd = wcschr(psz, L'"');
										if (pszEnd)
											*pszEnd = 0;
									}
									else
									{
										psz = szPath;
									}
									if (*psz)
									{
										pszEnd = psz+lstrlen(psz);
										if (*(pszEnd-1) != L'\\')
											*(pszEnd++) = L'\\';
										lstrcpyn(pszEnd, L"tcc.exe", 8);
										if (FileExists(psz))
										{
											bFound = true;
											if (b == 0)
												wcscpy_c(pOpt->Comspec32, psz);
											else
												wcscpy_c(pOpt->Comspec64, psz);
										}
									}
								}
							}
							RegCloseKey(hk2);
						}
					} // for, подключи
					RegCloseKey(hk);
				} // L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
			} // for (int b = 0; b <= 1; b++)
		}

		// Попытаться "в лоб" из "Program Files"
		if (!*pOpt->Comspec32 && !*pOpt->Comspec64)
		{

			const wchar_t* pszTcmd  = L"C:\\Program Files\\JPSoft\\TCMD13\\tcc.exe";
			const wchar_t* pszTccLe = L"C:\\Program Files\\JPSoft\\TCCLE13\\tcc.exe";
			if (FileExists(pszTcmd))
				wcscpy_c(pOpt->Comspec32, pszTcmd);
			else if (FileExists(pszTccLe))
				wcscpy_c(pOpt->Comspec32, pszTccLe);
		}

		if (*pOpt->Comspec32 && !*pOpt->Comspec64)
			wcscpy_c(pOpt->Comspec64, pOpt->Comspec32);
		else if (*pOpt->Comspec64 && !*pOpt->Comspec32)
			wcscpy_c(pOpt->Comspec32, pOpt->Comspec64);
	} // if (pOpt->csType == cst_AutoTccCmd)

	// С поиском tcc закончили. Теперь, если pOpt->Comspec32/pOpt->Comspec64 остались не заполнены
	// нужно сначала попытаться обработать переменную окружения ComSpec, а потом - просто "cmd.exe"
	if (!*pOpt->Comspec32)
		GetComspecFromEnvVar(pOpt->Comspec32, countof(pOpt->Comspec32), csb_x32);
	if (!*pOpt->Comspec64)
		GetComspecFromEnvVar(pOpt->Comspec64, countof(pOpt->Comspec64), csb_x64);
}
示例#25
0
// --------------------------------------------------------------------------
//
// Function
//		Name:    BackupStoreCheck::Check()
//		Purpose: Perform the check on the given account. You need to
//			 hold a lock on the account before calling this!
//		Created: 21/4/04
//
// --------------------------------------------------------------------------
void BackupStoreCheck::Check()
{
	if(mFixErrors)
	{
		std::string writeLockFilename;
		StoreStructure::MakeWriteLockFilename(mStoreRoot, mDiscSetNumber, writeLockFilename);
		ASSERT(FileExists(writeLockFilename));
	}

	if(!mQuiet && mFixErrors)
	{
		BOX_INFO("Will fix errors encountered during checking.");
	}

	BackupStoreAccountDatabase::Entry account(mAccountID, mDiscSetNumber);
	mapNewRefs = BackupStoreRefCountDatabase::Create(account);

	// Phase 1, check objects
	if(!mQuiet)
	{
		BOX_INFO("Checking store account ID " <<
			BOX_FORMAT_ACCOUNT(mAccountID) << "...");
		BOX_INFO("Phase 1, check objects...");
	}
	CheckObjects();

	// Phase 2, check directories
	if(!mQuiet)
	{
		BOX_INFO("Phase 2, check directories...");
	}
	CheckDirectories();

	// Phase 3, check root
	if(!mQuiet)
	{
		BOX_INFO("Phase 3, check root...");
	}
	CheckRoot();

	// Phase 4, check unattached objects
	if(!mQuiet)
	{
		BOX_INFO("Phase 4, fix unattached objects...");
	}
	CheckUnattachedObjects();

	// Phase 5, fix bad info
	if(!mQuiet)
	{
		BOX_INFO("Phase 5, fix unrecovered inconsistencies...");
	}
	FixDirsWithWrongContainerID();
	FixDirsWithLostDirs();

	// Phase 6, regenerate store info
	if(!mQuiet)
	{
		BOX_INFO("Phase 6, regenerate store info...");
	}
	WriteNewStoreInfo();

	try
	{
		std::auto_ptr<BackupStoreRefCountDatabase> apOldRefs =
			BackupStoreRefCountDatabase::Load(account, false);
		mNumberErrorsFound += mapNewRefs->ReportChangesTo(*apOldRefs);
	}
	catch(BoxException &e)
	{
		BOX_WARNING("Reference count database was missing or "
			"corrupted, cannot check it for errors.");
		mNumberErrorsFound++;
	}

	// force file to be saved and closed before releasing the lock below
	if(mFixErrors)
	{
		mapNewRefs->Commit();
	}
	else
	{
		mapNewRefs->Discard();
	}
	mapNewRefs.reset();

	if(mNumberErrorsFound > 0)
	{
		BOX_WARNING("Finished checking store account ID " <<
			BOX_FORMAT_ACCOUNT(mAccountID) << ": " <<
			mNumberErrorsFound << " errors found");
		if(!mFixErrors)
		{
			BOX_WARNING("No changes to the store account "
				"have been made.");
		}
		if(!mFixErrors && mNumberErrorsFound > 0)
		{
			BOX_WARNING("Run again with fix option to "
				"fix these errors");
		}
		if(mFixErrors && mNumberErrorsFound > 0)
		{
			BOX_WARNING("You should now use bbackupquery "
				"on the client machine to examine the store.");
			if(mLostAndFoundDirectoryID != 0)
			{
				BOX_WARNING("A lost+found directory was "
					"created in the account root.\n"
					"This contains files and directories "
					"which could not be matched to "
					"existing directories.\n"\
					"bbackupd will delete this directory "
					"in a few days time.");
			}
		}
	}
	else
	{
		BOX_NOTICE("Finished checking store account ID " <<
			BOX_FORMAT_ACCOUNT(mAccountID) << ": "
			"no errors found");
	}
}
示例#26
0
bool DirectGraphicsFont::LoadFont(const char *Filename, int xts, int yts,
								  int xCharsize, int yCharsize, int xChars,int yChars)
{
	mTexture = new (DirectGraphicsSprite);
	if (!mTexture->LoadImage(Filename, xts, yts, xCharsize, yCharsize, xChars, 0))
		return false;

	// Grösse setzen
	//
	mXCharSize		= xCharsize;
	mYCharSize		= yCharsize;
	mXChars			= xChars;
	mXTextureSize	= xts;
	mYTextureSize	= yts;

	// Länge der einzelnen Zeichen aus der Grafik bestimmen
	//

	// Geladene Font Textur locken
	//
#if defined(PLATFORM_DIRECTX)
	D3DSURFACE_DESC d3dsd;
	D3DLOCKED_RECT  d3dlr;

	HRESULT hresult;

	mTexture->itsTexture->GetLevelDesc(0, &d3dsd);
	hresult = mTexture->itsTexture->LockRect    (0, &d3dlr, 0, 0 );

	// Fehler beim Locken ?
	if (hresult != D3D_OK)
		Protokoll.WriteText("error locking font texture!", true);

	// Colorkey feststellen
	DWORD key = ((DWORD*)d3dlr.pBits)[0];
#elif defined(PLATFORM_SDL)
	image_t image;
	char Temp[256];
	char *pData;
	unsigned long Size;

	if (CommandLineParams.RunOwnLevelList == true)
	{
	    sprintf_s(Temp, "levels/%s/%s", CommandLineParams.OwnLevelList, Filename);
		if (FileExists(Temp))
		{
			loadImage(image, Temp);
		}
	}

	if (image.data == NULL)
	{
	    sprintf_s(Temp, "data/%s", Filename);
		if (FileExists(Temp))
		{
			loadImage(image, Temp);
		}
	}

	if (image.data == NULL)
	{
		if (urarlib_get(&pData, &Size, Filename, RARFILENAME, convertText(RARFILEPASSWORD)) != false)
	    {
			loadImage(image, pData, Size);
			free(pData);
		}
	}

	if (image.data  == NULL)
	{
		return true;
	}

#if 1
    /* menufont.png: pixel at (0,0) (upper left corner) is part of a char/glyph,
       so pick key from lower left corner. Maybe in DirectX image is flipped
       vertically? */

    DWORD key = (((DWORD*)image.data )[image.w * (image.h - 1)]);
#else
    DWORD key = ((DWORD*)image.data )[0];
#endif

/* // PICKLE Not OpenGLES compat, left for info
    int textureWidth, textureHeight;
    glBindTexture( GL_TEXTURE_2D, mTexture->itsTexture );
    glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &textureWidth );
    glGetTexLevelParameteriv( GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &textureHeight );

    GLubyte *buffer = (GLubyte *)malloc(textureWidth*textureHeight*4);
    glGetTexImage( GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer );
    DWORD key = ((DWORD*)buffer)[0];

    glBindTexture( GL_TEXTURE_2D, 0 );
*/
#endif
	//key = 0;

	// Einzelne Zeichen durchgehen
	for (int i=0; i < xChars; i++)
	 for (int j=0; j < yChars; j++)
	 {
		int		last  = 0;
		bool	found = false;

		for (int k = 0; k<xCharsize; k++)
		{
			found = false;

			for (int l = 0; l<yCharsize; l++)
			{
#if defined(PLATFORM_DIRECTX)
				if (((DWORD*)d3dlr.pBits)[(j * yCharsize + l) * d3dsd.Width + (i*xCharsize + k)] != key)
					found = true;
#elif defined(PLATFORM_SDL)
				if (((DWORD*)image.data)[(j * yCharsize + l) * image.w + (i*xCharsize + k)] != key)
					found = true;
/*
				if (((DWORD*)buffer)[(j * yCharsize + l) * textureWidth + (i*xCharsize + k)] != key)
					found = true;
*/
#endif
			}

			if (found == true)
				last = k;
		}

		mCharLength[j * xChars + i] = last+1;
	 }

#if defined(PLATFORM_DIRECTX)
	// Unlocken
	mTexture->itsTexture->UnlockRect(0);
#elif defined(PLATFORM_SDL)
    delete [] image.data;
#endif

	return false;
}
示例#27
0
void FilesExist()
{
  FileExists("dissent.ini");
  FileExists("private_key");
  FileExists("public_key");
}
int main(int argc, char *argv[]) 
{
  int time_limit;
  char name[1000];
  double cutoff=0.0;
  ListGraph g;
  EdgeWeight lpvar(g);
  EdgeWeight weight(g);
  NodeName vname(g);
  ListGraph::NodeMap<double> posx(g),posy(g);
  string filename;

  int seed=1;


  // uncomment one of these lines to change default pdf reader, or insert new one
  //set_pdfreader("open");    // pdf reader for Mac OS X
  //set_pdfreader("xpdf");    // pdf reader for Linux
  //set_pdfreader("evince");  // pdf reader for Linux

  srand48(seed);
  time_limit = 3600; // solution must be obtained within time_limit seconds
  if (argc!=2) {cout<< endl << "Usage: "<< argv[0]<<" <graph_filename>"<<endl << endl <<
      "Example: " << argv[0] << " gr_berlin52" << endl <<
      "         " << argv[0] << " gr_att48" << endl << endl; exit(0);}
  
  else if (!FileExists(argv[1])) {cout<<"File "<<argv[1]<<" does not exist."<<endl; exit(0);}
  filename = argv[1];
  
  // Read the graph
  if (!ReadListGraph(filename,g,vname,weight,posx,posy)) 
    {cout<<"Error reading graph file "<<argv[1]<<"."<<endl;exit(0);}

  TSP_Data tsp(g,vname,posx,posy,weight); 
  ListGraph::EdgeMap<GRBVar> x(g);
  GRBEnv env = GRBEnv();
  GRBModel model = GRBModel(env);
#if GUROBI_NEWVERSION
  model.getEnv().set(GRB_IntParam_LazyConstraints, 1);
  model.getEnv().set(GRB_IntParam_Seed, seed);
#else
  model.getEnv().set(GRB_IntParam_DualReductions, 0); // Dual reductions must be disabled when using lazy constraints
#endif
  model.set(GRB_StringAttr_ModelName, "Undirected TSP with GUROBI"); // name to the problem
  model.set(GRB_IntAttr_ModelSense, GRB_MINIMIZE); // is a minimization problem
  
  // Add one binary variable for each edge and also sets its cost in the objective function
  for (ListGraph::EdgeIt e(g); e!=INVALID; ++e) {
    sprintf(name,"x_%s_%s",vname[g.u(e)].c_str(),vname[g.v(e)].c_str());
    x[e] = model.addVar(0.0, 1.0, weight[e],GRB_BINARY,name);
  }
  model.update(); // run update to use model inserted variables

  // Add degree constraint for each node (sum of solution edges incident to a node is 2)
  for (ListGraph::NodeIt v(g); v!=INVALID; ++v) {
    GRBLinExpr expr;
    for (ListGraph::IncEdgeIt e(g,v); e!=INVALID; ++e) expr += x[e];
    //aqui model.addConstr(expr == 2 ); what? ignorou!
    model.addConstr(expr == 2 );

  }

  try {
    model.update(); // Process any pending model modifications.
    if (time_limit >= 0) model.getEnv().set(GRB_DoubleParam_TimeLimit,time_limit);

    subtourelim cb = subtourelim(tsp , x);
    model.setCallback(&cb);
    
    tsp.max_perturb2opt_it = 200; //1000; // number of iterations used in heuristic TSP_Perturb2OPT
    TSP_Perturb2OPT(tsp);
    if (tsp.BestCircuitValue < DBL_MAX) cutoff = tsp.BestCircuitValue-BC_EPS; // 
    // optimum value for gr_a280=2579, gr_xqf131=566.422, gr_drilling198=15808.652
    if (cutoff > 0) model.getEnv().set(GRB_DoubleParam_Cutoff, cutoff );
    model.update(); // Process any pending model modifications.
    model.optimize();

    double soma=0.0;
    for (ListGraph::EdgeIt e(g); e!=INVALID; ++e) {
      lpvar[e] = x[e].get(GRB_DoubleAttr_X);
      if (lpvar[e] > 1-BC_EPS ) {
	soma += weight[e];
	if (
	    (vname[g.u(e)] == "243")||(vname[g.v(e)] == "243") ||
	    (vname[g.u(e)] == "242")||(vname[g.v(e)] == "242")
	    ) {
	  cout << "Achei, x("<< vname[g.u(e)] << " , " << vname[g.v(e)] << " = " << lpvar[e] <<"\n";
	}
      }
    }

    cout << "Solution cost = "<< soma << endl;
    Update_Circuit(tsp,x); // Update the circuit in x to tsp circuit variable (if better)
    ViewTspCircuit(tsp);

  }catch (...) {
    if (tsp.BestCircuitValue < DBL_MAX) {
      cout << "Heuristic obtained optimum solution"  << endl;
      ViewTspCircuit(tsp);
      return 0;
    }else {
      cout << "Graph is infeasible"  << endl;
      return 1;
    }
  }
}
示例#29
0
文件: System.cpp 项目: armm77/AscEmu
int main(int argc, char * arg[])
{
    printf("Map & DBC Extractor\n");
    printf("===================\n\n");

    HandleArgs(argc, arg);

    int FirstLocale = -1;
    uint32 build = 0;

    for (int i = 0; i < LANG_COUNT; i++)
    {
        char tmp1[512];
        sprintf(tmp1, "%s/Data/%s/locale-%s.MPQ", input_path, langs[i], langs[i]);
        if (FileExists(tmp1))
        {
            printf("Detected locale: %s\n", langs[i]);

            //Open MPQs
            LoadLocaleMPQFiles(i);

            if((CONF_extract & EXTRACT_DBC) == 0)
            {
                FirstLocale = i;
                build = ReadBuild(FirstLocale);
                printf("Detected client build: %u\n", build);
                break;
            }

            //Extract DBC files
            if(FirstLocale < 0)
            {
                FirstLocale = i;
                build = ReadBuild(FirstLocale);
                printf("Detected client build: %u\n", build);
                ExtractDBCFiles(i, true);
            }
            else
                ExtractDBCFiles(i, false);

            //Close MPQs
            CloseMPQFiles();
        }
    }

    if(FirstLocale < 0)
    {
        printf("No locales detected\n");
        return 0;
    }

    if (CONF_extract & EXTRACT_MAP)
    {
        printf("Using locale: %s\n", langs[FirstLocale]);

        // Open MPQs
        LoadLocaleMPQFiles(FirstLocale);
        LoadCommonMPQFiles();

        // Extract maps
        ExtractMapsFromMpq(build);

        // Close MPQs
        CloseMPQFiles();
    }

    return 0;
}
示例#30
0
// Returns true, if application was found in registry:
// [HKCU|HKLM]\Software\Microsoft\Windows\CurrentVersion\App Paths
// Also, function may change local process %PATH% variable
bool SearchAppPaths(LPCWSTR asFilePath, CmdArg& rsFound, bool abSetPath, CmdArg* rpsPathRestore /*= NULL*/)
{
	if (rpsPathRestore)
		rpsPathRestore->Empty();

	if (!asFilePath || !*asFilePath)
		return false;

	LPCWSTR pszSearchFile = PointToName(asFilePath);
	LPCWSTR pszExt = PointToExt(pszSearchFile);

	// Lets try find it in "App Paths"
	// "HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths\"
	// "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"
	LPCWSTR pszRoot = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\";
	HKEY hk; LONG lRc;
	CmdArg lsName; lsName.Attach(lstrmerge(pszRoot, pszSearchFile, pszExt ? NULL : L".exe"));
	// Seems like 32-bit and 64-bit registry branches are the same now, but just in case - will check both
	DWORD nWOW[2] = {WIN3264TEST(KEY_WOW64_32KEY,KEY_WOW64_64KEY), WIN3264TEST(KEY_WOW64_64KEY,KEY_WOW64_32KEY)};
	for (int i = 0; i < 3; i++)
	{
		bool bFound = false;
		DWORD nFlags = ((i && IsWindows64()) ? nWOW[i-1] : 0);
		if ((i == 2) && !nFlags)
			break; // This is 32-bit OS
		lRc = RegOpenKeyEx(i ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER, lsName, 0, KEY_READ|nFlags, &hk);
		if (lRc != 0) continue;
		wchar_t szVal[MAX_PATH+1] = L"";
		DWORD nType, nSize = sizeof(szVal)-sizeof(szVal[0]);
		lRc = RegQueryValueEx(hk, NULL, NULL, &nType, (LPBYTE)szVal, &nSize);
		if (lRc == 0)
		{
			wchar_t *pszCheck = NULL;
			if (nType == REG_SZ)
			{
				pszCheck = szVal;
			}
			else if (nType == REG_EXPAND_SZ)
			{
				pszCheck = ExpandEnvStr(szVal);
			}
			// May be quoted
			if (pszCheck)
			{
				LPCWSTR pszPath = Unquote(pszCheck, true);
				if (FileExists(pszPath))
				{
					// asFilePath will be invalid after .Set
					rsFound.Set(pszPath);
					bFound = true;

					if (pszCheck != szVal)
						free(pszCheck);

					// The program may require additional "%PATH%". So, if allowed...
					if (abSetPath)
					{
						nSize = 0;
						lRc = RegQueryValueEx(hk, L"PATH", NULL, &nType, NULL, &nSize);
						if (lRc == 0 && nSize)
						{
							wchar_t* pszCurPath = GetEnvVar(L"PATH");
							wchar_t* pszAddPath = (wchar_t*)calloc(nSize+4,1);
							wchar_t* pszNewPath = NULL;
							if (pszAddPath)
							{
								lRc = RegQueryValueEx(hk, L"PATH", NULL, &nType, (LPBYTE)pszAddPath, &nSize);
								if (lRc == 0 && *pszAddPath)
								{
									// Если в "%PATH%" этого нет (в начале) - принудительно добавить
									int iCurLen = pszCurPath ? lstrlen(pszCurPath) : 0;
									int iAddLen = lstrlen(pszAddPath);
									bool bNeedAdd = true;
									if ((iCurLen >= iAddLen) && (pszCurPath[iAddLen] == L';' || pszCurPath[iAddLen] == 0))
									{
										wchar_t ch = pszCurPath[iAddLen]; pszCurPath[iAddLen] = 0;
										if (lstrcmpi(pszCurPath, pszAddPath) == 0)
											bNeedAdd = false;
										pszCurPath[iAddLen] = ch;
									}
									// Если пути еще нет
									if (bNeedAdd)
									{
										if (rpsPathRestore)
										{
											rpsPathRestore->SavePathVar(pszCurPath);
										}
										pszNewPath = lstrmerge(pszAddPath, L";", pszCurPath);
										if (pszNewPath)
										{
											SetEnvironmentVariable(L"PATH", pszNewPath);
										}
										else
										{
											_ASSERTE(pszNewPath!=NULL && "Allocation failed?");
										}
									}
								}
							}
							SafeFree(pszAddPath);
							SafeFree(pszCurPath);
							SafeFree(pszNewPath);
						}
					}
				}
			}
		}
		RegCloseKey(hk);

		if (bFound)
			return true;
	}

	return false;
}