unread input lazarus / 21-General ---------------------------------------------------------------------- freemind001 · 2023-03-18 08:34 how do i discard unread input in console program? need to clear everything before calling readln(); ---------------------------------------------------------------------- KodeZwerg · 2023-03-18 09:42 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Project1; {$IFDEF MSWINDOWS}{$APPTYPE CONSOLE}{$ENDIF} uses  CRT; // this must be included for oldschool console apps begin  ClrScr; // this method "Clr = Clear / Scr = Screen" call whenever neededend. ---------------------------------------------------------------------- freemind001 · 2023-03-18 10:40 I'm not about about clearing the screen, I'm about standart input. During execution of program the user is asked to press keys, that readln(); can't handle. (e.g. ENTER or PAUSE) These keypresses are handled with direct '/dev/input' reading. Then i need user to enter the string. i do readln(str); but after that str also contains all the stuff that user entered before readln call. how do i clear it? ---------------------------------------------------------------------- jcmontherock · 2023-03-18 11:11 Did you try "Keyboard" ? ---------------------------------------------------------------------- Warfley · 2023-03-18 11:27 Simple do a non bocking read (or peak) to stdin, if there is something read it and discard what you have read ---------------------------------------------------------------------- freemind001 · 2023-03-18 11:54 Quote from: jcmontherock on March 18, 2023, 12:11:03 pmDid you try "Keyboard" ? what do you mean? ---------------------------------------------------------------------- freemind001 · 2023-03-18 11:57 Quote from: Warfley on March 18, 2023, 12:27:16 pmSimple do a non bocking read (or peak) to stdin, if there is something read it and discard what you have read How do i do that in pascal? ---------------------------------------------------------------------- Warfley · 2023-03-18 12:07 Depends on your concrete situation, and what you want to do. You need to first understand how console I/O is working. There are two modes of reading input, the first one is raw, the second one is buffered. The default configuration is buffered, then your terminal emulator will capture all the inputs and only send them to your programs stdin when you pressed enter/newline. If you are operating in this configuration it's really easy, just check if input is available (e.g. using fpselect) and do readlines until no more input is available. In raw mode each char (and keycode) is sent individually to your application, in this case you could read every char until the buffer is empty, or you do a non blocking read with a large buffer until you don't read any more bytes. You may take a look at my LazTermUtils compatibility unit, which has a lot of the raw functionality: https://github.com/Warfley/LazTermUtils/ blob/master/src/compatibility.pas#L175 ---------------------------------------------------------------------- KodeZwerg · 2023-03-18 12:14 Quote from: freemind001 on March 18, 2023, 11:40:33 ami do readln(str); but after that str also contains all the stuff that user entered before readln call. how do i clear it?Switch from ReadLn() to ReadKey() from unit CRT and filter there everything out what you not need in final string (a simple while or repeat until loop would be okay for that scenario) ---------------------------------------------------------------------- freemind001 · 2023-03-18 12:18 Quote from: Warfley on March 18, 2023, 01:07:33 pmwhat you want to do Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program project1;uses  sysutils;var  s:string;begin  writeln('Program is doing some job, emulating this with sleep');  sleep(5000); //input A while program is busy  //need to clear input here  writeln('Now input B');  Readln(s);  writeln('s contains A and B: ', s); // need s to contain B only end. ---------------------------------------------------------------------- Warfley · 2023-03-18 12:45 So you are in buffered mode, the problem here is a bit that this way you can only clear full lines. Take the following example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   sleep(5000); // Type something without pressing enter  WriteLn('Test');  ReadLn(ln); // Now waits for enter but still has the things typed before  WriteLn(ln); It should be also noted that there are big differences between windows and Linux, I am currently under Windows so I can't just test it out for you. But if you want to avoid this, I think what should work is changing the mode to raw mode (see EnableDirectRead in my Compatibility.pas htt ps://github.com/Warfley/LazTermUtils/blob/master/src/compatibility.pas #L143) Then read the data, as this now does not need to be buffered anymore, and then restore to buffered mode when reading the line (see RestoreDirectRead right below EnableDirectRead). Or with my TermUtils Unit: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Project1; {$mode objfpc}{$H+} uses  SysUtils, Terminal; var  term: TTerminal;  ln: String;  dummy: Char;begin  term := TTerminal.Create;  try    Sleep(1000);    term.Input.DirectRead := True; // Enable raw mode for consuming buffer    try      while term.Input.ReadCharNonBlocking(dummy) do; // Consume all buffer    finally      term.Input.DirectRead := false; // Disable raw mode for normal readln behavior    end;    WriteLn('Please enter text');    ln := term.input.ReadLn; // Or plain old readln if you want to    WriteLn(ln);  finally    term.Free;  end;  ReadLn;end. ---------------------------------------------------------------------- Warfley · 2023-03-18 12:50 Quote from: KodeZwerg on March 18, 2023, 01:14:01 pmSwitch from ReadLn() to ReadKey() from unit CRT and filter there everything out what you not need in final string (a simple while or repeat until loop would be okay for that scenario) But you should be aware that including crt into the project will completely alter the behavior of input reading and buffering (well, not just input but also output behavior will be completely altered). This means that most low level OS operations like ioctl might not work as expected, select, or non blocking reads don't work anymore, etc. If you choose to use CRT you must know that you can't use any non CRT terminal functionality anymore. It especially detaches from the low level OS APIs, which might make it incompatible with other code. My personal recommendation is to avoid the CRT unit whenever possible ---------------------------------------------------------------------- KodeZwerg · 2023-03-18 13:02 Quote from: Warfley on March 18, 2023, 01:50:06 pmQuote from: KodeZwerg on March 18, 2023, 01:14:01 pmSwitch from ReadLn() to ReadKey() from unit CRT and filter there everything out what you not need in final string (a simple while or repeat until loop would be okay for that scenario)My personal recommendation is to avoid the CRT unit whenever possibleI do fully second that but since I do know as much as you, nothing about target OS, nothing about real purpose, IMHO my answer was legit. ---------------------------------------------------------------------- jamie · 2023-03-18 13:22 SeekEof; ? ---------------------------------------------------------------------- freemind001 · 2023-03-18 13:34 Quote from: KodeZwerg on March 18, 2023, 02:02:01 pm nothing about target OS, nothing about real purpose, IMHO my answer was legit. target os is linux, the purpose is writing config file for app. user runs app --config and follows instructions: Key "A" will be used for "Action A". Press key "A"  Key "B" will be used for "Action B". Press key "B" keys A and B may not be readable by readln, so they are read directly from '/dev/input/' while user presses A and B, they are kept in buffer, and this is a problem for further readln Quote from: Warfley on March 18, 2023, 01:45:24 pmEnableDirectRead in my Compatibility.pas what is oldState in your EnableDirectRead? this Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program project1; uses  SysUtils, termio,  BaseUnix; var  s: string;  newTIO, oldTIO: Termios;begin  TCGetAttr(0, oldTIO);  TCGetAttr(0, newTIO);  CFMakeRaw(newTIO);  TCSetAttr(0, TCSANOW, newTIO);  writeln('Program is doing some job, emulating this with sleep');  sleep(5000); //press A  TCSetAttr(0, TCSANOW, oldTIO);  writeln('Now input B');  Readln(s);  writeln('s contains', s);end.   doesn't work, or maybe I do not understand the idea ---------------------------------------------------------------------- jamie · 2023-03-18 13:38 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i While Not SeekEOF do;  Have you tried that? Otherwise you could simply loop with the same thing using the READ; ---------------------------------------------------------------------- Warfley · 2023-03-18 14:15 Quote from: freemind001 on March 18, 2023, 02:34:03 pmtarget os is linux, the purpose is writing config file for app. user runs app --config and follows instructions: Key "A" will be used for "Action A". Press key "A"  Key "B" will be used for "Action B". Press key "B" keys A and B may not be readable by readln, so they are read directly from '/dev/input/' while user presses A and B, they are kept in buffer, and this is a problem for further readln If you want to read keys, don't read them from /dev/input, use the raw mode directly, this way you don't have different read states between that and readln. Also have you considered using my TermUtils? Because they already said, they support exactly what you are describing: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  Term: TTerminal;  k: TTerminalKey;  ln: String;begin  term := TTerminal.Create;  try    WriteLn('Interactive Mode:');    term.Input.DirectRead := True;    try      while true do      begin      k := Term.Input.ReadKey;        if k.SpecialKeyCode = skEscape then // Escape: Exit loop          break;        if k.CharValue = 'a' then          term.Output.WriteLn('User Pressed A');        if k.CharValue = 'b' then          term.Output.WriteLn('User Pressed B');      end;    finally      term.Input.DirectRead := False;    end;    WriteLn('Back to line based mode:');    ReadLn(ln);    WriteLn(ln);  finally    term.Free;  end;end. ---------------------------------------------------------------------- Thaddy · 2023-03-18 14:21 Quote from: jamie on March 18, 2023, 02:38:07 pmCode: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i While Not SeekEOF do;  Have you tried that? Otherwise you could simply loop with the same thing using the READ; Much simpler: EOF() is basic Pascal. ---------------------------------------------------------------------- Warfley · 2023-03-18 14:53 Neither EOF nor SeekEOF will work on StdIn/Input, because it is a pipe, and this is only EOF when the other side is closed. So as long as it was not closed (e.g. by using ctrl+D in the console), this will try to continue to read, and therefore be blocking. It's not usable to check how much is buffered within a pipe. What can be done is to use select to check if something is in buffer, do a non blocking read (set O_NOBLOCK in the file descriptor attributes on Linux), or try to do a read with the PEEK flag (but I don't know if this works for pipes or only for sockets) ---------------------------------------------------------------------- freemind001 · 2023-03-18 14:54 Quote from: jamie on March 18, 2023, 02:38:07 pmHave you tried that? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  s: string;begin  writeln('Program is doing some job, emulating this with sleep');  sleep(5000); //press A  while not SeekEOF do    Read();  writeln('Now input B');  Readln(s);  writeln('s contains ', s);   program never goes out of while seems like there is no EOF in input Quote from: Warfley on March 18, 2023, 03:15:54 pmAlso have you considered using my TermUtils? Do they handle keys like ctrl, win, pause/break? ---------------------------------------------------------------------- Warfley · 2023-03-18 15:02 Quote from: freemind001 on March 18, 2023, 03:54:07 pmDo they handle keys like ctrl, win, pause/break? ctrl and win (meta) are only readable as modifiers (i.e. you can recognize ctrl + a, but not ctrl seperately). Pause is actually a bug, which I just found and will fix later today. Also remember that whats possible is often highly dependent on the terminal emulator used, not everything that xterm does is for example supported by gnome terminal and vice versa ---------------------------------------------------------------------- jamie · 2023-03-18 15:15 Can't help if things don't work as documented. have you tried this? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Flush(Input); ---------------------------------------------------------------------- Warfley · 2023-03-18 15:21 EOF works as it should, it's just that the end of the file for a pipe is not when there is no more input in the buffer, it's when the pipe is closed. And flush will also not work, because flush is for writing the buffer to the filesystem, but this only makes sense for output files not input files. Pipes are a bit special, they work more like sockets than "real" files (you can see them as sockets lite, because the sockets api has a bit more functionality than is applicable to pipes) ---------------------------------------------------------------------- Thaddy · 2023-03-18 15:37 Quote from: Warfley on March 18, 2023, 03:53:07 pmNeither EOF nor SeekEOF will work on StdIn/Input Nonsense. Be careful. SeekEof - who did that!  -should not be there and Eof() is proper Pascal. And of course both should work in any terminal. Really strange remark.Works with :Input, Output, StdIn, StdOut, StdErr and whatever I forgot.... Silly. ---------------------------------------------------------------------- Warfley · 2023-03-18 15:47 Yes they do work, but not for the purposes as described here, they don't tell you if there is something in the buffer, but if the pipe was closed on the other end. I sometimes feel like you don't read my posts fully, because this is literally one comma after the part you quoted: QuoteNeither EOF nor SeekEOF will work on StdIn/Input, because it is a pipe, and this is only EOF when the other side is closed. So as long as it was not closed (e.g. by using ctrl+D in the console), this will try to continue to read, and therefore be blocking. Sure I could have been more precise, EOF works in general, but it does not work *as described/expected in this thread* ---------------------------------------------------------------------- freemind001 · 2023-03-18 16:22 Warfley, for couple of reasons we need to read keys directly from '/dev/input' (keyboard is not a keyboard, but a keyboard-like device, it can send exotic scancodes, we need to track them) is it possible somehow to "close" the pipe and then "reopen" it to clear the buffer? ---------------------------------------------------------------------- Warfley · 2023-03-18 17:30 As I've mentioned earlier, the consumption of the data through using raw mode should work easiely. I just taken the functions from TermUtils (removed the Windows specific part) and build the following: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Test;{$mode ObjFPC}{$H+} uses  SysUtils, termio, baseunix; function EnableDirectRead(Handle: THandle): Termios;var  nTIO: Termios;begin  TCGetAttr(Handle, Result);  nTIO := Result;  // Raw to not echo the characters inputted  CFMakeRaw(nTIO);  // Directly read and don't line buffer  TCSetAttr(Handle, TCSANOW, nTIO);end; procedure RestoreDirectRead(Handle: THandle; oldState: Termios);begin  TCSetAttr(Handle, TCSANOW, oldState);end; function CharAvailable(Handle: THandle): Boolean;var  fdSet: TFDSet;  timeout: TTimeVal;begin  fpFD_ZERO(fdSet);  fpFD_SET(Handle, fdSet);  timeout.tv_sec:=0;  timeout.tv_usec:=0;  Result := fpSelect(Handle + 1, @fdSet, nil, nil, @timeout) = 1;end; procedure DiscardBuffered(handle: THandle);var  oldState: Termios;  buff: array[0..1023] of Byte;begin  oldState := EnableDirectRead(handle);  try    while CharAvailable(Handle) do      fpRead(handle, buff, sizeOf(Buff));  finally    RestoreDirectRead(handle, oldState);  end;end; var  ln: String;begin  Sleep(5000);  WriteLn('test');  DiscardBuffered(StdInputHandle);  ReadLn(ln);  WriteLn(ln);end. This works on my linux system. If you don't want the inputs to be printed to the screen, you can slightly modify it: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Test;{$mode ObjFPC}{$H+} uses  SysUtils, termio, baseunix; function EnableDirectRead(Handle: THandle): Termios;var  nTIO: Termios;begin  TCGetAttr(Handle, Result);  nTIO := Result;  // Raw to not echo the characters inputted  CFMakeRaw(nTIO);  // Directly read and don't line buffer  TCSetAttr(Handle, TCSANOW, nTIO);end; procedure RestoreDirectRead(Handle: THandle; oldState: Termios);begin  TCSetAttr(Handle, TCSANOW, oldState);end; function CharAvailable(Handle: THandle): Boolean;var  fdSet: TFDSet;  timeout: TTimeVal;begin  fpFD_ZERO(fdSet);  fpFD_SET(Handle, fdSet);  timeout.tv_sec:=0;  timeout.tv_usec:=0;  Result := fpSelect(Handle + 1, @fdSet, nil, nil, @timeout) = 1;end; procedure DiscardBuffered(handle: THandle);var  buff: array[0..1023] of Byte;begin  while CharAvailable(Handle) do    fpRead(handle, buff, sizeOf(Buff));end; var  oldState: Termios;  ln: String;begin  oldState := EnableDirectRead(StdInputHandle);  try    Sleep(5000);  finally    RestoreDirectRead(StdInputHandle, oldState);  end;  WriteLn('test');  DiscardBuffered(StdInputHandle);  ReadLn(ln);  WriteLn(ln);end. Between the EnableDirectRead and RestoreDirectRead, all inputs the user makes will not be echoed to the terminal. So you can just surround the block where you don't need the user input by that, then discard the buffer afterwards and then start reading using Readln ---------------------------------------------------------------------- freemind001 · 2023-03-18 17:44 works, thank you! ---------------------------------------------------------------------- Kays · 2023-03-18 17:45 Quote from: Warfley on March 18, 2023, 04:21:49 pmAnd flush will also not work, because flush is for writing the buffer to the filesystem, but this only makes sense for output files not input files.On the contrary, flush is correct. However system.flush will, as you have also correctly stated, only work as desired on buffers managed by our Pascal program, in other words output files. You will need to ask the terminal driver to flush its buffer.Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses      baseUnix;const        TCFLSH = $0000540B;type        queueSelector = (TCIFLUSH, TCOFLUSH, TCIOFLUSH);begin        { Determine first if STDIN is connected to a terminal, then: }        fpIOCtl(stdInputHandle, TCFLSH, pointer(ord(TCIFLUSH)));end.