示例#1
0
文件: DlgMain.c 项目: chrisdone/hugs
void MainCommand(HWND hWnd, int ID)
{
    switch (ID) {
	case IDCANCEL: EndDialog(hWnd, 0); break;
	case ID_OPEN: MainOpenFile(hWnd); break;
	case ID_SCRIPTMAN: ShowScriptMan(); break;
	case ID_EXIT: FireCommand(":quit\n"); break;

	/* Load one of the last 10 open files */
	case ID_MRU+0: case ID_MRU+1: case ID_MRU+2: case ID_MRU+3:
	case ID_MRU+4: case ID_MRU+5: case ID_MRU+6: case ID_MRU+7:
	case ID_MRU+8: case ID_MRU+9:
	    {
		char Command[1000];
		wsprintf(Command, ":load %s", ExpandFileName(MruGetItem(ID-ID_MRU)));
		FireCommand(Command);
	    }
	    break;

	// EDIT MENU
	case ID_CUT: RtfWindowClipboard(WM_CUT); break;
	case ID_COPY: RtfWindowClipboard(WM_COPY); break;
	case ID_PASTE: RtfWindowClipboard(WM_PASTE); break;
	case ID_CLEARSCREEN: RtfWindowClear(); break;
	case ID_DELETE: RtfWindowDelete(); break;
	case ID_SELECTALL: RtfWindowSelectAll(); break;
	case ID_GOPREVIOUS: RtfWindowHistory(-1); break;
	case ID_GONEXT: RtfWindowHistory(+1); break;


	// ACTIONS MENU
	// Reload script files
	case ID_COMPILE: case ID_MAKE: FireCommand(":reload"); break;
	case ID_CLEARALL: FireCommand(":load"); break;
	case ID_GOEDIT: FireCommand(":edit"); break;

	/* Stop program execution */
	case ID_STOP:
	    MessageBeep(0xFFFFFFFF);
	    AbortExecution();
	    break;

	/* Evaluate main expression */
	case ID_RUN:
	    {
		char Buffer[1000];
		RtfWindowGetCommand(Buffer);
		if (Buffer[0] == '\0')
			FireCommand(":main");
		else
		    FireCommand(Buffer);
	    }
	    break;

	/* Set interpreter options using dialog box */
	case ID_SETOPTIONS:
	    if (ShowOptionsDialog(hWnd))
		RtfWindowUpdateFont();
	    break;


	// BROWSE MENU
	case ID_BROWSEHIERARCHY: DrawClassesHierarchy(); break;
	case ID_BROWSECLASSES: DoBrowseClasses(); break;
	case ID_BROWSENAMES: DoBrowseNames(); break;
	case ID_BROWSETYCONS: DoBrowseTycons(); break;

	// HELP MENU
	case ID_HELPCONTENTS: ExecuteFileDocs("hugs98.chm"); break;
	case ID_HELPCOMMANDS: FireCommand(":?\n"); break;
	case ID_LIBRARIES: ExecuteFile("http://www.haskell.org/ghc/docs/latest/html/libraries/index.html"); break;
	case ID_WWWHASKELL: ExecuteFile("http://haskell.org/"); break;
	case ID_WWWHUGS: ExecuteFile("http://haskell.org/hugs/"); break;
	case ID_ABOUT: ShowAboutDialog(hWnd); break;
    }
}
示例#2
0
void listener::findDestination(SOCKET socket,TCHAR **destination, int *dport)
{
	TCHAR buf[1000];
	int pos=0;

	sockaddr_in inAddr;
	int addrLen=sizeof(inAddr);
	getpeername(socket,(sockaddr *)&inAddr,&addrLen);

	while(rules[pos].type!=RULES_T_EOL)
	{
		TCHAR TSTRinAddr[100];

		wsprintf(TSTRinAddr,_T("%d.%d.%d.%d"),inAddr.sin_addr.S_un.S_un_b.s_b1,inAddr.sin_addr.S_un.S_un_b.s_b2,inAddr.sin_addr.S_un.S_un_b.s_b3,inAddr.sin_addr.S_un.S_un_b.s_b4);

		char *szInaddr=UnicodeToCChar(TSTRinAddr);
		char *szMatch=UnicodeToCChar(rules[pos].match);
		
		boost::RegEx *r=new boost::RegEx(szMatch);		
		bool match=r->Match(szInaddr);
		delete(r);
		delete(szInaddr);
		delete(szMatch);
		SvcDebugOut(_T("Before match\r\n"));
		if(match)
		{
			SvcDebugOut(_T("match=true\r\n"));
			if(rules[pos].type==RULES_T_FORWARD)
			{	
				SvcDebugOut(_T("Forw\r\n"));
				wsprintf(buf,_T("Client connected from %d.%d.%d.%d to port %d. Forwarding it to %s:%d\r\n")
					,inAddr.sin_addr.S_un.S_un_b.s_b1,inAddr.sin_addr.S_un.S_un_b.s_b2,inAddr.sin_addr.S_un.S_un_b.s_b3,inAddr.sin_addr.S_un.S_un_b.s_b4
					,port,rules[pos].dest,rules[pos].destPort);
				SvcDebugOut(buf);
				*destination=rules[pos].dest;
				*dport=rules[pos].destPort;
				return;
			}

			if(rules[pos].type==RULES_T_DENY)
			{	
				wsprintf(buf,_T("Client connected from %d.%d.%d.%d to port %d. Dropping because deny rule:%s\r\n")
					,inAddr.sin_addr.S_un.S_un_b.s_b1,inAddr.sin_addr.S_un.S_un_b.s_b2,inAddr.sin_addr.S_un.S_un_b.s_b3,inAddr.sin_addr.S_un.S_un_b.s_b4
					,port,rules[pos].match);
				SvcDebugOut(buf);

				*destination=NULL;
				*dport=0;
				return;
			}
		}
		pos++;
		SvcDebugOut(_T("pos++\r\n"));
	}

	wsprintf(buf,_T("Client connected from %d.%d.%d.%d to port %d. Dropping because hitting end of rules\r\n")
					,inAddr.sin_addr.S_un.S_un_b.s_b1,inAddr.sin_addr.S_un.S_un_b.s_b2,inAddr.sin_addr.S_un.S_un_b.s_b3,inAddr.sin_addr.S_un.S_un_b.s_b4);
	SvcDebugOut(buf);
	*destination=NULL;
	*dport=0;
}
//---------------------------------------------------------------------------//
bool CAddInRawPrinter::CallAsProc(const long lMethodNum,
                    tVariant* paParams, const long lSizeArray)
{ 
    switch(lMethodNum)
    { 
    case eMeth_Open:
		{
			if (hPrinter) {
				ClosePrinter(hPrinter);
				hPrinter = NULL;
			}

			WCHAR_T *m_PrinterName = paParams[0].pwstrVal;
			uint32_t len = paParams[0].wstrLen;
			uint32_t sz = sizeof(WCHAR_T)*(len + 1);
		
			if (PrinterName) {
				m_iMemory->FreeMemory(reinterpret_cast<void**>(&PrinterName));
				PrinterName = NULL;
				//delete PrinterName;
			}

			{
				m_iMemory->AllocMemory(reinterpret_cast<void**>(&PrinterName), sz);
				//PrinterName = new WCHAR_T[len + 1];
			}
			memcpy(reinterpret_cast<void*>(PrinterName), reinterpret_cast<void*>(m_PrinterName), sz);
			PrinterName[len] = 0;
			
			
			wchar_t *wp_Name = NULL;
			::convFromShortWchar(&wp_Name, PrinterName, len + 1);
			
			if (!OpenPrinterW(wp_Name, &hPrinter, NULL)) {
				wchar_t buf[512];
				wsprintf(buf, L"OpenPrinterW(%s) failed with code: %u", wp_Name, GetLastError());
				addError(1, L"Printer error", buf, 1);
			}
			
			delete [] wp_Name;
			
		}
        break;

    case eMeth_Close:
		
		if (PrinterName) {
			m_iMemory->FreeMemory(reinterpret_cast<void**>(&PrinterName));
			//delete PrinterName;
		}
		ClosePrinter(hPrinter);

		break;

    case eMeth_SendRaw:

		{
			WCHAR_T *wc = paParams[0].pwstrVal;
			char *utf8 = ConvToUtf8(wc);

			DWORD len = strlen(utf8), sent;
			if (!WritePrinter(hPrinter, utf8, len, &sent))
				addError(2, L"Failed to send data to printer!", L"Failed!", 2);

			delete [] utf8;
		}
        break;

	case eMeth_StartDocument:

		{
			
			wchar_t *doc_name = NULL;
			wchar_t *data_type = NULL;
			::convFromShortWchar(&doc_name, paParams[0].pwstrVal);
			::convFromShortWchar(&data_type, paParams[1].pwstrVal);

			DOC_INFO_1 doc;
			doc.pDocName = doc_name;
			doc.pOutputFile = NULL;
			doc.pDatatype = data_type;

			DWORD print_job = StartDocPrinter(hPrinter, 1, (LPBYTE)&doc);

			delete [] doc_name;
			delete [] data_type;
		}

		break;

	case eMeth_EndDocument:

		EndDocPrinter(hPrinter);
		break;

    default:
        return false;
    }

    return true;
}
示例#4
0
/****************************************************************************
*
*  FUNCTION: DoTheMenuThing(HWND hwnd, 
*                           LPSHELLFOLDER lpsfParent,
*                           LPITEMIDLIST  lpi,
*                           LPPOINT lppt)
*
*  PURPOSE: Displays a popup context menu, given a parent shell folder,
*           relative item id and screen location.
*
*  PARAMETERS:
*    hwnd       - Parent window handle
*    lpsfParent - Pointer to parent shell folder.
*    lpi        - Pointer to item id that is relative to lpsfParent
*    lppt       - Screen location of where to popup the menu.
*
*  RETURN VALUE:
*    Returns TRUE on success, FALSE on failure
*
****************************************************************************/
BOOL
Pidl::DoTheMenuThing(HWND hwnd, LPSHELLFOLDER lpsfParent,
     LPITEMIDLIST  lpi, LPPOINT lppt)
{
    LPCONTEXTMENU lpcm;
    HRESULT       hr;
    char          szTemp[64];
    CMINVOKECOMMANDINFO cmi;
//    DWORD               dwAttribs=0;
    int                 idCmd;
    HMENU               hMenu;
    BOOL                bSuccess=TRUE;

    hr=lpsfParent->GetUIObjectOf(hwnd,
        1,  //Number of objects to get attributes of
        (const struct _ITEMIDLIST **)&lpi,
        IID_IContextMenu,
        0,
        (LPVOID *)&lpcm);
    if (SUCCEEDED(hr))  
    {
       hMenu = CreatePopupMenu();

       if (hMenu)
       {
          hr=lpcm->QueryContextMenu(hMenu, 0, 1, 0x7fff, CMF_EXPLORE);
          if (SUCCEEDED(hr))
          {
             idCmd=TrackPopupMenu(hMenu, 
                TPM_LEFTALIGN | TPM_RETURNCMD | TPM_RIGHTBUTTON, 
                lppt->x, lppt->y, 0, hwnd, NULL);

             if (idCmd)
             {
                cmi.cbSize = sizeof(CMINVOKECOMMANDINFO);
                cmi.fMask  = 0;
                cmi.hwnd   = hwnd;
                cmi.lpVerb = MAKEINTRESOURCE(idCmd-1);
                cmi.lpParameters = NULL;
                cmi.lpDirectory  = NULL;
                cmi.nShow        = SW_SHOWNORMAL;
                cmi.dwHotKey     = 0;
                cmi.hIcon        = NULL;
                hr=lpcm->InvokeCommand(&cmi);
                if (!SUCCEEDED(hr))  
                {
                   wsprintf(szTemp, "InvokeCommand failed. hr=%lx", hr);
                   AfxMessageBox(szTemp);
                }
             }

          }
          else
             bSuccess = FALSE;

          DestroyMenu(hMenu);
       }
       else
          bSuccess = FALSE;

       lpcm->Release();
    } 
    else
    {
       wsprintf(szTemp, "GetUIObjectOf failed! hr=%lx", hr);
       AfxMessageBox(szTemp );
       bSuccess = FALSE;
    }
    return bSuccess;
}
示例#5
0
static LPSTR GetColorString(LPCOLORINFO lpColor, COLORSPACE ColorSpace,
					LPSTR lpColorString)
/***********************************************************************/
{
STRING szFormat, szPercent;
LPSTR lpString;

*lpColorString = 0;
if (!Control.DisplayPixelValue && AstralStr(IDS_PERCENT, &lpString))
	lstrcpy(szPercent, lpString);
else
	szPercent[0] = '\0';
switch (ColorSpace)
	{
	case CS_GRAY:
	if (!AstralStr(IDS_GRAYVALUE, &lpString))
		break;
	lstrcpy(szFormat, lpString);
	wsprintf(lpColorString, szFormat,
		GRAY2DISP(lpColor->gray),
		(LPSTR)szPercent);
	break;

	case CS_RGB:
	if (!AstralStr(IDS_RGBVALUE, &lpString))
		break;
	lstrcpy(szFormat, lpString);
	wsprintf(lpColorString, szFormat,
		PIX2DISP(lpColor->rgb.red),
		PIX2DISP(lpColor->rgb.green),
		PIX2DISP(lpColor->rgb.blue),
		(LPSTR)szPercent);
	break;

	case CS_CMYK:
	if (!AstralStr(IDS_CMYKVALUE, &lpString))
		break;
	lstrcpy(szFormat, lpString);
	wsprintf(lpColorString, szFormat,
		PIX2DISP(lpColor->cmyk.c),
		PIX2DISP(lpColor->cmyk.m),
		PIX2DISP(lpColor->cmyk.y),
		PIX2DISP(lpColor->cmyk.k),
		(LPSTR)szPercent);
	break;

	case CS_HSL:
	if (!AstralStr(IDS_HSLVALUE, &lpString))
		break;
	lstrcpy(szFormat, lpString);
	wsprintf(lpColorString, szFormat,
		TOANGLE(lpColor->hsl.hue),
		TOPERCENT(lpColor->hsl.sat),
		TOPERCENT(lpColor->hsl.lum));
	break;

	default:
	break;
	}
return(lpColorString);
}
示例#6
0
BOOL HexStrIncreaseSkipAlpha(TCHAR *strValue,int spn,TCHAR *strNEW,int len)
{
    int         szChar;
    TCHAR       *STR;
    int         newChar;
    BOOL        isINC;
    int         i;
    int         nLen;
    if ( spn > 16 ||spn < -16 ) {  //here must ensure input is hex string and the span is less than 16,
                                                           //otherwise  will get wrong result 
        return FALSE;
    }
    if(0 > spn){
        spn   = -spn;
        isINC   = FALSE;
    } else if(0 < spn){
        isINC   = TRUE;
    } else {
        return FALSE;
    }
    nLen = _tcslen(strValue);
    if( NULL != strNEW ){
        if(nLen + 1 > len ){
            return FALSE;
        }
        wsprintf(strNEW,TEXT("%s"),strValue);
        STR = strNEW;
    } else {
        STR = strValue;
    }
    if(isINC) {
        for (i = nLen - 1;i >= 0;i-- ) {
            szChar  = STR[i];
            if(szChar >= TEXT('0')&&szChar <= TEXT('9')){
                newChar = szChar -  TEXT('0') + spn;
            }else if (szChar >= TEXT('A')&&szChar <= TEXT('F')){
                newChar = szChar -  TEXT('A') + spn + 10;
            }else if (szChar >= TEXT('a')&&szChar <= TEXT('f')){
                newChar = szChar -  TEXT('a') + spn + 10;
            } else {
                continue;
            }
            if(HEXTOCHARP(newChar,&szChar)){    //the input of HEXTOCHARP range is from 0 + 0 to 15 + 16
                                                
                STR[i]  =(TCHAR)szChar;
                spn     = 1;
                continue;
            } 
            STR[i] = (TCHAR)szChar;
            break;
        }
    } else {
        for (i = nLen-1;i >= 0;i--) {
            szChar  = STR[i];
            if(szChar >= TEXT('0')&&szChar <= TEXT('9')){
                newChar = szChar -  TEXT('0') - spn;
            }else if (szChar >= TEXT('A')&&szChar <= TEXT('F')){
                newChar = szChar -  TEXT('A') - spn + 10;
            }else if (szChar >= TEXT('a')&&szChar <= TEXT('f')){
                newChar = szChar -  TEXT('a') - spn + 10;
            } else {
                continue;
            }
            if(HEXTOCHARM(newChar,&szChar)){ //the input of HEXTOCHARP range is from -16 to 15
                STR[i]  =(TCHAR)szChar;
                spn     = 1;
                continue;
            } 
            STR[i] = (TCHAR)szChar;
            break;
        }
    }
    return TRUE;
}
示例#7
0
void Filesets_General_OnEndTask_InitDialog (HWND hDlg, LPTASKPACKET ptp, LPIDENT lpi)
{
   LPTSTR pszText;

   TCHAR szUnknown[ cchRESOURCE ];
   GetString (szUnknown, IDS_UNKNOWN);

   if (!ptp->rc)
      {
      SetDlgItemText (hDlg, IDC_SET_CREATEDATE, szUnknown);
      SetDlgItemText (hDlg, IDC_SET_UPDATEDATE, szUnknown);
      SetDlgItemText (hDlg, IDC_SET_ACCESSDATE, szUnknown);
      SetDlgItemText (hDlg, IDC_SET_BACKUPDATE, szUnknown);
      SetDlgItemText (hDlg, IDC_SET_USAGE, szUnknown);
      SetDlgItemText (hDlg, IDC_SET_STATUS, szUnknown);
      SetDlgItemText (hDlg, IDC_SET_FILES, szUnknown);

      TCHAR szSvrName[ cchNAME ];
      TCHAR szAggName[ cchNAME ];
      TCHAR szSetName[ cchNAME ];
      lpi->GetServerName (szSvrName);
      lpi->GetAggregateName (szAggName);
      lpi->GetFilesetName (szSetName);
      ErrorDialog (ptp->status, IDS_ERROR_REFRESH_FILESET_STATUS, TEXT("%s%s%s"), szSvrName, szAggName, szSetName);
      }
   else
      {
      TCHAR szText[ cchRESOURCE ];

      EnableWindow (GetDlgItem (hDlg, IDC_SET_LOCK), TRUE);
      EnableWindow (GetDlgItem (hDlg, IDC_SET_UNLOCK), TRUE);
      EnableWindow (GetDlgItem (hDlg, IDC_SET_QUOTA), TRUE);
      EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN), TRUE);
      EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN_SETFULL_DEF), TRUE);
      EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN_SETFULL), TRUE);
      EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN_SETFULL_PERCENT), TRUE);
      EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN_SETFULL_DESC), TRUE);

      if (!FormatTime (szText, TEXT("%s"), &TASKDATA(ptp)->fs.timeCreation))
         SetDlgItemText (hDlg, IDC_SET_CREATEDATE, szUnknown);
      else
         SetDlgItemText (hDlg, IDC_SET_CREATEDATE, szText);

      if (!FormatTime (szText, TEXT("%s"), &TASKDATA(ptp)->fs.timeLastUpdate))
         SetDlgItemText (hDlg, IDC_SET_UPDATEDATE, szUnknown);
      else
         SetDlgItemText (hDlg, IDC_SET_UPDATEDATE, szText);

      if (!FormatTime (szText, TEXT("%s"), &TASKDATA(ptp)->fs.timeLastAccess))
         SetDlgItemText (hDlg, IDC_SET_ACCESSDATE, szUnknown);
      else
         SetDlgItemText (hDlg, IDC_SET_ACCESSDATE, szText);

      if (!FormatTime (szText, TEXT("%s"), &TASKDATA(ptp)->fs.timeLastBackup))
         SetDlgItemText (hDlg, IDC_SET_BACKUPDATE, szUnknown);
      else
         SetDlgItemText (hDlg, IDC_SET_BACKUPDATE, szText);

      wsprintf (szText, TEXT("%lu"), TASKDATA(ptp)->fs.nFiles);
      SetDlgItemText (hDlg, IDC_SET_FILES, szText);

      size_t nAlerts = Alert_GetCount (lpi);
      if (nAlerts == 1)
         {
         GetString (szText, IDS_SETSTATUS_1ALERT);
         SetDlgItemText (hDlg, IDC_SET_STATUS, szText);
         }
      else if (nAlerts > 1)
         {
         pszText = FormatString (IDS_SETSTATUS_2ALERT, TEXT("%lu"), nAlerts);
         SetDlgItemText (hDlg, IDC_SET_STATUS, pszText);
         FreeString (pszText);
         }
      else // (nAlerts == 0)
         {
         if (TASKDATA(ptp)->fs.State & fsBUSY)
            GetString (szText, IDS_SETSTATUS_BUSY);
         else if (TASKDATA(ptp)->fs.State & fsSALVAGE)
            GetString (szText, IDS_SETSTATUS_SALVAGE);
         else if (TASKDATA(ptp)->fs.State & fsMOVED)
            GetString (szText, IDS_SETSTATUS_MOVED);
         else if (TASKDATA(ptp)->fs.State & fsLOCKED)
            GetString (szText, IDS_SETSTATUS_LOCKED);
         else if (TASKDATA(ptp)->fs.State & fsNO_VOL)
            GetString (szText, IDS_SETSTATUS_NO_VOL);
         else
            GetString (szText, IDS_STATUS_NOALERTS);
         SetDlgItemText (hDlg, IDC_SET_STATUS, szText);
         }

      if (TASKDATA(ptp)->fs.Type == ftREADWRITE)
         {
         Filesets_DisplayQuota (hDlg, &TASKDATA(ptp)->fs);
         }
      else
         {
         if (TASKDATA(ptp)->fs.Type == ftREPLICA)
            GetString (szText, IDS_USAGE_REPLICA);
         else // (TASKDATA(ptp)->fs.Type == ftCLONE)
            GetString (szText, IDS_USAGE_CLONE);

         pszText = FormatString (szText, TEXT("%.1B"), (double)TASKDATA(ptp)->fs.ckUsed * cb1KB);
         SetDlgItemText (hDlg, IDC_SET_USAGE, pszText);
         FreeString (pszText);

         if (GetDlgItem (hDlg, IDC_SET_USAGEBAR))
            {
            RECT rUsagebar;
            GetRectInParent (GetDlgItem (hDlg, IDC_SET_USAGEBAR), &rUsagebar);

            HFONT hf = (HFONT)SendMessage (GetDlgItem (hDlg, IDC_SET_USAGEBAR), WM_GETFONT, 0, 0);
            DestroyWindow (GetDlgItem (hDlg, IDC_SET_USAGEBAR));

            if (TASKDATA(ptp)->fs.Type == ftREPLICA)
               GetString (szText, IDS_NO_QUOTA_REPLICA);
            else // (TASKDATA(ptp)->fs.Type == ftCLONE)
               GetString (szText, IDS_NO_QUOTA_CLONE);

            HWND hDesc = CreateWindow (TEXT("static"),
                          szText,
                          WS_CHILD | SS_SIMPLE,
                          rUsagebar.left, rUsagebar.top,
                          cxRECT(rUsagebar), cyRECT(rUsagebar),
                          hDlg,
                          (HMENU)-1,
                          THIS_HINST,
                          0);
            SendMessage (hDesc, WM_SETFONT, (WPARAM)hf, MAKELPARAM(TRUE,0));
            ShowWindow (hDesc, SW_SHOW);
            }

         EnableWindow (GetDlgItem (hDlg, IDC_SET_QUOTA), FALSE);
         EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN), FALSE);
         EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN_SETFULL_DEF), FALSE);
         EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN_SETFULL), FALSE);
         EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN_SETFULL_PERCENT), FALSE);
         EnableWindow (GetDlgItem (hDlg, IDC_SET_WARN_SETFULL_DESC), FALSE);
         }

      if (TASKDATA(ptp)->lpsp->perWarnSetFull == 0)
         {
         GetString (szText, IDS_SETFULL_WARN_OFF);
         SetDlgItemText (hDlg, IDC_SET_WARN_SETFULL_DEF, szText);
         }
      else
         {
         GetString (szText, IDS_SETFULL_WARN_ON);
         pszText = FormatString (szText, TEXT("%lu"), TASKDATA(ptp)->lpsp->perWarnSetFull);
         SetDlgItemText (hDlg, IDC_SET_WARN_SETFULL_DEF, pszText);
         FreeString (pszText);
         }

      CheckDlgButton (hDlg, IDC_SET_WARN, (TASKDATA(ptp)->lpfp->perWarnSetFull != 0));
      if (TASKDATA(ptp)->lpfp->perWarnSetFull != 0)
         {
         if (TASKDATA(ptp)->lpfp->perWarnSetFull != -1)
            CheckDlgButton (hDlg, IDC_SET_WARN_SETFULL, TRUE);
         else
            CheckDlgButton (hDlg, IDC_SET_WARN_SETFULL_DEF, TRUE);
         }

      CreateSpinner (GetDlgItem (hDlg, IDC_SET_WARN_SETFULL_PERCENT),
                     10, FALSE,   // base, signed
                     1,
                     (TASKDATA(ptp)->lpfp->perWarnSetFull == 0 || TASKDATA(ptp)->lpfp->perWarnSetFull == -1) ? perDEFAULT_SETFULL_WARNING : TASKDATA(ptp)->lpfp->perWarnSetFull,
                     100); // min, default, max

      Filesets_General_OnWarnings (hDlg, lpi);
      }
}
示例#8
0
文件: timestmp.cpp 项目: wfmdyh/wecan
// **************************************************************************
// SetDate ()
//
// Description:
//	Set the date.
//
// Parameters:
///	LPCTSTR		lpDate		Pointer to string representation of date.  Date
//							  format is obtained from system.
//	bool		bInitialize	Set to true to initialize member variables.
//
// Returns:
//  bool - true if success
// **************************************************************************
bool CTimeStamp::SetDate (LPCTSTR lpDate, bool bInitialize)
	{
	TCHAR szFmt [32];
	int nRetVal;
	unsigned uMM, uDD, uYYYY;

	// Create a CSafeLock to make this object thread safe.  Our critical
	// section gets locked here, and will automatically be unlocked when the
	// CSafeLock goes out of scope.
	CSafeLock cs (&sm_cs);

	// Formatting info must be initialized:
	if (!stDateFmt.nFmtLen)
		SetDateTimeFormat ();

	// Create a format string using correct separator charactor:
	wsprintf (szFmt, _T("%%d%c%%d%c%%d"),
		*stDateFmt.szSeparator,
		*stDateFmt.szSeparator);

	// Extract month, day and year from input string according to system
	// time format type. _stscanf will return number of fields successfully
	// extracted from input string:
	switch (stDateFmt.nFmt)
		{
		case VDATE_MMDDYY:
			nRetVal = _stscanf (lpDate, szFmt, &uMM, &uDD, &uYYYY);
			break;

		case VDATE_DDMMYY:
			nRetVal = _stscanf (lpDate, szFmt, &uDD, &uMM, &uYYYY);
			break;

		case VDATE_YYMMDD:
			nRetVal = _stscanf (lpDate, szFmt, &uYYYY, &uMM, &uDD);
			break;

		default:
			nRetVal = 0;
			break;
		}

	// _stscanf should have extracted 3 fields from input string.  If not
	// return FALSE to indicate error:
	if (nRetVal != 3)
		return (FALSE);

	// Correct year if given as 2 digits:
	// (If between 90 and 99 assume 19xx.  if less than 90 assume 20xx):
	if (uYYYY < 100)
		uYYYY += (uYYYY >= 90) ? 1900 : 2000;

	// Check for valid month:
	if (uMM < 1 || uMM > 12)
		return (FALSE);

	// Make sure day is a not zero:
	if (uDD < 1)
		return (FALSE);

	// Make sure day is not greater than number of days in month:
	// If February, must account for leap year:
	if (uMM == 2)
		{
		// Use table to check  Use ISLEAP macro to adjust for leap year:
		if (uDD > (unsigned)(anDaysPerMonth [1] + ISLEAP (uYYYY)))
			return (FALSE);
		}

	// If any other month, just use table to check day:
	else
		{
		if (uDD > anDaysPerMonth [uMM - 1])
			return (FALSE);
		}

	// If we make it here, date is valid so save it:
	m_st.wYear = uYYYY;
	m_st.wDay = uDD;
	m_st.wMonth = uMM;

	// Convert date to day of year if specified:
	if (bInitialize)
		ConvertDateToDays ();

	// Return TRUE to indicate success:
	return (TRUE);
	}
示例#9
0
文件: timestmp.cpp 项目: wfmdyh/wecan
// **************************************************************************
// FormatTime ()
//
// Description:
//	Place the current time setting in specified output string buffer.  Format
//  will be obtained from the system.  If output buffer is too small, it will
//  be filled with "#" characters.
//
// Parameters:
//  LPTSTR		szTime		Output string buffer.
//	int			cnChars		Size of output string buffer.
//	bool		bUseSec		Set to true to include seconds.
//
// Returns:
//  void
// **************************************************************************
void CTimeStamp::FormatTime (LPTSTR szTime, int cnChars, bool bUseSec)
	{
	// Can't do anything if we are not given a valid output string
	// pointer, so return:
	if (!szTime)
		return;

	// Create a CSafeLock to make this object thread safe.  Our critical
	// section gets locked here, and will automatically be unlocked when the
	// CSafeLock goes out of scope.
	CSafeLock cs (&sm_cs);

	// Formatting info must be initialized:
	if (!stTimeFmt.nFmtLen)
		SetDateTimeFormat ();

	// Determine the minimum buffer requirements (add 3 characters for
	// seconds if used):
	int nMinChars = (bUseSec) ? stTimeFmt.nFmtLen + 3 : stTimeFmt.nFmtLen;

	// If the buffer is too small then fill with placeholders ("#") and
	// return:
	int i;
	if (cnChars <= nMinChars)
		{
		for (i = 0; i < cnChars; i++)
			szTime [i] = _T('#');

		szTime [i] = 0;
		return;
		}

	// Localize and round up to the nearest second:
	unsigned short wMinute = m_st.wMinute;
	unsigned short wSecond = m_st.wSecond;
	unsigned short wHour = m_st.wHour;

	// Need to round seconds up if milliseconds are >= 500:
	if (m_st.wMilliseconds >= 500)
		{
		// Increment seconds.  If this causes the seconds to equal
		// 60, we need to reset to 0 and increment minutes:
		if (++wSecond == 60)
			{
			wSecond = 0;
			
			// Increment minutes.  If this causes the minutes to equal
			// 60, we need to reset to 0 and increment hours:
			if (++wMinute == 60)
				{
				wMinute = 0;
				
				// Increment hours.  If this causes the hours to equal
				// 24, we need to reset to 0.
				if (++wHour == 24)
					{
					wHour = 0;
					}
				}
			}
		}
	
	// Save the proper separator character:
	TCHAR ch = *stTimeFmt.szSeparator;

	// Set flag if PM:
	bool bNight = (wHour >= 12);

	// Adjust for non-military system time format.  Hour value is currently
	// in 24 hour, military, format.
	if (!stTimeFmt.b24Hr)
		{
		// If PM, subtract 12 (value of 12 is OK as is):
		if (bNight && wHour > 12)
			wHour -= 12;

		// Else if 0, reset to 12:
		else if (!wHour)
			wHour = 12;
		}

	// Format the time with appropriate leading zero and seconds if required:
	if (bUseSec)
		{
		if (!stTimeFmt.bLeadingZero)
			wsprintf (szTime,	_T("%2d%c%02d%c%02d"), wHour, ch, wMinute, ch, wSecond);
		else
			wsprintf (szTime,	_T("%02d%c%02d%c%02d"),	wHour, ch, wMinute, ch, wSecond);
		}
	else
		{
		if (!stTimeFmt.bLeadingZero)
			wsprintf (szTime,	_T("%2d%c%02d"), wHour, ch, wMinute);
		else
			wsprintf (szTime,	_T("%02d%c%02d"),	wHour, ch, wMinute);
		}

	// Apply AM/PM indication if not using 24 hour format:
	if (!stTimeFmt.b24Hr)
		{
		// Add a space:
		lstrcat (szTime, _T(" "));

		// Add "PM" if night, or "AM" if not:
		lstrcat (szTime, (bNight) ? stTimeFmt.szPMString : stTimeFmt.szAMString);
		}
	}
// Handle the packet notification
HRESULT CSynForcePadDlg::OnSynDevicePacket(LONG lSeq)
{

	int evento = 1;

   // evento = 1 -> TOUCH_DOWN
   // evento = 2 -> TOUCH_MOVE
   // evento = 3 -> TOUCH_UP



	if (m_bCanProcessGroups) {
    SynGroup grp;
    // display raw data
    if (SYN_OK == (*m_pDevice)->LoadGroup(grp)) {
      LONG lGroup = grp.GroupNumber();
      
      LONG lForceGrams[MAX_NUM_FORCESENSORS];
      LONG lForceRaw[MAX_NUM_FORCESENSORS];
      LONG lTotal = 0;
      for(ULONG ul = 0; ul < MAX_NUM_FORCESENSORS; ul++) {
        lForceGrams[ul] = grp.Force(ul);
        lForceRaw[ul] = grp.ForceRaw(ul);
        lTotal += lForceGrams[ul];
      }

      TCHAR tszBuffer[100] = {0};
      // only update every 10th packet group, for readability
      if (!(lGroup % 10)) {
        wsprintf(tszBuffer, TEXT("Force %d %d %d %d  grams: %d %d %d %d total(g): %d\n"),
          lForceRaw[0], lForceRaw[1], lForceRaw[2], lForceRaw[3],
          lForceGrams[0], lForceGrams[1], lForceGrams[2], lForceGrams[3], lTotal );
        SetDlgItemText(IDC_STATIC0, tszBuffer);
      }

      for (ULONG ul = 0; ul < m_ulMaxGroupSize; ul++) {
        SynPacket pkt;
        LONG lX, lY, lZ, lForce, lGroup;
        
        grp.Packet(ul, pkt);
        
        // lX = pkt.GetLongProperty(SP_XRaw);
		lX = pkt.GetLongProperty(SP_X);
        lY = pkt.GetLongProperty(SP_YRaw);
        lZ = pkt.GetLongProperty(SP_ZRaw);
        lForce = pkt.GetLongProperty(SP_ZForce);
        lGroup = pkt.GetLongProperty(SP_PacketGroupNumber);

		int x = (int) ul;

        TCHAR tszBuffer[100] = {0};
        // only update every 10th packet group, for readability
        if (!(lGroup % 10)) {
          if (lZ) {
             wsprintf(tszBuffer, TEXT("Finger %d, XRaw %d, YRaw %d, ZRaw %d, Force %d\n"),
               ul, lX, lY, lZ, lForce);

			if(aDados[x] == -1)
			{
				// Colocar o id no array, então é o evento TOUCH_DOWN
				aDados[x] = 1;
				// evento = 1;
				EviaDadosViaSocket(ul, lX, lY, lZ, lForce,1);

			}
			else
			{ 
				// JÁ EXISTE ENTÃOÉ O TOUCH_MOVE
				// evento = 2;
				aDados[x] = 2;
				EviaDadosViaSocket(ul, lX, lY, lZ, lForce,2);
			}

			// Mandando para a aplicação em Java os dados do sensor!
		    // EviaDadosViaSocket(ul, lX, lY, lZ, lForce,aDados[ul]);

          } else {
            
			// Só mando o TOUCH_UP se já tiver mandando m TOUCH_DOWN ou TOUCH_MOVE ANTES!
			if(aDados[x] != -1)
			{
				aDados[x] = -1;
				// RETIRO O DEDO ENTÃO É O EVENTO TOUCH_UP
				EviaDadosViaSocket(ul, 0, 0, 0, 0, 3);
			}
			 wsprintf(tszBuffer, TEXT("Finger %d off the pad.\n"), ul);

          }

          switch(ul) {
            case 0: SetDlgItemText(IDC_STATIC1, tszBuffer); break;
            case 1: SetDlgItemText(IDC_STATIC2, tszBuffer); break;
            case 2: SetDlgItemText(IDC_STATIC3, tszBuffer); break;
            case 3: SetDlgItemText(IDC_STATIC4, tszBuffer); break;
            case 4: SetDlgItemText(IDC_STATIC5, tszBuffer); break;
            default: break;
          }
        }

      }
    }
  } else {
      TCHAR tszBuffer[100] = {0};
      wsprintf(tszBuffer, TEXT("This driver installation does not support"));
      SetDlgItemText(IDC_STATIC2, tszBuffer);
      wsprintf(tszBuffer, TEXT("packet group and force processing.\n"));
      SetDlgItemText(IDC_STATIC4, tszBuffer);
  }

  return 0;
}
示例#11
0
文件: timestmp.cpp 项目: wfmdyh/wecan
// **************************************************************************
// SetDateTimeFormat ()
//
// Description:
//	Obtain date and time format from system.  Called when a program starts up
//	and when win.ini changes
// Parameters:
//  none
//
// Returns:
//  void
// **************************************************************************
void CTimeStamp::SetDateTimeFormat ()
	{
	// Create a CSafeLock to make this object thread safe.  Our critical
	// section gets locked here, and will automatically be unlocked when the
	// CSafeLock goes out of scope.
	CSafeLock cs (&sm_cs);

	TRACE (_T("Reading system date/time settings ...\n"));

	// Create registry section string.  This is where time and date formats
	// are stored:
	LPCTSTR lpintl = _T("intl");

	// Get numerical format properties:
	stDateFmt.nFmt = GetProfileInt (lpintl, _T("iDate"), VDATE_MMDDYY);
	stTimeFmt.b24Hr = GetProfileInt (lpintl, _T("iTime"), FALSE);
	stTimeFmt.bLeadingZero = GetProfileInt (lpintl, _T("iTLZero"), FALSE);

	// Get string format properties:
	GetProfileString (lpintl, _T("sDate"), _T("/"), stDateFmt.szSeparator, 2);
	GetProfileString (lpintl, _T("sTime"), _T(":"), stTimeFmt.szSeparator, 2);
	GetProfileString (lpintl, _T("sShortDate"), _T("M/d/yy"), stDateFmt.szShortDate,
		_countof (stDateFmt.szShortDate));

	GetProfileString (lpintl, _T("s1159"), _T("am"), stTimeFmt.szAMString, 8);
	GetProfileString (lpintl, _T("s2359"), _T("pm"), stTimeFmt.szPMString, 8);


	// Determine where to place leading zeroes:
	int nLen = lstrlen (stDateFmt.szShortDate);

	// Initialize number of leading zero members so that when we increment 
	// for each corresponding field in format string, result will give
	// us the correct number of leading zeros:
	stDateFmt.bMonthLeadingZero = -1;	// Expect at least one digit
	stDateFmt.bDayLeadingZero = -1;		// Expect at least one digit
	stDateFmt.bFullYear = -2;			// Expect at least two digits

	// Process each character in format string.  Add increment leading
	// zero members each time we encounter one of their digit place holders
	// in string:
	for (int i = 0; i < nLen; i++)
		{
		switch (stDateFmt.szShortDate [i])
			{
			// Month place holders:
			case _T('m'):
			case _T('M'):
				++stDateFmt.bMonthLeadingZero;
				break;

			// Day place holders:
			case _T('d'):
			case _T('D'):
				++stDateFmt.bDayLeadingZero;
				break;

			// Year place holders:
			case _T('y'):
			case _T('Y'):
				++stDateFmt.bFullYear;
				break;

			// Skip over all other characters:
			default:
				continue;
			}
		}

	// Construct a format string for date display:
	switch (stDateFmt.nFmt)
		{
		case VDATE_MMDDYY:
			wsprintf (
				stDateFmt.szFmtString,
				_T("%%.%dd%c%%.%dd%c%%.%dd"),
				(stDateFmt.bMonthLeadingZero) ? 2 : 1,
				*stDateFmt.szSeparator,
				(stDateFmt.bDayLeadingZero) ? 2 : 1,
				*stDateFmt.szSeparator,
				(stDateFmt.bFullYear) ? 4 : 2
			);
			break;

		case VDATE_DDMMYY:
			wsprintf (
				stDateFmt.szFmtString,
				_T("%%.%dd%c%%.%dd%c%%.%dd"),
				(stDateFmt.bDayLeadingZero) ? 2 : 1,
				*stDateFmt.szSeparator,
				(stDateFmt.bMonthLeadingZero) ? 2 : 1,
				*stDateFmt.szSeparator,
				(stDateFmt.bFullYear) ? 4 : 2
			);
			break;

		case VDATE_YYMMDD:
			wsprintf (
				stDateFmt.szFmtString,
				_T("%%.%dd%c%%.%dd%c%%.%dd"),
				(stDateFmt.bFullYear) ? 4 : 2,
				*stDateFmt.szSeparator,
				(stDateFmt.bMonthLeadingZero) ? 2 : 1,
				*stDateFmt.szSeparator,
				(stDateFmt.bDayLeadingZero) ? 2 : 1
			);
			break;
		}

	// Initialize the time format length:
	stTimeFmt.nFmtLen = 5; // Minimum (hh:mm)

	// Adjust format length if 12 hour format:
	if (!stTimeFmt.b24Hr)
		{
		int nMaxLen;

		// Save length of "PM" string:
		nMaxLen = lstrlen (stTimeFmt.szPMString);

		// If length of "AM" string is longer than "PM" string, save it
		// instead:
		if (lstrlen (stTimeFmt.szAMString) > nMaxLen)
			nMaxLen = lstrlen (stTimeFmt.szAMString);

		// Add length of "AM" or "PM" string plus 1 for space:
		stTimeFmt.nFmtLen += (nMaxLen + 1);
		}

	// Assign the date format length:
	stDateFmt.nFmtLen = 8;	// Minimum (mm/dd/yy)

	// Add 2 if using 4 digit years:
	if (stDateFmt.bFullYear)
		stDateFmt.nFmtLen += 2;
	}
示例#12
0
///////////////////////////////////////////////////////////////
// EnumChildren - キーのサブキーを列挙する
int CFolderDlg::EnumChildren(HWND hwndTV, HTREEITEM hParent, LPTSTR pszPath)
{
	int rc;
    DWORD nChild;
	HANDLE ff;
	WIN32_FIND_DATA wfd;
	TCHAR szName[MAX_PATH];
	TVINSERTSTRUCT tvis;
	DWORD dwCnt = 0;

	wsprintf (szName, _T("%s\\*.*"), pszPath);

	ff = FindFirstFile (szName, &wfd);
	if (ff != INVALID_HANDLE_VALUE) {
		while (1) {
			if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ||
				wfd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
				// 下位のディレクトリがあるか検査
				nChild = CountChildren (pszPath, wfd.cFileName);

				// メモリカード?
				int nIndex = 1; // default icon index
				if (wfd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) {
					wsprintf(szName, _T("%s\\%s"), pszPath, wfd.cFileName);
					SHFILEINFO shfi;
					SHGetFileInfo(szName, NULL, &shfi, sizeof(shfi), SHGFI_SMALLICON | SHGFI_ICON);
					nIndex = ImageList_AddIcon(m_hImageList, shfi.hIcon);
				}

				// ツリー ビュー コントロールにキーを挿入する
				tvis.hParent      = hParent;
				tvis.hInsertAfter = TVI_SORT;
				tvis.item.mask    = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_CHILDREN;
				tvis.item.pszText = wfd.cFileName;
				tvis.item.iImage  = nIndex;
				tvis.item.iSelectedImage = nIndex;
				tvis.item.cChildren = (nChild ? 1 : 0);
				TreeView_InsertItem(hwndTV, &tvis);

				dwCnt++;
			}
			rc = FindNextFile (ff, &wfd);
			if (rc == 0)
				break;
		}
		FindClose(ff);
	}

    // サブキーがない場合は展開ボタンを削除する
    TVITEM tvi;
	tvi.hItem = hParent;
	tvi.mask  = TVIF_CHILDREN;
    if (dwCnt == 0)
        tvi.cChildren = 0;
    else
        tvi.cChildren = 1;
	TreeView_SetItem (hwndTV, &tvi);

	// ソート
	TreeView_SortChildren(hwndTV, hParent, 0);

	return dwCnt;
}
示例#13
0
//-----------------------------------------------------------------------------
// Name: OnSliderChanged()  
// Desc: Called when the dialog's slider bars are changed by the user, or need
//       updating
//-----------------------------------------------------------------------------
VOID OnSliderChanged( HWND hDlg )
{
    TCHAR strBuffer[10];

    // Get handles to dialog items
    HWND hFreqSlider   = GetDlgItem( hDlg, IDC_FREQUENCY_SLIDER );
    HWND hPanSlider    = GetDlgItem( hDlg, IDC_PAN_SLIDER );
    HWND hVolumeSlider = GetDlgItem( hDlg, IDC_VOLUME_SLIDER );

    // Get the position of the sliders
    LONG lFrequency = (LONG)SendMessage( hFreqSlider,   TBM_GETPOS, 0, 0 ) * 1L;
    LONG lPan       = (LONG)SendMessage( hPanSlider,    TBM_GETPOS, 0, 0 ) * 500L;
    LONG lVolume    = (LONG)SendMessage( hVolumeSlider, TBM_GETPOS, 0, 0 ) * 100L;

    // Set the static text boxes
    wsprintf( strBuffer, TEXT("%ld"), lFrequency );
    SetWindowText( GetDlgItem( hDlg, IDC_FREQUENCY ), strBuffer );

    wsprintf( strBuffer, TEXT("%ld"), lPan );
    SetWindowText( GetDlgItem( hDlg, IDC_PAN       ), strBuffer );

    wsprintf( strBuffer, TEXT("%ld"), lVolume );
    SetWindowText( GetDlgItem( hDlg, IDC_VOLUME    ), strBuffer );

    // Set the options in the DirectSound buffer
    if( g_pSound )
    {
        LPDIRECTSOUNDBUFFER pDSB = g_pSound->GetBuffer( 0 );

        if( pDSB )
        {
            if( FAILED( pDSB->SetFrequency( lFrequency ) ) )
            {
                DSCAPS dscaps;
                ZeroMemory( &dscaps, sizeof(DSCAPS) );
                dscaps.dwSize = sizeof(DSCAPS);
                g_pSoundManager->GetDirectSound()->GetCaps( &dscaps );
                
                DSBCAPS dsbcaps;
                ZeroMemory( &dsbcaps, sizeof(DSBCAPS) );
                dsbcaps.dwSize = sizeof(DSBCAPS);
                pDSB->GetCaps( &dsbcaps );

                // Try to guess why it failed 
                if( (dsbcaps.dwFlags & DSBCAPS_LOCHARDWARE) && 
                    (DWORD)lFrequency > dscaps.dwMaxSecondarySampleRate )
                {                    
                    // Hardware buffers don't support >dwMaxSecondarySampleRate
                    SetDlgItemText( hDlg, IDC_STATUS, TEXT("Hardware buffers don't support greater") 
                                                      TEXT("than dscaps.dwMaxSecondarySampleRate") );
                }
                else if( lFrequency > 100000 )
                {
                    // Some platforms (pre-WinXP SP1) do not support 
                    // >100k Hz so they will fail when setting it higher
                    SetDlgItemText( hDlg, IDC_STATUS, TEXT("Some OS platforms do not support >100k Hz") );
                }
                else
                {
                    SetDlgItemText( hDlg, IDC_STATUS, TEXT("Set frequency failed") );
                }

                // Reset to the last valid freq
                pDSB->SetFrequency( g_dwLastValidFreq );                  
                PostMessage( hFreqSlider, TBM_SETPOS, TRUE, g_dwLastValidFreq );               
            }
            else
            {
                g_dwLastValidFreq = lFrequency;
            }
            
            pDSB->SetPan( lPan );
            pDSB->SetVolume( lVolume );
        }
    }
}
示例#14
0
文件: ANSI.c 项目: aliking/ansicon
void InterpretEscSeq( void )
{
  int  i;
  WORD attribut;
  CONSOLE_SCREEN_BUFFER_INFO Info;
  CONSOLE_CURSOR_INFO CursInfo;
  DWORD len, NumberOfCharsWritten;
  COORD Pos;
  SMALL_RECT Rect;
  CHAR_INFO  CharInfo;

  if (prefix == '[')
  {
    if (prefix2 == '?' && (suffix == 'h' || suffix == 'l'))
    {
      if (es_argc == 1 && es_argv[0] == 25)
      {
	GetConsoleCursorInfo( hConOut, &CursInfo );
	CursInfo.bVisible = (suffix == 'h');
	SetConsoleCursorInfo( hConOut, &CursInfo );
	return;
      }
    }
    // Ignore any other \e[? or \e[> sequences.
    if (prefix2 != 0)
      return;

    GetConsoleScreenBufferInfo( hConOut, &Info );
    switch (suffix)
    {
      case 'm':
	if (es_argc == 0) es_argv[es_argc++] = 0;
	for (i = 0; i < es_argc; i++)
	{
	  switch (es_argv[i])
	  {
	    case 0:
	      foreground = org_fg;
	      background = org_bg;
	      bold	 = (es_argc == 1) ? org_bold : 0;
	      underline  = (es_argc == 1) ? org_ul   : 0;
	      rvideo	 = 0;
	      concealed  = 0;
	    break;
	    case  1: bold      = FOREGROUND_INTENSITY; break;
	    case  5: /* blink */
	    case  4: underline = BACKGROUND_INTENSITY; break;
	    case  7: rvideo    = 1; break;
	    case  8: concealed = 1; break;
	    case 21: bold      = 0; break;
	    case 25:
	    case 24: underline = 0; break;
	    case 27: rvideo    = 0; break;
	    case 28: concealed = 0; break;
	  }
	  if (30 <= es_argv[i] && es_argv[i] <= 37) foreground = es_argv[i]-30;
	  if (40 <= es_argv[i] && es_argv[i] <= 47) background = es_argv[i]-40;
	}
	if (concealed)
	{
	  if (rvideo)
	  {
	    attribut = foregroundcolor[foreground]
		     | backgroundcolor[foreground];
	    if (bold)
	      attribut |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
	  }
	  else
	  {
	    attribut = foregroundcolor[background]
		     | backgroundcolor[background];
	    if (underline)
	      attribut |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
	  }
	}
	else if (rvideo)
	{
	  attribut = foregroundcolor[background] | backgroundcolor[foreground];
	  if (bold)
	    attribut |= BACKGROUND_INTENSITY;
	  if (underline)
	    attribut |= FOREGROUND_INTENSITY;
	}
	else
	  attribut = foregroundcolor[foreground] | backgroundcolor[background]
		   | bold | underline;
	SetConsoleTextAttribute( hConOut, attribut );
      return;

      case 'J':
	if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[J == ESC[0J
	if (es_argc != 1) return;
	switch (es_argv[0])
	{
	  case 0:		// ESC[0J erase from cursor to end of display
	    len = (Info.dwSize.Y - Info.dwCursorPosition.Y - 1) * Info.dwSize.X
		  + Info.dwSize.X - Info.dwCursorPosition.X - 1;
	    FillConsoleOutputCharacter( hConOut, ' ', len,
					Info.dwCursorPosition,
					&NumberOfCharsWritten );
	    FillConsoleOutputAttribute( hConOut, Info.wAttributes, len,
					Info.dwCursorPosition,
					&NumberOfCharsWritten );
	  return;

	  case 1:		// ESC[1J erase from start to cursor.
	    Pos.X = 0;
	    Pos.Y = 0;
	    len   = Info.dwCursorPosition.Y * Info.dwSize.X
		    + Info.dwCursorPosition.X + 1;
	    FillConsoleOutputCharacter( hConOut, ' ', len, Pos,
					&NumberOfCharsWritten );
	    FillConsoleOutputAttribute( hConOut, Info.wAttributes, len, Pos,
					&NumberOfCharsWritten );
	    return;

	  case 2:		// ESC[2J Clear screen and home cursor
	    Pos.X = 0;
	    Pos.Y = 0;
	    len   = Info.dwSize.X * Info.dwSize.Y;
	    FillConsoleOutputCharacter( hConOut, ' ', len, Pos,
					&NumberOfCharsWritten );
	    FillConsoleOutputAttribute( hConOut, Info.wAttributes, len, Pos,
					&NumberOfCharsWritten );
	    SetConsoleCursorPosition( hConOut, Pos );
	  return;

	  default:
	  return;
	}

      case 'K':
	if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[K == ESC[0K
	if (es_argc != 1) return;
	switch (es_argv[0])
	{
	  case 0:		// ESC[0K Clear to end of line
	    len = Info.srWindow.Right - Info.dwCursorPosition.X + 1;
	    FillConsoleOutputCharacter( hConOut, ' ', len,
					Info.dwCursorPosition,
					&NumberOfCharsWritten );
	    FillConsoleOutputAttribute( hConOut, Info.wAttributes, len,
					Info.dwCursorPosition,
					&NumberOfCharsWritten );
	  return;

	  case 1:		// ESC[1K Clear from start of line to cursor
	    Pos.X = 0;
	    Pos.Y = Info.dwCursorPosition.Y;
	    FillConsoleOutputCharacter( hConOut, ' ',
					Info.dwCursorPosition.X + 1, Pos,
					&NumberOfCharsWritten );
	    FillConsoleOutputAttribute( hConOut, Info.wAttributes,
					Info.dwCursorPosition.X + 1, Pos,
					&NumberOfCharsWritten );
	  return;

	  case 2:		// ESC[2K Clear whole line.
	    Pos.X = 0;
	    Pos.Y = Info.dwCursorPosition.Y;
	    FillConsoleOutputCharacter( hConOut, ' ', Info.dwSize.X, Pos,
					&NumberOfCharsWritten );
	    FillConsoleOutputAttribute( hConOut, Info.wAttributes,
					Info.dwSize.X, Pos,
					&NumberOfCharsWritten );
	  return;

	  default:
	  return;
	}

      case 'L':                 // ESC[#L Insert # blank lines.
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[L == ESC[1L
	if (es_argc != 1) return;
	Rect.Left   = 0;
	Rect.Top    = Info.dwCursorPosition.Y;
	Rect.Right  = Info.dwSize.X - 1;
	Rect.Bottom = Info.dwSize.Y - 1;
	Pos.X = 0;
	Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
	CharInfo.Char.UnicodeChar = ' ';
	CharInfo.Attributes = Info.wAttributes;
	ScrollConsoleScreenBuffer( hConOut, &Rect, NULL, Pos, &CharInfo );
      return;

      case 'M':                 // ESC[#M Delete # lines.
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[M == ESC[1M
	if (es_argc != 1) return;
	if (es_argv[0] > Info.dwSize.Y - Info.dwCursorPosition.Y)
	  es_argv[0] = Info.dwSize.Y - Info.dwCursorPosition.Y;
	Rect.Left   = 0;
	Rect.Top    = Info.dwCursorPosition.Y + es_argv[0];
	Rect.Right  = Info.dwSize.X - 1;
	Rect.Bottom = Info.dwSize.Y - 1;
	Pos.X = 0;
	Pos.Y = Info.dwCursorPosition.Y;
	CharInfo.Char.UnicodeChar = ' ';
	CharInfo.Attributes = Info.wAttributes;
	ScrollConsoleScreenBuffer( hConOut, &Rect, NULL, Pos, &CharInfo );
      return;

      case 'P':                 // ESC[#P Delete # characters.
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[P == ESC[1P
	if (es_argc != 1) return;
	if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1)
	  es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X;
	Rect.Left   = Info.dwCursorPosition.X + es_argv[0];
	Rect.Top    = Info.dwCursorPosition.Y;
	Rect.Right  = Info.dwSize.X - 1;
	Rect.Bottom = Info.dwCursorPosition.Y;
	CharInfo.Char.UnicodeChar = ' ';
	CharInfo.Attributes = Info.wAttributes;
	ScrollConsoleScreenBuffer( hConOut, &Rect, NULL, Info.dwCursorPosition,
				   &CharInfo );
      return;

      case '@':                 // ESC[#@ Insert # blank characters.
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[@ == ESC[1@
	if (es_argc != 1) return;
	if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1)
	  es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X;
	Rect.Left   = Info.dwCursorPosition.X;
	Rect.Top    = Info.dwCursorPosition.Y;
	Rect.Right  = Info.dwSize.X - 1 - es_argv[0];
	Rect.Bottom = Info.dwCursorPosition.Y;
	Pos.X = Info.dwCursorPosition.X + es_argv[0];
	Pos.Y = Info.dwCursorPosition.Y;
	CharInfo.Char.UnicodeChar = ' ';
	CharInfo.Attributes = Info.wAttributes;
	ScrollConsoleScreenBuffer( hConOut, &Rect, NULL, Pos, &CharInfo );
      return;

      case 'A':                 // ESC[#A Moves cursor up # lines
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[A == ESC[1A
	if (es_argc != 1) return;
	Pos.Y = Info.dwCursorPosition.Y - es_argv[0];
	if (Pos.Y < 0) Pos.Y = 0;
	Pos.X = Info.dwCursorPosition.X;
	SetConsoleCursorPosition( hConOut, Pos );
      return;

      case 'B':                 // ESC[#B Moves cursor down # lines
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[B == ESC[1B
	if (es_argc != 1) return;
	Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
	if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
	Pos.X = Info.dwCursorPosition.X;
	SetConsoleCursorPosition( hConOut, Pos );
      return;

      case 'C':                 // ESC[#C Moves cursor forward # spaces
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[C == ESC[1C
	if (es_argc != 1) return;
	Pos.X = Info.dwCursorPosition.X + es_argv[0];
	if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
	Pos.Y = Info.dwCursorPosition.Y;
	SetConsoleCursorPosition( hConOut, Pos );
      return;

      case 'D':                 // ESC[#D Moves cursor back # spaces
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[D == ESC[1D
	if (es_argc != 1) return;
	Pos.X = Info.dwCursorPosition.X - es_argv[0];
	if (Pos.X < 0) Pos.X = 0;
	Pos.Y = Info.dwCursorPosition.Y;
	SetConsoleCursorPosition( hConOut, Pos );
      return;

      case 'E':                 // ESC[#E Moves cursor down # lines, column 1.
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[E == ESC[1E
	if (es_argc != 1) return;
	Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
	if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
	Pos.X = 0;
	SetConsoleCursorPosition( hConOut, Pos );
      return;

      case 'F':                 // ESC[#F Moves cursor up # lines, column 1.
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[F == ESC[1F
	if (es_argc != 1) return;
	Pos.Y = Info.dwCursorPosition.Y - es_argv[0];
	if (Pos.Y < 0) Pos.Y = 0;
	Pos.X = 0;
	SetConsoleCursorPosition( hConOut, Pos );
      return;

      case 'G':                 // ESC[#G Moves cursor column # in current row.
	if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[G == ESC[1G
	if (es_argc != 1) return;
	Pos.X = es_argv[0] - 1;
	if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
	if (Pos.X < 0) Pos.X = 0;
	Pos.Y = Info.dwCursorPosition.Y;
	SetConsoleCursorPosition( hConOut, Pos );
      return;

      case 'f':                 // ESC[#;#f
      case 'H':                 // ESC[#;#H Moves cursor to line #, column #
	if (es_argc == 0)
	  es_argv[es_argc++] = 1; // ESC[H == ESC[1;1H
	if (es_argc == 1)
	  es_argv[es_argc++] = 1; // ESC[#H == ESC[#;1H
	if (es_argc > 2) return;
	Pos.X = es_argv[1] - 1;
	if (Pos.X < 0) Pos.X = 0;
	if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
	Pos.Y = es_argv[0] - 1;
	if (Pos.Y < 0) Pos.Y = 0;
	if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
	SetConsoleCursorPosition( hConOut, Pos );
      return;

      case 's':                 // ESC[s Saves cursor position for recall later
	if (es_argc != 0) return;
	SavePos = Info.dwCursorPosition;
      return;

      case 'u':                 // ESC[u Return to saved cursor position
	if (es_argc != 0) return;
	SetConsoleCursorPosition( hConOut, SavePos );
      return;

      case 'n':                 // ESC[#n Device status report
	if (es_argc != 1) return; // ESC[n == ESC[0n -> ignored
	switch (es_argv[0])
	{
	  case 5:		// ESC[5n Report status
	    SendSequence( L"\33[0n" ); // "OK"
	  return;

	  case 6:		// ESC[6n Report cursor position
	  {
	    TCHAR buf[32];
	    wsprintf( buf, L"\33[%d;%dR", Info.dwCursorPosition.Y + 1,
					  Info.dwCursorPosition.X + 1 );
	    SendSequence( buf );
	  }
	  return;

	  default:
	  return;
	}

      case 't':                 // ESC[#t Window manipulation
	if (es_argc != 1) return;
	if (es_argv[0] == 21)	// ESC[21t Report xterm window's title
	{
	  TCHAR buf[MAX_PATH*2];
	  DWORD len = GetConsoleTitle( buf+3, lenof(buf)-3-2 );
	  // Too bad if it's too big or fails.
	  buf[0] = ESC;
	  buf[1] = ']';
	  buf[2] = 'l';
	  buf[3+len] = ESC;
	  buf[3+len+1] = '\\';
	  buf[3+len+2] = '\0';
	  SendSequence( buf );
	}
      return;

      default:
      return;
    }
  }
  else // (prefix == ']')
  {
    // Ignore any \e]? or \e]> sequences.
    if (prefix2 != 0)
      return;

    if (es_argc == 1 && es_argv[0] == 0) // ESC]0;titleST
    {
      SetConsoleTitle( Pt_arg );
    }
  }
}
示例#15
0
QUERYRESPONSE ProRbtDb::HandleCounterIdEntry(PRORBTCOUNTERSESSION * pCounterSession, CPharmaRobot10Dlg* pdialog)
{
	QUERYRESPONSE returnvalue = Q_NOACK;
	size_t retsize, len, convertedChars;
	int MessageLength, NumTenBatches;
	char buffer[MAX_CONSIS_MESSAGE_SIZE], numart[3];
	aConsisReplyHeader *paMesHeader;
	aConsisReplyDispensedOcc* aocc;
	REQUESTINTERMEIDATEDB InterMDb;
	CString StringFromProRbt, st;

	if (pCounterSession->ExpectedNumLines == pCounterSession->ReceivedNumLines)
	{
		//Protect with Mutex the CONSIS resource
		CSingleLock singleLock(&(pdialog->m_Mutex));

		// Attempt to lock the shared resource
		if (singleLock.Lock(INFINITE))
		{
			//log locking success
		}

		if (pdialog->Consis.ConnectionStarted == FALSE)
		{
			if (pdialog->Consis.ConnectToConsis("ShorT", &(pdialog->m_listBoxMain), &(pdialog->m_CheckBoxRemoteSvr)))
				pdialog->EnableCondsisTab();
		}

		if (pdialog->Consis.ConnectionStarted == TRUE)
		{ 
			//Clean intermideate database
			memset (&InterMDb, 0, sizeof(InterMDb));
			InterMDb.firstIndexToStartfrom = INITIAL;

			int l = 0;
			//build intermediate database that agregates identical article IDs (barcodes)
			for (int j = 0 ; j < pCounterSession->ExpectedNumLines ; j++)
			{
				bool entryfound = false;
				while (InterMDb.Entry[l].NumReq != 0) //search for an empty entry indicating the last entry in database
				{
					if (wcscmp(InterMDb.Entry[l].ArctileIdRequested, pCounterSession->RbtParamLinesArr[j + 1].Barcode) == 0)
					{
						InterMDb.Entry[l].NumReq += _wtoi(pCounterSession->RbtParamLinesArr[j+1].Qty); //aggregate number of requested articles
						entryfound = true;
					}
					l++;//Check next entry in intermediate database
				}
				if(entryfound == false)
				{//barcode not found in any of the entries in the database. 
					//Create new entry - copy Barcode number and requested quantity to inetrmediate database.
					StringFromProRbt = pCounterSession->RbtParamLinesArr[j + 1].Barcode;
					len = StringFromProRbt.GetLength();
					memcpy(&(InterMDb.Entry[l].ArctileIdRequested),pCounterSession->RbtParamLinesArr[j+1].Barcode,len*sizeof(wchar_t));
					InterMDb.Entry[l].ArctileIdRequested[len] = L'\0';//insure string ends with a null
					InterMDb.Entry[l].NumReq = _wtoi(&(pCounterSession->RbtParamLinesArr[j+1].Qty[0])); //insert numer of requested articles
					//Check if Item is in Stock
					char BarcodeString[31];	memset(BarcodeString, 0, 30);
					wcstombs(BarcodeString, InterMDb.Entry[l].ArctileIdRequested, len);
					int TotalStock;
					if (CheckAmountInStock(&TotalStock, BarcodeString, pdialog) == FALSE)
					{
						//Error with Consis, Init entire Database
						InitProRbtDb();
						singleLock.Unlock();
						memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
						wsprintf(ackemessage.Message,L"תקלה בשליחת שאילתת כמות במלאי לשרת קונסיס");
						return Q_ERROR;
					}
					if (TotalStock >= InterMDb.Entry[l].NumReq) 
					{
						InterMDb.Entry[l].NumInStock = InterMDb.Entry[l].NumReq;
					}
					else
					{
						InterMDb.Entry[l].NumInStock = TotalStock;
					}
					//the Item is in stock and may be dispensed
					if (InterMDb.Entry[l].NumInStock > 0) 
					{
						InterMDb.sizeInStock += 1;
						if (InterMDb.firstIndexToStartfrom == INITIAL)
						{
							InterMDb.firstIndexToStartfrom = l;
						}
					}
				}
				//record intermediate database size for all items inserted to it
				InterMDb.sizeRequested = l + 1;
				l = 0;
			}

			//Handling 'A' dialogue is done in a batches of 10
			NumTenBatches = 1 + (InterMDb.sizeInStock / 10);

			while (NumTenBatches !=0)
			{
				//Build 'A' Message with Barcode from RBT parameters only if there are items left to send
				if (InterMDb.sizeInStock > 0)
				{
					//This function will send the following 10 items in the database that are in stock
					if (BuildAndSendACommand(&InterMDb, pdialog, &(pCounterSession->RbtParamLinesArr[1])) == FALSE)
					{
						//Error with Consis, Init entire Database
						InitProRbtDb();
						singleLock.Unlock();
						memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
						wsprintf(ackemessage.Message,L"תקלה בשליחת בקשת ניפוק לשרת קונסיס");
						return Q_ERROR;
					}		

					if (InterMDb.sizeInStock >= 10) InterMDb.sizeInStock -= 10; //10 less in stock

					//Session state depends on the order state
					//Last message Should be '4' - Ready, but Server returns '5', so that's what we'll wait for
					char orderState[3];
					memset(&(orderState[2]),'\0',1);
					memset(orderState,'0',2);

					do
					{
						MessageLength = sizeof(buffer);
						paMesHeader = (aConsisReplyHeader *)buffer;
						//Break out of while if message reception fails
						if (pdialog->Consis.ReceiveConsisMessage(buffer, &MessageLength, 1000) == FALSE)
						{
							st = L"Receive Consis Message 'a' timed out";
							pdialog->m_listBoxMain.AddString(st);
						}
						else
						{
							buffer[MessageLength] = '\0';

							memcpy(orderState, paMesHeader->OrderState, sizeof(paMesHeader->OrderState));
							orderState[2] = '\0';

							//Print the reply of CONSIS 'a' to the dialog box
							size_t origsize = strlen(buffer) + 1;
							wchar_t wcstring[1000];
							mbstowcs_s(&convertedChars, wcstring, origsize, buffer, _TRUNCATE);
							st = wcstring; pdialog->m_listBoxMain.AddString(st);
						}

					}while ((paMesHeader->OrderState[1] != '4') && (paMesHeader->OrderState[1] != '3'));
					//Supposed to wait for quantity change by CONSIS to PMS, but now wait for ready. If Cancelled stop all.

					//'A' command was cancelled. Items are missing from Stock in consis. Find which items are missing
					//using the 'B' command, and build a new 'A' command.
					if (paMesHeader->OrderState[1] == '3')
					{//We checked that all the items are in stock. If Cancelled somthing is wrong in CONSIS
						//Error with Consis, Init entire Database
						InitProRbtDb();
						singleLock.Unlock();
						memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
						wsprintf(ackemessage.Message,L"תקלה בקבלת תשובה לבקשת ניפוק לשרת קונסיס");
						return Q_ERROR;
					}
					else//The 'A' request was not cancelled, go through the reply
					{
						//Extract number of locations
						memcpy(numart, paMesHeader->NumberOfArticles, sizeof(paMesHeader->NumberOfArticles));
						numart[2] = '\0';
						int numArticles =  atoi(numart);

						//TEMP RANM DEBUG
						wchar_t Stringnumdif1f[3]; _itow(numArticles,Stringnumdif1f,10);
						Stringnumdif1f[2] = '\0';
						st = L"numArticles = "; st += Stringnumdif1f; pdialog->m_listBoxMain.AddString(st);
						//TEMP RANM DEBUG

						for (int i = 0 ; i < numArticles ; i++ )
						{
							//Extract Article ID and Dispensed quantity from Occupancy entry in 'a' message occupany entry
							char* address = (char*)paMesHeader + sizeof(aConsisReplyHeader) + (i * 42);
							aocc = (aConsisReplyDispensedOcc*)address;

							//Get article ID from 'a' response
							wchar_t articleID[31];
							articleID[30] = '\0';
							mbstowcs_s(&retsize, articleID, sizeof(aocc->ArticleId) + 1, aocc->ArticleId, _TRUNCATE);

							//Clean leading zeroes
							CString cleanArticleID;
							cleanArticleID.SetString(articleID);
							cleanArticleID.TrimLeft(L'0');
							cleanArticleID.TrimLeft(L' ');
							wsprintf(articleID,cleanArticleID.GetString());
							articleID[cleanArticleID.GetLength()] = L'\0';

							//find article ID in intermediate database
							int k = 0;
							while (InterMDb.Entry[k].NumReq != 0)
							{
								if (wcscmp(articleID, InterMDb.Entry[k].ArctileIdRequested) == 0)
								{//found the entry accoridng to barcode in intermedeate database
									//Dispensed quantity handling. Fill intermediate database for handling at the end.
									char dispenssedQuantity[6];
									memcpy(dispenssedQuantity, aocc->DispensedQuantity, sizeof(aocc->DispensedQuantity));
									dispenssedQuantity[5] = '\0';
									InterMDb.Entry[k].NumDis += atoi(dispenssedQuantity);
									//IF NO CANCELLED STATE RECEIVED, THEN ALL ITEMS WERE DISPENSSED
									//	InterMDb.Entry[k].NumDis = InterMDb.Entry[k].NumInStock;
								}
								k++;//serach for article ID in the intermediate database further
							}
						}

					}

				}
				NumTenBatches--;
			}
		}
		else
		{
			//Error with Consis, Init entire Database
			InitProRbtDb();
			singleLock.Unlock();
			memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
			wsprintf(ackemessage.Message,L"תקלה בתקשורת לשרת קונסיס");
			return Q_ERROR;
		}

		//CONSIS Completed, Build Ack from intermediate database. Check if all entries in the aggregated database were dispensed.
		int m = 0;
		bool missingitems = false;
		CString AckedString = L"מבקשת הניפוק חסרים הפריטים הבאים"; AckedString += L":";AckedString += L"\n";
		while (InterMDb.Entry[m].NumReq != 0)
		{
			if (InterMDb.Entry[m].NumReq != InterMDb.Entry[m].NumDis)
			{
				missingitems = true;
				wchar_t description[256];
				//Get Description from Yarpa SQL. If failed publish back to Client the Barcode
				if (!pdialog->GetItemDescFromBarcode(InterMDb.Entry[m].ArctileIdRequested, description))
					wsprintf(description,  InterMDb.Entry[m].ArctileIdRequested);
				AckedString += L"סוג פריט"; AckedString += L":"; AckedString += L" ";
				AckedString += description; AckedString += L"\n";
				AckedString += L"חסרים"; AckedString += L":"; AckedString += L" ";
				wchar_t Stringnumdiff[3]; _itow(InterMDb.Entry[m].NumReq - InterMDb.Entry[m].NumDis,Stringnumdiff,10);
				AckedString += Stringnumdiff;
				AckedString += L"\n\n";
			}
			m++;//Go on to next item in intermediate databse.
		}

		if (missingitems)
		{
			memset(ackemessage.Message, 0, ACK_MESSAGE_SIZE * sizeof(_TCHAR));
			memcpy(ackemessage.Message, AckedString.GetString(), AckedString.GetLength() * sizeof(wchar_t));
			returnvalue = Q_SENDACK;
		}
		else
		{
			returnvalue = Q_NOACK;
		}

		//Prepare Database Line Entry for next Session
		pCounterSession->PreviousSessionId = pCounterSession->CurrentSessionId;
		pCounterSession->ExpectedNumLines = -1;
		pCounterSession->ReceivedNumLines = -1;
		pCounterSession->CurrentSessionId = -1;

		singleLock.Unlock();
	}
	return returnvalue;
}
示例#16
0
文件: llssrv.c 项目: mingpen/OpenNT
BOOL
NTIsPDC(
   LPTSTR ServerName
   )

/*++

Routine Description:


Arguments:


Return Value:

   None.

--*/

{
   static TCHAR Serv[MAX_COMPUTERNAME_LENGTH + 3];
   UNICODE_STRING us;
   NTSTATUS ret;
   OBJECT_ATTRIBUTES oa;
   ACCESS_MASK am;
   SECURITY_QUALITY_OF_SERVICE qos;
   LSA_HANDLE hLSA;
   PPOLICY_LSA_SERVER_ROLE_INFO pvBuffer;
   BOOL IsPDC = FALSE;

   if (ServerName[0] == TEXT('\\'))
      lstrcpy(Serv, ServerName);
   else
      wsprintf(Serv, TEXT("\\\\%s"), ServerName);

   // Set up unicode string structure
   us.Length = lstrlen(Serv) * sizeof(TCHAR);
   us.MaximumLength = us.Length + sizeof(TCHAR);
   us.Buffer = Serv;

   // only need read access
   am = POLICY_READ | POLICY_VIEW_LOCAL_INFORMATION;

   // set up quality of service
   qos.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
   qos.ImpersonationLevel = SecurityImpersonation;
   qos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
   qos.EffectiveOnly = FALSE;

   // Macro sets everything except security field
   InitializeObjectAttributes( &oa, NULL, 0L, NULL, NULL );
   oa.SecurityQualityOfService = &qos;

   ret = LsaOpenPolicy(&us, &oa, am, &hLSA);

   if (!ret) {
      ret = LsaQueryInformationPolicy(hLSA, PolicyLsaServerRoleInformation, (PVOID *) &pvBuffer);
      LsaClose(hLSA);
      if ((!ret) && (pvBuffer != NULL)) {
         if (pvBuffer->LsaServerRole == PolicyServerRolePrimary)
            IsPDC = TRUE;

         LsaFreeMemory((PVOID) pvBuffer);
      }
   }

   return IsPDC;

} // NTIsPDC
示例#17
0
BOOL ProRbtDb::BuildAndSendACommand(REQUESTINTERMEIDATEDB * pInteDb, CPharmaRobot10Dlg* pdialog, PRORBTPARAMS* pFirstLine)
{
	AConsisRequestHeader * pARequestHeader;
	int MessageASize, indexInAcommand = 0;;
	CString StringFromProRbt;
	char nstring[100], numart[3];;
	size_t convertedChars;

	//Clear message
	memset(pdialog->ConsisMessage, '0', 448); //18 header + 10 * 43 OCC size

	pARequestHeader = (AConsisRequestHeader *)pdialog->ConsisMessage;

	/*Counter Unit taken from ProRBT parameters*/
	StringFromProRbt = pFirstLine->CounterUnit;//Take counter ID from first line
	int len = StringFromProRbt.GetLength();
	int location = 12 - len;
	wchar_t Source[4];
	wsprintf(Source, StringFromProRbt.GetString());
	wcstombs(&(pdialog->ConsisMessage[location]), Source, len);

	/*Dispenser Taken from ProRBT parameters*/
	StringFromProRbt = pFirstLine->Dispenser;//Take Dispenser ID from first line
	len = StringFromProRbt.GetLength();
	location = 15 - len;
	wsprintf(Source, StringFromProRbt.GetString());
	wcstombs(&(pdialog->ConsisMessage[location]), Source, len);

	//Fill Barcode and Quantity per entry in stock
	int i = pInteDb->firstIndexToStartfrom;
	while (i < pInteDb->sizeRequested)
	{
		if (pInteDb->Entry[i].NumInStock > 0) //only if article is in stock, add it to the 'A' command
		{
			/*Barcode taken from ProRBT parameters*/
			StringFromProRbt = pInteDb->Entry[i].ArctileIdRequested;
			len = StringFromProRbt.GetLength();
			location = (18 + (43 * (indexInAcommand + 1))) - len;
			wchar_t barcodeSent[14];
			wsprintf(barcodeSent, StringFromProRbt.GetString());
			//Fill with blanks instaed of leading zeros
			memset(&(pdialog->ConsisMessage[(18 + (43 * (indexInAcommand + 1))) - 30]),' ', 30);
			//Set the barcode
			wcstombs(&(pdialog->ConsisMessage[location]), barcodeSent, len);

			/*Quantity Taken from ProRBT parameters*/
			wchar_t ReqQuantity[5] = {0,0,0,0,0};
			wsprintf(ReqQuantity,L"%d",pInteDb->Entry[i].NumInStock);
			StringFromProRbt = ReqQuantity;
			len = StringFromProRbt.GetLength();
			location = (30 + (indexInAcommand * 43)) - len;
			wcstombs(&(pdialog->ConsisMessage[location]), ReqQuantity, len);

			/* Clear PZN */
			location = (18 + (43 * indexInAcommand));
			memset(&(pdialog->ConsisMessage[location]),' ', 7);

			indexInAcommand++;//One more article in the 'A' command
		}
		//For Next time start scan from next index
		i += 1;
		pInteDb->firstIndexToStartfrom = i;
		if (indexInAcommand == 10) break; //Break from while, reached maximum allowed number of articles in 'A' command.
	}

	//Message size is a function of the number of articles in this 'A' command
	MessageASize = 18 + (43*(indexInAcommand));
	pdialog->ConsisMessage[indexInAcommand] = '\0';

	/* Number of articles */
	sprintf(numart,"%d",indexInAcommand);
	if (indexInAcommand < 10){
		pARequestHeader->NumberOfArticles[1] = numart[0];
	}
	else {
		pARequestHeader->NumberOfArticles[0] = numart[0];
		pARequestHeader->NumberOfArticles[1] = numart[1];
	}

	/*Order number Taken from GUI*/
	pdialog->m_OrderNum++; if (pdialog->m_OrderNum > 99999999) pdialog->m_OrderNum = 0;//for every request increase number
	WCHAR wideStr[10];
	wsprintf(wideStr,L"%d\0",pdialog->m_OrderNum);
	pdialog->m_EditOrderNum.SetWindowTextW(wideStr);

	size_t origsize = pdialog->m_EditOrderNum.GetWindowTextLengthW() + 1;
	pdialog->m_EditOrderNum.GetWindowTextW(wideStr,origsize);
	wcstombs_s(&convertedChars, nstring, origsize, wideStr , _TRUNCATE);
	location = 9 - (origsize - 1);
	memcpy((void*)&(pdialog->ConsisMessage[location]), (void*) nstring, (origsize - 1));

	/*Priority Taken from GUI*/
	origsize = pdialog->m_EditPriority.GetWindowTextLengthW() + 1;
	pdialog->m_EditPriority.GetWindowTextW(wideStr,origsize);
	wcstombs_s(&convertedChars, nstring, origsize, wideStr , _TRUNCATE);
	location = 16 - (origsize - 1);
	memcpy((void*)&(pdialog->ConsisMessage[location]), (void*) nstring, (origsize - 1));

	pdialog->ConsisMessage[0] = 'A';

	//Print in dialog box the A request
	origsize = MessageASize + 1;
	wchar_t wcstring[1000];
	mbstowcs_s(&convertedChars, wcstring, origsize, pdialog->ConsisMessage, _TRUNCATE);
	CString st = wcstring; pdialog->m_listBoxMain.AddString(st);

	/* Send 'A' message to CONSIS */
	if (pdialog->Consis.SendConsisMessage(pdialog->ConsisMessage, MessageASize) == FALSE)
		return FALSE;

	return TRUE;
}
示例#18
0
static BOOL MyEndTask(DWORD pid) {
    WCHAR szCmd[1024] = {0};
    wsprintf(szCmd, L"taskkill /f /pid %d", pid);
    return _wsystem(szCmd) == 0;
}
示例#19
0
BOOL IntStrIncreaseSkipAlpha(TCHAR *strValue,int spn,TCHAR *strNEW,int len)
{
    TCHAR       szChar;
    TCHAR       newChar;
    TCHAR       *STR;
    BOOL        isINC;
    int         i;
    int         nLen;
    if ( spn > 10 ||spn < -10) {
        return FALSE;
    }
    if(0 > spn){
        spn   = -spn;
        isINC   = FALSE;
    } else if(0 < spn){
        isINC   = TRUE;
    } else {
        return FALSE;
    }
    nLen    = _tcslen(strValue);
    if( NULL != strNEW ){
        if(nLen + 1 > len ){
            return FALSE;
        }
        wsprintf(strNEW,TEXT("%s"),strValue);
        STR = strNEW;
    } else {
        STR = strValue;
    }
    if(isINC) {
        for (i = nLen-1; i >= 0; i-- ) {
            szChar  = STR[i];
            if(!isdigit(szChar)){
                continue;
            }
            newChar = szChar + spn;
            if (newChar <=_T('9') ) {
                szChar  = newChar;
                spn     =  0;
            } else if (newChar > _T('9')) {
                szChar  = newChar - 10;
                STR[i]  = szChar;
                spn     =  1;
                continue;
            }else {
                continue;
            }
            STR[i] = szChar;
            break;
        }
    } else {
        for (i = nLen-1; i >= 0; i-- ) {
            szChar  = STR[i];
            if(!isdigit(szChar)){
                continue;
            }
            newChar = szChar - spn;
            if (newChar >=_T('0')) {
                szChar  = newChar;
                spn     =  0;
            } else if ( newChar < _T('0') ){
                szChar  = newChar + 10 ;
                STR[i]  = szChar;
                spn     =  1;
                continue;
            }
            STR[i] = szChar;
            break;
        }
    }
    return TRUE;
}
示例#20
0
文件: pluginapi.c 项目: 0xheart0/vlc
void NSISCALL pushint(int value)
{
	TCHAR buffer[1024];
	wsprintf(buffer, _T("%d"), value);
	pushstring(buffer);
}
示例#21
0
// interrogate the host system for the available display configurations
//
bool Display::interrogate(void* hwnd) {

    bool     rc = false;
    int      nAdapters, nModes, nPixelFormats;
	wchar_t  str[MAX_DESC + 1];

    D3DADAPTER_IDENTIFIER9 d3di;
    D3DDISPLAYMODE         mode;
    D3DFORMAT              Format[]  = D3D_DOC_FORMATS;
    // friendly descriptions for each format
    wchar_t*               fmtdesc[] = D3D_FORMAT_DESC;

    // adapter count
    nAdapters = d3d->GetAdapterCount();
    // maximum mode count
    nModes = 0;
    // pixel format count
    // number of pixel formats as described in the Direct3D documentation
    nPixelFormats = D3D_NO_DOC_FORMATS;
 
    // determine maximum number of modes with any adapter
    for (int id = 0; id < nAdapters; id++) {
        if (SUCCEEDED(d3d->GetAdapterIdentifier(id, 0, &d3di))) {
            for (int ip = 0; ip < nPixelFormats; ip++) {
                int i = d3d->GetAdapterModeCount(id, Format[ip]);
                if (i > nModes)
                    nModes = i;
            }
        }
    }
    if (nAdapters > MAX_ADAPTERS) {
        wchar_t str[MAX_DESC + 1];
        sprintf(str, nAdapters, L" Adapters found - increase MAX_ADAPTERS");
        error(str);
        nAdapters = MAX_ADAPTERS;
    }
    if (nModes > MAX_MODES) {
        wchar_t str[MAX_DESC + 1];
        sprintf(str, nModes, L" Modes found - increase MAX_MODES");
        error(str);
        nModes = MAX_MODES;
    }
    if (nPixelFormats > MAX_P_FORMATS) {
        wchar_t str[MAX_DESC + 1];
        sprintf(str, nPixelFormats, L" Pixel Formats found - increase MAX_P_FORMATS");
        error(str);
        nPixelFormats = MAX_P_FORMATS;
    }

    // set dimensions, allocate context memory for descriptions,
    // and allocate private memory for mode dimensions
    context->set(GF_DS_ACNT, nAdapters);
    context->set(GF_DS_MCNT, nModes);
    context->set(GF_DS_PCNT, nPixelFormats);
    if (modeDim) delete [] modeDim;
    modeDim = new int[nAdapters * nModes * nPixelFormats][2];

    // enumerate and set all descriptions
    for (int id = 0; id < nAdapters; id++) {
        if (SUCCEEDED(d3d->GetAdapterIdentifier(id, 0, &d3di))) {
            rc = false;
            for (int ip = 0; ip < nPixelFormats; ip++) {
                // mode count
                int nr = d3d->GetAdapterModeCount(id, Format[ip]);
                nr = (nr > nModes) ? nModes : nr;
                for (int ir = 0; ir < nr; ir++) {
                    if (SUCCEEDED(d3d->EnumAdapterModes(id, Format[ip], ir, &mode))
                     && mode.Width >= WND_WIDTH && mode.Height >= WND_HEIGHT &&
                     (D3D_OK == d3d->CheckDeviceFormat(id, D3DDEVTYPE_HAL, mode.Format,
                     D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE,  D3DFMT_D32) ||   
                     D3D_OK == d3d->CheckDeviceFormat(id, D3DDEVTYPE_HAL, mode.Format,
                     D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D16) ||
                     D3D_OK == d3d->CheckDeviceFormat(id, D3DDEVTYPE_REF, mode.Format,
                     D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D32) ||
                     D3D_OK == d3d->CheckDeviceFormat(id, D3DDEVTYPE_REF, mode.Format,
                     D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, D3DFMT_D16))) {
                        wchar_t hz[20] = L"";
                        if (mode.RefreshRate)
                            wsprintf(hz, L"(%d Hz)", mode.RefreshRate);
                        wsprintf(str, L"%dx%d %ls %ls bits", mode.Width, mode.Height,
                         hz, fmtdesc[ip]);
                        rc = true;
                        // store the description and dimensions
                        int i = (id * nModes + ir) * nPixelFormats + ip;
                        context->set(GF_MDEDESC,   i, str);
                        modeDim[i][0] = mode.Width;
                        modeDim[i][1] = mode.Height;
                    }
                }
            }
            if (rc) {
                // adapter description
		        strcpyFromMB(str, d3di.Description, MAX_DESC); 
                context->set(GF_ADPDESC, id, str);
            }
        }
    }

    return rc;
}
示例#22
0
void SetStatusStatus(void)
{
    char        szStatusStatusLine[MAX_BUF_MEDIUM];
    char        szCurrentStatusInfo[MAX_BUF_MEDIUM];
    char        szPercentString[MAX_BUF_MEDIUM];
    char        szPercentageCompleted[MAX_BUF_MEDIUM];
    static long lModLastValue = 0;
    double        dRate;
    static double dRateCounter;
    DWORD         dwTickNow;
    DWORD         dwTickDif;
    DWORD         dwKBytesSoFar;
    DWORD         dwRoundedRate;
    char          szTimeLeft[MAX_BUF_TINY];

    /* If the user just clicked on the Resume button, then the time lapsed
     * between gdwTickStart and when the Resume button was clicked needs to
     * be subtracted taken into account when calculating dwTickDif.  So
     * "this" lapsed time needs to be added to gdwTickStart. */
    if(gtiPaused.bTickDownloadResumed)
    {
        gdwTickStart = AddToTick(gdwTickStart, gtiPaused.dwTickDif);
        InitTickInfo();
    }

    /* GetTickCount() returns time in milliseconds.  This is more accurate,
     * which will allow us to get at a 2 decimal precision value for the
     * download rate. */
    dwTickNow = GetTickCount();
    if((gdwTickStart == 0) && gbStartTickCounter)
        dwTickNow = gdwTickStart = GetTickCount();

    dwTickDif = GetTickDif(dwTickNow, gdwTickStart);

    /* Only update the UI every UPDATE_INTERVAL_STATUS interval,
     * which is currently set to 1 sec. */
    if(!CheckInterval(&lModLastValue, UPDATE_INTERVAL_STATUS))
        return;

    if(glAbsoluteBytesSoFar == 0)
        dRateCounter = 0.0;
    else
        dRateCounter = dwTickDif / 1000;

    if(dRateCounter == 0.0)
        dRate = 0.0;
    else
        dRate = (glAbsoluteBytesSoFar - glBytesResumedFrom) / dRateCounter / 1024;

    dwKBytesSoFar = glAbsoluteBytesSoFar / 1024;

    /* Use a rate that is rounded to the nearest integer.  If dRate used directly,
     * the "Time Left" will jump around quite a bit due to the rate usually
     * varying up and down by quite a bit. The rounded rate give a "more linear"
     * count down of the "Time Left". */
    dwRoundedRate = RoundDouble(dRate);
    if(dwRoundedRate > 0)
        GetTimeLeft((glTotalKb - dwKBytesSoFar) / dwRoundedRate,
                    szTimeLeft,
                    sizeof(szTimeLeft));
    else
        lstrcpy(szTimeLeft, "00:00:00");

    if(!gbShowDownloadRetryMsg)
    {
        GetPrivateProfileString("Strings",
                                "Status Download",
                                "",
                                szStatusStatusLine,
                                sizeof(szStatusStatusLine),
                                szFileIniConfig);
        if(*szStatusStatusLine != '\0')
            sprintf(szCurrentStatusInfo,
                    szStatusStatusLine,
                    szTimeLeft,
                    dRate,
                    dwKBytesSoFar,
                    glTotalKb);
        else
            sprintf(szCurrentStatusInfo,
                    "%s at %.2fKB/sec (%uKB of %uKB downloaded)",
                    szTimeLeft,
                    dRate,
                    dwKBytesSoFar,
                    glTotalKb);
    }
    else
    {
        GetPrivateProfileString("Strings",
                                "Status Retry",
                                "",
                                szStatusStatusLine,
                                sizeof(szStatusStatusLine),
                                szFileIniConfig);
        if(*szStatusStatusLine != '\0')
            sprintf(szCurrentStatusInfo,
                    szStatusStatusLine,
                    szTimeLeft,
                    dRate,
                    dwKBytesSoFar,
                    glTotalKb);
        else
            sprintf(szCurrentStatusInfo,
                    "%s at %.2KB/sec (%uKB of %uKB downloaded)",
                    szTimeLeft,
                    dRate,
                    dwKBytesSoFar,
                    glTotalKb);
    }

    GetPrivateProfileString("Strings",
                            "Status Percentage Completed",
                            "",
                            szPercentageCompleted,
                            sizeof(szPercentageCompleted),
                            szFileIniConfig);
    wsprintf(szPercentString, szPercentageCompleted, (int)GetPercentSoFar());

    /* Set the download dialog title */
    SetDlgItemText(dlgInfo.hWndDlg, IDC_STATUS_STATUS, szCurrentStatusInfo);
    SetDlgItemText(dlgInfo.hWndDlg, IDC_PERCENTAGE, szPercentString);
}
示例#23
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
  TCHAR *cmdline;
  TCHAR seekchar = _T(' ');
  TCHAR *keyname, *file;

  // These are turned into heap memory to avoid _chkstk
  keyname = (TCHAR*) GlobalAlloc(GPTR, STR_SIZE*sizeof(TCHAR));
  file    = (TCHAR*) GlobalAlloc(GPTR, STR_SIZE*sizeof(TCHAR));

  cmdline = GetCommandLine();
  if (*cmdline == _T('\"'))
    seekchar = *cmdline++;

  while (*cmdline && *cmdline != seekchar)
    cmdline = CharNext(cmdline);
  cmdline = CharNext(cmdline);
  while (*cmdline == _T(' '))
    cmdline++;

  if (*cmdline++ != _T('/'))
  {
    ExitProcess(1);
    return 0;
  }

  if (*cmdline == _T('S'))
  {
    HKEY rootkey;

    if (SUCCEEDED(RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NSIS.Library.RegTool.v3"), 0, KEY_READ, &rootkey)))
    {
      while (RegEnumKey(rootkey, 0, keyname, STR_SIZE) == ERROR_SUCCESS)
      {
        HKEY key;

        if (SUCCEEDED(RegOpenKeyEx(rootkey, keyname, 0, KEY_READ, &key)))
        {
          DWORD t, count, l = sizeof(DWORD);

          if (SUCCEEDED(RegQueryValueEx(key, _T("count"), NULL, &t, (LPBYTE) &count, &l)) && t == REG_DWORD)
          {
            DWORD j;
            TCHAR valname[128], mode[3];

            for (j = 1; j <= count; j++)
            {
              wsprintf(valname, _T("%u.mode"), j);
              l = sizeof(mode);
              if (FAILED(RegQueryValueEx(key, valname, NULL, &t, (LPBYTE) mode, &l)) || t != REG_SZ)
                continue;

              wsprintf(valname, _T("%u.file"), j);
              l = STR_SIZE*sizeof(TCHAR);
              if (FAILED(RegQueryValueEx(key, valname, NULL, &t, (LPBYTE) file, &l)) || t != REG_SZ)
                continue;

              file[STR_SIZE - 1] = 0;

              // JP: Note, if this mode[1] is used as anything but a boolean later on,
              // we'll need to consider the next line carefully.
              RegFile(mode[0], file, mode[1] == 'X');
            }
          }

          RegCloseKey(key);
          RegDeleteKey(rootkey, keyname);
        }
      }

      RegCloseKey(rootkey);
      RegDeleteKey(HKEY_LOCAL_MACHINE, _T("Software\\NSIS.Library.RegTool.v3"));
    }

    {
      if (GetModuleFileName(GetModuleHandle(NULL), file, STR_SIZE))
      {
        DeleteFileOnReboot(file);
      }
    }
  }
  else
  {
    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
    OleInitialize(NULL);

    if (*cmdline == _T('D'))
    {
      RegDll(cmdline + 1);
    }
    else if (*cmdline == _T('T'))
    {
      RegTypeLib(cmdline + 1);
    }

    OleUninitialize();
    SetErrorMode(0);
  }

  GlobalFree(keyname);
  GlobalFree(file);
  ExitProcess(0);
  return 0;
}
示例#24
0
int DownloadFiles(char *szInputIniFile,
                  char *szDownloadDir,
                  char *szProxyServer,
                  char *szProxyPort,
                  char *szProxyUser,
                  char *szProxyPasswd,
                  BOOL bShowRetryMsg,
                  BOOL bIgnoreAllNetworkErrors,
                  char *szFailedFile,
                  DWORD dwFailedFileSize)
{
    char      szBuf[MAX_BUF];
    char      szCurrentFile[MAX_BUF];
    char      szSection[MAX_INI_SK];
    char      szKey[MAX_INI_SK];
    char      szSavedCwd[MAX_BUF_MEDIUM];
    int       iCounter;
    int       rv;
    int       iFileDownloadRetries;
    int       iIgnoreFileNetworkError;
    int       iLocalTimeOutCounter;
    DWORD     dwTotalEstDownloadSize;
    char      szPartiallyDownloadedFilename[MAX_BUF];
    BOOL      bDownloadInitiated;
    char      szTempURL[MAX_BUF];
    char      szWorkingURLPathOnly[MAX_BUF];
    siC       *siCCurrentFileObj = NULL;

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

    if(szFailedFile)
        ZeroMemory(szFailedFile, dwFailedFileSize);

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

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

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

    ShowMessage(NULL, FALSE);
    InitDownloadDlg();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                CloseSocket(szProxyServer, szProxyPort);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        UnsetSetupCurrentDownloadFile();
    }

    CloseSocket(szProxyServer, szProxyPort);
    DeInitDownloadDlg();
    SetCurrentDirectory(szSavedCwd);
    return(rv);
}
示例#25
0
bool LevelThemeLoader::loadTheme( char* themePath, ID3D11Device* device, WorldGenerator* worldGen, WorldDisplay* worldDisplay )
{
    std::ifstream file( themePath );
    char buffer[128];

    if( !file.is_open() ){
        LOG_ERRO << "Failed to open theme: " << themePath << LOG_ENDL; 
        return false;
    }

    WCHAR wallTexturePath[128];
    WCHAR floorTexturePath[128];
    WCHAR ceilingTexturePath[128];
    Fog fog;
    float wallTextureClip = 1.0f;
    float floorTextureClip = 1.0f;
    float ceilingTextureClip = 1.0f;
    float objectDrawDistance = 1.0f;
    float lightDrawDistance = 1.0f;
    float characterDrawDistance = 1.0f;

    PointLight candle;
    PointLight torch;
    PointLight chandelier;

    while( !file.eof() ){
        file.getline( buffer, 128 );

        //Allow Comments
        for(int i = 0; i < strlen(buffer); i++){
            if( buffer[i] == '#'){
                buffer[i] = '\0';
                break;
            }
        }

        //Blank lines should be skipped
        if( strlen( buffer ) == 0 ){
            continue;
        }

        char* setting = strtok(buffer, " ");
        char* equals = strtok(NULL, " ");
        char* value = strtok(NULL, " ");

        if( strcmp( setting, "WallTexture" ) == 0 ){
            wsprintf(wallTexturePath, L"content/textures/");
            mbstowcs(wallTexturePath + 17, value, 128);
        }else if( strcmp( setting, "WallClip" ) == 0  ){
            wallTextureClip = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "FloorTexture" ) == 0  ){
            wsprintf(floorTexturePath, L"content/textures/");
            mbstowcs(floorTexturePath + 17, value, 128);
        }else if( strcmp( setting, "FloorClip" ) == 0  ){
            floorTextureClip = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "CeilingTexture" ) == 0  ){
            wsprintf(ceilingTexturePath, L"content/textures/");
            mbstowcs(ceilingTexturePath + 17, value, 128);
        }else if( strcmp( setting, "CeilingClip" ) == 0  ){
            ceilingTextureClip = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "FogStart" ) == 0  ){
            fog.start = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "FogEnd" ) == 0  ){
            fog.end = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "FogColorRed" ) == 0  ){
            fog.color.x = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "FogColorGreen" ) == 0  ){
            fog.color.y = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "FogColorBlue" ) == 0  ){
            fog.color.z = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "ObjectDrawDistance" ) == 0  ){
            objectDrawDistance = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "LightDrawDistance" ) == 0  ){
            lightDrawDistance = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "CharacterDrawDistance" ) == 0  ){
            characterDrawDistance = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "CandleRadius" ) == 0  ){
            candle.set( static_cast<float>(atof( value ) ), candle.getIntensity(), candle.getColor() );
        }else if( strcmp( setting, "CandleIntensity" ) == 0  ){
            candle.set( candle.getRadius(), static_cast<float>(atof( value ) ), candle.getColor() );
        }else if( strcmp( setting, "CandleColorRed" ) == 0  ){
            candle.getColor().x = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "CandleColorGreen" ) == 0  ){
            candle.getColor().y = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "CandleColorBlue" ) == 0  ){
            candle.getColor().z = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "TorchRadius" ) == 0  ){
            torch.set( static_cast<float>(atof( value ) ), torch.getIntensity(), torch.getColor() );
        }else if( strcmp( setting, "TorchIntensity" ) == 0  ){
            torch.set( torch.getRadius(), static_cast<float>(atof( value ) ), torch.getColor() );
        }else if( strcmp( setting, "TorchColorRed" ) == 0  ){
            torch.getColor().x = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "TorchColorGreen" ) == 0  ){
            torch.getColor().y = static_cast<float>(atof( value ));
        }else if( strcmp( setting, "TorchColorBlue" ) == 0  ){
            torch.getColor().z = static_cast<float>(atof( value ));
        }else{
            LOG_ERRO << "Unknown Theme Configuration Setting: " << setting << LOG_ENDL;
        }
    }

    //Close the file
    file.close();

    //Calculate the number of rows/collumns in the texture, assuming they are the same
    int floorRows = static_cast<int>(1.0f / floorTextureClip);

    //Set the worldGen max Tile ID to generate
    worldGen->setTileIDMax( floorRows * floorRows );

    fog.diff = fog.end - fog.start;
    fog.color.w = 1.0f;

    LevelDisplay* levelDisplay = &worldDisplay->getLevelDisplay();

    //Setup the level display fog
	worldDisplay->getLevelDisplay().setFog( fog );

    //Setup the draw distances for things
    worldDisplay->getLevelDisplay().setDrawRange( objectDrawDistance );
    worldDisplay->getLightDisplay().setDrawRange( lightDrawDistance );
    worldDisplay->getPopulationDisplay().setDrawRange( characterDrawDistance );

    //Set the light values
    worldDisplay->getLightDisplay().setPointLight( Level::Light::Candle, candle );
    worldDisplay->getLightDisplay().setPointLight( Level::Light::Torch, torch );
    //worldDisplay->getLightDisplay().setPointLight( Level::Light::Chandelier, chandelier );

    //Set the level display textures and clipping info
    return levelDisplay->setTextures( device, floorTexturePath, floorTextureClip, 
                                              wallTexturePath, wallTextureClip,
                                              ceilingTexturePath, ceilingTextureClip);
}
示例#26
0
//-----------------------------------------------------------------------------
// Name: GreetingDlgProc()
// Desc: Handles dialog messages
//-----------------------------------------------------------------------------
INT_PTR CALLBACK GreetingDlgProc( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg ) 
    {
        case WM_INITDIALOG:
            {
                g_hDlg = hDlg;

                // Load and set the icon
                HICON hIcon = LoadIcon( g_hInst, MAKEINTRESOURCE( IDI_MAIN ) );
                SendMessage( hDlg, WM_SETICON, ICON_BIG,   (LPARAM) hIcon );  // Set big icon
                SendMessage( hDlg, WM_SETICON, ICON_SMALL, (LPARAM) hIcon );  // Set small icon

                // Display local player's name
                SetDlgItemText( hDlg, IDC_PLAYER_NAME, g_strLocalPlayerName );

                if( g_pNetConnectWizard->IsHostPlayer() )
                    SetWindowText( hDlg, TEXT("StagedPeer (Host)") );
                else
                    SetWindowText( hDlg, TEXT("StagedPeer") );

                PostMessage( hDlg, WM_APP_UPDATE_STATS, 0, 0 );
            }
            break;

        case WM_APP_UPDATE_STATS:
        {
            // Update the number of players in the game
            TCHAR strNumberPlayers[32];

            wsprintf( strNumberPlayers, TEXT("%d"), g_lNumberOfActivePlayers );
            SetDlgItemText( hDlg, IDC_NUM_PLAYERS, strNumberPlayers );
            break;
        }

        case WM_APP_DISPLAY_WAVE:
        {
            HRESULT          hr;
            DPNID            dpnidPlayer = (DPNID) wParam;
            APP_PLAYER_INFO* pPlayerInfo = NULL;

            PLAYER_LOCK(); // enter player context CS

            // Get the player context accosicated with this DPNID
            hr = g_pDP->GetPlayerContext( dpnidPlayer, 
                                          (LPVOID* const) &pPlayerInfo,
										  0);

            PLAYER_ADDREF( pPlayerInfo ); // addref player, since we are using it now
            PLAYER_UNLOCK(); // leave player context CS

            if( FAILED(hr) || pPlayerInfo == NULL )
            {
                // The player who sent this may have gone away before this 
                // message was handled, so just ignore it
                break;
            }
            
            // Make wave message and display it.
            TCHAR szWaveMessage[MAX_PATH];
            wsprintf( szWaveMessage, TEXT("%s just waved at you, %s!\r\n"), 
                      pPlayerInfo->strPlayerName, g_strLocalPlayerName );

            PLAYER_LOCK();
            PLAYER_RELEASE( pPlayerInfo );  // Release player and cleanup if needed
            PLAYER_UNLOCK();

            AppendTextToEditControl( hDlg, szWaveMessage );
            break;
        }

        case WM_COMMAND:
            switch( LOWORD(wParam) )
            {
                case IDC_WAVE:
                    if( FAILED( g_hrDialog = WaveToAllPlayers() ) )
                    {
                        DXTRACE_ERR( TEXT("WaveToAllPlayers"), g_hrDialog );
                        EndDialog( hDlg, 0 );
                    }

                    return TRUE;

                case IDCANCEL:
                    EndDialog( hDlg, 0 );
                    return TRUE;
            }
            break;
    }

    return FALSE; // Didn't handle message
}
示例#27
0
void listener::run()
{
	TCHAR buf[1000];
	SOCKET ListenSocket;
	ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (ListenSocket == INVALID_SOCKET) 
	{
		wsprintf(buf,_T("Error at socket(): %ld\r\n"), WSAGetLastError());
		SvcDebugOut(buf);
		return;
	}

	sockaddr_in service;
	service.sin_family = AF_INET;
	service.sin_addr.s_addr = inet_addr("0.0.0.0");
	service.sin_port = htons(port);

	if (bind( ListenSocket,(SOCKADDR*) &service, sizeof(service)) == SOCKET_ERROR) 
	{
		SvcDebugOut(_T("bind() failed.\r\n"));
		closesocket(ListenSocket);
		return;
	}

	if (listen( ListenSocket, 1 ) == SOCKET_ERROR)
		SvcDebugOut(_T("Error listening on socket.\r\n"));

	SOCKET AcceptSocket;
	wsprintf(buf,_T("Listening port %d with rules:\r\n"),port);
	SvcDebugOut(buf);

	int pos=0;

	while(rules[pos].type!=RULES_T_EOL)
	{
		if(rules[pos].type==RULES_T_FORWARD)
			wsprintf(buf,_T("Forward host matching %s to %s:%d\r\n"),rules[pos].match,rules[pos].dest,rules[pos].destPort);
		else
			wsprintf(buf,_T("Drop host matching %s\r\n"),rules[pos].match);
		SvcDebugOut(buf);
		pos++;
	}

	while(1) 
	{
		AcceptSocket = SOCKET_ERROR;
		while( AcceptSocket == SOCKET_ERROR ) 
		{
			AcceptSocket = accept( ListenSocket, NULL, NULL );
		}

		TCHAR *dest;
		int destPort;
		findDestination(AcceptSocket,&dest,&destPort);
		if(dest==NULL)
		{
			closesocket(AcceptSocket);
		}
		else
		{
			connection *con=new connection();
			con->inSock=AcceptSocket;
			con->destination=dest;
			con->destPort=destPort;
			con->run();
		}
	}
}
示例#28
0
LIBUTILS_API char * UTILS_API 
get_file_descriptionA(const char * szFile, char * szDescription, int len)
{	
	char * pVersion=0;
	DWORD dwVersionSize;
	struct LANGANDCODEPAGE {
	  WORD wLanguage;
	  WORD wCodePage;
	} *lpTranslate;
	char SubBlock[64];
	void * lpBuffer;
	UINT dwBytes;
	UINT cbTranslate;
	UINT i;
	
	*szDescription=0;
	

	dwVersionSize=GetFileVersionInfoSize((char *)szFile,0);
	if(!dwVersionSize){
		return szDescription;
	}
	pVersion=(char *)malloc(dwVersionSize);
	if(!pVersion){
		return "";
	}
	if( !GetFileVersionInfo((char*)szFile,0,dwVersionSize,pVersion) ){
		free(pVersion);
		return "";
	};
	// Read the list of languages and code pages.

	VerQueryValue(pVersion, 
				  TEXT("\\VarFileInfo\\Translation"),
				  (LPVOID*)&lpTranslate,
				  &cbTranslate);
	if(!cbTranslate){
		free(pVersion);
		return "";
	}
	// Structure used to store enumerated languages and code pages.
	lpBuffer=0;
	
	for(i=0; i < (cbTranslate/sizeof(struct LANGANDCODEPAGE)); i++ ){
		wsprintf( SubBlock, 
				TEXT("\\StringFileInfo\\%04x%04x\\FileDescription"),
				lpTranslate[i].wLanguage,
				lpTranslate[i].wCodePage);

		if(0x0804 == lpTranslate[i].wLanguage){
			// Retrieve file description for language and code page "i". 
			VerQueryValue(pVersion, 
						SubBlock, 
						&lpBuffer, 
						&dwBytes
			);
			strncpy(szDescription,(char*)lpBuffer,len);
			szDescription[len-1]=0;
			free(pVersion);
			return szDescription;
		}			
	};		
	wsprintf( SubBlock, 
			TEXT("\\StringFileInfo\\%04x%04x\\FileDescription"),
			lpTranslate[0].wLanguage,
			lpTranslate[0].wCodePage);
	// Retrieve file description for language and code page "i". 
	VerQueryValue(pVersion, 
				SubBlock, 
				&lpBuffer, 
				&dwBytes
	);
	if(lpBuffer) {
		strncpy(szDescription,(char*)lpBuffer,len);
		szDescription[len-1]=0;
	};
	free(pVersion);
	return szDescription;
}
示例#29
0
int main(int argc, char* argv[])
{
#if 0
    GtkWidget *window;
    gint my_timer;
    guint count = 1;
    gtk_init( &argc, &argv);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_decorated(GTK_WINDOW(window), FALSE);
    gtk_window_set_title(GTK_WINDOW(window), "step3");
    /* gtk_window_set_opacity(GTK_WINDOW(window), 0.5);*/
    gtk_signal_connect( GTK_OBJECT(window),"destroy",
                        GTK_SIGNAL_FUNC(destroy_window), NULL);
    gtk_widget_show(window);
    /*my_timer = gtk_timeout_add(2000,(GtkFunction)timer_event,NULL);*/
    gtk_main();
    /*gtk_timeout_remove(my_timer);*/
 	/**/
#endif
    HANDLE hMutex = CreateMutex(NULL,FALSE,"SakuraFMO");
    if ( hMutex == NULL ) {
        g_print("No SakuraFMO\n");
        return 0;
    }
    if ( WaitForSingleObject(hMutex, 1000) != WAIT_TIMEOUT ) {
        g_print("SakuraFMO\n");

        DWORD dwDesiredAccess = FILE_MAP_READ;
        BOOL bInheritHandle = TRUE;
        LPCTSTR lpName;
        HANDLE hFMO = OpenFileMapping(dwDesiredAccess,
                                      bInheritHandle,
                                      "Sakura");
        HANDLE hwnd;
        if (hFMO != NULL){
            DWORD dwFileOffsetHigh = 0;
            DWORD dwFileOffsetLow = 0;
            /* map all */
            DWORD dwNumberOfBytesToMap = 0;
            LPVOID lpBaseAddress = NULL;
            LPVOID lpMap = MapViewOfFileEx(hFMO,
                                           dwDesiredAccess,
                                           dwFileOffsetHigh,
                                           dwFileOffsetLow,
                                           dwNumberOfBytesToMap,
                                           lpBaseAddress);
            if (lpMap != NULL) {
                unsigned char *p = (unsigned char*)lpMap;
                DWORD *lp = (DWORD*)lpMap;
                int nIndex = 0;
                g_print("%p 0x%04x %ld\n", lp, lp[0], lp[0]);
                nIndex = 4;
                unsigned char kbuf[1024];
                unsigned char vbuf[1024];
                int nkbuf=-1;
                int nvbuf=-1;
                int flg = 0;
                while (nIndex < 1000){
                    if (p[nIndex] == 0x0d && p[nIndex+1] == 0x0a){
                        printf("\nkey:%s\n", kbuf);
                        vbuf[nvbuf]='\0';
                        printf("value:%s\n", vbuf);
                        nIndex++;
                        nkbuf=0;
                        nvbuf=0;
                        flg = 0;
                        if (strstr(kbuf, ".hwnd")!=NULL){
                            hwnd = (HANDLE)atoi(vbuf);
                            printf("hwnd:%d\n", hwnd);
                        }
                    } else if (p[nIndex] == 0x01){
                        printf(" => ");
                        kbuf[nkbuf] = '\0';
                        nvbuf=0;
                        flg = 1;
                    }else if (isascii(p[nIndex])==TRUE){
                        printf("%c",p[nIndex]);
                        if (flg){
                            vbuf[nvbuf++] = p[nIndex];
                        } else {
                            kbuf[nkbuf++] = p[nIndex];
                        }
                    }else {
                        g_print(" 0x%02x", p[nIndex]);
                    }
                    nIndex++;
                }

                COPYDATASTRUCT cds;
                CHAR lpszData[1024];

                wsprintf(lpszData, "SEND SSTP/1.4\r\nSender: ghostbiff\r\nScript: \\h\\s0 HWND:%d\\e\r\nHWnd: %dCharset: Shift_JISThis is DATA.\r\n", hwnd, hwnd);
                
                cds.dwData = 1;
                cds.cbData = sizeof(lpszData);
                cds.lpData = (LPVOID)lpszData;
                WPARAM wParam = (WPARAM)hwnd;/*hwnd;*/
                LPARAM lParam = (LPARAM)&cds;

                SendMessage((HANDLE)hwnd, WM_COPYDATA, wParam, lParam);
                UnmapViewOfFile(lpMap);
            }
        }
        ReleaseMutex(hMutex);
    }

    CloseHandle(hMutex);
    return 0;                   
}
示例#30
0
文件: imagesoft.c 项目: GYGit/reactos
int WINAPI
_tWinMain(HINSTANCE hThisInstance,
        HINSTANCE hPrevInstance,
        LPTSTR lpCmdLine,
        int nCmdShow)
{
    LPTSTR lpAppName, lpVersion, lpTitle;
    HWND hMainWnd;
    MSG Msg;
    BOOL bRet;
    int Ret = 1;
    size_t len;
    INITCOMMONCONTROLSEX icex;

    hInstance = hThisInstance;
    ProcessHeap = GetProcessHeap();

    icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
    icex.dwICC = ICC_BAR_CLASSES | ICC_COOL_CLASSES;
    InitCommonControlsEx(&icex);

    if ( !AllocAndLoadString(&lpAppName, hInstance, IDS_APPNAME) ||
         !AllocAndLoadString(&lpVersion, hInstance, IDS_VERSION) )
    {
        return Ret;
    }

    len = _tcslen(lpAppName) + _tcslen(lpVersion);
    lpTitle = HeapAlloc(ProcessHeap,
                        0,
                        (len + 2) * sizeof(TCHAR));
    if (lpTitle == NULL)
    {
        LocalFree((HLOCAL)lpAppName);
        LocalFree((HLOCAL)lpVersion);
        return Ret;
    }

    wsprintf(lpTitle,
             _T("%s %s"),
             lpAppName,
             lpVersion);

    LocalFree((HLOCAL)lpAppName);
    LocalFree((HLOCAL)lpVersion);

    if (TbdInitImpl())
    {
        if (InitMainWindowImpl())
        {
            if (InitImageEditWindowImpl())
            {
                if (InitFloatWndClass())
                {
                    hMainWnd = CreateMainWindow(lpTitle,
                                                nCmdShow);
                    if (hMainWnd != NULL)
                    {
                        /* pump the message queue */
                        while ((bRet = GetMessage(&Msg,
                                                  NULL,
                                                  0,
                                                  0) != 0))
                        {
                            if (bRet != (BOOL)-1)
                            {
                                if (!MainWndTranslateMDISysAccel(hMainWnd,
                                                                 &Msg))
                                {
                                    TranslateMessage(&Msg);
                                    DispatchMessage(&Msg);
                                }
                            }
                        }

                        Ret = 0;
                    }

                    UninitImageEditWindowImpl();
                }

                UninitFloatWndImpl();
            }

            UninitMainWindowImpl();
        }

        TbdUninitImpl();
    }

    HeapFree(GetProcessHeap(),
             0,
             lpTitle);

    return Ret;
}