Simulated Mouseevents ignored on macOS in OpenGL - c

I have a larger project for which I want to have function that if run, clicks 10 times as fast as possible at the current cursor location.
This kind of works on my desktop, for example I tried running the program in my terminal and had my cursor on the menu bar. But if I switch to another application however (I tried it with a game in window mode) (I first let my program sleep for 4 seconds so I have enough time to switch), it just clicks once. The game is a shooter, so it should fire a couple of times fast but it just fires once and ignores all other events.
If I let my program sleep for 1 sec between cycles, it works.
Maybe I used the CGEvents wrong? Is there a difference between using MouseEvents and actually clicking? I mean shouldn't it be exactly the same for the game?
Here is my isolated code:
// Compile with: gcc -o click test.c -Wall -framework ApplicationServices
#include <ApplicationServices/ApplicationServices.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
// To click on current position (seems to work)
CGEventRef event = CGEventCreate(NULL);
CGPoint cursor = CGEventGetLocation(event);
CGEventRef click_down = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, cursor, kCGMouseButtonLeft);
CGEventRef click_up = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseUp, cursor, kCGMouseButtonLeft);
// Tried adding usleep between both events but anything under 1s doesnt work
for(int i = 0; i < 10; i++){
CGEventPost(kCGSessionEventTap, click_down);
// usleep(500);
CGEventPost(kCGSessionEventTap, click_up);
// usleep(500);
}
// Release the events
CFRelease(event);
CFRelease(click_down);
CFRelease(click_up);
}
What I read and tried but didn't help:
Simulate mouse on Mac
Simulating mouse clicks on Mac OS X does not work for some applications
-> Unfortunately didn't help or fix the problem
Synthetic click doesn't switch application's menu bar (Mac OS X)

I found the solution myself and it is really simple:
First of all I forgot that usleep is in microseconds and not miliseconds.
Furthermore apparently macOS buffers the clicks or keyboard inputs in the native environment but OpenGL doesn't. So of course it works if you pause for 1 second between clicks/keyboard presses but in OpenGL it just discards them if they are too fast. The solution is to wait the a small amount between clicks or keypresses. For me worked 100ms, that means usleep(100000), before and after the press down.

Related

Atmel-Ice Debugging with software breakpoints (SAMD21, SWD)

I've been getting various issues while trying to set software breakpoints in Atmel Studio 7 with the Atmel-ICE debugger using SWD. I was wondering if anyone could explain in more detail (or point me in the direction of documentation) to give me a better understanding as to why I get the following issues:
Breakpoints being moved upon compilation
Being 'Unable to set requested breakpoint on target'
Breakpoint only being hit the first time in a loop
The following code is a test program I wrote to demonstrate this using the delay routines and the PORT driver of the ASF:
#include <asf.h>
#define LED PIN_PA01
int main (void)
{
system_init();
delay_init();
struct port_config config_port_pin;
config_port_pin.direction = PORT_PIN_DIR_OUTPUT;
port_pin_set_config(LED, &config_port_pin);
while(1)
{
port_pin_toggle_output_level(LED);
delay_ms(100);
}
}
If a breakpoint is set at the LED toggle line then the breakpoint is moved to the following delay line.
If the delay is commented out and a breakpoint placed at the LED toggle line then it tells me it is unable to set requested breakpoint on target
If a breakpoint is placed on the delay line it only gets hit (the program halts) on the first iteration of the while loop. If I continue (F5) the program keeps running ( LED toggles every 100 ms) but doesn't stop at the breakpoint.
The code runs fine as far as I'm aware. The LED toggles every 100 ms as expected when I run without debugging, it is just the software breakpoints that I don't quite understand, sorry for my ignorance.
i know you answered your problem but this is really good tutorial someone wrote
about optimization of compiler
https://www.avrfreaks.net/forum/tutcoptimization-and-importance-volatile-gcc

Drawing in a graphics window from a second thread in C

I am creating my first graphics program in C, using Codeblocks. I am trying to run two graphics loops simultaneously using two threads. One is for keyboard controls and the other is to move a rectangle vertically.
I have been trying to pass a graphics command from ObstacleHandler to the graphics window that main opens, using this condensed bit of code. When I run it, it will just crash as soon as it tries to draw the rectangle. If I initalise a window from the ObstacleHandler and then draw the rectangle, it will be fine. However, I need ObstacleHandler to draw the rectangle in the window that is initalised by the main.
Working example of the issue:
#include <pthread.h>
#include <semaphore.h>
#define NUM_THREADS 2
void *ObstacleHandler(void *threadid)
{
filled_rectangle(100, 120, 100, 120);
update_display();
pthread_exit(NULL);
return 0;
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
long t;
for(t=0;t<NUM_THREADS;t++)
{
printf("In main: creating thread %ld\n", t + 1);
}
pthread_create(&threads[1], NULL, ObstacleHandler, (void *)1);
initwindow(640, 480);
pthread_exit(NULL);
return 0;
}
The window has to be opened using the main function as the keyboard commands are in there. I cannot move them to the ObstacleHandler as that thread will be moving the obstacle.
Also, is there a way that you can have two graphics windows open and each one has a unique identification? I.e graph1 & graph2.
I am using allegro as the graphics library. However, not in the sample code.
I am new to programming so...! Any help would be appreciated!
Thanks
I use Borland/Embarcadero VCL so this could not be your case !!!
but my experience is that if you are accessing any Windows Visual stuff from different then owner window thread then somethings goes terribly wrong in the OS that creates:
visual artifacts
random unrelated crashes
unexpected behavior of the whole Application
this apply for any:
winapi call related to visual components of the window
drawing to window
any access to visual components (like adding line to memo,changing color of something,...)
I code win32 apps and this behavior is present on XP/SP3 x86,W7 x86,W7 x64(WoW64). I did not test different OS versions but suspect this behavior is present also there ...
What to do?
create your global message que
just a list of command you want to support
threads will fill your que
just add appropriate command to que like: redraw window, draw line ...,add to log ...
main window will read and execute it
inside OnTimer or OnIdle event
[Notes]
If you use threads to enhance rendering speed then you should render to thread local bitmap instead and when done add command to copy its contents to target visual component. Do not forget that the que has to be thread safe so add locks to it !!!

How can I have skinnier pthreads?

I have a really basic ncurses program to monitor machine statistics and launch remote xterms. It just sits on a window all day and helps me choose a not-heavily-loaded machine to work on. It works fine, and I love it dearly. But it's really fat. Much fatter than it needs to be, I think.
The program basically is as follows:
void * run(void * task) {
// once per minute:
popen( /* stats checking command */ )
// save output to global var
pclose
}
int main() {
// setup ncurses with halfdelay
for ( /* each machine */ )
pthread_create(somethread, NULL, run, (void *)somestruct);
while ( ( c = getch() ) != 'q' )
for ( /* each machine */ )
// print machine stats
// maybe launch an xterm
// die gracefully
}
And as stated above, it works just fine. The problem is that each thread has all the ncurses baloney tucked in private memory leading to one very fat process with a boatload of wasted bits.
The question, then, is this: how can I re-write or re-arrange this program so that each pthread doesn't carry around all the unnecessary ncurses stuff?
Side-question: You'll have to really sell me on it, but does anyone know of a better method than ncurses to do this? I want the stats on fixed positions in the terminal window, not scrolling text.

Execute command just before Mac going to sleep

I wrote a C program/LaunchDaemon that checks if my MacBook is at home (connected to my WLAN). If so, it disables my password protection; if not, it enables it.
Easy. But the problem is that when I take my MacBook anywhere else and password protection is disabled, it will wake up without a password protection.
My fix for this would be: enable the password protection every time just before it goes to sleep.
QUESTION: is there any way find out when my Mac is preparing for sleep? Some interupt I can let my program listen to?
You can do it using I/O Kit, check Apple's QA1340: Registering and
unregistering for sleep and wake notifications. You may also want to
analyze the SleepWatcher utility sources or use/integrate for your needs.
From the homepage:
SleepWatcher 2.2 (running with Mac OS X 10.5 to 10.8, source code included)
is a command line tool (daemon) for Mac OS X that monitors sleep, wakeup and
idleness of a Mac. It can be used to execute a Unix command when the Mac or
the display of the Mac goes to sleep mode or wakes up, after a given time
without user interaction or when the user resumes activity after a break or
when the power supply of a Mac notebook is attached or detached. It also can
send the Mac to sleep mode or retrieve the time since last user activity. A
little bit knowledge of the Unix command line is required to benefit from
this software.
I attach below the contents of my C file beforesleep.c which executes some command line commands (in my case shell commands and AppleScript scripts) when a "will sleep" notification is received.
Where you can put your code:
In order to run your code when the mac is going to sleep, just replace the system(...) calls with the code you wish to run.
In my case, I use system() as it allows me to run shell commands passed as strings, but if you prefer to run just C code instead, you can just put your C code there.
How to build it
In order to build this file, I run:
gcc -framework IOKit -framework Cocoa beforesleep.c
Remark
If you are going to use this code, make sure it is always running in background. For example, I have a Cron job which makes sure that this code is always running, and it launches it again in case it is accidentally killed for any reason (although it never happened to me so far). If you are experienced enough, you can find smarter ways to ensure this.
Further info
See this link (already suggested by sidyll) for more details about how this works.
Code template
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <mach/mach_port.h>
#include <mach/mach_interface.h>
#include <mach/mach_init.h>
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <IOKit/IOMessage.h>
io_connect_t root_port; // a reference to the Root Power Domain IOService
void
MySleepCallBack( void * refCon, io_service_t service, natural_t messageType, void * messageArgument )
{
switch ( messageType )
{
case kIOMessageCanSystemSleep:
IOAllowPowerChange( root_port, (long)messageArgument );
break;
case kIOMessageSystemWillSleep:
system("/Users/andrea/bin/mylogger.sh");
system("osascript /Users/andrea/bin/pause_clockwork.scpt");
IOAllowPowerChange( root_port, (long)messageArgument );
break;
case kIOMessageSystemWillPowerOn:
//System has started the wake up process...
break;
case kIOMessageSystemHasPoweredOn:
//System has finished waking up...
break;
default:
break;
}
}
int main( int argc, char **argv )
{
// notification port allocated by IORegisterForSystemPower
IONotificationPortRef notifyPortRef;
// notifier object, used to deregister later
io_object_t notifierObject;
// this parameter is passed to the callback
void* refCon;
// register to receive system sleep notifications
root_port = IORegisterForSystemPower( refCon, &notifyPortRef, MySleepCallBack, &notifierObject );
if ( root_port == 0 )
{
printf("IORegisterForSystemPower failed\n");
return 1;
}
// add the notification port to the application runloop
CFRunLoopAddSource( CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(notifyPortRef), kCFRunLoopCommonModes );
/* Start the run loop to receive sleep notifications. Don't call CFRunLoopRun if this code
is running on the main thread of a Cocoa or Carbon application. Cocoa and Carbon
manage the main thread's run loop for you as part of their event handling
mechanisms.
*/
CFRunLoopRun();
//Not reached, CFRunLoopRun doesn't return in this case.
return (0);
}

Console app with Qt Creator on Windows : wait before closing the console

I'm running a very simple console app on Windows with Qt Creator.
When launching it, the dos console is openned, my output is displayed, but then the app terminates and the console immediately closes.
How can I make sure the console will stay open until the user presses a key ?
Since Qt Creator 1.3.0, it's much easier :
Go to the project tab (on the left) to edit the project's setting.
In the section Run Settings, clic on Show details and check the Run in Terminalcheckbox.
Thus, the application will be launched in a console window and the console window will wait until the enter key is pressed before closing.
No need to add some lines to the code anymore !
Here are two solutions :
#include <QTextStream>
#include <QFile>
//#include <conio.h> // for getch()
int main(int argc, char *argv[])
{
// JC and friends code
// Qt Solution
QTextStream Qin(stdin);
forever
{
QString Line = Qin.readLine();
if (!Line.isNull())
{
break;
}
}
// conio solution
//getch();
return 0;
}
Both solutions tested with Qt Creator 1.2.1 on Windows Vista !
Hope it helps ;-)

Resources