How does one remove an SDL_Event from the event queue? - sdl-2

I've been looking through the documentation on SDL_Events. Is there a way to remove an SDL_UserEvent from the event queue before it gets polled by SDL_PollEvent? I've tried googling "sdl remove event", but came up with bubkis.

You can examine events that are on the queue before taking them out of the queue... and then decide to take them out.
Both can be done with SDL_PeepEvents ( http://wiki.libsdl.org/SDL_PeepEvents ). You can look at the next N events by passing in SDL_PEEKEVENT as the parameter action; or take them out with SDL_GETEVENT.
It should be possible also to take them with SDL_GETEVENT; edit the events array you get to remove the event you wanted discarded; then call it again with SDL_ADDEVENT to put them back.
At this point, though, I'd have to wonder if you're really getting done what you wanted. Why not just poll events, and ignore events of the type you wanted discarded? That's the way I do it.

You can take a look at SDL_FlushEvent or SDL_FlushEvents.
SDL_FlushEvent can be used to remove one specific type of event from the queue, while SDL_FlushEvents can be used with values SDL_USEREVENT and SDL_LASTEVENT in order to remove every user events from the queue.
You might want to use SDL_PumpEvents before, just to update the event queue.
You can also take a look at SDL_PeepEvents (with the same minType and maxType as SDL_FlushEvents).

I don't know of an easy way to remove just ONE event of that type, but you can do:
SDL_FlushEvents(SDL_USEREVENT, SDL_LASTEVENT);
To remove all pending user events already on the queue.

void Game::handleEvent() {
SDL_Event event;
SDL_PumpEvents();
SDL_FlushEvent(SDL_JOYHATMOTION);
SDL_FlushEvent(SDL_JOYAXISMOTION);
SDL_FlushEvent(SDL_CONTROLLERAXISMOTION);
SDL_FlushEvent(SDL_MOUSEMOTION);
SDL_FlushEvent(SDL_MOUSEBUTTONDOWN);
SDL_FlushEvent(SDL_MOUSEBUTTONUP);
SDL_FlushEvent(SDL_FINGERDOWN);
SDL_FlushEvent(SDL_FINGERUP);
SDL_FlushEvent(SDL_FINGERMOTION);
if (SDL_PollEvent(&event))
scene->handleEvent(screen, event)
}

Related

Wait for a job for a certain timespan

I want to dispatch a job to the queue and wait for it to finish, but only for a certain timespan (e.g. 10 seconds). If it does not finish in that timespan I want to do A, otherwise B.
How can this be accomplished? The only way I have seen is using events or the Queue triggers, but there seems to be no uniform way of checking if a certain job is finished.
Maybe I'm just blind and there is an easy solution, but I'm looking forward to your replies.
try this may it will help you
in your controller
use Carbon/Carbon;
public function yourmethodname (){
if(carbon::now()<=carbon::now()->addHours(2){
//dispatch a job to the queue
}else{
//do whatever you want here
}
}
you can add any time day or month in above carbon::now method for eg to add month carbon::now()->addMonths(whatever)
hope this will help you

Project reactor processors v3.X

We are trying to migrate from 2.X to 3.X.
https://github.com/reactor/reactor-core/issues/375
We have used the EventBus as event manager in our application(Low latency FX system) and it works very well for us.
After the change we decided to take every module and create his own processor to handle event.
1. Does this use seems to be correct from your point of view? Because lack of document at the current stage and after reviewing everything we could we don't really know what to do here
2. We have tried to use Flux in order to perform action every X interval
For example: Market is arriving 1000 for 1 second but we want to process an update only 4 time in a second. After upgrading we are using:
Processor with buffer and sending to another method.
In this method we have Flux that get list and try to work in parallel in order to complete his task.
We had 2 major problems:
1. Sometimes we received Null event which we cannot find that our system is sending to i suppose maybe we are miss using the processor
//Definition of processor
ReplayProcessor<Event> classAEventProcessor = ReplayProcessor.create();
//Event handler subscribing
public void onMyEventX(Consumer<Event> consumer) {
Flux<Event> handler = classAEventProcessor .filter(event -> event.getType().equals(EVENT_X));
handler.subscribe(consumer);
}
in the example above the event in the handler sometimes get null.. Once he does the stream stop working until we are restating server(Because only on restart we are doing creating processor)
2.We have tried to us parallel but sometimes some of the message were disappeared so maybe we are misusing the framework
//On constructor
tickProcessor.buffer(1024, Duration.of(250, ChronoUnit.MILLIS)).subscribe(markets ->
handleMarkets(markets));
//Handler
Flux.fromIterable(getListToProcess())
.parallel()
.runOn(Schedulers.parallel())
.doOnNext(entryMap -> {
DoBlockingWork(entryMap);
})
.sequential()
.subscribe();
The intention of this is that the processor will wakeup every 250ms and invoke the handler. The handler will work work with Flux parallel in order to make better and faster processing.
*In case that DoBlockingWork takes more than 250ms i couldn't understand what will be the behavior
UPDATE:
The EventBus was wrapped by us and every event subscribed throw the wrapped event manager.
Now we have tried to create event processor for every module but it works very slow. We have used TopicProcessor with ThreadExecutor and still very slow.. EventBus did the same work in high speed
Anyone has any idea? BTW when i tried to use DirectProcessor it seems to work much better that the TopicProcessor
Reactor 3 is built around the concept that you should avoid blocking as much as you can, so in your second snippet DoBlockingWork doesn't look good.
How are the events generated? Do you maybe have an listener-based asynchronous API to get them? If so, you could try using Flux.create.
For your use case of "we have 1000 events in 1 second, but only want to process 4", I'd chain a sample operator. For instance, sample(Duration.ofMillis(250)) will divide each second into 4 windows, from which it will only emit the last element.
The reference guide is being written, as well as a page where you can find links to external articles and learning material.There's a preview of the WIP reference guide here and the learning resources page here.

Not receiving Apache Camel Event Notifications under the smallest load

I have extended EventNotiferSupport, and set the isEnable() to respond True for all events. I have a notify() that logs what events I receive and the corresponding Exchange ID for the event.
I have added my ExchangeMessageNotifier with this.context.getManagementStrategy().addEventNotifier(this.exchangeMessageNotifier);
I run my program under basically no load, sending 1 message at a time 1 second delay between messages into Camel to send out. Everything works the way I expect. I receive my events everything looks good.
I decrease the delay between messages to 0 milliseconds, and I find that 1 out of approximately 20 messages I fail to receive one of the Events, (Often the Completed event).
Add a second thread sending at the same rate and I don't get any events for any messages.
What am I missing? I've done searches and I don't find anything that I need to do differently. Is there something I am missing?
I am using Apache Camel 2.16.3, and moved to 2.18.1 still see the same behavior.
Well found my own answer. Part of the fun of inheriting code without any informaiton.
In your implementation of the EventNotifierSupport you need to override the doStart() method and configure the EventNotifierSupport for what events you wish to receive.
protected void doStart() throws Exception {
// filter out unwanted events
setIgnoreCamelContextEvents(true);
setIgnoreServiceEvents(true);
setIgnoreRouteEvents(true);
setIgnoreExchangeCreatedEvent(true);
setIgnoreExchangeCompletedEvent(false);
setIgnoreExchangeFailedEvents(true);
setIgnoreExchangeRedeliveryEvents(true);
setIgnoreExchangeSentEvents(false);
}
This is in addition to doing the following:
public boolean isEnabled(EventObject event) {
return true;
}
Which enables you to determine if you want a particular event, out of the selected groups you had set in the doStart().
Once these changes were in I was receiving consistent events.

What's the right replacement for PostEvent

I'm getting a warning that PostEvent is deprecated and I assume that one is supposed to use PostEventToQueue but it takes two extra parameters and I can't find any documentation on what combination of parameters (one is a queue specification, the other is an event priority) will be equivalent to PostEvent.
PostEventToQueue is for a Carbon Event, not a low-level OS event like PostEvent. If you want to post a keyboard or mouse event, you should use CGEventPost.
Edit to add: To post a mouse down at the current location, I think (untested) that you can do this:
CGEventRef theEvent = CGEventCreate( NULL );
CGEventSetType( theEvent, kCGEventLeftMouseDown );
CGEventPost( theEvent );
CFRelease( theEvent );
I think it'd be reasonable to assume that using the event queue returned by GetMainEventQueue() (or GetCurrentEventQueue if you're on the main thread), and kEventPriorityStandard for the priority, will get you results equivalent to PostEvent.
Be aware, though, that these only affect your own application. Even the old Event Manager probably doesn't have access to an “Operating System event queue” anymore—I wouldn't be surprised if it's just a wrapper around the Carbon Event Manager version. You'd need to switch to CGEvent stuff if you want to post events that can hit other applications.

Can someone explain callback/event firing

In a previous SO question it was recommended to me to use callback/event firing instead of polling. Can someone explain this in a little more detail, perhaps with references to online tutorials that show how this can be done for Java based web apps.
Thanks.
The definition of a callback from Wikipedia is:
In computer programming, a callback is
executable code that is passed as an
argument to other code. It allows a
lower-level software layer to call a
subroutine (or function) defined in a
higher-level layer.
In it's very basic form a callback could be used like this (pseudocode):
void function Foo()
{
MessageBox.Show("Operation Complete");
}
void function Bar(Method myCallback)
{
//Perform some operation
//When completed execute the callback method
myCallBack().Invoke();
}
static int Main()
{
Bar(Foo); //Pops a message box when Bar is completed
}
Modern languages like Java and c# have a standardized way of doing this and they call it events. An event is simply a special type of property added to a class that contains a list of Delegates / Method Pointers / Callbacks (all three of these things are the same thing. When the event gets "fired" it simply iterates through it's list of callbacks and executes them. These are also referred to as listeners.
Here's an example
public class Button
{
public event Clicked;
void override OnMouseUp()
{
//User has clicked on the button. Let's notify anyone listening to this event.
Clicked(); //Iterates through all the callbacks in it's list and calls Invoke();
}
}
public class MyForm
{
private _Button;
public Constructor()
{
_Button = new Button();
//Different languages provide different ways of registering listeners to events.
// _Button.Clicked += Button_Clicked_Handler;
// _Button.Clicked.AddListener(Button_Clicked_Handler);
}
public void Button_Clicked_Handler()
{
MessageBox.Show("Button Was Clicked");
}
}
In this example the Button class has an event called Clicked. It allows anyone who wants to be notified when is clicked to register a callback method. In this case the "Button_Clicked_Handler" method would be executed by Clicked event.
Eventing/Callback architecture is very handy whenever you need to be notified that something has occurred elsewhere in the program and you have no direct knowledge of when or how this happens.
This greatly simplifies notification. Polling makes it much more difficult because you are responsible for checking every so often whether or not an operation has completed. A simple polling mechanism would be like this:
static void CheckIfDone()
{
while(!Button.IsClicked)
{
//Sleep
}
//Button has been clicked.
}
The problem is that this particular situation would block your existing thread and have to continue checking until Button.IsClicked is true. The nice thing about eventing architecture is that it is asynchronous and let's the Acting Item (button) notify the listener when it is completed instead of the listener having to keep checking,
The difference between polling and callback/event is simple:
Polling: You are asking, continuously or every fixed amount of time, if some condition is meet, for example, if some keyboard key have been pressed.
Callback: You say to some driver, other code or whatever: When something happens (the keyboard have been pressed in our example), call this function, and you pass it what function you want to be called when the event happens. This way, you can "forget" about that event, knowing that it will be handled correctly when it happens.
Callback is when you pass a function/object to be called/notified when something it cares about happens. This is used a lot in UI - A function is passed to a button that is called whenever the button is pressed, for example.
There are two players involved in this scenario. First you have the "observed" which from time to time does things in which other players are interested. These other players are called "observers". The "observed" could be a timer, the "observers" could be tasks, interested in alarm events.
This "pattern" is described in the book "Design Patterns, Elements of Reusable Object-Oriented Software" by Gamma, Helm, Johnson and Vlissides.
Two examples:
The SAX parser to parse XML walks
trough an XML file and raises events
each time an element is encountered.
A listener can listen to these
elements and do something with it.
Swing and AWT are based on this
pattern. When the user moves the
mouse, clicks or types something on
the keyboard, these actions are
converted into events. The UI
components listen to these
events and react to them.
Being notified via an event is almost always preferable to polling, especially if hardware is involved and that event originates from a driver issuing a CPU interrupt. In that case, you're not using ANY cpu at all while you wait for some piece of hardware to complete a task.

Resources