1/*
2 * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26#include "jni.h"
27#include "jni_util.h"
28#include "jvm.h"
29#include "java_io_Console.h"
30
31#include <stdlib.h>
32#include <Wincon.h>
33
34static HANDLE hStdOut = INVALID_HANDLE_VALUE;
35static HANDLE hStdIn = INVALID_HANDLE_VALUE;
36JNIEXPORT jboolean JNICALL
37Java_java_io_Console_istty(JNIEnv *env, jclass cls)
38{
39    if (hStdIn == INVALID_HANDLE_VALUE &&
40        (hStdIn = GetStdHandle(STD_INPUT_HANDLE)) == INVALID_HANDLE_VALUE) {
41        return JNI_FALSE;
42    }
43    if (hStdOut == INVALID_HANDLE_VALUE &&
44        (hStdOut = GetStdHandle(STD_OUTPUT_HANDLE)) == INVALID_HANDLE_VALUE) {
45        return JNI_FALSE;
46    }
47    if (GetFileType(hStdIn) != FILE_TYPE_CHAR ||
48        GetFileType(hStdOut) != FILE_TYPE_CHAR)
49        return JNI_FALSE;
50    return JNI_TRUE;
51}
52
53JNIEXPORT jstring JNICALL
54Java_java_io_Console_encoding(JNIEnv *env, jclass cls)
55{
56    char buf[64];
57    int cp = GetConsoleCP();
58    if (cp >= 874 && cp <= 950)
59        sprintf(buf, "ms%d", cp);
60    else
61        sprintf(buf, "cp%d", cp);
62    return JNU_NewStringPlatform(env, buf);
63}
64
65JNIEXPORT jboolean JNICALL
66Java_java_io_Console_echo(JNIEnv *env, jclass cls, jboolean on)
67{
68    DWORD fdwMode;
69    jboolean old;
70    if (! GetConsoleMode(hStdIn, &fdwMode)) {
71        JNU_ThrowIOExceptionWithLastError(env, "GetConsoleMode failed");
72        return !on;
73    }
74    old = (fdwMode & ENABLE_ECHO_INPUT) != 0;
75    if (on) {
76        fdwMode |= ENABLE_ECHO_INPUT;
77    } else {
78        fdwMode &= ~ENABLE_ECHO_INPUT;
79    }
80    if (! SetConsoleMode(hStdIn, fdwMode)) {
81        JNU_ThrowIOExceptionWithLastError(env, "SetConsoleMode failed");
82    }
83    return old;
84}
85