10 Things Every FireMonkey Developer Should Know About Styles

A recent Embarcadero webinar video by Eugene Kryukov (FireMonkey designer) and Vsevolod Leonov (FireMonkey evangelist) gives a really good, in depth look at FireMonkey styles and how they work. Here are some tips I distilled down from that video along with a few things I’ve learn myself.

1. How a style name is constructed

You’ll want to know this if you’re creating custom controls. If you don’t explicitly state a style name for your control (and you probably don’t want to) FireMonkey will search for a style based on te class name of your control - it removes the preceding ‘T’ and appends ‘Style’ to the end.

So, a TButton uses a style ‘ButtonStyle’. A TEdit, ‘EditStyle’, a TCalender ‘CalendarStyle’ and so on.

2. Style names can also be inherited

But if you’re subclassing a component you may not want to have to create a style for it if you haven’t modified anything which alters the styling. And if that’s the case you don’t need to.

If you create a component:

type TEditChild = class(TEdit); 

FireMonkey will first look for the style ‘EditChildStyle’ (as we saw above). If that doesn’t exist it will look for the style for the parent class, i.e, it will look for ‘EditStyle’ and apply that.

But, this doesn’t apply to grandchildren. If you then create:

type TEditGrandchild = class(TEditChild); 

FireMonkey will look for ‘EditGrandchildStyle’, then ‘EditChildStyle’, but it will stop there and not go any further up the component tree to ‘EditStyle’.

3. Loading default styles

The basic look of your application comes from the default style. If you want to change this you need to set the StyleFileName property of your forms Application object (in the FMX.Forms unit):

Application.StyleFileName := 'C:\Styles\MyStyle.style'

This is best done in your project file, before the line to Application.Initialize.

Ideally there should be some way to set the default style from within your applications project options, or to load it from a resource. Sadly, after much experimentation, I can’t find a way to do this. If you know better, please comment.

4. Where your application gets it’s styling info

As you know you can pop a StyleBook on a form to customise your style. But adding a separate stylebook to each and every form: duplicates data; increases redistributable sizes; is a mainainance nightmare (update every form when you change a style?); just isn’t DRY.

Much better to create a single master StyleBook on your main form, then link each child’s stylebook to that on the main form. You can do that with the following in each forms OnCreate event handler:[1]

StyleBook := TForm(Application.MainForm).StyleBook1

Note, however that this doesn’t work within the form editor. Create a custom control, add it to your child form and it won’t show the style you have loaded in your main forms StyleBook. I really hope Embarcadero find some kind of workaround for this. Or better yet, improve the style book handling within FireMonkey.

5. Set your StyleBook property

This gotcha has caught me a few times: You add a StyleBook to your form, change the style within it, set your components StyleLookup property and run your application. And you get the default style.

You should have set the forms StyleBook property to point to the StyleBook. Ouch.

Note that if you right click a control and edit it’s style, a StyleBook will be created and the StyleBook property will be set, but only if there isn’t already a StyleBook present. If you create the StyleBook manually, you need to set the StyleBook property yourself.

6. You can have multiple StyleBook objects

Your form can have multiple StyleBook objects. I figure that explains the behaviour in the above item - FireMonkey doesn’t want to assume whcih StyleBook to use. Why would you want multiple StyleBooks? I’m not really sure. The form and the components on it can only use one at a time.

7. Styles don’t have to come from style files

So, you know a style can come from the default style, or from a StyleBook, but it can also come from a control on a from. Simply set the StyleName property of a control and set the StyleLookup of another control to match.

8. Keep your StyleBooks light

The resources in a StyleBook take time up at form create time. For this reason you should keep your StyleBooks to a reasonable size. Instead you should put styling information in your default style (and load it with Application.StyleFileName - see above).

Sadly at the moment there’s no easy way to merge style files - so you’ll have to add your custom styling to the (probably Embarcadero supplied) default style and keep the merge up to date.

9. Beware the HitTest

Add a TImage to a button and you’ll notice that when the mouse is over the image the functionality of the button will be lost. I.e. mouseovers, clicks etc will be ignored. This is because the TImage is absorbing them. To fix this you needs to set the TImage’s HitTest property to False. This applies whether you’re adding controls on a form or in a style file.

10. If all else fails, set Locked := True

Every FireMonkey control has a Locked property. I’m not sure what this does. The Embarcadero doesn’t seem to know what it does either, the property reference simply says it locks controls at design time, but this page says “Enabling Locked changes the way hit testing works and triggers fire, so that the subcomponent is part of the larger whole.”. My experience (although somewhat limited in this area) is that if I’m having problems with mouse clicks going missing fiddling with Locked in association with HitTest (see above) is the best way to resolve things.

[1] An even better way to handle this is to create a custom form class, and set the StyleBook property in an overridden Create constructor. This is left as an exercise for the ready.

 

MonkeyStyler Build 4 beta

Build 4 beta is now available. Chief changes are improvements to property editors and property editor styling.

Full change list:
Fixed: GradientPointsEditor text values update when gradient points are selected (Update 4 bug? ColorPanel.OnChange is no longer called when value is set programmatically).
Fixed: Added editor for TControl.Position.*
Fixed: R and B values where swapped in text fields of GradientPointsEditor.
Added: Text entry for ColorEditor.
Fixed: GradientPointsEditor gradient updates when changing text fields.
Fixed: Files other than current one not being saved on SaveAll or Close.
Fixed: Alpha value (text edit) updates properly when selecting gradient points (FMX bug workaround).
Added: Property editor styling is slightly better.

MonkeyStyler Build 3 Beta

This build adds the ability to create a link to your application and have the styles within it updated with a single click. Read more about this in the wiki.

The full list of changes for this update:
Added: ‘Apply’ styles: One click to modify the style of a running FireMonkey application
Added EurekaLog error handling (some bugs with EL and FMX).

FireMonkey ListBox With In Place Editing

I’ll admit to having a personal bias against modal dialog boxes. They interrupt my workflow and thought process. So, I rather like the way Windows Explorer works when editing a filename - the text changes to an edit box and I can type in the new filename, or simply hit escape and move on.

I saw no reason why I shouldn’t be able to do the same thing in FireMonkey. A FireMonkey list box is simply a container for other controls, so I reasoned I could simply replace the existing text control with an edit control when the user began an edit, and swap back to the text control when the edit was finished. We’ll start editing when the user hits F2, finish on pressing the enter key and let users back out by hitting escape.

Here’s a screenshot of what I came up with:

EditListBoxItem

A listbox is a container for other controls, but only children of TListBoxItem will actually show up within the list, so first we need to create such a child, we’ll call it TEditListBoxItem:

type TEditListBoxItem = class(TListBoxItem)
  private
    
FEditControlTStyledControl;
    
procedure SetEditControl(const ValueTStyledControl);
  protected
    
procedure SetFocus;reintroduce;
    
procedure SetText(const ValueString);override;
    function 
GetTextString;
    
procedure EVKeyDown(SenderTObject; var KeyWord; var KeyCharWideCharShiftTShiftState);
    function 
GetDataVariant;override;
    
procedure SetData(const ValueVariant);override;
  public
    
constructor Create(AOwnerTComponent);override;
    
destructor Destroy;override;
    
property TextString read GetText write SetText;
    
property EditControlTStyledControl read FEditControl write SetEditControl;
  
end


EditControl is the control which will do the editing. I could have explicitly made this a TEdit, but if we use a TSyledControl then users of our code can substitute any suitable control. They could use some kind of date or filtered editor, or one with validation. Or they could use something completely unrelated to text and text editing.

procedure TEditListBoxItem.SetEditControl(const ValueTStyledControl);
var 
DataVariant;
begin
  
if EditControl <> nil then
    Data 
:= GetData
  
else
    
Data := varNull;
  
FreeAndNil(FEditControl);
  
FEditControl := Value;
  
FEditControl.Align := TAlignLayout.alClient;
  
FEditControl.Data := Data;
  
FEditControl.Parent := Self;
  
FEditControl.OnKeyDown := EVKeyDown;
end

We’re relying on the creator of the list box item to create and assign the edit control. When they do we need to do some setting of properties, as shown above. We need to monitor the OnKeyDown event so we can intercept the Enter and Escape keys to finish editing.

Because we don’t know that our edit control will be an edit box we can’t simply read and write the Text property. Fortunately FireMonkey gives us a more generic way of getting and setting content using the Data property. This is a Variant and can read or write any data type as used by the control.

Note in the SetEditControl method above that we took care to preserve the value of any control already in existence by getting the old Data and assigning it to the new Control.

And refer back to the class definition above to see that we override the GetData and SetData methods to get and set data. We also add our own Text property since GetText and SetText aren’t virtual. Our GetText and SetText simply pass values to and from the edit controls Data property. It’s a bit redundant in our usage, but adding this functionality should help prevent obscure errors somewhere down the line.

function TEditListBoxItem.GetDataVariant;
begin
  
if EditControl <> nil then
    Result 
:= EditControl.Data
  
else
    
Result := varNull;
end;

function 
TEditListBoxItem.GetTextString;
begin
  Result 
:= GetData;
end;

procedure TEditListBoxItem.SetData(const ValueVariant);
begin
  inherited
;
  if 
EditControl <> nil then
    EditControl
.Data := Value;
end;

procedure TEditListBoxItem.SetText(const ValueString);
begin
  inherited
;
  if 
EditControl <> nil then
    EditControl
.Data := Value;
end

TInPlaceEditListBox

Now we can move on to the list box itself:

type TInPlaceEditListBox = class(TListBox)
  private
    
EditItemTEditListBoxItem;
    
EditedItemTListBoxItem;
    
EditUpdateInteger;
    
FOnCreateEditControlTCreateControlEvent;
  protected
    
procedure KeyDown(var KeyWord; var KeyCharSystem.WideCharShiftTShiftState); override;
    
procedure EVEditKeyDown(SenderTObject; var KeyWord; var KeyCharWideCharShiftTShiftState);
    
procedure SetItemIndex(const ValueInteger);override;
    
procedure InPlaceEdit;
    
procedure EndInPlaceEdit(SaveBoolean);
  public
    
destructor Destroy;override;
    function 
CreateEditControlTStyledControl;virtual;
    
property OnCreateEditControlTCreateControlEvent read FOnCreateEditControl write FOnCreateEditControl;
  
end

We’ll start in the overridden KeyDown method, which simply monitors for the F2 key:

procedure TInPlaceEditListBox.KeyDown(var KeyWord;
  var 
KeyCharSystem.WideCharShiftTShiftState);
begin
  
if Key vkF2 then
    InPlaceEdit
  
else
    
inherited;
end;[/b]

Things get interesting in the inPlaceEdit method
:

[code]procedure TInPlaceEditListBox.InPlaceEdit;
var
  
OldYSingle;
  
ControlTStyledControl;
begin
  
if (ItemIndex 0then
    
EXIT;

  
EndInPlaceEdit(True);

  
OldY := VScrollBar.Value;
  try
    
Inc(EditUpdate);
    
FreeAndNil(EditItem);
    
EditItem := TEditListBoxItem.Create(Self);
    
EditItem.EditControl := CreateEditControl;
    
EditItem.OnKeyDown := EVEditKeyDown;

    
BeginUpdate;
    
EditedItem := ListItems[ItemIndex];
    
AddObject(EditItem);
        
Exchange(EditedItemEditItem);
    
EditedItem.Parent := nil;
    
EditItem.SetData((THackListBoxItem(EditedItem)).GetData);
    
EditItem.SetFocus;
    
EditItem.IsSelected := True;
    
VScrollBar.Value := OldY;
    
EditItem.Opacity := 0;
     
EndUpdate;
    
EditItem.AnimateFloat('Opacity'10.2);
  
finally
    dec
(EditUpdate);
  
end;
end

Here we,
* Check we have a valid ItemIndex.
* Stop any exising edits.
* Preserve the scollbar value so we can restore it later.
* EditUpdate is used to prevent some icky side effects (see below).
* We free any existing EditItem (our TEditListBoxItem), create a new one and call CreateEditControl to instantiate the control to go inside it.
* We preserve the existing ListBoxItem into EditedItem, so we can restore it once editing is complete.

Now we need to get our TEditListBoxItem (EditItem) into the list. TListBox has an InsertObject method to insert an item anywhere in the list. Unfortunately a bug in FireMonkey (as of XE2 update 4) means this always fails with an exception. The workaround for this is to call AddObject which adds the item to the end of the list (and is a synonym for setting the Parent property), and then call Exchange with the two items we want to swap.

EditItem (Our new item) is now in the correct place in the list, and EditedItem (the old text item) is now at the end. We can simply null EditedItems Parent property to remove it from the list.

Next comes a line lifted from the dark side, and one I’m not proud of. Recall our discussion on setting a generic data value through the Data property? What I should have been able to write here is

EditItem.Data := EditedItem.Data

But the FireMonkey designers borxed things up in TListBoxItem by adding a fresh Data property of type TObject which, as far as I can see, isn’t actually used anywhere in FireMonkey.

The workaround is to explicitly call the inherited GetData and SetData methods which aren’t overridden in TListBoxItem, but they are hidden because they’re protected and out of scope. We can bring them into scope by creating a do nothing descendant of TListBoxItem (

type THackListBoxItem = class(TListBoxItem); 

) in our unit and use some typecasting as shown above to get to the methods. Like I say, nasty but necessary.

After that we can return to sunnier climes. We:
* Give the edit control focus.
* Select the new item, to restore the list boxes ItemIndex property.
* Restore the scrollbar to where it was.
* Animate the opacity property for a pretty effect.

Tidying up

To handle when the user finishes editing we use the EVKeyDown event handler which monitors for Escape and Enter keys and calls EndInPlaceEdit, which is pretty much a reversed copy of InPlaceEdit: swapping out our editor for whatever was there before and saving (or not) the Data.

There’s only a couple more things of note.

We override the SetItemIndex method to stop editing if another item is selected (e.g. by a mouse click). Here’s where our EditUpdate field comes in useful: all that inserting and moving list items around plays havoc with the ItemIndex property and we need to protect against accidentally finishing editing before we’ve even started.

procedure TInPlaceEditListBox.SetItemIndex(const ValueInteger);
begin
  
if EditUpdate 0 then
    EndInPlaceEdit
(True);
  
inherited;
end

In EVKeyDown we add code to move the editor when the user keys up or down:

procedure TInPlaceEditListBox.EVEditKeyDown(SenderTObject; var KeyWord;
  var 
KeyCharWideCharShiftTShiftState);
begin
  
if EditItem nil then
    
EXIT;

    if 
Key vkUp then
    
if ItemIndex 0 then
    begin
      KeyDown
(KeyKeyCharShift);
      
InPlaceEdit;
    
end
    
else
  else if 
Key vkDown then
    
if ItemIndex Count-1 then
    begin
      KeyDown
(KeyKeyCharShift);
      
InPlaceEdit;
    
end;
end

but we double check ItemIndex can be changed. Otherwise moving up from the first item or down from the last would cause the editor to be recreated and look nasty.

Finally we’ll look at CreateEditControl which lets developers use their own edit control, or defaults to a TEdit:

function TInPlaceEditListBox.CreateEditControlTStyledControl;
begin
  Result 
:= nil;
  if 
Assigned(OnCreateEditControlthen
    OnCreateEditControl
(SelfResult)
  else
    
Result := TEdit.Create(Self);
end

Back to the list box item

Before I leave you in peace I’ve got something else to show you. Look at the constructor of TEditListBoxItem:

constructor TEditListBoxItem.Create(AOwnerTComponent);
begin
  inherited
;
  
CanClip := False;
end

We’re setting the CanClip property to false. This means that the item and it’s children can show outside the bounds of it’s owner (the list box). The first effect of this is that the editors glow effect can show outside the list box. IMHO this simply looks better.

The second and potentially more exciting effect is that the editor itself can appear outside the listbox. Imagine the list box contained some potentially long strings but you don’t want a wide form. The user can now have a compact display but with a nice long edit box when necessary.

The code to achieve this is simple, in the list items SetEditControl method simply comment out the line that sets the Align property and set a reasonable width for the edit control:

procedure TEditListBoxItem.SetEditControl(const ValueTStyledControl);
var 
DataVariant;
begin
  
if EditControl <> nil then
    Data 
:= GetData
  
else
    
Data := varNull;
  
FreeAndNil(FEditControl);
  
FEditControl := Value;
//  FEditControl.Align := TAlignLayout.alClient;
  
FEditControl.Width := 200;
  
FEditControl.Data := Data;
  
FEditControl.Parent := Self;
  
FEditControl.OnKeyDown := EVKeyDown;
end

Download the full source:

Enjoy, Mike.

Full Source

unit InPlaceEditList;

interface
uses FMX.ListBoxSystem.ClassesFMX.TypesFMX.Edit;

type TEditListBoxItem = class(TListBoxItem)
  private
    
FEditControlTStyledControl;
    
procedure SetEditControl(const ValueTStyledControl);
  protected
    
procedure SetFocus;reintroduce;
    
procedure SetText(const ValueString);override;
    function 
GetTextString;
    
procedure EVKeyDown(SenderTObject; var KeyWord; var KeyCharWideCharShiftTShiftState);
    function 
GetDataVariant;override;
    
procedure SetData(const ValueVariant);override;
  public
    
constructor Create(AOwnerTComponent);override;
    
destructor Destroy;override;
    
property TextString read GetText write SetText;
    
property EditControlTStyledControl read FEditControl write SetEditControl;
  
end;

type TCreateControlEvent procedure(SenderTObject;out ControlTStyledControlof object;

type TInPlaceEditListBox = class(TListBox)
  private
    
EditItemTEditListBoxItem;
    
EditedItemTListBoxItem;
    
EditUpdateInteger;
    
FOnCreateEditControlTCreateControlEvent;
  protected
    
procedure KeyDown(var KeyWord; var KeyCharSystem.WideCharShiftTShiftState); override;
    
procedure EVEditKeyDown(SenderTObject; var KeyWord; var KeyCharWideCharShiftTShiftState);
    
procedure SetItemIndex(const ValueInteger);override;
    
procedure InPlaceEdit;
    
procedure EndInPlaceEdit(SaveBoolean);
  public
    
destructor Destroy;override;
    function 
CreateEditControlTStyledControl;virtual;
    
property OnCreateEditControlTCreateControlEvent read FOnCreateEditControl write FOnCreateEditControl;
  
end;

procedure Register;

implementation
uses System
.UITypesSysutils;

procedure Register;
begin
  RegisterComponents
('SolentFMX'[TInPlaceEditListBox]);
end;

{ TEditListBoxItem }

constructor TEditListBoxItem
.Create(AOwnerTComponent);
begin
  inherited
;
  
CanClip := False;
end;

destructor TEditListBoxItem.Destroy;
begin
  FreeAndNil
(FEditControl);
  
inherited;
end;

procedure TEditListBoxItem.EVKeyDown(SenderTObject; var KeyWord;
  var 
KeyCharWideCharShiftTShiftState);
begin
  
if Assigned(OnKeyDownthen
    OnKeyDown
(SelfKeyKeyCharShift);
end;

function 
TEditListBoxItem.GetDataVariant;
begin
  
if EditControl <> nil then
    Result 
:= EditControl.Data
  
else
    
Result := varNull;
end;

function 
TEditListBoxItem.GetTextString;
begin
  Result 
:= GetData;
end;

procedure TEditListBoxItem.SetData(const ValueVariant);
begin
  inherited
;
  if 
EditControl <> nil then
    EditControl
.Data := Value;
end;

procedure TEditListBoxItem.SetEditControl(const ValueTStyledControl);
var 
DataVariant;
begin
  
if EditControl <> nil then
    Data 
:= GetData
  
else
    
Data := varNull;
  
FreeAndNil(FEditControl);
  
FEditControl := Value;
  
FEditControl.Align := TAlignLayout.alClient;
//  FEditControl.Width := 200;
  
FEditControl.Data := Data;
  
FEditControl.Parent := Self;
  
FEditControl.OnKeyDown := EVKeyDown;
end;

procedure TEditListBoxItem.SetFocus;
begin
  inherited
;
  if 
FEditControl <> nil then
    FEditControl
.SetFocus;
end;

procedure TEditListBoxItem.SetText(const ValueString);
begin
  inherited
;
  if 
EditControl <> nil then
    EditControl
.Data := Value;
end;

{ TInPlaceEditListBox }

function TInPlaceEditListBox.CreateEditControlTStyledControl;
begin
  Result 
:= nil;
  if 
Assigned(OnCreateEditControlthen
    OnCreateEditControl
(SelfResult)
  else
    
Result := TEdit.Create(Self);
end;

destructor TInPlaceEditListBox.Destroy;
begin
  FreeAndNil
(EditItem);
  
inherited;
end;

type THackListBoxItem = class(TListBoxItem);

procedure TInPlaceEditListBox.EndInPlaceEdit(SaveBoolean);
begin
  
if (EditItem nil) or (EditedItem nilthen
    
EXIT;

  try
    
Inc(EditUpdate);
    
BeginUpdate;
    if 
Save then
      THackListBoxItem
(EditedItem).SetData((EditItem).GetData);
    
AddObject(EditedItem);
    
Exchange(EditItemEditedItem);
    
EditedItem.IsSelected := True;
    
FreeAndNil(EditItem);
    
SetFocus;
    
EditedItem.Opacity := 0;
    
EndUpdate;
    
EditedItem.AnimateFloat('Opacity'10.2);
    
EditedItem := nil;
  
finally
    dec
(EditUpdate);
  
end;
end;

procedure TInPlaceEditListBox.EVEditKeyDown(SenderTObject; var KeyWord;
  var 
KeyCharWideCharShiftTShiftState);
begin
  
if EditItem nil then
    
EXIT;

  if 
Key vkReturn then
  begin
    EndInPlaceEdit
(True);
    
Key := 0;
  
end
  
else if Key vkEscape then
  begin
    EndInPlaceEdit
(False);
  
end
  
else if Key vkUp then
    
if ItemIndex 0 then
    begin
      KeyDown
(KeyKeyCharShift);
      
InPlaceEdit;
    
end
    
else
  else if 
Key vkDown then
    
if ItemIndex Count-1 then
    begin
      KeyDown
(KeyKeyCharShift);
      
InPlaceEdit;
    
end;
end;

procedure TInPlaceEditListBox.InPlaceEdit;
var
  
OldYSingle;
  
ControlTStyledControl;
begin
  
if (ItemIndex 0then
    
EXIT;

  
EndInPlaceEdit(True);

  
OldY := VScrollBar.Value;
  try
    
Inc(EditUpdate);
    
FreeAndNil(EditItem);
    
EditItem := TEditListBoxItem.Create(Self);
    
EditItem.EditControl := CreateEditControl;
    
EditItem.OnKeyDown := EVEditKeyDown;

    
BeginUpdate;
    
AddObject(EditItem);
    
EditedItem := ListItems[ItemIndex];
    
Exchange(EditedItemEditItem);
    
EditedItem.Parent := nil;
    
EditItem.SetData((THackListBoxItem(EditedItem)).GetData);
    
EditItem.SetFocus;
    
EditItem.IsSelected := True;
    
VScrollBar.Value := OldY;
    
EditItem.Opacity := 0;
    
EndUpdate;
    
EditItem.AnimateFloat('Opacity'10.2);
  
finally
    dec
(EditUpdate);
  
end;
end;

procedure TInPlaceEditListBox.KeyDown(var KeyWord;
  var 
KeyCharSystem.WideCharShiftTShiftState);
begin
  
if Key vkF2 then
    InPlaceEdit
  
else
    
inherited;
end;

procedure TInPlaceEditListBox.SetItemIndex(const ValueInteger);
begin
  
if EditUpdate 0 then
    EndInPlaceEdit
(True);
  
inherited;
end;

initialization
  RegisterFMXClasses
([TInPlaceEditListBoxTEditListBoxItem]);
end

MonkeyStyler build 2 beta

MonkeyStyler build 2 beta is now available. If you’re on the beta programme, use the link you already have to download.

Changes list

Added: Tooltips for toolbar buttons.
Fix: Error message popups now size properly on first showing.
Fix: Warnings for duplicate element names are no longer case sensitive.
Improved: validation of element names when adding, renaming or copying elements.
Added: Pasting a component switches the property editor to the pasted component.
Fix: Stepping of values now works for TAngleEditor (ie values in steps of 3 etc.)
Added: Copy To dialog remembers it’s settings between shows (not between sessions).
Added: Property grid scrolls up if necessary when expanding items.

Call for Beta Testers

MonkeyStyler is almost ready ... or at least almost ready for it’s debut. There’s still to do: fleshing out some areas of the product (i.e. property editors); one or two features still to be added; A few minor touches which really need to be added; And a whole load of wonderful time saving features to be added after public release.

But MonkeyStyler is feature complete enough to have a beta release. I’m now working on the installer and those other little bits needed by a public product.

If you want to be among the first to try MonkeyStyler out you need to act now. I need a small number of volunteers for the beta test. If you’re interested, drop me an email to monkey@solentsoftware.com. Remember places are limited.

Enjoy.

Mike

Triggering Effects and Animations in FireMonkey Components

If you’ve used FireMonkey styles, you’ve probably got used to using triggers to initiate animations and effects. I.e. setting a TColorAnamation when IsMouseOver = True and triggering a TGlowEffect when IsFocused = True. But if you’re creating your own components, how do you create triggers which you and others can use to style your component? That’s what we’re going to look at today.

Below is a form with two TEdit controls. I’ve coded them to show basic password validation. The first box shows a red background if the password is not secure enough (less that six characters here), the second shows a TInnerGlowEffect under the same conditions. Both boxes show clear when the password is adequate (see the second screenshot).

TValidateEdit

I started by subclassing TEdit as follows to create a generic edit box with validation. Validation is done by calling the OnValidate event:

type TValidateEvent = function(SenderTObject;const TextString): Boolean of object;

type TValidateEdit = class(TEdit)
  private
    
FIsInvalidBoolean;
    
FOnValidateTValidateEvent;
  protected
    
procedure ApplyStyle;override;
    
procedure KeyDown(var KeyWord; var KeyCharSystem.WideCharShiftTShiftState); override;
    
procedure DoIsValid;virtual;
  
published
    property IsInvalid
Boolean read FIsInvalid;
    
property OnValidateTValidateEvent read FOnValidate write FOnValidate;
  
end


The first thing to notice is our trigger property, IsInvalid. As with the triggers you’ve already seen it starts with ‘Is’. This is not a requirement, but it is a convention, and one you would do well to keep to, just like you start your types with a T. Following the convention means that you and others will instantly know which propetries can be used as triggers. This is important since controls with trigger properties have special code to enable the property to be used as a trigger. Other than the naming convention there is nothing special about the declaration of trigger properties.

Now, lets take a run through the code and see how things work. First up is our overridden KeyDown method.

procedure TValidateEdit.KeyDown(var KeyWord; var KeyCharSystem.WideChar;
  
ShiftTShiftState);
begin
  inherited
;
  
DoIsValid;
end

All we do here is call DoIsValid to check whether the new content is valid.

procedure TValidateEdit.ApplyStyle;
begin
  inherited
;
  
DoIsValid;
end

We need to override ApplyStyle and call DoIsValid so that IsInvalid will be set properly at startup and if the style is ever reloaded. In our case this means that when the password editor is created, and therefore empty, it will show as invalid.

procedure TValidateEdit.DoIsValid;
var 
ValueBoolean;
begin
  
if Assigned(OnValidatethen
  begin
    Value 
:= not OnValidate(SelfText);
    
FIsInvalid := Value;
    
StartTriggerAnimation(Self'IsInvalid');
    
ApplyTriggerEffect(Self'IsInvalid');
  
end;
end

And finally on to the meat of our code, DoIsValid. First we call the onIsValidate event handler and set FIsInvalid. All bog standard stuff.

Following that are the two lines which do the work:

StartTriggerAnimation(Self'IsInvalid');
    
ApplyTriggerEffect(Self'IsInvalid'); 


These are two standard methods of TFMXObject (a parent of all FireMonkey objects). StartTriggerAnimation starts any appropriate animations. ApplyTriggerEffect shows or hides any appropriate effects.

Both methods look through the child objects for effects and animations to trigger. These can be animations and effects in the control’s style, or those added directly to the control either at deisgn time or run time.

The first parameter is AInstance (of type TFMXObject). This is the object which contains the trigger property. Here we’re passing Self, but you could just as easily pass in another control with a trigger property. For example you could change a property of another control, and then trigger an animation in your own style based on that controls state.

Finally we have the trigger property itself. This takes the name of a property as a string. The property must be a boolean. Refer to the discussion above about naming conventions, but also keep in mind the previous paragraph: you could start an animation based on any boolean property on any object. But if you do this, note that the animation will not get updated when that property is changed unless you explicitly do it yourself. Caveat emptor.

Styling

Here is the style using animations, a straight copy of the EditStyle to which I added two animations, one to initiate the animation, the second to clear it:

And the properties for the first animation:

Here we have the StartValue and StopValue and the Trigger (IsInvalid=True). The second animation is simply the reverse. Note however that we also have StartFromCurrent=True. If this is not set then each time we call the StartTriggerAnimation function the animation will change to the StartValue and animate to the StopValue. In our case that means that each time we type a character the background would turn white, then fade to red. Not what we want. Starting from the current value stops this (It starts at red and stays there).

Prior to XE2 Update 4 I noticed a bug with this behaviour. Under some circumstances the animation would switch immediately to the StopValue, rather than animating. To get around this I changed DoIsValid so that the animations would only run if the trigger property had actually changed:

procedure TValidateEdit.DoIsValid;
var 
ValueBoolean;
begin
  
if Assigned(OnValidatethen
  begin
    Value 
:= not OnValidate(SelfText);
    if 
Value <> FIsInvalid then
    begin
      FIsInvalid 
:= Value;
      
StartTriggerAnimation(Self'IsInvalid');
      
ApplyTriggerEffect(Self'IsInvalid');
    
end;
  
end;
end

Now that this is fixed with Update 4, you have a choice of using either technique.

Styling for effects

Here is the style for the version which uses an effect, with the newly added TInnerGlowEffect highlighted:

The only thing to note here is that the effect must be added as a child of the object in which we want the effect to appear, the background rectangle here. I first created this code under XE2 Update 3 and added the effect as a child of the main TLayout and it worked fine. This no longer applied under Update 4: hence it’s current placement.

Round up

And that’s all there is to it. Just remember that you can be incredibly creative with FireMonkey styles. Instead of changing the background of the TEdit I could have added an image and had it change from a cross to a tick. I could have added some text (‘Password too short’) either below or beside the edit box and changed it’s opacity. The beauty with FireMonkey is that once I’ve added the trigger property you (or your designer) are free to be really creative with how that trigger affects the styling.

Download sources

Full source of ValidateEdit unit:

unit uValidateEdit;

interface
uses FMX.EditSystem.Classes;

type TValidateEvent = function(SenderTObject;const TextString): Boolean of object;

type TValidateEdit = class(TEdit)
  private
    
FIsInvalidBoolean;
    
FOnValidateTValidateEvent;
  protected
    
procedure ApplyStyle;override;
    
procedure KeyDown(var KeyWord; var KeyCharSystem.WideCharShiftTShiftState); override;
    
procedure DoIsValid;virtual;
  
published
    property IsInvalid
Boolean read FIsInvalid;
    
property OnValidateTValidateEvent read FOnValidate write FOnValidate;
  
end;

implementation
uses System
.UITypes;

{ TValidateEdit }

procedure TValidateEdit
.ApplyStyle;
begin
  inherited
;
  
DoIsValid;
end;

procedure TValidateEdit.DoIsValid;
var 
ValueBoolean;
begin
  
if Assigned(OnValidatethen
  begin
    Value 
:= not OnValidate(SelfText);
//    if Value <> FIsInvalid then
    
begin
      FIsInvalid 
:= Value;
      
StartTriggerAnimation(Self'IsInvalid');
      
ApplyTriggerEffect(Self'IsInvalid');
    
end;
  
end;
end;

procedure TValidateEdit.KeyDown(var KeyWord; var KeyCharSystem.WideChar;
  
ShiftTShiftState);
begin
  inherited
;
  
DoIsValid;
end;

end

s opacity. The beauty with FireMonkey is that once I

Anatomy of a FireMonkey Style

FireMonkey styles have a similar relationship to controls as CSS styles have to tags in a HTML file. The control handles the functionality of the application. The style tells FireMonkey how the control should look. Styles not only specify colors, border styles and fonts, but they can specify everything about the appearance. For example a style could move the button of a TComboBox from right to left and make it’s text right-aligned.

Style elements are made up of components in the same way that your application is also made up of components. Indeed, the same components that are available in the component palette are also available in styles, although most of the components you will use are made up from the more ‘primitive’ components - shapes (TRectangle, TCircle, TPath) etc., animations and effects as well as TLayout and TText.

A typical style

Lets take a look at a typical FireMonkey style. The following is the component tree for a TButton in the windows 7 style:

buttonstyleTLayout
  background
TRectangle
    a TRectangle
    four TColorAnimations
    a TInnerGlowEffect
    another TRectangle
  text
TText
  a TGlowEffect 

(Note from the indentation above that certain components are children of other components.)

So, we start with a TLayout. This is a useful container component. It is similar to a TPanel, but has no ‘styling’ itself - ie. it has no way to specify it’s appearance (because it has no appearance).

The TLayout has three children, a TRectangle for the background, a TText for the text and a TGlowEffect to show selected state. Both of these are ‘styled’ components - ie that have an appearance which can be modified. A TRectangle, for instance, has stroke and fill ‘brushes’ for the outline and infill respectively, as well as properties for stroke thickness, corner type, which sides to show and much more besides.

The background rectangle contains another two rectangles, which add extra subtlely to the style, four animations and an effect.

Animations modify a property of their parent component. For example, when you hover your mouse over a button the background changes color due to an animation modifying the Fill.Color property. However, animations are not (necessarily) instant flips from one value to another. In the example just stated the fill color ‘animates’ gently from the original color to the target color over a fraction of a second.

In styles animations are usually activated by a boolean Trigger property, which is linked to the name of property on the parent component. When the trigger property changes state, the animation fires. There are a number of properties which can be used to trigger an animation including mouse overs and clicks.

Different animation components modify different types of property. A TFloatAnimation modifies a numeric property, a TColorAnimation modifies a color property, and so on.

Effects are similar to animations, in that the are tied to a trigger property and modify the appearance of the control when the trigger property is True. Effects can do things like display a glowing border (TGlowEffect), a drop shadow (TGlowEffect) or blur a control (TBlurEffect).

Styles and Components

So, above we have the component tree for a TButton in the Windows 7 style, but the tree is not fixed across styles: we could create a style with components added or removed, with components rearranged, even with components of different types. It is entirely up to the style designer to decide how a style element is made up.

However, there do need to be links between the developers code and the designers style. For example, when the developer sets the text of a TButton, he searches the buttonstyle for a component called ‘text’, expects that it is of type TText and sets it’s Text property. So, in this case the style must have a TText component called ‘text’ somewhere within it in order to provide the full functionality of the control. When designing styles (and the code to go with it) it is important that the designer and developer communicate and document any such links.

Other components

A style may also contain any component available on the Delphi/C++Builder component palette. For example, a TScrollBox contains two TScrollBar components, for the vertical and horizontal scroll bars. In such a case the component in the style file can be used to specify things such as the width and height of the component.

However, the styling for these control will be picked up from the usual style elements for that class of component (ie. ‘scrollbarstyle’ for a TScrollBar). You can, however, override the components default styling by setting it’s StyleLookup property and creating the appropriate style element.

FireMonkey Grids: Basics, Custom Cells and Columns

MonkeyStyler uses a couple of heavily customised grid columns. I spent some of last week finishing off the styling for them. The whole process has taught me a lot about FireMonkey grids. Prompted by this question on StackOverflow I though now would be a good time to share some of what I have learnt.

So, in this post I’m going to cover the following:

  • How FireMonkey grids work;
  • How to create a custom cell class;
  • How to create a custom column class;

Our StackOverflow poster wanted to know how to set the alignment and color of a grid cell, so I’ll concentrate on those issues in this post. We’ll create an app which has a grid showing two columns. The first will display the row index, the second financial figures, which are right aligned and with a background which changes to red when the figure is negative. I’ll cover most of that today with the styling issues in a future post.

FireMonkey Grids

Grids in FireMonkey are much more flexible than those in the VCL. But, of course with flexibility comes complexity. Fortunately, once you’ve learnt a few basics the rest comes fairly easy.

A FireMonkey TGrid is simply a container, adapted to contain children of type TColumn. A column is simply a container for a series of cells. We’ll get to the cells later.

To start with we’ll create an app which contains a TGrid. In the Delphi form designer, right click on the empty grid and select the Element Editor. Here, add a TColumn and back out. This will be a basic column in which we’ll display the row index.

On to the code, here’s the interface:

type
  TForm1 
= class(TForm)
    
Grid1TGrid;
    
Column1TColumn;
    
procedure FormCreate(SenderTObject);
    
procedure FormDestroy(SenderTObject);
  private
  protected
    
ValueColumnTColumn;
    
DataTList<Single>;
    
procedure PopulateData;
  public
  
end


Data is a list which we populate with random values in PopulateData.

FormCreate sets up our Data values, and also creates and adds another TColumn to the grid. We’ll create this in code so it’s easier to play around with. Note that, as always in FireMonkey, we simply assign it’s Parent property to the grid to assign it to the appropriate container.

procedure TForm1.FormCreate(SenderTObject);
begin
  Data 
:= TList<Single>.Create;

  
PopulateData;
  
Grid1.RowCount := RowCount;

  
ValueColumn := TColumn.Create(Grid1);
  
ValueColumn.Parent := Grid1;
end

Go back to the form editor and create a method for the grids OnGetValue event:

procedure TForm1.Grid1GetValue(SenderTObject; const ColRowInteger;
  var 
ValueVariant);
begin
  
if Col 0 then
    Value 
:= Row
  
else if Col 1 then
    Value 
:= Data[Row];
end

What happens here? The TColumn has a number of cells to display data but it only creates as many cells as it has visible rows. I.e. if a grid has a RowCount of 100, but only 20 cells are visible then only 20 cells are created. Whenever you scroll the grid each cell gets recycled. Because of this a grid cell cannot store any data between refreshes. (Or, more accurately, it should not store data because if it does it will be displaying the wrong data).

So, every time a cell is displayed the grid calls the OnGetValue event for that cell. OnGetValue passes the column and row indexes for the cell (the virtual column and row indexes) and our event handler needs to return the value to display in the Value variant parameter.

Run the above and you’ll see something like:

(Aside: the grid appears to have a few display issues if you don’t show headers, hence why I’ve kept the headers here).

Custom Columns

Ignoring the rounding issues (we’re using Singles for simplicity here), you can see that the column of supposedly financial figures really needs to be right aligned (we’ll come to rounding and formating later).

We’re using a TColumn for the figures, which is a container for TTextCell. The definition for TTextCell is:

TTextCell = class(TEdit)
  
end


So, it’s just an edit control with the parent set to the column. Haha. Easy. To get our control right aligned we just need to set the TEdit’s TextAlign property, which we can assign when the cell is created.

Each cell is created in the columns CreateCellControl virtual method. Look for the method in TColumn and we see:

function TColumn.CreateCellControlTStyledControl;
begin
  Result 
:= TTextCell.Create(Self);
  
TTextCell(Result).OnTyping := DoTextChanged;
  
TTextCell(Result).OnExit := DoTextExit;
end

So, we’ll create our own custom column and override the CreateCellControl to do our work for us:

type TFinancialColumn = class(TColumn)
  protected
    function 
CreateCellControlTStyledControl;override;
  
end;
    
    ...
    
function 
TFinancialColumn.CreateCellControlTStyledControl;
begin
  Result 
:= inherited;
  
TEdit(Result).TextAlign := TTextAlign.taTrailing;
end

Update the FormCreate to create TFinancialColumn and we see:

Custom Cells

But we’ve now taken things as far as they can go with the built in TTextCell. It’s time to create our own cell class so we can really get things looking how we want.

Look again at the definition of TColumn.CreateCellControl. Note that it returns an object descending from TStyledControl. A TStyledControl is the parent of any control which can have styling applied. In other words, any visual control in FireMonkey. FireMonkey already does that with TCheckCell, TProgressCell and TImageCell for check boxes, progress bars and images.

And you can extend this to create custom cells using any control you like. You could go really freaky and use a list box or tree view within a cell. You probably wouldn’t want to, but FireMonkey is flexible enough to do it if you want. And all FireMonkey controls can own - be containers for - other controls. So you can create a cell which is made up of multiple controls.

Take a look at the property editor grid for MonkeyStyler in the screenshot below from the the preview images blog post and you’ll see that the values column contains:

  • A TColorBox for color previews (the Fill.Color property);
  • A TEdit (editable properties);
  • A TCheckBox (boolean properties);
  • A TButton (for the animation menu button and image)

with code to set each item’s Visible property depending on the data type.

TFinancialCell

But, enough showing off, lets get back to our financial column. The TTextCell is just a TEdit. Not much customisation we can do there. What we’ll do is create our cell as a TStyledControl which will contain an alClient aligned TEdit.

type TFinancialCell = class(TStyledControl)
  protected
    
FEditTEdit;
    
procedure SetData(const ValueVariant); override;
  public
    
constructor Create(AOwnerTComponent); override;
  
end;

...

constructor TFinancialCell.Create(AOwnerTComponent);
begin
  inherited
;
  
FEdit := TEdit.Create(Self);
  
FEdit.Parent := Self;
  
FEdit.Align := TAlignLayout.alClient;
  
FEdit.TextAlign := TTextAlign.taTrailing;
end

Now, look at the SetData method, which is the Setter for the Data property. Data is defined in TFMXObject, the parent of all FireMonkey objects. Earlier we saw how the grid fetches data for each cell by called the OnGetValue event, well after it’s fetched the data it passes it on to the cell objects Data property. So, we override the SetData method to get the data we need to display.

procedure TFinancialCell.SetData(const ValueVariant);
var 
FSingle;
begin
  inherited
;
  
:= Value;
  
FEdit.Data := Format('%m'[F]);
end

Before we can run things we need to update the columns CreateCellControl to reflect our new cell class:

function TFinancialColumn.CreateCellControlTStyledControl;
begin
  Result 
:= TFinancialCell.Create(Self);
  
TTextCell(Result).OnTyping := DoTextChanged;
  
TTextCell(Result).OnExit := DoTextExit;
end

Now things are looking much better:

Round up

So, we have a grid column which is formatting the data how we want. This article is already long enough, so I won’t bore you any longer, other than to say that I will return at some future point to show you how you can use styles to format the grid cells we created today.

Enjoy.

GridBasics.zip - Download the project sources.

Full source:

unit Main;

interface

uses
  System
.SysUtilsSystem.TypesSystem.UITypesSystem.ClassesSystem.Variants,
  
FMX.TypesFMX.ControlsFMX.FormsFMX.DialogsGenerics.Collections,
  
FMX.GridFMX.LayoutsFMX.EditFMX.ListBox;

type TFinancialCell = class(TStyledControl)
  protected
    
FEditTEdit;
    
procedure SetData(const ValueVariant); override;
  public
    
constructor Create(AOwnerTComponent); override;
  
end;

type TFinancialColumn = class(TColumn)
  protected
    function 
CreateCellControlTStyledControl;override;
  
end;

type
  TForm1 
= class(TForm)
    
Grid1TGrid;
    
Column1TColumn;
    
procedure FormCreate(SenderTObject);
    
procedure FormDestroy(SenderTObject);
    
procedure Grid1GetValue(SenderTObject; const ColRowInteger;
      var 
ValueVariant);
  private
  protected
    
ValueColumnTFinancialColumn;
    
DataTList<Single>;
    
procedure PopulateData;
  public
  
end;

var
  
Form1TForm1;

implementation

{$R 
*.fmx}

const RowCount 20;
{ TForm1 }

procedure TForm1
.FormCreate(SenderTObject);
begin
  Data 
:= TList<Single>.Create;

  
PopulateData;
  
Grid1.RowCount := RowCount;

  
ValueColumn := TFinancialColumn.Create(Grid1);
  
ValueColumn.Parent := Grid1;
end;

procedure TForm1.FormDestroy(SenderTObject);
begin
  Data
.Free;
end;

procedure TForm1.Grid1GetValue(SenderTObject; const ColRowInteger;
  var 
ValueVariant);
begin
  
if Col 0 then
    Value 
:= Row
  
else if Col 1 then
    Value 
:= Data[Row];
end;

procedure TForm1.PopulateData;
var 
IInteger;
begin
  
for := 1 to RowCount do
    
Data.Add((Random(10000)-1000)/100);
end;

{ TFinancialColumn }

function TFinancialColumn.CreateCellControlTStyledControl;
begin
  Result 
:= TFinancialCell.Create(Self);
  
TTextCell(Result).OnTyping := DoTextChanged;
  
TTextCell(Result).OnExit := DoTextExit;
end;

{ TFinancialCell }

constructor TFinancialCell
.Create(AOwnerTComponent);
begin
  inherited
;
  
FEdit := TEdit.Create(Self);
  
FEdit.Parent := Self;
  
FEdit.Align := TAlignLayout.alClient;
  
FEdit.TextAlign := TTextAlign.taTrailing;
end;

procedure TFinancialCell.SetData(const ValueVariant);
var 
FSingle;
begin
  inherited
;
  
:= Value;
  
FEdit.Data := Format('%m'[F]);
end;

end

TBitmapSpeedButton: Loading Images from the Style

Recently recently blogged about creating a TBitmapSpeedButton - a button which could show a bitmap image. When I came to use it I realised an ideological flaw. I was using the old VCL style model of loading a bitmap at design time to use in the application.

That works fine for VCL, but in FireMonkey it’s good practice to offload the visuals to the style. What would be ideal is if, in the form designer, I can specify a style resource for the image to be used. Now I, or my visual designer, can choose an image to use without needing access to my source code. If the look of the software needs updating I can just update the style file with new images and the app will look different without having to edit the source code (or at least the FMX file, which as far as I’m concerned is the same thing.

So, I’ve updated my component with two new properties:

property ImageTypeTImageType read FImageType write SetImageType;
    
property ImageStyleLookupString read FImageStyleLookup write SetImageStyleLookup

TImageType is either itBitmap or itStyleLookup and tells the component where to get the bitmap data from.

The only interesting bit of new code is the new UpdateImage method:

procedure TBitmapSpeedButton.UpdateImage;
var 
ObjTFMXObject;
begin
  
if FImageType itBitmap then
    
if FImage <> nil then
      FImage
.Bitmap.Assign(FBitmap)
    else
  else 
//itResource
  
begin
    Obj 
:= nil;
    if (
FScene <> nil) and (FScene.GetStyleBook <> nil) and (FScene.GetStyleBook.Root <> nilthen
      Obj 
:= TControl(FScene.GetStyleBook.Root.FindStyleResource(FImageStyleLookup));
    if 
Obj nil then
      
if Application.DefaultStyles <> nil then
        Obj 
:= TControl(Application.DefaultStyles.FindStyleResource(FImageStyleLookup));
    if (
Obj <> nil) and (Obj is TImage) and (FImage <> nilthen
      FImage
.Bitmap.Assign(TImage(Obj).Bitmap);
  
end;
end

which shows how to find a style resource either from the current stylebook, or if that isn’t found, from the applications default style.

Download updated sources

 

RSS feed