Golang detect if in focus or minimized - go

How would I go about detecting if my go CLI program is in focus or minimized?
Current program based off https://github.com/jroimartin/gocui
I require the functionality as it is a chat program and I would like to send OS notifications but only when the program is not in focus or is minimized.
Your help/direction is much appreciated as of right now unsure where to start.

This is not possible from the library itself. A command line program does now have a focus, but the terminal program it is running in.
To implement that (if possible at all) would be dependent on os, window manager etc.

To refine the answer provided by #mbuechmann, I suggest the OP not to try to resort to APIs etc.
The reasoning is simple.
"Contemporary" users are used to running programs in terminal emulators which are typically presented as separate windows, and so the users naturally think of these programs as not really different from GUI apps.
But the reality is different: a terminal emulator—whether graphical or not (for instance, so-called "virtual consoles" provided by the Linux kernel running on an x86/amd64 hardware are terminal emulators as well)—really emulates a typical work session on a real hardware terminal, and there, a program would work in foreground solely, and the only means of "switching" to another program was using the shell's job control (those jobs, bg and fg commands).
In other words, the whole concept of a program working in a terminal has an inbuilt assumption that the terminal is always "foreground"—since at the time the concept was developed, a terminal was a physical device.
Now please also consider that "terminal emulation" may be more pervasive on a contemporary system than you might think: screen and tmux on a Unix-like OS are multiplexing terminal emulators—which may themselves be run in a terminal emulator, and a console window on Windows™ may be considered to be a terminal emulator of sorts as well.
So, "resorting to APIs" have several technical problems:
Terminal emulation tries to actually decouple the program which uses this facility from being aware of how the facility is actually provided.
To put it simple, there's, say, no easy way on X Window System, to know what window is used by the terminal emulator running your program.
You'd need to cover diverse set of APIs in order for your program to still be useful: X Window System on Unix-like systems, Mac OS, Windows™. And contemporary GUI stacks running on Linux tend to be switching to Wayland instead of X.
In certain cases, like running a program in a "nested" terminal emulation sessions (for example, a pane in a "window" of a tmux running in xterm), figuring out such facts about the environment might be next to impossible.
And still the crucial problem is that if your program really needs to know whether it's focused or not, it actually wants to be aware about the concepts currently hardly accessible to it. I mean, it wants to be GUI. And if so, just make it GUI.
In fact, it may be simpler than you think. The core of your program might still be a CLI app with a thin GUI wrapper around it which uses any sort of IPC to talk with the app (which might be two-way, if needed).
The simplest is to write some (usually line-wise) data to the program's standard input.

Related

How to create stand-alone mock up program running in raspberry

I need to create a very simple program, that should run on raspberry pi without network connection. The program should first show one full-screen bitmap ("insert disk"), and after receiving somehow an external signal (disk inserted), another bitmap which would ask to input password. After inputting the password (each pushed button shows an asterisk *) the application should show yet another bitmap, which would inform whether the password was correct or not.
So in principle I would like to create something that looks like password screen in any Hollywood movie!
Raspberry should boot directly to the application.
I was expecting that this would be easy to do (and it would be if we could use Windows and Visual Studio), but I haven't yet found a simple tool to create this for pi. Booting Raspberry into browser with kiosk mode and creating HTML application seems like an overkill.
Although a browser in kiosk mode might look that a sledgehammer to crack a nut, I think you might find this nut harder than it looks.
It wouldn't be difficult to write a simple app in Java, or Python, or perhaps even C using GTK, that carries out the actions you want. You could have the app loaded when X starts, as an alternative to a desktop and Window manager. You could even do away with X altogether, and write some code that interacts directly with the video framebuffer and the keyboard hardware. Or, heck, go the whole hog, and have your code substitute for the operating system kernel :)
I would guess that even the simplest of these approaches involves more work than hacking something up using a HTML and JavaScript in a browser.

Using USB keyboard device to trigger terminal commands on raspberry pi

I have a small robot which runs on a raspberry pi.
I need to be able to control it with an RF remote to trigger a few different terminal commands which run short python scrips.
Previously I did this with a GUI on my macbook, triggering these commands over ssh, but I now need to be able to trigger them in the absence of an internet connection.
The remote I bought is:
https://www.adafruit.com/products/3092?gclid=CNPj7LjTgNECFdOPswodsiULYA
I realize that this is designed for OSMC.
This remote shows up as a USB keyboard on the Pi, which makes the challenge more general:
* - How could one rig a 'USB keyboard device' to trigger entire terminal commands with the click of one key?*
My low-level knowledge of hardware is limited, and my programming experience extends little beyond python.
Any direct solution or suggested reading is much appreciated.
I am also open to alternatives, however I do not have time to order new hardware online.
You could write a python script which uses the 'os' library to interact with the terminal, have it looking for certain keystrokes and then writing the relevant commands to the terminal via os.
e.g
if (KEY == "F"):
os.system("cd Dropbox")
I have no idea how to do formatting here, but you get the idea.

How do I open a program in a Win32 Console without cmd.exe?

I have little previous experience with Windows (for programming, anyway), but recognizing that Windows has an enormous market share, I am trying to support it in my programs (even though they are just for fun, I like to pretend they're big projects). I have written a tiny shell with minimal (and when I say minimal, I mean minimal) features.
I am trying to port it to Windows and would like to use it independently from cmd.exe in a Win32 Console window (meaning the shell part of cmd.exe isn't running at all, but the window used for it shows). I have already done most of the other porting stuff such as build system (CMake) and changing appropriate Unix syscalls to Windows ones in a #define. I have done a little research and found little on this topic, however. I know it is possible because I've seen it done with Bash. Visual Studio also used to do it when I ran a program in its GUI.
Reference article I got some of this info from: https://en.wikipedia.org/wiki/Win32_console
Note: What I mean is when you click on it and it opens it without running cmd in its own little console window. Or when you type it into cmd it opens in a separate window that isn't running cmd. I am assuming cmd.exe and the console window it runs in are two separate things, but if I am wrong, please let me know. :)
This question is inspired by https://askubuntu.com/questions/111144/are-terminal-and-shell-the-same and a similar question where I got that Wikipedia link. Someone said that the console window and the shell were separate. I was writing my own shell so I started to wonder how to make mine independent of the default one.
The Win32 Console and cmd.exe are two different things. Windows automatically opens a console window when a program that needs one is started. It decides whether do to so by switches hard-wired into the executable. This window will be running said program. If the program that started the process is running in a console window, the two programs will share that console window.
As Noodles said, it really is that simple. You just start it. Double-clicking on it will do it. The CreateProcess() function with CREATE_NEW_CONSOLE passed to it will do it. Running the program from cmd.exe with
start <command>
will do it.
There is also a family of functions in the Windows API, called FreeConsole() and AllocConsole() that will free a program from its current console and create a new console for it, respectively.
Reference link (given by Noodles): https://msdn.microsoft.com/en-us/library/windows/desktop/ms682010(v=vs.85).aspx

How to detect from console or GUI app was run?

Is it's possible to detect inside app from where it was run? From cmd/bash or from GUI? Assume that we are working in graphical mode, not in pure console.
Not really, but sort of. Short answer: better not to try, get the user to tell you via an argument, which you can pre-fill in a shortcut.
Long answer:
In both cases, the program is launched in a similar way: the shell application (whether cmd/bash or Windows explorer/whatever gui launcher linux has) call CreateProcess or ShellExecute on Windows or fork+exec on Linux and the way the user executed it gets lost.
However, the process does have a parent ID which might be useful.... but it isn't reliable either for a few reasons: telling if it is a gui or command line shell isn't easy (best you can do is look at the image name) and the parent might terminate as soon as you launch, so there'd be no parent! (Linux gui apps often fork themselves to detach from the terminal. Of course, if you do this you'd probably know, but if you use a library it might happen without you realizing it.)
Well, the fact that I'm going off on parenthetical asides after every sentence shows how unreliable and complicate that is. If you want to try though, looking at your parent process ID before doing any fork/detaching might be helpful.
BTW looking for a parent console isn't very helpful: a Windows GUI subsystem program won't attach to the parent console even if one exists and a Linux GUI program may attach to the controlling tty of the X window manager.
What I'd actually recommend though is passing an argument to your function to tell it how it got started. When you create the GUI shortcut, make it automatically pass the "started by gui" argument to you. Then you can check args for it and react accordingly.
It still isn't perfect, but it is fairly easy to implement and probably good enough - gui launchers would probably use a shortcut anyway and you can pass arguments through them, so the user doesn't need to know about how it is implemented.
Or you could install two programs, one which is convenient from the command line and one which is optimized for the gui environment.
But I think that's the best you can do.

Windows application that optionally remains attached to console

I've got a Windows application (written in C, compiled with MSVC Express edition, 32-bit mode), which has two main modes of operation:
Windowed mode -- create a window, and draw stuff in it (namely, a fractal).
Benchmark mode -- when run with --benchmark as an argument, don't make a window but just print some benchmark statistics to stdout.
During development I've compiled as a Console app, and used SDL to create the window and perform other GUI functions. So benchmark mode runs fine (no window is created), and graphical mode just has a lingering console window.
However for my release compilation I've enabled the Windows subsystem instead of Console. (As explained in this question). This works great except I've suddenly discovered I can't run benchmarks any more. :o
I'm just wondering, is there a way for an application to choose at run time (e.g. based on the command line it's given) which kind of subsystem behaviour to use?
I've done some experimentation with EXE files in Windows (explorer, notepad, winword) and none of them seem to print anything to the console when run with an argument like "/?" (which most Windows console apps support). So it doesn't look like it, but I thought it's worth asking here in case there's a special trick.
Update. It looks like, no, you can't. Thanks for the answers guys.
Additional academic question. Does this mean that the subsystem choice is marked in the EXE header, and it's the operating system that examines this and sets up the Window or connects it to the console it's run from? I don't know much about EXE loading, but I would be curious to learn a few details here.
Conclusion. I think there are four good solutions (plus two semi-solutions, making five total :p) to choose from:
Use the console subsystem, but use FreeConsole when running in GUI mode.
Use the windows system, and use AllocConsole when running in benchmark mode. Not perfect if fractal.exe is run from an existing console, so I'll count this as half a solution ;-).
Just have one executable for each subsystem, fractal.exe and fractalgui.exe.
Have two (or more) executables, one of which does the work and passes it to the other to be displayed on the console or in a Window as appropriate. Needs some thought on how to divide the programs and how to communicate between them.
Another half-solution: have fractalgui.exe print the benchmark to standard out, and pipe that to a utility that will simply print it.
I haven't yet chosen, but I'm leaning towards #3.
Thanks to Matteo and smerlin for the ideas!
There is no way a application can choose her subsystem at runtime (well there are some really ugly workarounds, but those are full of quirks).
Then general solution for this problem is to have a console application, which starts your gui application if necessary
For your benchmark case, it would just print your benchmark statistics.
example setup:
- fractalgui.exe (subsystem: windows)
- fractal.exe (subsystem: console)
* the shortcut on the user desktop links to your fractalgui.exe
* if the user starts fractal.exe from the console, fractal exe starts fractalgui.exe
* if the user starts fractal.exe --benchmark, it either does the benchmark itself (if its possible to add this benchmark logic to another executable) and prints the information directly to console, or - if thats not possible - it will need to start fractalgui.exe --nogui --benchmark. The tricky case here is to get your output from fractalgui.exe to fractal.exe, so you can print it on the appropriate console. There are several ways to do this, e.g. named pipes (there are ways to start fractalgui.exe in a way, that you can just use stdout / cout there, and the data will be piped to the stdout of fractal.exe, but i dont recall how excactly this works anymore (edit: maybe this works)). The easiest way would be to start fractalgui.exe --nogui --benchmark > mylogfile and then print mylogfile after fractalgui.exe finished (since stdout/cout of fractalgui.exe will work if the output is redirected to a file), however you wont get "live" output, since all the output will be printed on the console when fractalgui.exe is already finished.
To add to #smerlin's answer, the other oft-seen method (cited into the articles I linked inside the comment) is to mark your application as a console application, but free the console (using FreeConsole) when you determine that you don't need it.
This is how ildasm does it, but it has the disadvantage of flashing the console for a brief moment between the start of the application and the call to FreeConsole.
Additional academic question. Does this mean that the subsystem choice is marked in the EXE header, and it's the operating system that examines this and sets up the Window or connects it to the console it's run from? I don't know much about EXE loading, but I would be curious to learn a few details here.
Yes, the loader checks the PE header and sets up everything according to the subsystem specified here.
Contrast with the *NIX approach: no executable is "special", and everyone has a working stdin/stdout/stderr; applications that want to display something will call the appropriate functions of Xlib. The drawback is that GUI applications have no clue if the application you are starting normally uses the console, so the system has to ask if you want to spawn also a terminal emulator or to discard the standard streams and just wait for it to spawn a window (obviously shortcuts store this information).
I described a technique for achieving this in my question here.
Matteo already mentioned the .com trick, but that's only part of a viable solution.

Resources