Conversion of Gdk Events in Mono - events

I'm trying to intercept events using Gdk.Window.AddFilter(Gdk.FilterFunc) in Mono. So far, I have been able to hook up the filter function, but now I am trying to use the events in the filter function.
This is what I have in the filter function so far:
private Gdk.FilterReturn FilterFunction(IntPtr xEvent, Gdk.Event evnt)
{
if (evnt.Type == Gdk.EventType.KeyPress)
{
Gdk.EventKey eventKey = (Gdk.EventKey)evnt; // fails here
if (eventKey.Key == this.key && eventKey.State == this.modifiers)
{
this.OnPressed(EventArgs.Empty);
}
}
return Gdk.FilterReturn.Continue;
}
How can I convert the Gdk.Event to Gdk.EventKey? I have tried casting it, but that doesn't seem to work.
Edit: Oops! The problem was that I had accidentally added a semicolon to the if statement, making it an empty statement. For some reason, the Gdk.Event does not correspond to the XEvent, so I am now pursuing a solution that uses the XEvent instead.

Why don't you try printing out the type so you can see what it really is? (it may not be EventKey)
Like:
Console.WriteLine (evnt.GetType ());
(or pause it in a debugger and examine it to see the type)

Related

catching Enter in a multiline Fyne Entry widget (more generally, calling "parent classes")

This question is more about Go than Fyne. Having extended Fyne's Entry widget is the prescribed fashion, I want to detect when Enter (Return) is pressed and use it as a signal that I need to act on the content of the Entry. I want Shift-Return to add a newline to the text without signalling that I need to act.
Given a struct that starts with
type myEntry struct {
widget.Entry
.....more... }
It's easy enough to add
func (m *myEntry) TypedKey(key *fyne.KeyEvent) {
if key.Name == "Return" {
///send m.Text somewhere...
} else {
//WRONG: m.(*widget.Entry).TypedKey(key) //give Key to Entry widget to process
}
}
but the else clause doesn't compile. So after having decided this isn't a Key I want to intercept, how do I give it back to widget.Entry? Other questions here about calling "base classes", which Go doesn't quite have, don't seem to cover this case.
I thought I could finesse this by adding
type myEntry struct {
widget.Entry
me *Fyne.Focusable
and setting me to the address of myEntry on creation, so I could simply call me.TypedKey. But keys were not handled, and then there was a crash. Setting me=&myNewEntryObject on creation apparently isn't sufficiently "widget.Entry-like" to win the day.
I know Go isn't an OO language, but extending a type and then redirecting calls back to the parent type is a fundamental programming technique; I'd go as far as saying there's no point in extending a struct if you can't get back to the "base struct's" behaviour from the extension. What am I missing?
Embedded types without a name can be referenced using the name of the type - so the following will work:
func (m *myEntry) TypedKey(key *fyne.KeyEvent) {
if key.Name == "Return" {
// send m.Text somewhere...
} else {
Entry.TypedKey(key)
}
}

Is there some syntactic sugar for matching on deeply nested Option and Result chains?

I am issuing calls that return an Option that contains a Result which contains another Option that contains custom variants.
I am only ever interested in a specific chain of variant results like this:
if let Some(Ok(Some(CustomVariant(Some(value))))) = expr {
// handle value case
}
This is getting quite verbose and not really helpful, since I actually treat it as a single Result in all of my code. Can I somehow alias this code so that instead of writing the entire chain of Options and Results I can do something similar to:
alias TheCase(value) = Some(Ok(Some(CustomVariant(Some(value))));
if let TheCase(value) = expr {
//handle value
}
You don't need such an alias, just use a function to retrieve the one case you want:
fn oneCaseICareAbout(value: &Option<Result<Option<Foo>, Bar>>) -> Option<&Foo> {
if let Some(Ok(Some(CustomVariant(Some(value)))) = value {
Some(value)
} else {
None
}
}
if let Some(value) = oneCaseICareAbout(expr) {
//handle value
}
I would however consider refactoring your code not to use such a type. Option<Result<_, _>> is already a red flag, but Some(Ok(Some(CustomVariant(Some(…)))) is just on the edge of insanity!

In C++/CLI how do you define thread-safe event accessors?

The code sample "How to: Define Event Accessor Methods" at
http://msdn.microsoft.com/en-us/library/dw1dtw0d.aspx
appears to mutate the internal pE without taking locks. (It doesn't look like Delegate::Combine does anything magical that would prevent issues.) It also does
void raise() {
if (pE != nullptr)
pE->Invoke();
}
which can be problematic if pE changes to null between the check and the Invoke(). I have two questions:
Am I right in that the existing code is not thread-safe?
Since I want a thread-safe version of the code, I was thinking of locking the add and remove functions. Is it premature optimization to use
void raise() {
MyDel^ handler = pE;
if (handler != nullptr)
handler->Invoke();
}
or should I just lock that function too?
All three accessors are thread-safe by default (raise includes a null-check, and uses a local variable to avoid the race condition) unlike the example in the page you linked.
When it comes to custom event implementations, you're right about needing to synchronize the add and remove accessors. Just put a mutex around the implementation. But there's no need to throw away type safety by calling Delegate::Combine and then casting, since operator + and - are overloaded for delegate handles. Or you can go lockless, as follows:
void add(MyDel^ p)
{
MyDel^ old;
MyDel^ new;
do {
old = pE;
new = pE + p;
} while (old != Interlocked::CompareExchange(pE, new, old));
}
Define remove mutatis mutandis (new = pE - p;). And the code you gave for raise will be perfectly fine for a custom event implementation.
In summary, that MSDN sample is total garbage. And the simplest way to achieve thread-safety is with an auto-implemented event.

How to replace lambda written in Where clause of Linq with equivalent delegate

I have an Query expression that uses a predicate type and lambda expression.
I am getting desired result with this. But I am not clear with how this expression is getting evaluated.
I tried to break this lambda expression by creating delegate and replacing condition under Where with delegate type.
If I have to rewrite the same thing with writing a delegate instead of anonymous type. What will be the syntax. How the delegate will be return for the same.
if (((DataTable)dgvAssignedRpm.DataSource).AsEnumerable()
.Where(row => row.Field<long>("FK_RPM_BTN_SETTING_ID") == objRpmButtonHolder.RpmSettingId).Count() > 1)
{
List<DataRow> listPkgBtnSettings = SearchForExistingSettingId();
}
void MethodSignature(...)
{
...
if (((DataTable)dgvAssignedRpm.DataSource).AsEnumerable()
.Where(RowCondition)
{
List<DataRow> listPkgBtnSettings = SearchForExistingSettingId();
}
...
}
// Where want a Func<T,bool> parameter
// T is the first parameter type (DataRow here)
// bool represents the return value
bool RowCondition(DataRow row)
{
return row.Field<long>("FK_RPM_BTN_SETTING_ID") == objRpmButtonHolder.RpmSettingId).Count() > 1
}
I assume the correct delegate replacement would be:
if (((DataTable)dgvAssignedRpm.DataSource).AsEnumerable().Where(
delegate(DataRow row) {
return (row.Field<long>("FK_RPM_BTN_SETTING_ID") == objRpmButtonHolder.RpmSettingId.Count() > 1);
}))
{
List<DataRow> listPkgBtnSettings = SearchForExistingSettingId();
}
But it's morning for me, so forgive me if I'm a bit off.
What the where desires is to give a DataRow as a parameter and a bool to return. You could just about fill in anything in the lambda or delegate, as long as it matches these requests.
To your question why it requests Func<> and how it works. The statement you're using is LINQ, so I found you a reference regarding this which can probably explain it better than me:
http://blogs.msdn.com/b/mirceat/archive/2008/03/13/linq-framework-design-guidelines.aspx
But yeah, the last type here in the Func<> is what it returns. (However, I can still recommend using the Lambda expression, as it's pretty clean, neat and serves the Func<> best.
(Also, look at what intellisence gives you when you write "new Func<....", it should give you a good idea of what Func wants and can do!)
Hope I was of help.

How to avoid Linq chaining to return null?

I have a problem with code contracts and linq. I managed to narrow the issue to the following code sample. And now I am stuck.
public void SomeMethod()
{
var list = new List<Question>();
if (list.Take(5) == null) { }
// resharper hints that condition can never be true
if (list.ForPerson(12) == null) { }
// resharper does not hint that condition can never be true
}
public static IQueryable<Question> ForPerson(this IQueryable<Question> source, int personId)
{
if(source == null) throw new ArgumentNullException();
return from q in source
where q.PersonId == personId
select q;
}
What is wrong with my linq chain? Why doesn't resharper 'complain' when analyzing the ForPerson call?
EDIT: return type for ForPerson method changed from string to IQueryable, which I meant. (my bad)
Reshaper is correct that the result of a Take or Skip is never null - if there are no items the result is an IEnumerable<Question> which has no elements. I think to do what you want you should check Any.
var query = list.Take(5);
if (!query.Any())
{
// Code here executes only if there were no items in the list.
}
But how does this warning work? Resharper cannot know that the method never returns null from only looking at the method definition, and I assume that it does not reverse engineer the method body to determine that it never returns null. I assume therefore that it has been specially hard-coded with a rule specifying that the .NET methods Skip and Take do not return null.
When you write your own custom methods Reflector can make assumptions about your method behaviour from the interface, but your interface allows it to return null. Therefore it issues no warnings. If it analyzed the method body then it could see that null is impossible and would be able to issue a warning. But analyzing code to determine its possible behaviour is an incredibly difficult task and I doubt that Red Gate are willing to spend the money on solving this problem when they could add more useful features elsewhere with a much lower development cost.
To determine whether a boolean expression can ever return true is called the Boolean satisfiability problem and is an NP-hard problem.
You want Resharper to determine whether general method bodies can ever return null. This is a generalization of the above mentioned NP-hard problem. It's unlikely any tool will ever be able to do this correctly in 100% of cases.
if(source == null) throw new ArgumentNullException();
That's not the code contract way, do you instead mean:
Contract.Require(source != null);

Resources