How to detect Caps Lock with ncurses? - c

I need to detect that caps lock is turned on/off on c with ncurses. Is it possible? If yes, how to?
Googling this question gives nothing useful.
Update
The reason I'm looking for it is as follows: I need to handle such key combinations as alt+F and alt+shift+F with different handlers. But alt+F with caps lock and alt+shift+F without caps lock return the same key code (by getch())

You can't. The state of Caps Lock is not made visible to terminals.

This can only be done with platform specific interface, i.e. using system interface rather than through the terminal/tty device. In Linux, you can read the keyboard device in /dev/input/ or by parsing the output of xset -q. Note that this will only be able to read local keyboard devices, which means that you won't be able to use this key if you need to use the program through ssh. You may need elevated permission to read input devices directly.

Related

How to get current keyboard cursor position in Linux terminal

I am dealing with an issue in Ubuntu. I want to get current keyboard cursor position in terminal via Gcc
any assist...
"Terminal" is a program, or more accurately a description of a large class of programs, which implements a graphical interface emulating an external terminal (which would have been connected to your computer via a serial cable, or in some similar fashion). Your program communicates with the terminal emulator through a kind of bidirectional pipe (a "pseudoterminal") implemented by the operating system; to your program it looks like a pair of ordinary streams (stdin and stdout).
Linux itself has a terminal emulator, called "the console", which can be used instead of a window manager. Few programmers use it these days, but it's still there if you want to experiment. The console is a "terminal" (and there are usually several of them which you can switch between using a control+function key). As you might expect from the words "terminal" and "pseudoterminal", these basically look the same to your application.
There are a ton of details, which I'm skipping over because it would take a book to describe the whole thing.
The only connection between your program and the terminal (or pseudoterminal) is that you can send it a stream of characters, and you can receive a stream of characters from it. There is no other communication. There's no hidden operating system interface, because the terminal emulator is not part of the operating system. It's not even part of the window manager. It's just another userland application running without special privileges, just like your application.
You often want to do things other than just send characters to the output device. Maybe you want to clear the screen, or move the cursor to another location, or change the colour of the text or the background. All of these things are done by sending specially coded sequences interspersed with the text you're displaying. The operating system doesn't mediate or verify these sequences, and there's no definitive standard for how the terminal emulator should interpret them, but there is common framework which most terminal emulators conform to, to some extent, which makes it possible to actually write code which doesn't need to know exactly which terminal emulator is being used at the moment. The terminfo library is commonly used to describe the available terminals; by convention, the environment variable TERM contains the name of the relevant terminfo configuration, and that configuration can be used to create concrete control sequence strings suitable for the configured terminal [Note 1].
Now let's get back to your initial question: "how do I find out the current cursor location?" That's one of a small number of possible queries, which are also implemented as control sequences. Specifically, you send the terminal a control sequnce which asks it where the cursor is (usually the four characters \x1B[6n) and the terminal eventually replies with a control sequence which might look something like \x1B12,7R meaning that the cursor was on row 12 at column 7 at the moment that the control sequence was sent [Note 2]. So you could use terminfo to help you send the query and then attempt to parse the reply when it comes.
Note that the response is not synchronous with the query, since the user could be typing while the query is sent. (However, the response is sent as a contiguous sequence.) So part of the parsing process is disentangling the user input from the query response.
My guess is that you don't actually want to do all that work. In most cases, if you want to write a console application which does something less boring than just write output sequentially to a terminal window, you should use ncurses (also maintained by Thomas Dickey) or some other similar library. Ncurses takes full responsibility for maintaining the console image, jumping through the necessary hoops to communicate with the terminal emulator; one of its features is to keep track of the current cursor position [Note 3].
Another option, if you are only trying to provide better line editing and tab completion, is to use the GNU Readline library, or similar interfaces available for other operating systems.
Notes
This might or might not be the terminal you're actually using, since TERM is just an environment variable. You could set it yourself if you wanted it.
I took those codes from man 4 console_codes; another good source of information is Thomas Dickey's terse list of code sequences understood by xterm.
As far as I know, Ncurses does not use the cursor-position query to figure out where the cursor is on the screen. It maintains its own copy of the screen being displayed, which includes the current cursor position. You can use the macro getyx() to ask for what it considers the current cursor position.

How to capture an input device and prevent it's default behavior

I have an RFID tag reader. But it works like a HID device (like a keyboard). It sends keystrokes to the computer when a tag is scanned. When I open notepad and scan a tag - it types the ID one digit at a time. Is there a way to create a program to listen to this device (or this port) and capture (intercept) all input. So that the keystrokes wouldn't appear on my system but I could assign my own events when the device sends and input. I don't want it to show up on Notepad.
I realize that the implementation can differ depending on the OS and programming language used. Ideally, I would like to make this work on both Windows and Linux. I would prefer to use something like Node.js but I suppose C could also be good.
I would appreciate any hints or pointing me in the right direction.
You could open the raw input device for reading (basically ioctl with parameter EVIOCGRAB for Linux and RegisterRawInputDevices() for Windows as discussed here and here). However, the mechanisms are quite different for Windows and Linux, so you will end up implementing all the low-level logic twice.
It should also be possible to read the input data stream from the standard input just like you would read an input from the keyboard (e.g. scanf() or fgets() in C) with some logic that recognizes when a data set (= tag ID) is complete - the reader device might for example terminate an input with a newline '\n' or null character '\0'.
You should probably do this in a separate thread and have some kind of producer-consumer mechanism or event model for communication with your main application.

How can I poll keyboard input in c?

I'm trying to make a simple game for the unix terminal, written in c. I've
been looking for a way to poll the keyboard, but haven't had any luck.
Currently I'm using ncurses getch() function. It works okay but if the user holds a key, the keyboard repeat will take a moment to start - also it will halt if any other key is pressed. This causes problems when playing (especially in two player mode where both games are controlled from a single input thread).
For example, if player 1 holds down 'a' and player 2 holds down 'b', I need to poll the keyboard and handle a stream of input like this:
abababababababab
As another example, if player 1 holds down the 'a' key and also presses the 'b' key, I need the input to be handled like this:
aaaaaaabaaaaaaaa
This way the simultaneous key presses don't interrupt each other. So I basically need to poll the keys on the keyboard on a set interval, and create my own implementation of a key press repeater.
Is there a way in c (with or without ncurses) to simply poll the keyboard on a time interval and read in all keys that are currently being pressed? From there I can just design the keyboard input thread to manage repeating actions manually. Basically something along the lines of kbhit, so I can check the status of a given key. But that will also let me poll the arrow keys.
It doesn't work that way:
Basically something along the lines of kbhit, so I can check the status of a given key. But that will also let me poll the arrow keys.
In any system that doesn't allow direct access to the hardware (MS-DOS is the only example you're likely to have encountered, others would include embedded systems), you're only able to read a sequence of characters (not keys) in a terminal application. GUI applications rely upon a server which does access some of the hardware (more) directly, but transforms the data.
In a terminal (such as used by ncurses), you can only check if the incoming characters includes the one that corresponds to the keyboard-key that you're interested in. Arrow keys send a sequence of characters: with ncurses you can either read the individual characters in the sequence, or rely upon ncurses to match the sequence to a known key in the terminal description.
Even with system-specific things such as the Linux console, you won't find much support for reading the keyboard as a whole: only character events. Read kbd_mode and console_ioctl to see what's available, keeping in mind this ancient caveat from the latter:
Warning: Do not regard this man page as documentation of the Linux
console ioctls. This is provided for the curious only, as an
alternative to reading the source. Ioctl's are undocumented Linux
internals, liable to be changed without warning. (And indeed, this
page more or less describes the situation as of kernel version
1.1.94; there are many minor and not-so-minor differences with
earlier versions.)
The suggested link Receiving key press and key release events in Linux terminal applications? gives some useful information. But as noted, the question (aside from the last point mentioned) is a duplicate.

How does one disable access to the keyboard and mouse from a linux kernel module?

I'm trying to write a kernel module which disables input between certain times of day. I found out how to get the time (How to get current hour (time of day) in linux kernel space) and how to schedule a function.
I can't seem to work out how to disable the inputs though. I'm thinking there has to be some place the kernel to do this but having read the API I'm still no further forward. I suppose I should just access the drivers directly and shut them off or something, but that seems a little non-generic.
Is this even possible?
Thanks for your time.
I'm not sure, but if you're in userspace, it should be sufficient to switch to an unused virtual console, then put the keyboard into raw mode. This will block the key combinations which would normally switch back into another virtual console. That won't disable the mouse, but X should ignore the mouse if it is not the current VT (just make sure gpm isn't running).
You also have to disable the magic-sysrq key combination if that is enabled, as there is a sysrq key to take the keyboard out of raw mode, which would otherwise get around this.
EDIT: it should be possible to do all of this from kernel space, provided you're in a normal task context. A kernel thread would do, I expect.
You can open files and devices from the kernel, it's just not recommended. A task which has a namespace containing /dev (I'm not sure whether kernel tasks do). You can call filp_open (I think) and get a file *, which you can then call the appropriate methods on its file_operations (f_op). This should include the ioctls required to do the above.
There might be a way of opening a device directly, not via the filp_open.
In short, it should be possible. It's a very dodgy thing to do from kernel space.
One way I can think of is disabling the IRQs for keyword and mouse.
disable_irq and enable_irq can be used to do that.
Here is IRQ numbers for x86. May be you have to consult other table to get IRQ for other platforms like SPARC, IA-64 if you need.

Get an input from keyboard without 'return' in C

How do i get an input from keyboard, without pressing 'return' in C / Mac Os
On Unix-like systems with terminals (I suppose that MacOS X qualifies), then you need to set the terminal to so-called "cbreak" mode. The point is that the terminal is keeping the data until "return" is pressed, so that there is nothing your C code can do, unless it instructs the terminal not to do such buffering. This is often called "cbreak mode" and involves the tcsetattr() function.
A bit of googling found this code which seems fine. Once the terminal is in cbreak mode, you will be able to read data as it comes with standard getchar() or fgetc() calls.
From the comp.lang.c FAQ:
How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they're typed?
If you have to handle the details yourself, use a curses variant. If it is available, prefer "ncurses" over "curses". Note that some keys are "Meta" keys which really just modify the base key codes. There are several "modes" for reading key input, which range from "cooked", through "partially cooked", to "raw". Each mode has its own peculiarities, read the documentation carefully.
Sometimes it's better to use existing key handling code from various game programming libraries, I've heard of some good results using SDL's key scanning loops. That was a while back, so perhaps newer (and better) toolkits exist.

Resources