2016/04/05

rustlang dynamic library part 2

A previous post was about getting a simple rust dynamic library working. The next thing I wanted to do was try passing a more complex type from the dynamic library to the executable using it.

First, I changed dynamiclib to:

#[derive(Debug)]
pub struct Tuple (u32,);

#[derive(Debug)]
pub struct MyStruct {
    s1: &'static str,
    s2: String,
    t: Tuple,
}

#[no_mangle]
pub extern "C" fn test() -> MyStruct {
    MyStruct {
        s1: "hello",
        s2: "world".to_string(),
        t: Tuple(47),
    }
}
And dynamic to:
#[link(name="dynamiclib")]
extern {
    fn test() -> MyStruct;
}

fn main() {
    let retval = unsafe { test() };
    println!("Got: {:?}", retval);
}
And (somewhat surprisingly) it worked as expected. Although you get the following error:
warning: found struct without foreign-function-safe representation annotation in foreign module, consider adding a #[repr(C)] attribute to the type, #[warn(improper_ctypes)] on by default
At first I considered appeasing the warning, but if it's a library written in rust and called from rust, shouldn't the default
repr(Rust)
be safe/correct?

Next, I decided to try loading and re-loading the shared library using this more complex struct... and I started getting SIGSEGV the second time I attempted to use the library.

I came across libloading (crates.io) which purports to be safer wrapper for working with dyanmic libraries, and if nothing else has much better documentation.

A quick change to dynamic/src/main.rs (devoid of error-checking):

    let lib = Library::new("libdynamiclib.dylib").unwrap();
    let test: Symbol MyStruct> = unsafe {
        lib.get(b"test\0").unwrap()
    };
    println!("Got: {:?}", test());
And it works correctly even when re-loading the library. So, I was either using stale symbols, or something else. Still several things that I obviously don't fully understand. Hopefully pouring over Rustonomicon will reveal the secrets to me.

Xamarin Forms part 1

This is the first part of my Xamarin Forms dive.

Binding

Arguably the single most important thing to master as it connects your View (UI) to the ViewModel, it's only fitting I start out with Binding (1, 2 and 3). Since I’ve been using Forms I’ve found that binding is key to getting things working but various nuances are scattered about in numerous demos.

Bindings connect a "source" (either another UI element in the View or something in the ViewModel) to a "target" (some UI element in the View) that displays it.

To start with, you'll see that most projects create an XML namespace that refers to a .Net assembly generated by your project:

<!-- "xmlns:local" ties "local" XML namespace to the "luck" C# namespace in the "luck" assembly -->
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:luck;assembly=luck"
    x:Class="luck.MainPage"
    >
</ContentPage>

// "local:MainViewModel" in XAML thus refers to a C# class similar to:
namespace luck {
    public class MainViewModel {
        // Implementation
    }
}
You can then easily create static bindings, references, and resources:
<!-- Static -->
<Label Text="{x:Static local:MainViewModel.Text}" />

// C# ViewModel
public class MainViewModel {
    public static string Text = "text";
}

<!-- Reference -->
<Label Text="text" x:Name="MyText" />
<Label Text="{x:Reference MyText}" />

<!-- Resource -->
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:LocalizationConverter
                x:Key="LocalizationConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <Label Text="{Binding SelectedItem.DisplayName,
        Converter={StaticResource LocalizationConverter}}" />
There's additional information about Resources and markup extensions here, and I'll come back to ResourceDictionary a bit later in this series when I get to Styles.

Alternatively, the Binding markup extension is the most common binding technique and more advanced as it supports several different properties. The easiest way of specifying a source is by setting the BindingContext for the entire Page since it is inherited by all children. This can be done either in your code-behind constructor:

public MainPage ()
{
     InitializeComponent ();
     BindingContext = new MainViewModel (); 
}
or via XAML:
    <ContentPage.BindingContext>
        <local:MainViewModel />
    </ContentPage.BindingContext>
You can then bind a simple value:
<Label Text="{Binding Text}" />

public class MainViewModel {
    public string Text { get; set; }
}
As already mentioned, Binding supports several different properties. Path specifies the property of the source to which we are binding and can be omitted if it's the first property. The following two are equivalent:
<Label Text="{Binding Text}" />
<Label Text="{Binding Path=Text}" />
The Path property is able to access sub-properties as well as the index operator. For example:
<Label Text="{Binding Values.Count}" />
<Label Text="{Binding Values[key]}" />

// In the ViewModel
public Dictionary Values { get; set; }
According to this, if you have large numbers of values to set you can simplify multiple indexed bindings by setting the binding context:
<StackLayout BindingContext="{Binding Values}" />
    <Label Text="{Binding [key]}" />
<StackLayout />
There is also a shorthand syntax to bind directly to the BindingContext itself:
<Label Text="{Binding .}" />
The Source property allows the binding to explicitly specify the "source" of a binding. It's analogous to the BindingContext (where the target specifies the source) and the following are equivalent:
<Label BindingContext="{x:Reference items}" Text="{Binding SelectedItem, StringFormat='{0}'}" />
<Label Text="{Binding SelectedItem, Source={x:Reference items}, StringFormat='{0}'}" />
The biggest difference being using BindingContext will be inherited by all sub-children of the UI element. At one point I found myself repeatedly specifying BindingContext and Source for a number of nested elements and then running into problems where I could no longer reference the original BindingContext, etc. In this case I had to carefully consider what I was binding where and reorganise the data provided by my ViewModel to cut back on the excessive use of Source.

StringFormat can be used to apply string conversion and formatting:

<Label Text="{Binding Value, StringFormat='Formatted {0}'}" />
Internally it uses String.Format method so it accepts all the same forms. Note that because both .Net formatting and markup extensions use curly braces, StringFormat must be enclosed in single quotes.

The Converter property is more generalised than StringFormat and also accepts an optional ConverterParameter value:

 <Label Text="{Binding SomeInt, Converter={StaticResource IntConverter}, ConverterParameter=10}" />

 public class IntConverter : IValueConverter
 {
  public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
   int intparam;
   if (!int.TryParse(parameter as string, out intparam))
    intparam = 1;

   return (int)value * intparam;
  }

  public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
   int intparam;
   if (!int.TryParse(parameter as string, out intparam))
    intparam = 1;

   return ((int)value) / intparam;
  }
 }
Mode The final property Mode is available to solve some specific binding problems. I've not done anything with it just yet, so I'll refer to two relevant documents from Xamarin (1, 2) and revisit it later when I understand it better.

Dynamic Bindings

For values that can be changed at runtime, either the property you're binding to or the entire ViewModel needs to implement INotifyPropertyChanged interface. For example, using System.Collections.ObjectModel.ObservableCollection:
public static ObservableCollection Chats = new ObservableCollection();


You can even define your own:
    public class ObservableString : System.ComponentModel.INotifyPropertyChanged
    {
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        string val;
        public string Value
        {
            get { return val; }
            set {
                val = value;
                OnPropertyChanged ("Value");
            }
        }

        void OnPropertyChanged(string propertyName = null)
        {
            if (PropertyChanged != null)
                PropertyChanged (this, new System.ComponentModel.PropertyChangedEventArgs (propertyName));
        }
    }
But this only seems to work with static bindings. The more standard approach is to implement INotifyPropertyChanged for your entire ViewModel:
    public class LoginViewModel : INotifyPropertyChanged
    {
        bool m_isBusy = false;
        public bool IsBusy {
            get {
                return m_isBusy;
            }
            set {
                if (value != m_isBusy) {
                    m_isBusy = value;
                    OnPropertyChanged ("IsBusy");
                }
            }
        }

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged (string propertyName)
        {
            var changed = PropertyChanged;
            if (changed != null) {
                PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
            }
        }
        #endregion
    }
With .Net 4.5 OnPropertyChanged can be simplified:
        public bool IsBusy {
            get {
                return m_isBusy;
            }
            set {
                if (value != m_isBusy) {
                    m_isBusy = value;
                    OnPropertyChanged ();
                }
            }
        }

        protected virtual void OnPropertyChanged ([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
        { /* same as above */ }
A minor improvement, but now the compiler guarantees that the property name always matches the "magic string". There’s further improvements to reduce all the boilerplate needed to implement properties (specifically this, and more generally like this and this).

This ran a bit long, but it should wrap up the first dump of my notes on Xamarin Forms. Next up: Callbacks, Commands, and Triggers... oh my!