#!/usr/bin/env python

"""
Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""

class _Getch(object):
    """
    Gets a single character from standard input.  Does not echo to
    the screen (reference: http://code.activestate.com/recipes/134892/)
    """
    def __init__(self):
        # 尝试使用Windows系统的方法获取字符
        try:
            self.impl = _GetchWindows()
        # 如果Windows系统的方法不可用，则尝试使用Mac系统的方法获取字符
        except ImportError:
            try:
                self.impl = _GetchMacCarbon()
            # 如果Mac系统的方法不可用，则使用Unix系统的方法获取字符
            except(AttributeError, ImportError):
                self.impl = _GetchUnix()

    def __call__(self):
        # 调用获取字符的方法
        return self.impl()

class _GetchUnix(object):
    """
    Unix implementation of _Getch
    """
    def __init__(self):
        # 导入tty模块
        __import__("tty")

    def __call__(self):
        # 导入sys、termios、tty模块
        import sys
        import termios
        import tty

        # 获取标准输入的文件描述符
        fd = sys.stdin.fileno()
        # 获取当前终端的属性
        old_settings = termios.tcgetattr(fd)
        try:
            # 设置终端为原始模式
            tty.setraw(sys.stdin.fileno())
            # 读取一个字符
            ch = sys.stdin.read(1)
        finally:
            # 恢复终端的属性
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        # 返回读取的字符
        return ch

class _GetchWindows(object):
    """
    Windows implementation of _Getch
    """
    def __init__(self):
        # 导入msvcrt模块
        __import__("msvcrt")

    def __call__(self):
        # 导入msvcrt模块
        import msvcrt
        # 调用msvcrt模块的getch函数，获取键盘输入
        return msvcrt.getch()

class _GetchMacCarbon(object):
    """
    A function which returns the current ASCII key that is down;
    if no ASCII key is down, the null string is returned.  The
    page http://www.mactech.com/macintosh-c/chap02-1.html was
    very helpful in figuring out how to do this.
    """
    def __init__(self):
        # 导入Carbon模块
        import Carbon

        # 检查Carbon模块中是否有Evt属性
        getattr(Carbon, "Evt")  # see if it has this (in Unix, it doesn't)

    def __call__(self):
        # 导入Carbon模块
        import Carbon

        # 检查是否有按键按下
        if Carbon.Evt.EventAvail(0x0008)[0] == 0:  # 0x0008 is the keyDownMask
            return ''
        else:
            #
            # The event contains the following info:
            # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            #
            # The message (msg) contains the ASCII char which is
            # extracted with the 0x000000FF charCodeMask; this number is
            # number is converted to an ASCII character with chr() and
            # returned
            #
            (what, msg, when, where, mod) = Carbon.Evt.GetNextEvent(0x0008)[1]
            return chr(msg & 0x000000FF)

getch = _Getch()
