Prevent Mac Laptop from sleeping when closed? - c

I'm writing a program in C and want it to have an option that will keep a mac laptop awake even if the lid is closed so processes can continue. There seems to be very little information available on this topic so I really don't know where to begin. If anyone knows how to accomplish this or where I can find more information I would really appreciate (i.e. will I need to work with the BIOS for this or are there built in functions?). Also, if it's easier to do it in another language that is fine as I'm not stubbornly set on using C.

You need to write a kernel extension for this. The OS doesn't support it by default because the laptops aren't designed to properly cool themselves with the lid closed and internal display enabled. SleepLess is a $10 utility that'll do what you want, too. If you warp the display or something, it's your own fault. :-).
If you want to write something yourself, LidSleep.kext looks like a good start (it does the opposite, i.e. sleeping on lid close) and comes with source code.
(It is possible and supported to wake up some Mac laptops with the screen closed by using an external input device.)

You can do this using the I/O Kit framework, see QA1340 listing 2 for sample code using IOPMAssertionCreateWithName to temporarily prevent sleep.

The link to LidSleep.kext listed above is not working, so I can inform that the author of NoSleep has made the source code available here, so you can see for yourself how it can be done:
https://code.google.com/p/macosx-nosleep-extension/

If your laptop is a reasonably recent model, you don't need to add anything. If you are running Lion, it simply works. If you're running an older OS you have to wake up the laptop by sending it a keystroke or mouse click from an external keyboard or mouse. See http://support.apple.com/kb/ht3131

Related

Hook keyboard shortcuts from Windows lock screen

I have an arduino in keyboard emulation mode that sends keyboard keystrokes to the computer it's connected to, the latter appending a log line in a local webpage upon receiving each keystroke. The log program is coded in C using Win32 API.
Now, since it's supposed to function at work (the idea is to get a log file online of when pushbuttons on my desk have been activated), I will be locking my computer...
How can I keep processing CTRL+ALT+key strokes from the windows lock screen?
Thanks,
Mister Mystère
This seems to work: https://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook
When you run the compiled executable, the keys A and B are detected globally even when the screen is locked.
I ended up downloading a third party lock screen and my program works in its background as it is a standard program. For those of you in the same situation, as far as I know after all that research I'm afraid you'll have to do that instead: it seems like it is not possible starting from Vista.

OS X Intercept Keyboard Events to Password Forms Elements

I am currently creating a c program that counts all of the keys I press in a day and sorts the key types by amount, so I can tell which ones I press most often. It was more of a side project than anything else but I have become annoyed with the fact that my program doesn't seem to be able to intercept any input to password fields. I suppose this is a good thing, but I have been spending hours looking at documentation and trying to figure how to do this. I am not trying to create any sort of malicious software. Is there a way around this? My program is running as root. I am using the ApplicationServices framework and CGEventRef and the CGEventTapCreate funcion. Should I be using a different framework or struct? Also, is there a difference between kCGHIDEventTap, kCGSessionEventTap, and kCGAnnotatedSessionEventTap? I have tried using each of them and it does not seem to make a difference in my program.
I am running this on OS X 10.9
UPDATE
Apparently I cannot capture keystrokes going to terminal either, which is where I spend most of my time on my laptop. This is a problem.
What you want is fairly complicated and requires a kernel extension. The interprocess communication is also not trivial. Take a look at logKext, specifically logKext.cpp. That project actually logs the keystrokes to an encrypted file. You should be able to pull everything you need from it.

Avoiding all system messages and messages from other software

Here is the situation. The company I work for builds this piece of software in c that can make a Windows computer act a bit like a TV. Essentially, our piece of software is meant to be played full screen and content is displayed from the internet without the user having to ever touch the computer again.
The problem is that once in a while, the system brings up pop-ups like "Your Windows system is ready for an upgrade." or "Please renew your Norton subscription" etc. which the user has to periodically and manually remove.
Is there a way to display content full screen without being bothered by those warnings?
Yah, whether or not the development community agrees, Microsoft has several standards for when and why it might be acceptable to have exclusive use of the monitor.
The most official strategy is to use DirectX in exclusive mode. This is what games do, what windows media player does in full screen video with hardware acceleration enabled, etc... If your application is multimedia intensive (as suggested by TV like functionality), you should probably be using DirectX too. Besides giving you the exclusive display access it will also increase your applications performance while lowering the CPU load (as it will overload graphics work to the video card when possible).
If DirectX is not an option, there are a great number of hacks available that seem to all behave differently between various generations of windows operating systems. So you might have to be prepared to implement several techniques to cover each OS you plan to support.
One technique is to set your application as the currently running screensaver. A screensaver if really just an EXE renamed to SCR with certain command line switches it should support. But you can write your own application to be such a screensaver and a little launcher stub that sets it as the screensaver and launches it. Upon exit the application should return the original screensaver settings (perhaps the launcher waits for the process to exit so that it returns the settings in both graceful exits and any unplanned process terminations ie: app crash). I'm not sure if this behavior is consistent across platforms though, you'll have to test it.
Preventing other applications from creating window handles is truly a hack in my opinion and pretty bad one that I wouldn't appreciate as a customer of such software.
A constant BringWindowToTop() call to keep you in front is better (it doesn't break other software) but still a little hack-ish.
Catch window creation messages with a global hook. This way you can close or hide unwanted windows before they become visible.
EDIT: If you definitely want to avoid hooks, then you can call a function periodically, which puts your window to the top of the z-stack.
You could disable system updates http://support.microsoft.com/kb/901037 and remove the norton malware.
You could also connect a second screen so that the bubbles appear in the the first monitor.
Or you rewrite it for linux or windows ce.
One final option is to install software that reconfigures your os into a kiosk http://shop.inteset.com/Products/9-securelockdown.aspx
If you don't need keyboard or mouse input, how about running your application as a screensaver?
A lot of thoses messages are trigged/managed by Windows Explorer.
Just replace it with your dummy c#/winform.
By changing the registry value
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon]
"Shell"="Explorer.exe"
You can specify virtually any exe as an alternative to explorer.exe
That's the way all windows based (embedded) system (ATM & co) do.
There's still few adjustment (disable services you dont need / dr watson & others), and of course, you'll want to keep a "restart explorer.exe" backdoor.
But that's a good start

Launch OpenGL app straight from a windowless Linux Terminal

How exactly would one go about getting an OpenGL app to run fullscreen straight from the terminal (Ubuntu Server 9.04)? I've developed an application for visual diagnostics on my server, but, I'm not totally sure the best way to get it to run in a windowless environment.
Ideally, I would run my program:
./visualdiagnostics
and have that launch the OpenGL app. Then, via a simple Ctrl+X key binding, I'll kill the app and go back to the terminal.
Do I need to install X11 and then somehow launch it from within the program? What would be the best way to detect if it's already running and, start/stop it if necessary?
And FYI: No, I'm not trying to get this to run over Putty or anything... I have a monitor hooked straight up to the server. The server has proper video drivers installed.
There are several parts to your task. Keep in mind that some of this can be very distro-specific; but since you said Ubuntu we'll talk Ubuntu!
Also you tagged this question C however I am starting off with a common Linux pattern: a native application with a Bash shell script wrapper. Perhaps once you get things working well you might fold that functionality into C if you have to.
Detecting whether X is running
Being root can help a lot. Some things that work.
pgrep Xorg
Check whether /var/lib/gdm/:0.Xauth exists. This will be there even if nobody has logged in but GDM is running.
ls -l /home/*/.Xauthority (Even if you're not root you can at least confirm whether you are running X.
Piggybacking an existing X session
You did not specifically mention it but if you are root at the console, or if you want to run the app as the same user who is already logged in, it's pretty easy.
You have to get the DISPLAY and XAUTHORITY environment variables right, and once you do you can use the existing X display.
For DISPLAY you might just assume :0 or you could find an existing X program (x-session-manager is the GNOME standard) and read its environment from /proc/PID/environ. Variables are in key=value format delimited by a null byte. For example, if its PID is 12345:
cat /proc/12345/environ \
| ruby -ne 'puts $_.split("\0").select {|e| e.starts_with? "DISPLAY=" }'
For XAUTHORITY you could get it the same way. Or if you prefer guessing, it's almost always /home/whoever/.Xauthority
Once you have those two variables, running X code is easy, for example:
env DISPLAY=:0 XAUTHORITY=/home/brian/.Xauthority ./visualdiagnostics
Stopping X
This one is easy if you're root: /etc/init.d/gdm stop. killall Xorg will work too.
If you are a user, kill your own Xorg or x-session-manager process. (I'd welcome input from others for the canonical way to do this. Maybe some dbus-send message?)
Starting X
I would recommend xinit whose goal in life is to fire X and run exactly one program.
For example: xinit ./visualdiagnostics
You can also tell xinit what resolution to run X at which may or may not be important to you. (This becomes important in the full-screen section below.)
The problem with this is you will have no window manager— no maximize and minimize buttons. It's not just cosmetic. Usually an app is useless because a popup window cannot be moved or you cannot focus on the right input field. However if you have a special app it could be sufficient (see full-screen below).
The next step would be my answer to everything: another shell script wrapper! Something simple that starts the window manager and then becomes your program should work.
#!/bin/bash
#
# Start visualdiagnostics once xinit calls me.
/usr/bin/metacity& # Or ratpoison, or fluxbox, or compiz, etc.
exec ./visualdiagnostics
It's important to exec (become) the main program because once that first program exits, X will shut down.
Running fullscreen
I am not 100% certain on this. Some ideas:
Try the standard X -geometry parameters to set 0,0 as the upper-left corner and +x+y for your horizontal and vertical size. How do you know the size? Either you hard-coded it when you launched xinit or you could ask the X server. xwininfo -root will tell you and there is an xlib API call that would do that too—check the xwininfo source I guess.
Your app itself can request maximization and/or resizing to fill the screen. I'm not familiar but it is definitely in the X API.
Some of the more configurable window managers can be pre-configured to run you maximized already. This is probably what I personally would check first. Your wrapper script could create a $HOME/.fluxboxrc just by echoing some hard-coded configs > the file.
Summary
The others are right. X is not strictly necessary sine OpenGL can run against a framebuffer. However considering how ubiquitous X is and how much work has gone into automating it for distributions, I would probably invest my effort into the X route as it might be easier long-term even though it's a little convoluted.
(By the way, I sincerely hope when you say "terminal" you mean you are at the text console, not gnome-terminal that would be awful! :)
Well I am clearly not sure my answer might help you out.
Long ago when I was student, I manage to do so (launching an openGL app from a terminal only linux installation) by installing frame buffer. As long as I remember I needed to recompile my kernel (as framebuffer was/is a kernel module).
This was maybe 5 years ago on a debian distrib, and I don't know how does it work now for up-to-date debian distrib as Ubuntu. Maybe framebuffer is compiled statically in the binary kernel provided by default with Ubuntu. May be not. Maybe framebuffer is irrelevant now... Or I may be totally wrong and not remembering every details of my own adventure 5 years ago now ..
Have a look on Google ! ;-)
Hope it will help...
**
Update:
**
What is frame buffer ?
How to install it? Here or there
As yves pointed out, you can avoid running the X server if you use the framebuffer. Actually, the framebuffer modules are often yet available (for example, they are used to have the tux logo during the kernel start or a text terminal with fancy images in the background), this anyway depends on the distribution and the settings you are using.
The kernel side is quite primitive so I'd suggest to use some higher level library such as DirectFB. The framebuffer is usable without problems but don't expect the same maturity level than a full blown X server.
Are you trying to have the video be on the monitor connected directly to the computer?
Is X running on the server?
If X is running, you can do
export DISPLAY=:0.0
which tells X apps to connect to the X server at localhost, rather than where' you're coming from.
If you're actually logging in locally (from a direct terminal) ... yes, you need X installed and running.

Is there a way for my binary to react to some global hotkeys in Linux?

Is it possible to listen for a certain hotkey (e.g:Ctrl-I) and then perform a specific action? My application is written in C, will only run on Linux, and it doesn't have a GUI. Are there any libraries that help with this kind of task?
EDIT: as an example, amarok has global shortcuts, so for example if you map a combination of keys to an action (let's say Ctrl-+, Ctrl and +) you could execute that action when you press the keys. If I would map Ctrl-+ to the volume increase action, each time I press ctrl-+ the volume should increase by a certain amount.
Thanks
How global do your hotkeys need to be? Is it enough for them to be global for a X session? In that case you should be able to open an Xlib connection and listen for the events you need.
Ordinarily keyboard events in X are delivered to the window that currently has the focus, and propagated up the hierarchy until they are handled. Clearly this is not what we want. We need to process the event before any other window can get to it. We need to call XGrabKey on the root window with the keycode and modifiers of our hotkey to accomplish this.
I found a good example here.
I think smoofra is on the right track here; you're looking to register a global hotkey with X so that you can intercept keypresses and take appropriate action. Xlib is probably what you want, and XGrabKey is the function, i think.
It's not easy to learn, I'm afraid; I did locate this example that seems useful: TinyWM. I also found an example using Java/JNI (accessing the same underlying Xlib function).
You should look at the source code of xbindkeys.
Xlib programming is pretty arcane, documentation is hard to find, and there are subtle portability issues. You'll be better off copying some battle-hardened code.
One way to do it is to have your application listen on a certain port, or socket file, for incoming requests.
Then you can write a small client application that connects to that port or socket file and sends commands to the running application.
Then you can configure your window manager to bind certain key combinations to launch your small client app.
In UNIX, your access to a commandline shell is via a terminal. This harks back to the days when folks accessed their big shared computers literally via terminals connected directly to the machines (e.g. by a serial cable).
In fact, the 'xterm' program or whatever derivative you use on your UNIX box is properly referred to as a terminal emulator - it behaves (from both your point of view and that of the operating system) much like one of those old-fashioned terminal machines.
This makes it slightly complicated to handle input in interesting ways, since there are lots of different kinds of terminals, and your UNIX system has to know about the capabilities of each kind. These capabilities were traditionally stored in a termcap file, and I think more modern systems use terminfo instead. Try
man 5 terminfo
on a Linux system for more information.
Now, the good news is that you don't need to do too much messing about with terminal capabilities, etc. to have a commandline application that does interesting things with input or windowing features. There's a library, curses, that will help. Lookup
man 3 ncurses
on your Linux system for more information. You will probably be able to find a decent tutorial on using curses online.

Resources