示例#1
0
BOOL WINAPI OnReadConsoleInputA(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer, DWORD nLength, LPDWORD lpNumberOfEventsRead)
{
	//typedef BOOL (WINAPI* OnReadConsoleInputA_t)(HANDLE hConsoleInput, PINPUT_RECORD lpBuffer, DWORD nLength, LPDWORD lpNumberOfEventsRead);
	SUPPRESSORIGINALSHOWCALL;
	ORIGINAL_KRNL(ReadConsoleInputA);
	//if (gpFarInfo && bMainThread)
	//	TouchReadPeekConsoleInputs(0);
	BOOL lbRc = FALSE;

	#if defined(_DEBUG)
	#if 1
	UINT nCp = GetConsoleCP();
	UINT nOutCp = GetConsoleOutputCP();
	UINT nOemCp = GetOEMCP();
	UINT nAnsiCp = GetACP();
	#endif
	#endif

	// To minimize startup duration and possible problems
	// hook server will start on first 'user interaction'
	CheckHookServer();

	if (ph && ph->PreCallBack)
	{
		SETARGS4(&lbRc,hConsoleInput,lpBuffer,nLength,lpNumberOfEventsRead);

		// Если функция возвращает FALSE - реальное чтение не будет вызвано
		if (!ph->PreCallBack(&args))
			return lbRc;
	}

	CESERVER_CONSOLE_APP_MAPPING* pAppMap = NULL;
	PreReadConsoleInput(hConsoleInput, rcif_Ansi|rcif_LLInput, &pAppMap);

	//#ifdef USE_INPUT_SEMAPHORE
	//DWORD nSemaphore = ghConInSemaphore ? WaitForSingleObject(ghConInSemaphore, INSEMTIMEOUT_READ) : 1;
	//_ASSERTE(nSemaphore<=1);
	//#endif

	lbRc = F(ReadConsoleInputA)(hConsoleInput, lpBuffer, nLength, lpNumberOfEventsRead);

	PostReadConsoleInput(hConsoleInput, rcif_Ansi|rcif_LLInput, pAppMap);

	//#ifdef USE_INPUT_SEMAPHORE
	//if ((nSemaphore == WAIT_OBJECT_0) && ghConInSemaphore) ReleaseSemaphore(ghConInSemaphore, 1, NULL);
	//#endif

	if (ph && ph->PostCallBack)
	{
		SETARGS4(&lbRc,hConsoleInput,lpBuffer,nLength,lpNumberOfEventsRead);
		ph->PostCallBack(&args);
	}

	if (lbRc && lpNumberOfEventsRead && *lpNumberOfEventsRead && lpBuffer)
	{
		OnPeekReadConsoleInput('R', 'A', hConsoleInput, lpBuffer, *lpNumberOfEventsRead);
	}

	return lbRc;
}
示例#2
0
文件: batch.c 项目: AlexSteel/wine
WCHAR *WCMD_fgets(WCHAR *buf, DWORD noChars, HANDLE h)
{
  DWORD charsRead;
  BOOL status;
  DWORD i;

  /* We can't use the native f* functions because of the filename syntax differences
     between DOS and Unix. Also need to lose the LF (or CRLF) from the line. */

  if (!WCMD_is_console_handle(h)) {
      LARGE_INTEGER filepos;
      char *bufA;
      UINT cp;
      const char *p;

      cp = GetConsoleCP();
      bufA = heap_alloc(noChars);

      /* Save current file position */
      filepos.QuadPart = 0;
      SetFilePointerEx(h, filepos, &filepos, FILE_CURRENT);

      status = ReadFile(h, bufA, noChars, &charsRead, NULL);
      if (!status || charsRead == 0) {
          heap_free(bufA);
          return NULL;
      }

      /* Find first EOL */
      for (p = bufA; p < (bufA + charsRead); p = CharNextExA(cp, p, 0)) {
          if (*p == '\n' || *p == '\r')
              break;
      }

      /* Sets file pointer to the start of the next line, if any */
      filepos.QuadPart += p - bufA + 1 + (*p == '\r' ? 1 : 0);
      SetFilePointerEx(h, filepos, NULL, FILE_BEGIN);

      i = MultiByteToWideChar(cp, 0, bufA, p - bufA, buf, noChars);
      heap_free(bufA);
  }
  else {
      status = WCMD_ReadFile(h, buf, noChars, &charsRead);
      if (!status || charsRead == 0) return NULL;

      /* Find first EOL */
      for (i = 0; i < charsRead; i++) {
          if (buf[i] == '\n' || buf[i] == '\r')
              break;
      }
  }

  /* Truncate at EOL (or end of buffer) */
  if (i == noChars)
    i--;

  buf[i] = '\0';

  return buf;
}
示例#3
0
PW32CP const struct php_win32_cp *php_win32_cp_do_setup(const char *enc)
{/*{{{*/
	if (!enc) {
		enc = php_win32_cp_get_enc();
	}

	cur_cp = php_win32_cp_get_by_enc(enc);
	if (!orig_cp) {
		orig_cp = php_win32_cp_get_by_id(GetACP());
	}
	if (!strcmp(sapi_module.name, "cli")) {
		if (!orig_in_cp) {
			orig_in_cp = php_win32_cp_get_by_id(GetConsoleCP());
			if (!orig_in_cp) {
				orig_in_cp = orig_cp;
			}
		}
		if (!orig_out_cp) {
			orig_out_cp = php_win32_cp_get_by_id(GetConsoleOutputCP());
			if (!orig_out_cp) {
				orig_out_cp = orig_cp;
			}
		}
		php_win32_cp_cli_io_setup();
	}

	return cur_cp;
}/*}}}*/
示例#4
0
/*
 * call-seq:
 *   Encoding.locale_charmap -> string
 *
 * Returns the locale charmap name.
 * It returns nil if no appropriate information.
 *
 *   Debian GNU/Linux
 *     LANG=C
 *       Encoding.locale_charmap  #=> "ANSI_X3.4-1968"
 *     LANG=ja_JP.EUC-JP
 *       Encoding.locale_charmap  #=> "EUC-JP"
 *
 *   SunOS 5
 *     LANG=C
 *       Encoding.locale_charmap  #=> "646"
 *     LANG=ja
 *       Encoding.locale_charmap  #=> "eucJP"
 *
 * The result is highly platform dependent.
 * So Encoding.find(Encoding.locale_charmap) may cause an error.
 * If you need some encoding object even for unknown locale,
 * Encoding.find("locale") can be used.
 *
 */
VALUE
rb_locale_charmap(VALUE klass)
{
#if defined NO_LOCALE_CHARMAP
    return rb_usascii_str_new2("ASCII-8BIT");
#elif defined _WIN32 || defined __CYGWIN__
    const char *codeset = 0;
    char cp[sizeof(int) * 3 + 4];
# ifdef __CYGWIN__
    const char *nl_langinfo_codeset(void);
    codeset = nl_langinfo_codeset();
# endif
    if (!codeset) {
	UINT codepage = GetConsoleCP();
	if (!codepage) codepage = GetACP();
	snprintf(cp, sizeof(cp), "CP%d", codepage);
	codeset = cp;
    }
    return rb_usascii_str_new2(codeset);
#elif defined HAVE_LANGINFO_H
    char *codeset;
    codeset = nl_langinfo(CODESET);
    return rb_usascii_str_new2(codeset);
#else
    return Qnil;
#endif
}
示例#5
0
PyObject *
_Py_device_encoding(int fd)
{
#if defined(MS_WINDOWS)
    UINT cp;
#endif
    if (!_PyVerify_fd(fd) || !isatty(fd)) {
        Py_RETURN_NONE;
    }
#if defined(MS_WINDOWS)
    if (fd == 0)
        cp = GetConsoleCP();
    else if (fd == 1 || fd == 2)
        cp = GetConsoleOutputCP();
    else
        cp = 0;
    /* GetConsoleCP() and GetConsoleOutputCP() return 0 if the application
       has no console */
    if (cp != 0)
        return PyUnicode_FromFormat("cp%u", (unsigned int)cp);
#elif defined(CODESET)
    {
        char *codeset = nl_langinfo(CODESET);
        if (codeset != NULL && codeset[0] != 0)
            return PyUnicode_FromString(codeset);
    }
#endif
    Py_RETURN_NONE;
}
示例#6
0
文件: localeinit.c 项目: DashYang/sim
static VALUE
locale_charmap(VALUE (*conv)(const char *))
{
#if defined NO_LOCALE_CHARMAP
# error NO_LOCALE_CHARMAP defined
#elif defined _WIN32 || defined __CYGWIN__
    const char *codeset = 0;
    char cp[SIZEOF_CP_NAME];
# ifdef __CYGWIN__
    const char *nl_langinfo_codeset(void);
    codeset = nl_langinfo_codeset();
# endif
    if (!codeset) {
	UINT codepage = GetConsoleCP();
	if (!codepage) codepage = GetACP();
	CP_FORMAT(cp, codepage);
	codeset = cp;
    }
    return (*conv)(codeset);
#elif defined HAVE_LANGINFO_H
    char *codeset;
    codeset = nl_langinfo(CODESET);
    return (*conv)(codeset);
#else
    return ENCINDEX_US_ASCII;
#endif
}
示例#7
0
文件: inoutimg.c 项目: hrouault/Brecs
/* Not thread safe 

   Assumes the string to convert was received from the console.
*/
static wchar_t* wide(const char* fname) {
    static wchar_t *buf=0;
    static int len=0;
    int n;
    ERR(n=MultiByteToWideChar(GetConsoleCP(),0,fname,(int)strlen(fname),buf,0));
    if(len<n) {
        if(buf)
            VirtualFree(buf,0,MEM_RELEASE);
        ERR(buf=VirtualAlloc(0,(n+1)*sizeof(wchar_t),MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE));
        len=n;
    }
    ERR(MultiByteToWideChar(GetConsoleCP(),0,fname,(int)strlen(fname),buf,len));
    return buf;
Error:
    exit(-1);
    return 0;
}
示例#8
0
static char* getConsoleEncoding()
{
    char* buf = malloc(16);
    int cp = GetConsoleCP();
    if (cp >= 874 && cp <= 950)
        sprintf(buf, "ms%d", cp);
    else
        sprintf(buf, "cp%d", cp);
    return buf;
}
示例#9
0
 /** Initialize the console. */
 ConsoleInitializer::ConsoleInitializer()
   : m_inputCP(GetConsoleCP()), m_outputCP(GetConsoleOutputCP())
 {
   // http://msdn.microsoft.com/en-us/library/ms686036%28VS.85%29.aspx
   //bool b1 = SetConsoleCP(65001); // set to UTF-8
   //bool b2 = SetConsoleOutputCP(65001); // set to UTF-8
   //bool b1 = SetConsoleCP(1200); // set to UTF-16LE
   //bool b2 = SetConsoleOutputCP(1200); // set to UTF-16LE
   //unsigned inputCP = GetConsoleCP();
   //unsigned outputCP = GetConsoleOutputCP();
 }
示例#10
0
/* stdio functions - versions that translate to/from utf-8 */
static int GSDLLCALL
gsdll_stdin_utf8(void *instance, char *buf, int len)
{
    static WCHAR thiswchar = 0; /* wide character to convert to multiple bytes */
    static int nmore = 0;       /* number of additional encoding bytes to generate */
    UINT consolecp = 0;
    int nret = 0;               /* number of bytes returned to caller */
    int i;

    while (len) {
        while (len && nmore) {
            nmore--;
            *buf++ = 0x80 | ((thiswchar >> (6 * nmore)) & 0x3F), nret++;
            len--;
        }
        while (len) {
            if (0 >= _read(fileno(stdin), buf, 1))
                return nret;
            nret++, buf++, len--;
            if (buf[-1] == '\n')
                /* return at end of line (note: no traslation needed) */
                return nret;
            else if ((unsigned char)buf[-1] <= 0x7F)
                /* no translation needed for 7-bit ASCII codes */
                continue;
            else {
                /* extended character, may be double */
                BYTE dbcsstr[2];

                dbcsstr[0] = buf[-1];
                if (!consolecp)
                    consolecp = GetConsoleCP();
                thiswchar = L'?'; /* initialize in case the conversion below fails */
                if (IsDBCSLeadByteEx(consolecp, dbcsstr[0])) {
                    /* double-byte character code, fetch the trail byte */
                    _read(fileno(stdin), &dbcsstr[1], 1);
                    MultiByteToWideChar(consolecp, 0, dbcsstr, 2, &thiswchar, 1);
                }
                else {
                    MultiByteToWideChar(consolecp, 0, dbcsstr, 1, &thiswchar, 1);
                }
                /* convert thiswchar to utf-8 */
                if (thiswchar <= 0x007F) {          /* encoded as single byte */
                    buf[-1] = (char)thiswchar;
                } else if (thiswchar <= 0x07FF) {   /* encoded as 2 bytes */
                    buf[-1] = 0xC0 | ((thiswchar >> 6) & 0x1F);
                    nmore = 1;
                    break;
                } else if (thiswchar <= 0xFFFF) {   /* encoded as 3 bytes */
                    buf[-1] = 0xE0 | ((thiswchar >> 12) & 0xF);
                    nmore = 2;
                    break;
                } else
DiagnosticsDialog::DiagnosticsDialog( QWidget *parent )
:	QDialog( parent )
{
	setupUi( this );
	setAttribute( Qt::WA_DeleteOnClose, true );

	QString info;
	QTextStream s( &info );

	s << "<b>" << tr("Locale (time-, number format / codepage):") << "</b> ";
	QLocale::Language language = QLocale::system().language();
	QString locale = (language == QLocale::C ? "English/United States" : QLocale::languageToString( language ) );
	CPINFOEX CPInfoEx;
	if ( GetCPInfoEx( GetConsoleCP(), 0, &CPInfoEx ) != 0 )
		locale.append( " / " ).append( CPInfoEx.CodePageName );
	s << locale << "<br />";
	s << "<b>" << tr("User rights: ") << "</b>" << getUserRights() << "<br />";

	QStringList base = Common::packages( QStringList() << "Eesti ID kaardi tarkvara", false );
	if ( !base.isEmpty() )
		s << "<b>" << tr("Base version:") << "</b> " << base.join( "<br />" ) << "<br />";
	s << "<b>" << tr("ID-card utility version:") << "</b> "<< QCoreApplication::applicationVersion() << "<br />";

	s << "<b>" << tr("OS:") << "</b> " << Common::applicationOs() << "<br />";
	s << "<b>" << tr("CPU:") << "</b> " << getProcessor() << "<br /><br />";

	s << "<b>" << tr("Library paths:") << "</b> " << QCoreApplication::libraryPaths().join( ";" ) << "<br />";

	s << "<b>" << tr("Libraries") << ":</b><br />";
	s << getLibVersion( "digidoc" ) << "<br />";
	s << getLibVersion( "digidocpp" ) << "<br />";
	s << getLibVersion( "advapi32" ) << "<br />";
	s << getLibVersion( "crypt32" ) << "<br />";
	s << getLibVersion( "winscard" ) << "<br />";
	s << getLibVersion( "esteidcsp|esteidcm" ) << "<br />";
	s << getLibVersion( "libeay32" ) << "<br />";
	s << getLibVersion( "ssleay32" ) << "<br />";
	s << getLibVersion( "opensc-pkcs11" ) << "<br />";
	s << "QT (" << qVersion() << ")<br />" << "<br />";

	s << "<b>" << tr("Smart Card service status: ") << "</b>" << " " << (isPCSCRunning() ? tr("Running") : tr("Not running")) << "<br /><br />";

	s << "<b>" << tr("Card readers") << ":</b><br />" << getReaderInfo() << "<br />";

	QStringList browsers = Common::packages( QStringList() << "Mozilla" << "Google Chrome" );
	QSettings reg( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer", QSettings::NativeFormat );
	browsers << QString( "Internet Explorer (%1)" ).arg( reg.value( "Version" ).toString() );
	s << "<b>" << tr("Browsers:") << "</b><br />" << browsers.join( "<br />" ) << "<br /><br />";

	diagnosticsText->setHtml( info );

	details = buttonBox->addButton( tr( "More info" ), QDialogButtonBox::HelpRole );
}
示例#12
0
void subsurface_console_init(bool dedicated)
{
	(void)console_desc;
	/* if this is a console app already, do nothing */
#ifndef WIN32_CONSOLE_APP
	/* just in case of multiple calls */
	memset((void *)&console_desc, 0, sizeof(console_desc));
	/* the AttachConsole(..) call can be used to determine if the parent process
	 * is a terminal. if it succeeds, there is no need for a dedicated console
	 * window and we don't need to call the AllocConsole() function. on the other
	 * hand if the user has set the 'dedicated' flag to 'true' and if AttachConsole()
	 * has failed, we create a dedicated console window.
	 */
	console_desc.allocated = AttachConsole(ATTACH_PARENT_PROCESS);
	if (console_desc.allocated)
		dedicated = false;
	if (!console_desc.allocated && dedicated)
		console_desc.allocated = AllocConsole();
	if (!console_desc.allocated)
		return;

	console_desc.cp = GetConsoleCP();
	SetConsoleOutputCP(CP_UTF8); /* make the ouput utf8 */

	/* set some console modes; we don't need to reset these back.
	 * ENABLE_EXTENDED_FLAGS = 0x0080, ENABLE_QUICK_EDIT_MODE = 0x0040 */
	HANDLE h_in = GetStdHandle(STD_INPUT_HANDLE);
	if (h_in) {
		SetConsoleMode(h_in, 0x0080 | 0x0040);
		CloseHandle(h_in);
	}

	/* dedicated only; disable the 'x' button as it will close the main process as well */
	HWND h_cw = GetConsoleWindow();
	if (h_cw && dedicated) {
		SetWindowTextA(h_cw, "Subsurface Console");
		HMENU h_menu = GetSystemMenu(h_cw, 0);
		if (h_menu) {
			EnableMenuItem(h_menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED);
			DrawMenuBar(h_cw);
		}
		SetConsoleCtrlHandler(NULL, TRUE); /* disable the CTRL handler */
	}

	/* redirect; on win32, CON is a reserved pipe target, like NUL */
	console_desc.out = freopen("CON", "w", stdout);
	console_desc.err = freopen("CON", "w", stderr);
	if (!dedicated)
		puts(""); /* add an empty line */
#endif
}
示例#13
0
int encode_to_mbs_size(const char *src, int srcsz)
{
	int unicode_size;
    wchar_t *unicode;
	//int unicode_len;
    int /*chars,*/ err;

	unicode_size = u8_wc_size(src, srcsz);
	unicode = (wchar_t *) alloca((unicode_size + 1) * sizeof(unsigned short));
	unicode[unicode_size] = L'\0';
	u8_toucs(unicode, unicode_size, src, srcsz);

    err = WideCharToMultiByte(GetConsoleCP(), WC_COMPOSITECHECK, unicode, unicode_size, NULL, 0, NULL, NULL);
    return err;
}
示例#14
0
文件: codepage.c 项目: 20uf/php-src
PW32CP const struct php_win32_cp *php_win32_cp_do_setup(const char *enc)
{/*{{{*/
	if (!enc) {
		enc = php_win32_cp_get_enc();
	}

	if (!strcmp(sapi_module.name, "cli")) {
		orig_cp = php_win32_cp_get_by_id(GetConsoleCP());
	} else {
		orig_cp = php_win32_cp_get_by_id(GetACP());
	}
	cur_cp = php_win32_cp_get_by_enc(enc);

	return cur_cp;
}/*}}}*/
示例#15
0
文件: command.c 项目: 50wu/gpdb
static void
checkWin32Codepage(void)
{
	unsigned int wincp,
				concp;

	wincp = GetACP();
	concp = GetConsoleCP();
	if (wincp != concp)
	{
		printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
				 "         8-bit characters might not work correctly. See psql reference\n"
				 "         page \"Notes for Windows users\" for details.\n"),
			   concp, wincp);
	}
}
示例#16
0
文件: reg.c 项目: farp90/nativecmd
int __cdecl main(int argc, char *argv[])
{
    WCHAR **argvW = HeapAlloc(GetProcessHeap(),0,argc*sizeof(LPWSTR));
    UINT cp = GetConsoleCP();
    int len = 0;
    int i = 0;
//    BREAK_POINT
//    reg_printfW(L"argc=%d\r\n", argc);
    for(i = 0; i < argc; i++)
    {
        len = strlen(argv[i]) + 1;
        argvW[i] = HeapAlloc(GetProcessHeap(),0,len*sizeof(WCHAR));
        //RtlZeroMemory(argvW[i], (len + 1)*sizeof(WCHAR));
        MultiByteToWideChar(cp, 0, argv[i], len, argvW[i], len);
//    printf("argv[%d]:%S\r\n", i, argvW[i]);
    }
    return wmain(argc, argvW);
}
示例#17
0
bool IsConsoleDoubleCellCP()
{
	static bool bDBCS = false, bDBCS_Checked = false;
	if (!bDBCS_Checked)
	{
		bDBCS = (GetSystemMetrics(SM_DBCSENABLED) != 0);
		bDBCS_Checked = true;
	}

	static bool  bDBCS_CP = false;
	static DWORD nLastCP = 0;
	UINT   MaxCharSize = 0;
	DWORD  nCP;
	#ifdef _DEBUG
	DWORD  nCP1;
	//DWORD  nMode;
	#endif

	if (bDBCS)
	{
		nCP = GetConsoleOutputCP();
		#ifdef _DEBUG
		nCP1 = GetConsoleCP();
		_ASSERTE(nCP1==nCP);
		//GetConsoleMode(hOut, &nMode);
		#endif

		if (!nLastCP || (nLastCP != nCP))
		{
			bool bNewVal = true;
			if (!AreCpInfoLeads(nCP, &MaxCharSize) || MaxCharSize < 2)
			{
				// gh-879: Windows 10 (since 14931) has changed behavior for double-cell glyphs
				// Now they are doubled (COMMON_LVB_LEADING_BYTE/COMMON_LVB_TRAILING_BYTE) even for UTF-8 codepage
				if (!IsWin10())
					bNewVal = false;
			}
			bDBCS_CP = bNewVal;
			nLastCP = nCP;
		}
	}

	return bDBCS_CP;
}
示例#18
0
int __cdecl main(int argc, char *argv[])
{
    UINT uiCP = 0;

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    uiCP = GetConsoleCP();
    if ((uiCP != CP_ACP) && (uiCP != GetACP()) && (uiCP != 437)) /*437 for MSDOS*/
    {
        Fail("GetConsoleCP: ERROR -> The invalid code page %d was returned.\n", 
            uiCP);
    }

    PAL_Terminate();
    return PASS;
}
示例#19
0
int encode_to_mbs(char *dest, int sz, const char *src, int srcsz)
{
	int unicode_size;
    wchar_t *unicode;
	//int unicode_len;
    int /*chars,*/ err;

	unicode_size = u8_wc_size(src, srcsz);
	unicode = (wchar_t *) alloca((unicode_size + 1) * sizeof(unsigned short));
	unicode[unicode_size] = L'\0';
	u8_toucs(unicode, unicode_size, src, srcsz);

    err = WideCharToMultiByte(GetConsoleCP(), WC_COMPOSITECHECK, unicode, unicode_size, dest, sz, NULL, NULL);
    if(err < 1)
    {
        fprintf(stderr, "Unicode translation error %d\n", GetLastError());
        return -1;
    }

    return err;
}
示例#20
0
文件: l10n.c 项目: oblalex/horus
void locale_init(char* code)
{
    int locale_id = get_locale_id(code);

#ifdef _WIN_
    CP_OLD = GetConsoleCP();
    if (CP_OLD == 866)
        SetConsoleCP(1251);

    LC_ALL_OLD = getenv(LC_ALL_VAR);

    char var[20];
    sprintf(var, LC_ALL_VAR "=%s\0", locales[locale_id]);
    putenv(var);
#else
    setlocale(LC_ALL, locales[locale_id]);
#endif

	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
}
示例#21
0
static DWORD WINAPI _stdinthreadproc(LPVOID lpParameter)
{
#define STDIN_WCHAR_BUF_SIZE (1024 * 2)
#define STDIN_CCHAR_BUF_SIZE (1024 * 4)
	WCHAR wbuf[STDIN_WCHAR_BUF_SIZE];
	char cbuf[STDIN_CCHAR_BUF_SIZE];
	HANDLE hconsolein = GetStdHandle(STD_INPUT_HANDLE);
	UINT oldcp = GetConsoleCP();
	SetConsoleCP(CP_UTF8);
	(void)lpParameter;
	do
	{
		DWORD cmode;
		if(GetConsoleMode(hconsolein, &cmode))
		{
			SetConsoleMode(hconsolein, cmode | ENABLE_LINE_INPUT);
		}
	}
	while(0);
	while(1)
	{
		DWORD read;
		int x;
		if(!ReadConsoleW(hconsolein, wbuf, STDIN_WCHAR_BUF_SIZE, &read, NULL))
			break;
		cbuf[0] = 0;
		_widetoutf8(wbuf, read, cbuf, STDIN_CCHAR_BUF_SIZE);
		_fix_stdinsockaddr();
		x = bind(_stdinsock, (struct sockaddr*)&_stdinsockaddr, sizeof(struct sockaddr_in));
		_fix_stdinsockaddr();
		x = sendto(_stdinsock, cbuf, strlen(cbuf), 0, (struct sockaddr*)&_stdinsockaddr, sizeof(struct sockaddr_in));
	}
	SetConsoleCP(oldcp);
	CloseHandle(hconsolein);
	return 0;
}
示例#22
0
idupdater::idupdater( QObject *parent )
:	QNetworkAccessManager( parent )
,	m_autoupdate( false )
,	m_autoclose( false )
,	w(0)
{
	QLocale::Language language = QLocale::system().language();
	QString locale = language == QLocale::C ? "English/United States" : QLocale::languageToString( language );
#ifdef Q_OS_WIN
	CPINFOEX CPInfoEx = { 0 };
	if( GetCPInfoExW( GetConsoleCP(), 0, &CPInfoEx ) != 0 )
		locale += " / " + QString( (QChar*)CPInfoEx.CodePageName );
#else
	QString ctype = QProcessEnvironment::systemEnvironment().value( "LC_CTYPE" );
	locale += " / " + (!ctype.isEmpty() ? ctype : QProcessEnvironment::systemEnvironment().value( "LANG" ));
#endif

	QPCSC pcsc;
	QString userAgent = QString( "%1/%2 (%3) Locale: %4 Devices: %5")
		.arg( qApp->applicationName(), InstallChecker::installedVersion("{58A1DBA8-81A2-4D58-980B-4A6174D5B66B}"), applicationOs(), locale, pcsc.drivers().join("/") );
	qDebug() << "User-Agent:" << userAgent;
	request.setRawHeader( "User-Agent", userAgent.toUtf8() );
	connect( this, SIGNAL(finished(QNetworkReply*)), SLOT(reply(QNetworkReply*)) );
}
示例#23
0
static unsigned char *
_clip_win_cp(int who)
{
	int cp_num = 0;
	unsigned char * buf;
	switch (who)
	{
		case 1:
			cp_num = GetConsoleCP();
			break;
		case 2:
			cp_num = GetACP();
			break;
		case 3:
			cp_num = GetOEMCP();
			break;
		case 4:
			cp_num = GetConsoleOutputCP();
			break;
	}
	buf = malloc(10);
	snprintf(buf,10,"cp%d",cp_num);
	return buf;
}
示例#24
0
	uintptr_t console::GetInputCodepage() const
	{
		return GetConsoleCP();
	}
示例#25
0
FBSTRING *fb_DrvIntlGetWeekdayName( int weekday, int short_names )
{
    char *pszName = NULL;
    size_t name_len;
    LCTYPE lctype;
    FBSTRING *result;

    if( weekday < 1 || weekday > 7 )
        return NULL;

    if( weekday==1 )
        weekday = 8;

    if( short_names ) {
        lctype = (LCTYPE) (LOCALE_SABBREVDAYNAME1 + weekday - 2);
    } else {
        lctype = (LCTYPE) (LOCALE_SDAYNAME1 + weekday - 2);
    }

    pszName = fb_hGetLocaleInfo( LOCALE_USER_DEFAULT, lctype,
                                 NULL, 0 );
    if( pszName==NULL )
        return NULL;

    name_len = strlen(pszName);

    result = fb_hStrAllocTemp( NULL, name_len );
    if( result!=NULL ) {
        /* !!!FIXME!!! GetCodepage() should become a hook function for console and gfx modes */
        int target_cp = /*( FB_GFX_ACTIVE() ? FB_GFX_GET_CODEPAGE() : GetConsoleCP() );*/ GetConsoleCP();
        if( target_cp!=-1 ) {
            FB_MEMCPY( result->data, pszName, name_len + 1 );
            result = fb_hIntlConvertString( result,
                                            CP_ACP,
                                            target_cp );
        }
    }

   free( pszName );

    return result;
}
示例#26
0
文件: w32inevt.c 项目: exedre/emacs
/* return code -1 means that event_queue_ptr won't be incremented.
   In other word, this event makes two key codes.   (by himi)       */
static int
key_event (KEY_EVENT_RECORD *event, struct input_event *emacs_ev, int *isdead)
{
  static int mod_key_state = 0;
  int wParam;

  *isdead = 0;

  /* Skip key-up events.  */
  if (!event->bKeyDown)
    {
      switch (event->wVirtualKeyCode)
	{
	case VK_LWIN:
	  mod_key_state &= ~LEFT_WIN_PRESSED;
	  break;
	case VK_RWIN:
	  mod_key_state &= ~RIGHT_WIN_PRESSED;
	  break;
	case VK_APPS:
	  mod_key_state &= ~APPS_PRESSED;
	  break;
	}
      return 0;
    }

  /* Ignore keystrokes we fake ourself; see below.  */
  if (faked_key == event->wVirtualKeyCode)
    {
      faked_key = 0;
      return 0;
    }

  /* To make it easier to debug this code, ignore modifier keys!  */
  switch (event->wVirtualKeyCode)
    {
    case VK_LWIN:
      if (NILP (Vw32_pass_lwindow_to_system))
	{
	  /* Prevent system from acting on keyup (which opens the Start
	     menu if no other key was pressed) by simulating a press of
	     Space which we will ignore.  */
	  if ((mod_key_state & LEFT_WIN_PRESSED) == 0)
	    {
	      if (NUMBERP (Vw32_phantom_key_code))
		faked_key = XUINT (Vw32_phantom_key_code) & 255;
	      else
		faked_key = VK_SPACE;
	      keybd_event (faked_key, (BYTE) MapVirtualKey (faked_key, 0), 0, 0);
	    }
	}
      mod_key_state |= LEFT_WIN_PRESSED;
      if (!NILP (Vw32_lwindow_modifier))
	return 0;
      break;
    case VK_RWIN:
      if (NILP (Vw32_pass_rwindow_to_system))
	{
	  if ((mod_key_state & RIGHT_WIN_PRESSED) == 0)
	    {
	      if (NUMBERP (Vw32_phantom_key_code))
		faked_key = XUINT (Vw32_phantom_key_code) & 255;
	      else
		faked_key = VK_SPACE;
	      keybd_event (faked_key, (BYTE) MapVirtualKey (faked_key, 0), 0, 0);
	    }
	}
      mod_key_state |= RIGHT_WIN_PRESSED;
      if (!NILP (Vw32_rwindow_modifier))
	return 0;
      break;
    case VK_APPS:
      mod_key_state |= APPS_PRESSED;
      if (!NILP (Vw32_apps_modifier))
	return 0;
      break;
    case VK_CAPITAL:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_enable_caps_lock))
	goto disable_lock_key;
      return 0;
    case VK_NUMLOCK:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_enable_num_lock))
	goto disable_lock_key;
      return 0;
    case VK_SCROLL:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_scroll_lock_modifier))
	goto disable_lock_key;
      return 0;
    disable_lock_key:
      /* Ensure the appropriate lock key state is off (and the
	 indicator light as well).  */
      wParam = event->wVirtualKeyCode;
      if (GetAsyncKeyState (wParam) & 0x8000)
	{
	  /* Fake another press of the relevant key.  Apparently, this
	     really is the only way to turn off the indicator.  */
	  faked_key = wParam;
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | 0, 0);
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
	}
      break;
    case VK_MENU:
    case VK_CONTROL:
    case VK_SHIFT:
      return 0;
    case VK_CANCEL:
      /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
	 which is confusing for purposes of key binding; convert
	 VK_CANCEL events into VK_PAUSE events.  */
      event->wVirtualKeyCode = VK_PAUSE;
      break;
    case VK_PAUSE:
      /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
	 for purposes of key binding; convert these back into
	 VK_NUMLOCK events, at least when we want to see NumLock key
	 presses.  (Note that there is never any possibility that
	 VK_PAUSE with Ctrl really is C-Pause as per above.)  */
      if (NILP (Vw32_enable_num_lock)
	  && (event->dwControlKeyState
	      & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0)
	event->wVirtualKeyCode = VK_NUMLOCK;
      break;
    }

  /* Recognize state of Windows and Apps keys.  */
  event->dwControlKeyState |= mod_key_state;

  /* Distinguish numeric keypad keys from extended keys.  */
  event->wVirtualKeyCode =
    map_keypad_keys (event->wVirtualKeyCode,
		     (event->dwControlKeyState & ENHANCED_KEY));

  if (lispy_function_keys[event->wVirtualKeyCode] == 0)
    {
      if (!NILP (Vw32_recognize_altgr)
	  && (event->dwControlKeyState & LEFT_CTRL_PRESSED)
	  && (event->dwControlKeyState & RIGHT_ALT_PRESSED))
	{
	  /* Don't try to interpret AltGr key chords; ToAscii seems not
	     to process them correctly.  */
	}
      /* Handle key chords including any modifiers other than shift
         directly, in order to preserve as much modifier information as
         possible.  */
      else if (event->dwControlKeyState
	       & (  RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED
		  | RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED
		  | (!NILP (Vw32_lwindow_modifier) ? LEFT_WIN_PRESSED : 0)
		  | (!NILP (Vw32_rwindow_modifier) ? RIGHT_WIN_PRESSED : 0)
		  | (!NILP (Vw32_apps_modifier) ? APPS_PRESSED : 0)
		  | (!NILP (Vw32_scroll_lock_modifier) ? SCROLLLOCK_ON : 0)))
	{
	  /* Don't translate modified alphabetic keystrokes, so the user
	     doesn't need to constantly switch layout to type control or
	     meta keystrokes when the normal layout translates
	     alphabetic characters to non-ascii characters.  */
	  if ('A' <= event->wVirtualKeyCode && event->wVirtualKeyCode <= 'Z')
	    {
	      event->uChar.AsciiChar = event->wVirtualKeyCode;
	      if ((event->dwControlKeyState & SHIFT_PRESSED) == 0)
		event->uChar.AsciiChar += ('a' - 'A');
	    }
	  /* Try to handle unrecognized keystrokes by determining the
             base character (ie. translating the base key plus shift
             modifier).  */
	  else if (event->uChar.AsciiChar == 0)
	    w32_kbd_patch_key (event, -1);
	}

      if (event->uChar.AsciiChar == 0)
	{
	  emacs_ev->kind = NO_EVENT;
	  return 0;
	}
      else if (event->uChar.AsciiChar > 0)
	{
	  /* Pure ASCII characters < 128.  */
	  emacs_ev->kind = ASCII_KEYSTROKE_EVENT;
	  emacs_ev->code = event->uChar.AsciiChar;
	}
      else if (event->uChar.UnicodeChar > 0
	       && w32_console_unicode_input)
	{
	  /* Unicode codepoint; only valid if we are using Unicode
	     console input mode.  */
	  emacs_ev->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
	  emacs_ev->code = event->uChar.UnicodeChar;
	}
      else
	{
	  /* Fallback handling of non-ASCII characters for non-Unicode
	     versions of Windows, and for non-Unicode input on NT
	     family of Windows.  Only characters in the current
	     console codepage are supported by this fallback.  */
	  wchar_t code;
	  char dbcs[2];
          int cpId;

	  /* Get the current console input codepage to interpret this
	     key with.  Note that the system defaults for the OEM
	     codepage could have been changed by calling SetConsoleCP
	     or w32-set-console-codepage, so using GetLocaleInfo to
	     get LOCALE_IDEFAULTCODEPAGE is not TRT here.  */
          cpId = GetConsoleCP ();

	  dbcs[0] = dbcs_lead;
	  dbcs[1] = event->uChar.AsciiChar;
	  if (dbcs_lead)
	    {
	      dbcs_lead = 0;
	      if (!MultiByteToWideChar (cpId, 0, dbcs, 2, &code, 1))
		{
		  /* Garbage  */
		  DebPrint (("Invalid DBCS sequence: %d %d\n",
			     dbcs[0], dbcs[1]));
		  emacs_ev->kind = NO_EVENT;
		}
	    }
	  else if (IsDBCSLeadByteEx (cpId, dbcs[1]))
	    {
	      dbcs_lead = dbcs[1];
	      emacs_ev->kind = NO_EVENT;
	    }
	  else
	    {
	      if (!MultiByteToWideChar (cpId, 0, &dbcs[1], 1, &code, 1))
		{
		  /* Garbage  */
		  DebPrint (("Invalid character: %d\n", dbcs[1]));
		  emacs_ev->kind = NO_EVENT;
		}
	    }
	  emacs_ev->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
	  emacs_ev->code = code;
	}
    }
  else
    {
      /* Function keys and other non-character keys.  */
      emacs_ev->kind = NON_ASCII_KEYSTROKE_EVENT;
      emacs_ev->code = event->wVirtualKeyCode;
    }

  XSETFRAME (emacs_ev->frame_or_window, get_frame ());
  emacs_ev->modifiers = w32_kbd_mods_to_emacs (event->dwControlKeyState,
					       event->wVirtualKeyCode);
  emacs_ev->timestamp = GetTickCount ();
  return 1;
}
示例#27
0
int
main(int argc, char **argv)
#endif
{
    int i;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    setuid(getuid());
#endif

#if defined(MSDOS) && !defined(_Windows) && !defined(__GNUC__)
    PC_setup();
#endif /* MSDOS !Windows */

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    int rc;
#ifdef OS2_IPC
    char semInputReadyName[40];
    sprintf( semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid() );
    rc = DosCreateEventSem(semInputReadyName,&semInputReady,0,0);
    if (rc != 0)
      fputs("DosCreateEventSem error\n",stderr);
#endif
    rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif

/* get helpfile from home directory */
#ifdef __DJGPP__
    {
	char *s;
	strcpy(HelpFile, argv[0]);
	for (s = HelpFile; *s; s++)
	    if (*s == DIRSEP1)
		*s = DIRSEP2;	/* '\\' to '/' */
	strcpy(strrchr(HelpFile, DIRSEP2), "/gnuplot.gih");
    }			/* Add also some "paranoid" tests for '\\':  AP */
#endif /* DJGPP */

#ifdef VMS
    unsigned int status[2] = { 1, 0 };
#endif

#if defined(HAVE_LIBEDITLINE)
    rl_getc_function = getc_wrapper;
#endif

#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc' 
     * or gnuplot specific commands in '.editrc' (when using editline
     * instead of readline) */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
    using_history();
#endif
#if defined(HAVE_LIBREADLINE) && !defined(MISSING_RL_TILDE_EXPANSION)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION]... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n"
#ifdef DIST_CONTACT
		    "Report bugs to "DIST_CONTACT"\n"
		    "            or %s\n",
#else
		    "Report bugs to %s\n",
#endif
		    gnuplot_version, gnuplot_patchlevel, bug_email);
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")) {
	    persist_cl = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* this was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     * Failing this, I propose we just make the call and
     * ignore the return : its probably not a big deal
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

#ifdef X11
    /* This call used to be in x11.trm, with the following comment:
     *   Multi-character inputs like escape sequences but also mouse-pasted
     *   text got buffered and therefore didn't trigger the select() function
     *   in X11_waitforinput(). Switching to unbuffered input solved this.
     *   23 Jan 2002 (joze)
     * But switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * The #ifdef X11 is probably unnecessary, but makes the change minimal.
     * Do any non-X platforms suffer from the same problem?
     * EAM - Jan 2004.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);
#endif

#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    (void) Gcomplex(&udv_pi.udv_value, M_PI, 0.0);
    udv_NaN = add_udv_by_name("NaN");
    (void) Gcomplex(&(udv_NaN->udv_value), not_a_number(), 0.0);
    udv_NaN->udv_undef = FALSE;

    init_memory();

    interactive = FALSE;
    init_terminal();		/* can set term type if it likes */
    push_terminal(0);		/* remember the default terminal */

    /* reset the terminal when exiting */
    /* this is done through gp_atexit so that other terminal functions
     * can be registered to be executed before the terminal is reset. */
    GP_ATEXIT(term_reset);

# if defined(_Windows) && ! defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif

    if (argc > 1)
	interactive = noinputfiles = FALSE;
    else
	noinputfiles = TRUE;

    /* Need this before show_version is called for the first time */

#ifdef HAVE_SYS_UTSNAME_H
    {
	struct utsname uts;

	/* something is fundamentally wrong if this fails ... */
	if (uname(&uts) > -1) {
# ifdef _AIX
	    strcpy(os_name, uts.sysname);
	    sprintf(os_name, "%s.%s", uts.version, uts.release);
# elif defined(SCO)
	    strcpy(os_name, "SCO");
	    strcpy(os_rel, uts.release);
# elif defined(DJGPP)
	    if (!strncmp(uts.sysname, "??Un", 4)) /* don't print ??Unknow" */
		strcpy(os_name, "Unknown");
	    else {
		strcpy(os_name, uts.sysname);
		strcpy(os_rel, uts.release);
	    }
# else
	    strcpy(os_name, uts.sysname);
	    strcpy(os_rel, uts.release);
# ifdef OS2
	    if (!strchr(os_rel,'.'))
		/* write either "2.40" or "4.0", or empty -- don't print "OS/2 1" */
		strcpy(os_rel, "");
# endif

# endif
	}
    }
#else /* ! HAVE_SYS_UTSNAME_H */

    strcpy(os_name, OS);
    strcpy(os_rel, "");

#endif /* HAVE_SYS_UTSNAME_H */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

#ifdef WGP_CONSOLE
#ifdef CONSOLE_SWITCH_CP
    if (cp_changed && interactive) {
	fprintf(stderr,
	    "\ngnuplot changed the codepage of this console from %i to %i to\n" \
	    "match the graph window. Some characters might only display correctly\n" \
	    "if you change the font to a non-raster type.\n", 
	    cp_input, GetConsoleCP());
    }
#else
    if ((GetConsoleCP() != GetACP()) && interactive) {
	fprintf(stderr,
	    "\nWarning: The codepage of the graph window (%i) and that of the\n" \
	    "console (%i) differ. Use `set encoding` or `!chcp` if extended\n" \
	    "characters don't display correctly.\n", 
	    GetACP(), GetConsoleCP());
    }
#endif
#endif

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    if (status[1] = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(status[1]);
    if (status[1] = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(status[1]);
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	/* should move this stuff another initialisation routine,
	 * something like init_set() maybe */
	get_user_env();
	init_loadpath();
	init_locale();
	/* HBB: make sure all variables start in the same mode 'reset'
	 * would set them to. Since the axis variables aren't in
	 * initialized arrays any more, this is now necessary... */
	reset_command();
	init_color();  /*  Initialization of color  */
	load_rcfile();
	init_fit();		/* Initialization of fitting module */

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
	    FPRINTF((stderr, "Before read_history\n"));
#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    FPRINTF((stderr, "expanded_history_filename = %s\n", expanded_history_filename));
	    read_history(expanded_history_filename);
	    {
		/* BEGIN: Go local to get environment variable */
		const char *temp_env = getenv ("GNUPLOT_HISTORY_SIZE");
		if (temp_env)
		    gnuplot_history_size = strtol (temp_env, (char **) NULL, 10);
	    } /* END: Go local to get environment variable */

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     * This is the default behaviour (traditional reasons), too.
	     * In case you don't have one of these functions, or you don't
	     * want to use them, 'write_history()' is called directly.
	     */
	    GP_ATEXIT(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

	    fprintf(stderr, "\nTerminal type set to '%s'\n", term->name);
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_READLINE_RESET
	else
	{
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

	load_file_error();	/* if we were in load_file(), cleanup */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */
	if (!interactive && !noinputfiles) {
	    term_reset();
	    exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    if (argc > 1) {
#ifdef _Windows
	TBOOLEAN noend = persist_cl;
#endif

	/* load filenames given as arguments */
	while (--argc > 0) {
	    ++argv;
	    c_token = 0;
#ifdef _Windows
	    if (stricmp(*argv, "-noend") == 0 || stricmp(*argv, "/noend") == 0
	       	|| stricmp(*argv, "-persist") == 0)
		noend = TRUE;
	    else
#endif
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));

	    } else if (strcmp(*argv, "-") == 0) {
		interactive = TRUE;
		while (!com_line());
		interactive = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		do_string(*argv);

	    } else {
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), FALSE);
	    }
	}
#ifdef _Windows
	if (noend) {
	    interactive = TRUE;
	    while (!com_line());
	}
#endif
    } else {
	/* take commands from stdin */
	while (!com_line());
    }

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
    return exit_status;
}
示例#28
0
void Diagnostics::run()
{
	QString info;
	QTextStream s( &info );

	s << "<b>" << tr("Locale (time-, number format / codepage):") << "</b> ";
	QLocale::Language language = QLocale::system().language();
	QString locale = (language == QLocale::C ? "English/United States" : QLocale::languageToString( language ) );
	CPINFOEX CPInfoEx;
	if( GetCPInfoEx( GetConsoleCP(), 0, &CPInfoEx ) != 0 )
		locale.append( " / " ).append( QString( (QChar*)CPInfoEx.CodePageName ) );
	s << locale << "<br />";
	emit update( info );
	info.clear();

	s << "<b>" << tr("User rights: ") << "</b>" << getUserRights() << "<br />";
	emit update( info );
	info.clear();

	QStringList base = Common::packages( QStringList()
		<< "Eesti ID-kaardi tarkvara" << "Estonian ID-card software", false );
	if( !base.isEmpty() )
		s << "<b>" << tr("Base version:") << "</b> " << base.join( "<br />" ) << "<br />";
	s << "<b>" << tr("Application version:") << "</b> "<< QCoreApplication::applicationVersion()
#ifdef INTERNATIONAL
		<< " INTERNATIONAL"
#endif
		<< "<br />";
	emit update( info );
	info.clear();

	s << "<b>" << tr("OS:") << "</b> " << Common::applicationOs() << "<br />";
	SYSTEM_INFO sysinfo;
	GetSystemInfo( &sysinfo );
	s << "<b>" << tr("CPU:") << "</b> " << QString::number( sysinfo.dwProcessorType ) << "<br /><br />";
	emit update( info );
	info.clear();

	s << "<b>" << "URLs:" << "</b>";
	const QHash<QString,QString> urls = qApp->urls();
	for(auto i = urls.constBegin(); i != urls.constEnd(); ++i)
		s << "<br />" << i.key() << ": " << i.value();
	s << "<br /><br />";

	s << "<b>" << tr("Arguments:") << "</b> " << qApp->arguments().join(" ") << "<br />";
	s << "<b>" << tr("Library paths:") << "</b> " << QCoreApplication::libraryPaths().join( ";" ) << "<br />";

	s << "<b>" << tr("Libraries") << ":</b><br />" << "QT (" << qVersion() << ")<br />";
	Q_FOREACH( const QString &lib, QStringList()
			<< "digidoc" << "digidocpp" << "qdigidocclient.exe" << "qesteidutil.exe" << "id-updater.exe"
			<< "esteidcsp" << "esteidcm" << "opensc-pkcs11" << "esteid-pkcs11" << "EsteidShellExtension"
			<< "esteid-plugin-ie" << "npesteid-firefox-plugin" << "chrome-token-signing.exe"
			<< "zlib1" << "libeay32" << "ssleay32" << "xerces-c_3_1" << "xsec_1_7" << "libxml2"
			<< "advapi32" << "crypt32" << "winscard" )
	{
		DWORD infoHandle = 0;
		LONG sz = GetFileVersionInfoSize( LPCWSTR(lib.utf16()), &infoHandle );
		if( !sz )
			continue;
		QByteArray data( sz * 2, 0 );
		if( !GetFileVersionInfoW( LPCWSTR(lib.utf16()), 0, sz, data.data() ) )
			continue;
		VS_FIXEDFILEINFO *info = 0;
		UINT len = 0;
		if( !VerQueryValueW( data.constData(), L"\\", (LPVOID*)&info, &len ) )
			continue;
		s << QString( "%1 (%2.%3.%4.%5)" ).arg( lib )
			.arg( HIWORD(info->dwFileVersionMS) )
			.arg( LOWORD(info->dwFileVersionMS) )
			.arg( HIWORD(info->dwFileVersionLS) )
			.arg( LOWORD(info->dwFileVersionLS) ) << "<br />";
	}
	s << "<br />";
	emit update( info );
	info.clear();

	enum {
		Running,
		Stopped,
		NotFound
	} atrfiltr = NotFound, certprop = NotFound;
	if( SC_HANDLE h = OpenSCManager( 0, 0, SC_MANAGER_CONNECT ) )
	{
		if( SC_HANDLE s = OpenService( h, L"atrfiltr", SERVICE_QUERY_STATUS ) )
		{
			SERVICE_STATUS status;
			QueryServiceStatus( s, &status );
			atrfiltr = (status.dwCurrentState == SERVICE_RUNNING) ? Running : Stopped;
			CloseServiceHandle( s );
		}
		if( SC_HANDLE s = OpenService( h, L"CertPropSvc", SERVICE_QUERY_STATUS ))
		{
			SERVICE_STATUS status;
			QueryServiceStatus( s, &status );
			certprop = (status.dwCurrentState == SERVICE_RUNNING) ? Running : Stopped;
			CloseServiceHandle( s );
		}
		CloseServiceHandle( h );
	}
	s << "<br /><b>" << tr("ATRfiltr service status: ") << "</b>" << " ";
	switch( atrfiltr )
	{
	case NotFound: s << tr("Not found"); break;
	case Stopped: s << tr("Not running"); break;
	case Running: s << tr("Running"); break;
	}
	s << "<br /><b>" << tr("Certificate Propagation service status: ") << "</b>" << " ";
	switch( certprop )
	{
	case NotFound: s << tr("Not found"); break;
	case Stopped: s << tr("Not running"); break;
	case Running: s << tr("Running"); break;
	}
	s << "<br />";

	getReaderInfo( s );
	emit update( info );
	info.clear();

	QStringList browsers = Common::packages( QStringList() << "Firefox" << "Google Chrome" );
	QSettings reg( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer", QSettings::NativeFormat );
	browsers << QString( "Internet Explorer (%1)" ).arg(
		reg.value("svcVersion", reg.value( "Version" ) ).toString() );
	s << "<br /><br /><b>" << tr("Browsers:") << "</b><br />" << browsers.join( "<br />" ) << "<br /><br />";
	emit update( info );
	info.clear();
}
示例#29
0
Tcl_Channel
TclWinOpenConsoleChannel(
    HANDLE handle,
    char *channelName,
    int permissions)
{
    char encoding[4 + TCL_INTEGER_SPACE];
    ConsoleInfo *infoPtr;
    DWORD id, modes;

    ConsoleInit();

    /*
     * See if a channel with this handle already exists.
     */

    infoPtr = (ConsoleInfo *) ckalloc((unsigned) sizeof(ConsoleInfo));
    memset(infoPtr, 0, sizeof(ConsoleInfo));

    infoPtr->validMask = permissions;
    infoPtr->handle = handle;
    infoPtr->channel = (Tcl_Channel) NULL;

    wsprintfA(encoding, "cp%d", GetConsoleCP());

    infoPtr->threadId = Tcl_GetCurrentThread();

    /*
     * Use the pointer for the name of the result channel. This keeps the
     * channel names unique, since some may share handles (stdin/stdout/stderr
     * for instance).
     */

    wsprintfA(channelName, "file%lx", (int) infoPtr);

    infoPtr->channel = Tcl_CreateChannel(&consoleChannelType, channelName,
	    (ClientData) infoPtr, permissions);

    if (permissions & TCL_READABLE) {
	/*
	 * Make sure the console input buffer is ready for only character
	 * input notifications and the buffer is set for line buffering. IOW,
	 * we only want to catch when complete lines are ready for reading.
	 */

	GetConsoleMode(infoPtr->handle, &modes);
	modes &= ~(ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT);
	modes |= ENABLE_LINE_INPUT;
	SetConsoleMode(infoPtr->handle, modes);

	infoPtr->readable = CreateEvent(NULL, TRUE, TRUE, NULL);
	infoPtr->startReader = CreateEvent(NULL, FALSE, FALSE, NULL);
	infoPtr->stopReader = CreateEvent(NULL, FALSE, FALSE, NULL);
	infoPtr->readThread = CreateThread(NULL, 256, ConsoleReaderThread,
		infoPtr, 0, &id);
	SetThreadPriority(infoPtr->readThread, THREAD_PRIORITY_HIGHEST);
    }

    if (permissions & TCL_WRITABLE) {
	infoPtr->writable = CreateEvent(NULL, TRUE, TRUE, NULL);
	infoPtr->startWriter = CreateEvent(NULL, FALSE, FALSE, NULL);
	infoPtr->stopWriter = CreateEvent(NULL, FALSE, FALSE, NULL);
	infoPtr->writeThread = CreateThread(NULL, 256, ConsoleWriterThread,
		infoPtr, 0, &id);
	SetThreadPriority(infoPtr->writeThread, THREAD_PRIORITY_HIGHEST);
    }

    /*
     * Files have default translation of AUTO and ^Z eof char, which means
     * that a ^Z will be accepted as EOF when reading.
     */

    Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto");
    Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "\032 {}");
    if (tclWinProcs->useWide)
	Tcl_SetChannelOption(NULL, infoPtr->channel, "-encoding", "unicode");
    else
	Tcl_SetChannelOption(NULL, infoPtr->channel, "-encoding", encoding);

    return infoPtr->channel;
}
示例#30
0
文件: sys.cpp 项目: Thooms/pyston
void setEncodingAndErrors() {
    // Adapted from pythonrun.c in CPython, with modifications for Pyston.

    char* p;
    char* icodeset = nullptr;
    char* codeset = nullptr;
    char* errors = nullptr;
    int free_codeset = 0;
    int overridden = 0;
    PyObject* sys_stream, *sys_isatty;
    char* saved_locale, *loc_codeset;

    if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
        p = icodeset = codeset = strdup(p);
        free_codeset = 1;
        errors = strchr(p, ':');
        if (errors) {
            *errors = '\0';
            errors++;
        }
        overridden = 1;
    }

#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
    /* On Unix, set the file system encoding according to the
       user's preference, if the CODESET names a well-known
       Python codec, and Py_FileSystemDefaultEncoding isn't
       initialized by other means. Also set the encoding of
       stdin and stdout if these are terminals, unless overridden.  */

    if (!overridden || !Py_FileSystemDefaultEncoding) {
        saved_locale = strdup(setlocale(LC_CTYPE, NULL));
        setlocale(LC_CTYPE, "");
        loc_codeset = nl_langinfo(CODESET);
        if (loc_codeset && *loc_codeset) {
            PyObject* enc = PyCodec_Encoder(loc_codeset);
            if (enc) {
                loc_codeset = strdup(loc_codeset);
                Py_DECREF(enc);
            } else {
                if (PyErr_ExceptionMatches(PyExc_LookupError)) {
                    PyErr_Clear();
                    loc_codeset = NULL;
                } else {
                    PyErr_Print();
                    exit(1);
                }
            }
        } else
            loc_codeset = NULL;
        setlocale(LC_CTYPE, saved_locale);
        free(saved_locale);

        if (!overridden) {
            codeset = icodeset = loc_codeset;
            free_codeset = 1;
        }

        /* Initialize Py_FileSystemDefaultEncoding from
           locale even if PYTHONIOENCODING is set. */
        if (!Py_FileSystemDefaultEncoding) {
            Py_FileSystemDefaultEncoding = loc_codeset;
            if (!overridden)
                free_codeset = 0;
        }
    }
#endif

#ifdef MS_WINDOWS
    if (!overridden) {
        icodeset = ibuf;
        codeset = buf;
        sprintf(ibuf, "cp%d", GetConsoleCP());
        sprintf(buf, "cp%d", GetConsoleOutputCP());
    }
#endif

    if (codeset) {
        sys_stream = PySys_GetObject("stdin");
        sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
        if (!sys_isatty)
            PyErr_Clear();
        if ((overridden || (sys_isatty && PyObject_IsTrue(sys_isatty))) && PyFile_Check(sys_stream)) {
            if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
                Py_FatalError("Cannot set codeset of stdin");
        }
        Py_XDECREF(sys_isatty);

        sys_stream = PySys_GetObject("stdout");
        sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
        if (!sys_isatty)
            PyErr_Clear();
        if ((overridden || (sys_isatty && PyObject_IsTrue(sys_isatty))) && PyFile_Check(sys_stream)) {
            if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
                Py_FatalError("Cannot set codeset of stdout");
        }
        Py_XDECREF(sys_isatty);

        sys_stream = PySys_GetObject("stderr");
        sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
        if (!sys_isatty)
            PyErr_Clear();
        if ((overridden || (sys_isatty && PyObject_IsTrue(sys_isatty))) && PyFile_Check(sys_stream)) {
            if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
                Py_FatalError("Cannot set codeset of stderr");
        }
        Py_XDECREF(sys_isatty);

        if (free_codeset)
            free(codeset);
    }
}