How can I use the FilterFunction passed to Gdk.Window.AddFilter? - mono

I need to intercept several events before they are delivered to the widget's standard handlers, so I've done this already:
//Inside the definition of my custom widget
protected override void OnRealized()
{
base.OnRealized();
this.GdkWindow.AddFilter(PreFilterMessage);
...
}
So, later I define the PreFilterMessage method:
public Gdk.FilterReturn PreFilterMessage(IntPtr xEvent, Gdk.Event evnt)
{
Console.WriteLine(evnt.Type);
...
}
But the thing is that when I test it, whatever message gets to the window (KeyEvent, ButtonEvent, etc.) it always prints "Nothing", so I'm only getting empty events every time. Somewhere I read that the real information gets through the xEvent parameter, but that's just an IntPtr, so I don't know how to get the information I need (event type, pointer coordinates, etc.) from it.
Can anyone tell me how to do this? Thanks in advance.

Per the docs on the gtk.org website, the GdkEvent received in the filter func is unpopulated. The purpose of this AddFilter mechanism is to allow the user to intercept X events before the gdk event processing starts up. We do not bind any of the X data structures in Gtk#, so you would need to manually marshal that data from the IntPtr using System.Runtime.InteropServices Marshal.
So, unless that sounds familiar as far as what you are trying to accomplish, you may want to consider other alternatives.

Related

Disable control callbacks when setting values in code?

I've noticed that when a control such as an AutoSuggestBox has a callback, the callback is executed both when a user interacts with the control and when my code changes the associated value.
For example, if I set the TextChanged property on an AutoSuggestBox, the function is called even when my code sets the Text property to an initial value.
This is causing problems in my application in the form of both bugs and unnecessary function calls. You may be wondering how the code came to be in this state -- the answer is, I don't know. The project was handed off to me from another developer and I've been tasked to fix a number of bugs.
Although I can individually hunt down all the places in the code where this happens and temporarily remove the callback, I'm wondering if there is an easier way, for example a property I can set on the control that says, "don't call the callbacks when it is the code making a change rather than the UI".
For the AutoSuggestBox.TextChanged event, the attribute of the trigger reason is provided in AutoSuggestBoxTextChangedEventArgs, and you can judge based on this
private void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (args.Reason == AutoSuggestionBoxTextChangeReason.ProgrammaticChange)
{
return;
}
//other code
}
For other controls, you need to deal with them according to your situation.
Best regards.

Possibility to complete current statement with anonymous implementation

Is there a shortcut (or menu entry) in IntelliJ IDEA to complete the current statement with an anonymous implementation. To make this more understandable:
I type something like: view.setOnClickListener( and would now like a shortcut to get the completion to:
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
<<new caret position>>
}
});
Assuming that the setOnClickListener method would accept one parameter of type OnClickListener. I don't care if there are already implementations of OnClickListener I would just like the very basic type (or interface) that is expected as an anonymous inner class.
So do anyone know if there is a possibility for this in IntelliJ IDEA, without the need of typing new OnClickListener (with auto completion) yourself?
The only thing you have to do is to write:
view.setOnClickListener(new + Ctrl+Shift+Space
This will bring up a list of alternatives but since you used the Smart Type Code Completion (instead of Basic Code Completion which is Ctrl+Space) you will have the one that fits best at the top.
So now just press Tab and the rest will be filled in for you.
You save some writing but still have to at least write new in order for it to work.
Smart Type code completion filters the suggestion list and includes only those types that are applicable to the current context.

Best OO way to handle "cancel button"

I always wondered what's the best way of handling a cancel button in a more OO way. In the hurry I always end up putting the ugly checking of a boolean form property if the button was canceled of not.
The thing is that way makes the code dirty, having a lot of "cancel checks" between logic that matters.
I always get to something like this:
void doLogic()
{
checkIfIsCancelled();
callOtherFunction();
checkIfIsCancelled();
callAnotherFunction();
checkIfIsCancelled();
callAnotherFunction();
checkIfIsCancelled();
callAnotherFunction();
}
I hope I was clear enough. I just want a neater way to do this :)
A proper way to handle this is the strategy pattern, where you have a default strategy where you do the normal processing and you have a Cancelled strategy.
Canceling changes the strategy to the cancelledStrategy that does nothing but some cleanup. The next call will go to the cancelledStrategy.
In this way even the cleanup is pretty straight forward because you know exactly where in the flow it was cancelled.
Another possible solution (but very dependent on your situation) would be the state pattern, but if you only need it for canceling it creates a lot of overhead.
it would REALLY help to know what GUI kit you're using here. Just from this it's impossible to know if you're taking about a windows, linux or mac machine. Add to that I can't think of a single GUI that that would function in this manner.
Most GUI's operate with a 'callback' pattern Widgets(buttons, menus, listboxes etc) are created and your code attaches a 'callback', a piece code or object&method that is executed when an action is performed on a widget.
In java for example:
Button b = JButton("Push") ;
listener = new ActionListener()_ {
public void actionPerformed(ActionEvent e) {
System.out.println("I was pushed!") ;
}
} ;
b.addActionListener(listener)
Arranges for the message "I was pushed!" to be printed when the button is pressed. Of course this thin examples omits all of the work you need to do to setup your window, populate this widget etc.
1st what comes to mind is http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern but I'm not sure, it's good here.
You can use the command pattern alongwith a stack to implement multi level undo support.

How do I make Message targets be the only recipent of a targeted Message?

First time poster.
I'm using MVVM-Light with Silverlight 4 and RIA Services. This has been a learning experience! But so far, it's working beautifully. I was wondering two things. Right now, I'm using the Messenger framework to pass EntityObjects back to the ViewModel. For instance, I need to open a View Model with a specific "Course" object. So I instantiate the View, and the View sends a Message to the ViewModel with the Course. I've got a couple questions.
First question: Is this the best way to do this? I don't want to use Prism or Unity or any of those other things because I don't have the time to learn them. (This was, for me, the big draw of MVVM Light. The Light part.) But I couldn't see any other way to pass parameters to the VM Locator.
The second part is, this means I am sending messages from the View to that View's specific ViewModel. My messages look like this:
Tuple<Models.Course, Services.VWDS> courseDomainContextTuple = new Tuple<Models.Course, Services.VWDS>(Course, DomainContext);
NotificationMessage<Tuple<Models.Course, Services.VWDS>> message = new NotificationMessage<Tuple<Models.Course, Services.VWDS>>(this, this.DataContext, courseDomainContextTuple, Models.MessageString.EditCourse);
Messenger.Default.Send<NotificationMessage<Tuple<Models.Course, Services.VWDS>>>(message);
So, as you can see, I'm bundling the Course and the DomainContext (Ah RIA. Why won't you let me get the Context from the EntityObject?) and sending them to the ViewModel (which is "this.DataContext") - and yes, I know I should make a class for that message.
Here's the problem - every object that gets a Course and a DomainContext receives that message, not just the VM that I've designated the Target.
So, second question: Is that by design, or is that a bug, or am I doing something wrong?
Thanks!
To answer your second question, if you're sending a NotificationMessage of a specific type, anything registering for that same message type will receive the message. If you want to limit who receives the message, either create a new message class inheriting from MessageBase or NotificationMessage or whatever, send your message with a Token, or have an if statement in your message receive handler to filter out messages you don't care about.
Messaging is more useful when you need to communicate from one ViewModel to another, or you need to send a message where zero to many things can take action on it. From your View's code behind, I think you should just call your ViewModel directly. Its easy enough - here's how I usually do it in my code.
public partial class ExampleView : UserControl
{
private IExampleViewModel ViewModel
{
get { return this.DataContext as IExampleViewModel; }
}
public ExampleView()
{
InitializeComponent();
// Call directly to my View Model
ViewModel.SomeMethod();
// Register for View Model's event
ViewModel.SomeEvent += ViewModel_SomeEvent;
}
private void ViewModel_SomeEvent(object sender, EventArgs e)
{
// do stuff
}
}
I also included in the example how I handle communications from the ViewModel back to the View - through events.

Explain ASP.NET Events

See Also:
understanding events and event handlers in C#
As a web dev, I don't typically have to get into building my own events for objects, since most are inherent in the page. However, now I'm into a pretty complex (web) project where I think I may have to use them. I just read a chapter out of Pro VB 2008 and the .NET 3.5 Platform regarding events, delegates and lambdas (ch. 11) and while I have a better idea of what's going on, I am still having trouble wrapping my mind around when exactly to use them and how to use them. I understand their implementation, but the example in the book is a bit contrived.
I was hoping someone with a bit more understanding on the subject of events could provide me with a really solid example.
For my real-world application, I'm trying to use an event that would let me know when an item (some class, named OrderItem) has been updated and perform actions based on whether or not it's been updated. I considered using a flag/boolean property, but I know this doesn't smell right, and it's high-time I learn about how to use events correctly.
Thanks a lot!
EDIT Ok, so I guess to clarify a bit, what is the point of calling an event when all it is doing is calling a method? Why not simply call the method? This isn't a duplicate either, as I'm talking conceptually and she wants to know about handlers specifically. Also, I want to know what the difference would be between using an event or a "flag" property. And what do people mean by "subscribe" to an event?
Lets say you had an elevator system, and the part that moves up and down is called the ElevatorCar. When a person pushes a button to go to the 5th floor, it would make sense for the ElevatorController to call the ElevatorCar.RequestToFloor(5) method. Now when the car actually arrives at the 5th floor, it makes sense for it to raise an event like ArrivedAtFloor, passing 5 as the argument. The ElevatorController class would subscribe to the ArrivedAtFloor event of the ElevatorCar class.
This is all becauase the ElevatorCar class doesn't "know" anything about the ElevatorController class, but the ElevatorController class does know about the ElevatorCar class. Therefore the ElevatorCar class is given instructions by means of Methods, and it notifies the outside world of stuff that happens by means of events.
Does that make any sense?
EDIT:
Ok, first, go read the excellent answer listed in the See Also link (assume you've done that). An event is basically an object saying "if you want me to call you whenever X happens, then register your method here". Registering an event handler with the event is "subscribing". This allows encapsulation. So you can write, for instance, your ElevatorCar class once, and use it many times by many other classes.
As for the difference between using an event, or just calling a method, you have to ask yourself, should the ElevatorCar know about the ElevatorController class. If ElevatorController calls ElevatorCar.GoToFloor(x), how could the ElevatorCar class "call back" to ElevatorController without storing a reference to ElevatorController? That means the call has to become ElevatorCar.GoToFloor(int floor, ElevatorController ctrlr). Then the ElevatorCar class eventually has to call ctrlr.ArrivedAtFloor(floor). But you get into a lot of complexities... what if there's more than one car? You probably have to call ctrlr.ArrivedAtFloor(floor, this). Passing around references to yourself isn't optimal.
As for just setting a property, how does the other class know to come and read the property? The only way is to poll the property over and over to check for it to change. You can solve this, of course, by implementing INotifyPropertyChanged, but then again you're back to events!
Events are a specific case of the Inversion of Control (IoC) pattern. The traditional control flow, the caller invokes a method on the callee (like you are suggesting). With IoC (and thus events), we change around the application control and instead of tell the callee what to do, we tell the callee to notify us when something we are interested in happens.
Consider the case of a Timer. I want to be notified every 5 seconds (say). I don't want to constantly poll the timer ("is it time yet? is it time yet? is it time yet?"). Instead, I want to invert the flow control of my application. I want to tell the timer: "When it's time, please tell me by calling this method." That way, control is "inverted", the callee is invoking a method on the caller!
Consider the following code ...
using System;
using System.Timers;
namespace TestTimer
{
class Program
{
static void Main(string[] args)
{
// create my timer.
var t = new System.Timers.Timer(1000);
// register for notification
// tell the timer, "when it's time, call TimerGoesOff method"
t.Elapsed += new ElapsedEventHandler( TimerGoesOff );
// start the timer
t.Start();
// wait
Console.ReadLine();
}
// this gets called when the timer goes off
public static void TimerGoesOff(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Time is " + e.SignalTime);
}
}
}
Rather than call a method on the Timer to ask when it will go off again (as you suggest), I tell it, "when you go off, call the TimerGoesOff" method. Now, instead of just waiting for the Timer to go off, I could do some work. Consider this code ...
using System;
using System.Threading;
using System.Timers;
namespace TestTimer
{
class Program
{
static void Main(string[] args)
{
// create my timer.
var t = new System.Timers.Timer(1000);
// register for notification
t.Elapsed += new ElapsedEventHandler( TimerGoesOff );
// start the timer
t.Start();
// do some work while timer is going
new Thread(() => DoWork()).Start();
Console.ReadLine();
}
// this gets called when the timer goes off
public static void TimerGoesOff(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Time is " + e.SignalTime);
}
public static void DoWork()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine( "Working ..." );
Thread.Sleep( 1000 );
}
}
}
}
Now, I get output something like ...
Working ...
The Time is 8/25/2009 1:05:59 PM
Working ...
Working ...
The Time is 8/25/2009 1:06:00 PM
Working ...
The Time is 8/25/2009 1:06:01 PM
Working ...
The Time is 8/25/2009 1:06:02 PM
The Time is 8/25/2009 1:06:03 PM
I have used the Timer.Elapsed Event to change the control flow of my application. I can go off and do work while "waiting" for the timer event to pulse. This is made possible by IoC and Events.
This is particularly visible (hehe) in User Interfaces. I don't want to keep asking "has the user done anything yet? has the user done anything yet?" (that's the way it used to be done way back when). Instead, I tell Controls for example, "when the user clicks you, let me know". That way, I can go off and do other great stuff and still be responsive to the user.