TMS FNC Ribbon : modern ribbon UI on every operating system and for every Pascal framework

Bookmarks: 

Monday, September 04, 2017

With the FNC product line (framework-neutral-components), it is our vision to enable developers with a single UI controls set, a single learning-curve and a single license to have the freedom of choice to develop Delphi VCL Windows applications, Delphi FMX cross-platform applications for Windows, macOS, Android, iOS or even LCL based Lazarus applications for Windows, macOS or Linux.

Since our study & research to realize this FNC layer, we have already created a powerful grid, a flexible planning/scheduling/calendar control, a feature-rich treeview, a rich editor, a toolbar and many more smaller UI controls. The next logical step was to create a ribbon UI control to enable building modern user interfaces for your VCL, FireMonkey Delphi applications of Windows, macOS or Linux applications created with Lazarus/FPC. Our ribbon UI control takes the hard work out of your hands to offer the subtle differences a Microsoft Office 2016 style colourful ribbon UI comprises on these different operating systems.

To get started, we have integrated ribbon application and ribbon form repository items in the Delphi "new item" wizard. You can select from there to create a new VCL or FMX ribbon project or to add a new VCL or FMX ribbon form to your existing project.



It is of course also possible to add a new ribbon UI to an existing form. To do so, drop the TTMSFNCRibbon control on the form and do not forget to descend your form from TTMSFNCRibbonForm instead of a TForm.

The ribbon architecture
Let's have a look at the TTMSFNCRibbon control itself. It consists of several parts, the main parts being:



TMSFNCRibbonWrapper : This is the container component for the ribbon form caption that contains the QAT, caption text, system menu
TMSFNCRibbonQAT : This is the quick access toolbar that can sit in the window caption or below the ribbon. The position can be set via the property TTMSFNCRibbon.QATMode.
TMSFNCRibbonCaption : This represents the caption text of the window itself
TMSFNCRibbonSystemMenu : This is the application system menu typically used to close, minimize or maximize the form
TTMSFNCRibbonFileButton : This is the application menu button
TMSFNCRibbonPageControl : This is the page control that is used to paginate between different ribbon pages
TTMSFNCRibbonPageControlContainer : This is a single ribbon page that is a container for toolbars on the ribbon

To add a toolbar and toolbar controls to the ribbon, right-click the TTMSFNCRibbonPageControlContainer and from the context menu select to add a toolbar.
Next, right-click the toolbar and from the context menu you can choose to add several toolbar controls.


The controls that can be added to the ribbon toolbar are not limited to this set of controls and as such other UI controls can be added as well to the toolbar. More later about the dynamic sizing configurability of the toolbar controls and the toolbar compact mode.

Matching the Microsoft Office 2016 theme, the TTMSFNCRibbon has a property Theme from where a number of predefined colors can be selected (like the MS Word, MS Excel, MS PowerPoint ribbon colors) but this property can also be set to rbtCustom and then a custom application color can be selected with TTMSFNCRibbon.CustomThemeColor. The TTMSFNCRibbon control will automatically calculate lighter & darker color variants to make up such custom color theme. The color & appearance of each individual element on the ribbon can be customized, but the easiest way to select a consistent looking color is clearly with the TTMSFNCRibbon.Theme and TTMSFNCRibbon.CustomThemeColor setting.

The ribbon toolbar
The place where buttons for interaction with your application are placed is the ribbon toolbar and typically, controls are grouped on toolbars that belong together. By default, the size of the toolbar will automatically adapt to the number & size of controls added to the toolbar. The default size is TMSFNCRibbonToolBar.AutoSize = true, TMSFNCRibbonToolBar.AutoWidth = true, TMSFNCRibbonToolBar.AutoAlign = true. This means that when adding controls to the toolbar, these will be added starting left aligned and the size of the toolbar will grow as controls are added. The toolbar can have a dynamic sizing behavior. That means that when the application window width will become smaller or larger, the toolbar can dynamically size to fit all toolbars in the width of the ribbon. The smallest mode for the toolbar is the compact state. In this state, the toolbar is only a button and the toolbar buttons will only become visible when the toolbar compact state button is clicked. In compact state, the toolbar can display a picture on the button and this is selected via TMSFNCRibbonToolBar.CompactBitmaps: TTMSFNCScaledBitmaps. This is a collection of bitmaps that can be used for different DPI sizes. The control will decide itself what bitmap to use from the collection depending on the DPI of the screen the application is running on. Further customization of the compact state is done via TTMSFNCRibbonToolBar.CompactAppearance, TTMSFNCRibbonToolBar.CompactWidth, TTMSFNCRibbonToolBar.CompactBitmapVisible. When the toolbar is not in compact state, its controls are visible but these can be visible in different sizes. The sizes a ribbon toolbar button can have is set with TMSFNCRibbonDefaultToolBarButton.MinimumLayout, TMSFNCRibbonDefaultToolBarButton.MaximumLayout. By default, the minimum size is bblBitmap, the maximum size is bblLarge and the size in between is bblLabel. When the application is maximized for example and thus the toolbar has sufficient space, all buttons on the toolbar can be shown in bblLarge state. When the application width shrinks, the controls on the toolbar can first reduce to bblLabel state where the controls become a label with attached glyph. When the form width further shrinks, the next step is when the toolbar controls are rendered in bblBitmap state, essentially, only showing the button glyph. Of course, if for a button the MinimumLayout and MaximumLayout are both set to bblLarge, the toolbar control size will never change during application for width changes. Only when the toolbar width cannot longer fit on the ribbon, the entire toolbar will go to compact state.

Visualizing this is probably the best way to make this more clear.
In this first step, notice the Insert toolbar that has sufficient space for hosting two large state buttons:


As the form width decreases, the Insert toolbar shrinks by putting its controls in label layout:


Making the form even smaller now makes the toolbar shrink its controls to bitmap layout:


The final and smallest state of the toolbar is the compact state, where all its controls are hidden and the toolbar controls only become visible by clicking the compact state toolbar button to show the full toolbar in a popup:


The ribbon page groups
Another often used ribbon UI feature is the ribbon page groups. Sometimes functionality in the application has so much controls to interact with the features of the functionality that it is too much to have one ribbon page for it and that it is better to divide it in two or more pages. To make the ribbon pages look consistently together, the concept of page groups is used. This is a group indicator above the ribbon page tabs. Adding a ribbon page group can be easily done via the collection TTMSFNCRibbon.Groups. Add a new TMSFNCRibbonGroup item to this collection and here it can be configured what the index is of the first ribbon page in the group (TMSFNCRibbonGroup.StartPageIndex) and the last page (TTMSFNCRibbonGroup.EndPageIndex). The group can be given a group name set via TTMSFNCRibbonGroup.Text and with the group the selected ribbon page tab can have its own color set via TTMSFNCRibbonGroup.Color & TTMSFNCRibbonGroup.TextColor. The page group itself is a darker variant from the ribbon theme color. In this example, a ribbon page group was created for the Insert and Export page. The page group name is Tools and was created by setting TMSFNCRibbonGroup.StartPageIndex to 1 and TTMSFNCRibbonGroup.EndPageIndex to 2.
g := rb.Groups.Add;
g.Text := 'Tools';
g.StartPageIndex := 1;
g.EndPageIndex := 2;



The ribbon QAT
Frequently used functions, like a save, undo, ... function can be added to the always visible QAT (quick access toolbar). This QAT sits normally on the form caption or right below the ribbon. By default, on a new TMSFNCRibbon, the QAT is available on the caption. To add controls to it, also right-click the control at design-time and from the context menu select the controls to add. The QAT has by default an automatically managed option menu (at the right-side of the QAT). From this options menu, controls on the QAT can be hidden or made visible and the position of the QAT can be selected. The option menu can be further customized by implementing any of its menu event handlers like OnOptionsMenuCustomize, OnOptionsMenuItemCanShow, OnOptionsMenuMoreCommands, ...



Learn more
Several resources are available for you to learn more about our FNC abstraction layer and controls:
Blog post about FNC UI pack
Blog post about developing FNC custom controls
FNC controls video series

Conclusion
Our TMS FNC ribbon control has everything on board to allow you to add a ribbon UI to your applications, be it Delphi VCL Windows applications, cross platform FireMonkey applications or applications created with Lazarus for Windows, macOS or Linux. It is easy & fast to configure but at the same time can be extensively and in detail customized. Together with our FNC grid control, you can build Excel like user interfaces in a matter of hours, or in combination with our FNC rich editor a word processor like application, etc... Once you learned to use the TMS FNC Ribbon control, you can apply this knowledge to your next project developed against another UI control framework or you could reuse code from one application in a given framework for another application using another framework. We look forward to see awesome applications you create and hear about further needs you might have to facilitate your development and make it even faster.

Bruno Fierens


Bookmarks: 

This blog post has received 4 comments. Add a comment.



TMS FNC Core

Bookmarks: 

Tuesday, January 31, 2017

With the 1.7.1.0 release of the TMS FNC UI Pack we have introduced a TMS FNC Core separation. This means the TMS FNC Core needs to be installed as a prerequisite in order to successfully install the TMS FNC UI Pack. Apart from this separation, the new core setup will not introduce breaking changes in your application, as the file names for both the TMS FNC Core and TMS FNC UI Pack have remained the same. The separation gives us the benefit of writing components that all rely on a single core, instead of duplicating units that offer exactly the same features in multiple component sets. All current and future TMS FNC products will build upon this common core.

Custom Component Development for FNC

Now the TMS FNC Core is released, you'll have a series of units available that can be used to write custom components yourself for our FNC framework.

[FMX.][VCL.][LCL]TMSFNCBitmapContainer.pas
[FMX.][VCL.][LCL]TMSFNCCustomComponent.pas
[FMX.][VCL.][LCL]TMSFNCCustomControl.pas
[FMX.][VCL.][LCL]TMSFNCCustomScrollControl.pas
[FMX.][VCL.][LCL]TMSFNCGraphics.pas
[FMX.][VCL.][LCL]TMSFNCGraphicsTypes.pas
[FMX.][VCL.][LCL]TMSFNCHTMLEngine.pas
[FMX.][VCL.][LCL]TMSFNCStyles.pas
[FMX.][VCL.][LCL]TMSFNCTypes.pas
[FMX.][VCL.][LCL]TMSFNCURLBitmapContainer.pas
[FMX.][VCL.][LCL]TMSFNCUtils.pas

Note that with this set of units, you are able to write a custom component from scratch. A tutorial on writing a custom component can be found in this blog post: http://www.tmssoftware.com/site/blog.asp?post=346

Pieter Scheldeman


Bookmarks: 

This blog post has not received any comments yet. Add a comment.



Generating PDF files cross-platform with ease

Bookmarks: 

Thursday, December 22, 2016

With the new 1.7 release of the TMS FNC UI Pack we've added a completely new PDF library built from the ground up, that is capable of generating PDF files on all supported frameworks (FMX, VCL, LCL). Via all supported frameworks, you can easily target minimum 5 different operating systems: Windows, macOS, iOS, Android, Linux (&Raspbian),.. To introduce this new PDF library I've written a small tutorial to start generating your own PDF files.

Getting Started

To get started with the PDF library, add the FMX.TMSFNCPDFLib, VCL.TMSFNCPDFLib or LCLTMSFNCPDFLib depending on the chosen framework. The PDF library class is called TTMSFNCPDFLib, and the code is shareable between the three supported frameworks.

Starting a new document

Starting a new document can be file-based, or TMemoryStream-based. To start a new document, call the BeginDocument function. The BeginDocument always needs to be paired with EndDocument, which is responsible for writing the contents to a file or TMemoryStream. When the AFileName parameter in the BeginDocument call is empty, the contents will be written to a TMemoryStream, returned by the EndDocument call. The EndDocument call also has an additional parameter to allow opening the generated PDF file in the default PDF reader application.

procedure TForm1.GeneratePDF(AFileName: string);
var
  p: TTMSFNCPDFLib;
begin
  p := TTMSFNCPDFLib.Create;
  try
    p.BeginDocument(AFileName);
    p.EndDocument;
  finally
    p.Free;
  end;
end;

Adding pages

Adding pages can be done by calling the NewPage function. The NewPage is responsible for starting a new page content stream on which the graphics / text can be written. Each NewPage call will clear the content buffer and allow you to start with new text and graphics. Please note though that all appearance settings such as fill, stroke and font are stored for the entire document, so starting a new page will allow you to continue in the same appearance settings as the previous page.

procedure TForm1.GeneratePDF(AFileName: string);
var
  p: TTMSFNCPDFLib;
begin
  p := TTMSFNCPDFLib.Create;
  try
    p.BeginDocument(AFileName);
    p.NewPage;
    p.EndDocument;
  finally
    p.Free;
  end;
end;

Drawing content on a page

After adding a new page, the page can be filled with content such as HTML formatted text, plain text as well as some basic drawing primitives such as rectangles, circles and lines. To starting drawing content, the pdf library has a Graphics property that provides access to the drawing functionality. The following sample uses the Fill and Stroke properties to generate a PDF with a gradient rectangle and a dotted border.

procedure TForm1.GeneratePDF(AFileName: string);
var
  p: TTMSFNCPDFLib;
begin
  p := TTMSFNCPDFLib.Create;
  try
    p.BeginDocument(AFileName);
    p.NewPage;
    p.Graphics.Stroke.Color := gcRed;
    p.Graphics.Stroke.Width := 3;
    p.Graphics.Stroke.Kind := gskDashDotDot;
    p.Graphics.Fill.Kind := gfkGradient;
    p.Graphics.Fill.Color := gcBlue;
    p.Graphics.Fill.ColorTo := gcOrange;
    p.Graphics.DrawRectangle(RectF(10, 50, 100, 150));
    p.EndDocument(True);
  finally
    p.Free;
  end;
end;

Drawing Text

Drawing text on a PDF page is done via the DrawText function. The DrawText has a set of parameters to allow drawing wordwrapped text in a rectangle, or simply as-is at a specific position. The DrawText function has a set of overloads that also supports column drawing. Each call to DrawText returns a value that can either contain the calculated text rectangle or the amount of left-over characters after an overflow is detected when drawing text in a column. The font that is used when drawing text can be controlled separately via the Font property. With this property, the font name, size, color and style can be set.

procedure TForm1.GeneratePDF(AFileName: string);
var
    p: TTMSFNCPDFLib;
begin
    p := TTMSFNCPDFLib.Create;
  try
    p.BeginDocument(AFileName);
    p.NewPage;
    p.Graphics.Font.Name := 'Segoe UI';
    p.Graphics.Font.Size := 16;
    p.Graphics.Font.Color := gcRed;
    p.Graphics.Font.Style := [TFontStyle.fsBold];
    p.Graphics.DrawText('Hello World !', PointF(10, 50));
    p.EndDocument(True);
  finally
    p.Free;
  end;
end;

HTML formatted text

HTML formatted text is also supported by using the DrawHTMLText call. When passing a TMSFNCBitmapContainer reference it can even draw images referenced by the <IMG> tag. HTML support is based on the miniHTML reference.

procedure TForm1.GeneratePDF(AFileName: string);
var
  p: TTMSFNCPDFLib;
  s: string;
  r: TRectF;
begin
  p := TTMSFNCPDFLib.Create;
  try
    s := 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum     has been the industry''s standard dummy'+
'text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. '+
'It has survived not only five centuries, but also the leap into electronic typeset'+
'ting, 
remaining essentially unchanged. It'+ ' was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with des'+ 'ktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'; p.BitmapContainer := TMSFNCBitmapContainer1; p.BeginDocument(AFileName); p.NewPage; p.Graphics.Font.Name := 'Arial'; p.Graphics.Font.Size := 10; p.Graphics.Fill.Color := gcNull; r := RectF(10, 50, 300, 400); p.Graphics.DrawHTMLText(s, r); p.EndDocument(True); finally p.Free; end; end;

The PDF library supports more than simple text and graphics. More information on the PDF library and the features can be found at the following page http://www.tmssoftware.com/site/tmsfncuipack.asp?s=fncpdf#features.

The PDF library is also available in the TMS FMX UI Pack and is coming to the TMS Component Pack at the beginning of 2017!

Pieter Scheldeman


Bookmarks: 

This blog post has not received any comments yet. Add a comment.



TMS X-Cloud Todolist with FNC

Bookmarks: 

Wednesday, June 22, 2016

It's almost three months since we released the first version of the TMS FNC UI Pack, a set of Framework Neutral Components (FNC), and have meanwhile released 2 major updates which include the TTMSFNCTabSet/TTMSFNCPageControl (v1.1), the recently introduced TTMSFNCListBox/TTMSFNCCheckedListBox and significant improvements / new features to the TTMSFNCTreeView such as filtering, sorting, keyboard lookup, clipboard support, ... (v1.2).

As already explained in previous blog posts (http://www.tmssoftware.com/site/blog.asp?post=335 and http://tmssoftware.com/site/blog.asp?post=346), the TMS FNC UI Pack is a set of UI controls that can be used from VCL Windows applications, FireMonkey (FMX) Windows, Mac OS-X, iOS, Android applications and LCL framework based Lazarus applications for Windows, Linux, Mac OS-X, ... . The TMS FNC UI Pack contains highly complex & feature-rich components such as grid, planner, rich editor, treeview, toolbars. So, with a single set of controls, you have the freedom of choice to use Delphi, C++Builder or the free Lazarus to create applications for a myriad of operating systems, you have a single learning curve to these components and as demonstrated here, you can use a single source to create apps for multiple targets.

This blog post will cover the TTMSFNCCheckedListBox, which is one of the new components that are added in the latest release (v1.2) of the TMS FNC UI Pack, show how to use myCloudData.net to store data and demonstrate how easy it is to switch between FMX, VCL and LCL with one shared source code. myCloudData is an easy to use & flexible service to make use of structured storage in the cloud from Windows, web, mobile or IoT apps and is offered by tmssoftware.com. myCloudData is OAUTH/JSON REST based and our TMS Cloud Pack includes a component to access the service and thus your data seamlessly.

Click image for more screenshots.

A single shared source

As with our TV-guide sample we have created a single shared source file that is used in a FMX, VCL and LCL project. The unit starts by defining the business logic class that will be instantiated in our application main form unit.
  TTODOListLogic = class
  private
    FTable: TMyCloudDataTable;
    FListBox: TTMSFNCCheckedListBox;
    FMyCloudDataAccess: TMyCloudDataAccess;
    FOnConnected: TNotifyEvent;
    FBitmapContainer: TTMSFNCBitmapContainer;
  protected
    procedure DoConnected(Sender: TObject);
  public
    destructor Destroy; override;
    procedure InitListBox(AListBox: TTMSFNCCheckedListBox);
    procedure InitMyCloudData;
    procedure Refresh;
    procedure InitializeTable;
    procedure AddNewItem(AText: string; ADate: TDateTime; APriority: TPriority);
    procedure DeleteItem;
    procedure Connect;
    procedure DoBeforeDrawItem(Sender: TObject; AGraphics: TTMSFNCGraphics; ARect: TRectF; AItem: TTMSFNCListBoxItem; var AAllow: Boolean; var ADefaultDraw: Boolean);
    procedure DoItemCheckChanged(Sender: TObject; AItem: TTMSFNCCheckedListBoxItem);
    procedure DoItemCompare(Sender: TObject; Item1, Item2: TTMSFNCListBoxItem; var ACompareResult: Integer);
    property OnConnected: TNotifyEvent read FOnConnected write FOnConnected;
    property BitmapContainer: TTMSFNCBitmapContainer read FBitmapContainer write FBitmapContainer;
  end;
Each framework has its own set of units in order to compile succesfully. We use the conditional defines added to our project to make the difference between each framework.
uses
  Classes, SysUtils, DB
  {$IFDEF VCL}
  ,VCL.TMSFNCListBox, VCL.TMSFNCCheckedListBox, CloudMyCloudData, CloudBase, VCL.TMSFNCUtils,
  CloudCustomMyCloudData, VCL.TMSFNCGraphics, VCL.Dialogs, VCL.TMSFNCTypes, Types, VCL.TMSFNCBitmapContainer;
  {$ENDIF}

  {$IFDEF FMX}
  ,FMX.TMSFNCListBox, FMX.TMSFNCCheckedListBox, FMX.TMSCloudMyCloudData, FMX.TMSCloudBase,
  FMX.TMSFNCUtils, FMX.TMSCloudCustomMyCloudData, FMX.TMSFNCGraphics, FMX.TMSFNCTypes, FMX.Dialogs, Types, FMX.TMSFNCBitmapContainer;
  {$ENDIF}

  {$IFDEF LCL}
  ,LCLTMSFNCListBox, LCLTMSFNCCheckedListBox, LCLTMSCloudMyCloudData, LCLTMSCloudBase,
  LCLTMSFNCUtils, LCLTMSCloudCustomMyCloudData, LCLTMSFNCGraphics, Dialogs, LCLTMSFNCTypes, LCLTMSFNCBitmapContainer;
  {$ENDIF}

myCloudData

As our todolist is storing its todo items in the cloud we take advantage of our own service, that can virtually store anything we want. The initialization is done programmatically.
procedure TTODOListLogic.InitMyCloudData;
begin
  FMyCloudDataAccess := TMyCloudDataAccess.Create(nil);
  FMyCloudDataAccess.PersistTokens.Location := plIniFile;
  {$IFDEF FMX}
  FMyCloudDataAccess.PersistTokens.Key := TTMSFNCUtils.GetDocumentsPath + PthDel + 'myclouddatafmx.ini';
  FMyCloudDataAccess.OnConnected := DoConnected;
  {$ENDIF}
  {$IFDEF VCL}
  FMyCloudDataAccess.PersistTokens.Key := TTMSFNCUtils.GetDocumentsPath + PthDel + 'myclouddatavcl.ini';
  FMyCloudDataAccess.OnConnected := DoConnected;
  {$ENDIF}
  {$IFDEF LCL}
  FMyCloudDataAccess.PersistTokens.Key := TTMSFNCUtils.GetDocumentsPath + PthDel + 'myclouddatalcl.ini';
  FMyCloudDataAccess.OnConnected := @DoConnected;
  {$ENDIF}
  FMyCloudDataAccess.PersistTokens.Section := 'tokens';
  FMyCloudDataAccess.App.Key := MYCLOUDDATAKEY;
  FMyCloudDataAccess.App.Secret := MYCLOUDDATASECRET;
  FMyCloudDataAccess.App.CallBackPort := 8888;
  FMyCloudDataAccess.App.CallBackURL := 'http://127.0.0.1:8888';
end;
You might notice 3 things here. First is the TMyCloudDataAccess class which is common between FMX, VCL and LCL. This is defined earlier in our business logic as the unit names are different for FMX, VCL and LCL.
type
  {$IFDEF VCL}
  TMyCloudDataAccess = class(TAdvMyCloudData);
  {$ENDIF}

  {$IFDEF FMX}
  TMyCloudDataAccess = class(TTMSFMXCloudMyCloudData);
  {$ENDIF}

  {$IFDEF LCL}
  TMyCloudDataAccess = class(TTMSLCLCloudMyCloudData);
  {$ENDIF}
Second, is the event handler assignment, that we also need to wrap with conditional defines because LCL works with an additional @. Third is the ini file that is also created with a framework suffix, as the token and token encryption are unique per application and not shareable. After defining our business logic, it's time to setup our GUI. The form unit is shared between FMX, VCL and LCL and there you will also notice the uses list and the form file is separated with defines. After designing our form (using the TTMSFNCCheckedListBox, some tool bar buttons (TTMSFNCToolBarButton) we are ready to connect to our business logic and create a working todo list that stores its items in the cloud.
procedure TTODOListForm.DoConnected(Sender: TObject);
begin
  Panel1.Enabled := True;
  Panel2.Enabled := True;
  TMSFNCToolBarButton2.Enabled := False;
  TMSFNCCheckedListBox1.Enabled := True;
  TMSFNCToolBarButton4.Enabled := True;
  TMSFNCToolBarButton5.Enabled := True;
  TMSFNCToolBarButton6.Enabled := True;
  TMSFNCToolBarItemPicker1.Enabled := True;
  FTODOListLogic.InitializeTable;
  FTODOListLogic.Refresh;
end;

procedure TTODOListForm.FormCreate(Sender: TObject);
begin
  FTODOListLogic := TTODOListLogic.Create;
  FTODOListLogic.InitListBox(TMSFNCCheckedListBox1);
  FTODOListLogic.InitMyCloudData;
  {$IFDEF LCL}
  FTODOListLogic.OnConnected := @DoConnected;
  {$ELSE}
  FTODOListLogic.OnConnected := DoConnected;
  {$ENDIF}
  TMSFNCCheckedListBox1.BitmapContainer := TMSFNCBitmapContainer1;
  TMSFNCToolBarItemPicker1.BitmapContainer := TMSFNCBitmapContainer1;
  TMSFNCToolBarItemPicker1.Bitmaps.Clear;
  TMSFNCToolBarItemPicker1.Bitmaps.AddBitmapName('low');
  TMSFNCToolBarItemPicker1.DisabledBitmaps.Assign(TMSFNCToolBarItemPicker1.Bitmaps);
  TMSFNCToolBarButton2.DisabledBitmaps.Assign(TMSFNCToolBarButton2.Bitmaps);
  TMSFNCToolBarButton4.DisabledBitmaps.Assign(TMSFNCToolBarButton4.Bitmaps);
  TMSFNCToolBarButton5.DisabledBitmaps.Assign(TMSFNCToolBarButton5.Bitmaps);
  TMSFNCToolBarButton6.DisabledBitmaps.Assign(TMSFNCToolBarButton6.Bitmaps);

  dt := TMyDateTimePicker.Create(Self);
  {$IFDEF FMX}
  dt.Position.X := 5;
  dt.Position.Y := 40;
  {$ELSE}
  dt.Left := 5;
  dt.Top := 40;
  {$ENDIF}
  dt.Date := Now;
  dt.Parent := Panel1;
  dt.Width := 105;
end;

procedure TTODOListForm.FormDestroy(Sender: TObject);
begin
  FTODOListLogic.Free;
end;

procedure TTODOListForm.TMSFNCCheckedListBox1ItemSelected(Sender: TObject;
  AItem: TTMSFNCListBoxItem);
begin
  TMSFNCToolBarButton6.Enabled := True;
end;

procedure TTODOListForm.TMSFNCToolBarButton1Click(Sender: TObject);
begin
  FTODOListLogic.Refresh;
end;

procedure TTODOListForm.TMSFNCToolBarButton2Click(Sender: TObject);
begin
  FTODOListLogic.Connect;
end;

procedure TTODOListForm.TMSFNCToolBarButton3Click(Sender: TObject);
begin
  FTODOListLogic.DeleteItem;
end;

procedure TTODOListForm.TMSFNCToolBarButton4Click(Sender: TObject);
begin
  FTODOListLogic.AddNewItem(Edit1.Text, dt.Date, TPriority(TMSFNCToolBarItemPicker1.SelectedItemIndex));
end;

procedure TTODOListForm.TMSFNCToolBarItemPicker1ItemSelected(Sender: TObject;
  AItemIndex: Integer);
begin
  TMSFNCToolBarItemPicker1.Bitmaps.Clear;
  TMSFNCToolBarItemPicker1.Bitmaps.AddBitmapName(TMSFNCBitmapContainer1.Items[AItemIndex].Name);
  TMSFNCToolBarItemPicker1.DisabledBitmaps.Assign(TMSFNCToolBarItemPicker1.Bitmaps);
end;
When starting the application, and clicking the connect button, our business logic unit will do the work. It will create a table in myCloudData, send a notification to our GUI, which will then allow to add items to our listbox, refresh or delete existing items, and this is done with one source code, available on multiple frameworks, multiple platforms.

The full source code is available for download

Click image for more screenshots.

Pieter Scheldeman


Bookmarks: 

This blog post has not received any comments yet. Add a comment.



Developing your first FNC custom control

Bookmarks: 

Friday, May 13, 2016

Some weeks ago, we released the TMS FNC UI Pack, a set of Framework Neutral Components (FNC), i.e. UI controls that can be used from VCL Windows applications, FireMonkey (FMX) Windows, Mac OS-X, iOS, Android applications and LCL framework based Lazarus applications for Windows, Linux, Mac OS-X,..
The TMS FNC UI Pack contains highly complex & feature-rich components such as grid, planner, rich editor, treeview, toolbars. To create such complex components that work under 3 frameworks and a myriad of operating systems is not a trivial excercise and requires intricate knowledge about the VCL, FMX and LCL frameworks as well as the operating systems the controls need to work under.
To help ourselves and the users of the TMS FNC UI Pack, we have introduced several abstractions that facilitate creating framework neutral components and this is what we want to cover in this brief introduction to developing FNC custom controls.

FNC custom control basics

The structure of the FNC custom control we want to present is this of a classic UI control. The control is responsible for painting itself and interacts with keyboard and/or mouse. The control has several properties to control its appearance and behavior. If we look at this concept from the perspective of implementing this for 3 different frameworks, the biggest challenges faced are:

1) abstractions in the code for dealing with graphics: especially VCL and FMX are quite different in this respect, so abstraction is welcome.
2) abstractions in keyboard and mouse handling: also here there are differences, although subtle, between VCL, FMX and LCL.
3) abstractions in types: types such as font, color, rectangles, points are different in FMX and VCL.

So, we'll cover what is included in FNC to facilitate dealing with this.

Unit organisation

Perhaps the biggest stumbling block is unit organisation. As it is desirable to create components that can be installed in the IDE, (which means for Delphi for both the VCL and FireMonkey framework simultanously) we'll need units for VCL and units for FireMonkey. Although we can use the same class name, the class hierarchy for the VCL control and the FMX control will be different. The VCL FNC control will descend from the VCL TCustomControl and the FMX FNC control will descend from the FMX TControl. In Lazarus, the FNC control will descend from the LCL TCustomControl. In a nutshell, to solve this, we create 3 units for a component that will be nearly identical and we provide a conversion step to allow you to write the code in one unit and automatically generate the other units for the other frameworks. For this example, in total, we'll have 6 units: 3 units with the code for the control for the 3 supported frameworks and 3 units for the component registration in the IDE:

// Units for the VCL variant of the FNC control
VCL.TMSFNCCust.pas
VCL.TMSFNCCustReg.pas

// Units for the FMX variant of the FNC control
FMX.TMSFNCCust.pas
FMX.TMSFNCCustReg.pas

// Units for the LCL variant of the FNC control
LCLTMSFNCCust.pas
LCLTMSFNCCustReg.pas
We'll also use 3 packages: a package for VCL, a package for FMX and a package for LCL. We can install the VCL & FMX package simultanously in the Delphi IDE and the LCL package in the Lazarus IDE. The package for the custom control will have a dependency to the framework plus to the TMS FNC UI Pack for the framework. The structure of the packages in the Delphi 10.1 Berlin IDE is:


and in Lazarus, this is:

Getting to grips

Ok, now that the unit structure is setup, we can focus on writing the code. To write this code, we'll use 3 TMS FNC UI Pack units with abstractions: xxx.TMSFNCCustomControl, xxx.TMSFNCGraphics and xxx.TMSFNCTypes (with xxx = the framework). In this example, we'll write the code in VCL and automatically generate the FMX & LCL equivalents from it, so the uses list becomes:

for FMX
uses
  Classes, Types, FMX.TMSFNCCustomControl, FMX.TMSFNCGraphics, FMX.TMSFNCTypes;
for LCL
uses
  Classes, Types, LCLTMSFNCCustomControl, LCLTMSFNCGraphics, LCLTMSFNCTypes;
The FNC control we'll write here is very rudimentary for the sake of focusing on the abstractions. It is basically a gauge control that can be clicked with the mouse to set the gauge value, has a gauge value property to set it and can use the key up & down to change the gauge value. So, we need painting of the gauge, we need some gauge line color & font settings and we need handling of the mouse click and keyboard.


Control initialization

The control descends from the abstract FNC class TTMSFNCCustomControl and exposes one extra color property for the gauge line color (note that this are of the abstract type TTMSFNCGraphicsColor), a font (of the abstract type TTMSFNCGraphicsFont, that has also a font color in all frameworks) and a gauge value property of the type TControlValue. Note that the Stroke & Fill properties are published. This contains the control border & control background color and even enables things such as setting a background gradient, a border with a specific pen style etc...

  TControlValue = 0..100;

  TTMSFNCCustomControlSample = class(TTMSFNCCustomControl)
  private
    FLineColor: TTMSFNCGraphicsColor;
    FFont: TTMSFNCGraphicsFont;
    FValue: TControlValue;
  protected
    procedure Draw({%H-}AGraphics: TTMSFNCGraphics; {%H-}ARect: TRectF); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property Stroke;
    property Fill;
    property Font: TTMSFNCGraphicsFont read FFont write SetFont;
    property LineColor: TTMSFNCGraphicsColor read FLineColor write SetLineColor default gcRed;
    property Value: TControlValue read FValue write SetValue default 0;
  end;
In the constructor, initialization of the line color property value is done as well as the border color and the font is created. This is of the type TTMSFNCGraphicsFont and the main purpose is to have a font with font color in all frameworks. There is one more thing particular in the constructor and that is the assignment of the Font.OnChange event handler. In Delphi Pascal, we can simply assign the object method but for the FPC compiler, this needs to be prefixed with the @ symbol. Fortunately, the Lazarus environment has the LCL define we can use to handle this.

{ TTMSFNCCustomControlSample }

constructor TTMSFNCCustomControlSample.Create(AOwner: TComponent);
begin
  inherited;
  Stroke.Color := gcBlack;
  FLineColor := gcRed;
  FFont := TTMSFNCGraphicsFont.Create;
  FFont.OnChanged := {$IFDEF LCL}@{$ENDIF}FontChanged;
  Width := 100;
  Height := 100; 
end;

destructor TTMSFNCCustomControlSample.Destroy;
begin
  FFont.Free;
  inherited;
end;
Painting

The control descends from the abstract FNC class TTMSFNCCustomControl and exposes 3 color properties, the border, background and gauge line color (note that these are of the type TTMSFNCGraphicsColor), a font (of the type TTMSFNCGraphicsFont, that has also a font color in all frameworks) and a gauge value property of the type TControlValue.

Painting is done in the override of the Draw() method that has 2 parameters: AGraphics: TTMSFNCGraphics, a framework neutral graphics library and the rectangle of the control via ARect of the type TRectF. In VCL and LCL only the not fractional part of the floating point numbers is used but of course in the FireMonkey framework, this can use the fractional parts as well.

The painting code itself is:

procedure TTMSFNCCustomControlSample.Draw(AGraphics: TTMSFNCGraphics;
  ARect: TRectF);
var
  angle: double;
  lf,tf: TPointF;
  w: single;
begin
  inherited;

  angle := Value/High(Value)*2*PI;

  w := Min(ARect.Right - ARect.Left, ARect.Bottom - ARect.Top) / 2;

  lf.X := (ARect.Right - ARect.Left)/2;
  lf.Y := (ARect.Bottom - ARect.Top)/2;

  tf.X := lf.X + Cos(angle) * w;
  tf.Y := lf.Y - Sin(angle) * w;

  AGraphics.Stroke.Color := LineColor;

  AGraphics.DrawLine(lf,tf);

  AGraphics.Font.Assign(Font);
  AGraphics.DrawText(ARect, InttoStr(Value),false, gtaCenter, gtaCenter);
end;

Mouse and keyboard handling

The mouse and keyboard handling is via the HandleKeyDown and HandleMouseDown virtual method overrides:

  TTMSFNCCustomControlSample = class(TTMSFNCCustomControl)
  protected
    procedure HandleKeyDown(var {%H-}Key: Word; {%H-}Shift: TShiftState); override;
    procedure HandleMouseDown({%H-}Button: TMouseButton; {%H-}Shift: TShiftState; {%H-}X, {%H-}Y: Single); override;
  end;
The implementation is straightforward. One thing that is noteworthy, is that the unit xxx.TTMSFNCTypes has a list of keys in a framework and operating system neutral way, i.e. we can check for the arrow up and arrow down keys with the constants KEY_DOWN and KEY_UP.

procedure TTMSFNCCustomControlSample.HandleKeyDown(var Key: Word;
  Shift: TShiftState);
begin
  inherited;

  if Key = KEY_DOWN then
  begin
    if Value > Low(Value) then
      Value := Value - 1;
  end;

  if Key = KEY_UP then
  begin
    if Value < High(Value) then
      Value := Value + 1;
  end;
end;
In the mouse down handler, we set the focus to the control when possible and then calculate the value of the gauge that matches with the mouse click position. Note that the X,Y values are of the type single to accomodate FMX and will contain non fractional values in VCL and LCL.

procedure TTMSFNCCustomControlSample.HandleMouseDown(Button: TTMSFNCMouseButton;
  Shift: TShiftState; X, Y: Single);
var
  angle: single;
  dx,dy: single;

begin
  inherited;

  if AllowFocus then
    SetFocus;

  dx := x - (Width/2);
  dy := - y + (Height/2);

  if dx = 0 then
    angle := sign(dy) * PI / 2
  else
    angle := ArcTan(dy/dx);

  if dx < 0 then
    angle := PI + angle;

  if angle < 0 then
    angle := angle + 2 * PI;

  Value := Round((angle / 2 / PI) * High(Value));
end;
Creating the units for FMX and LCL

Now that we have the VCL framework FNC component ready that contains 100% framework neutral code, let's create automatically the FMX and LCL units from this. 3 steps are needed:

1) Rename the unit VCL.TMSFNCCust.pas to FMX.TMSFNCCust.pas and LCLTMSFNCCust.pas
2) Change in the unit .PAS file the unit name, i.e. replace VCL.TMSFNCCust by FMX.TMSFNCCust and LCLTMSFNCCust respectively
3) Change the unit references in the uses list from
VCL.TMSFNCCustomControl, VCL.TMSFNCGraphics, VCL.TMSFNCTypes;
to
FMX.TMSFNCCustomControl, FMX.TMSFNCGraphics, FMX.TMSFNCTypes;
or
LCLTMSFNCCustomControl, LCLTMSFNCGraphics, LCLTMSFNCTypes;

To accomplish this, we call a simple powershell script that performs text replacement from VCL.TMS to FMX.TMS or LCLTMS respectively:

powershell -command "(gc VCL.TMSFNCCust.pas) -replace 'VCL.TMS','LCLTMS' |Out-file LCLTMSFNCCust.pas -Encoding utf8"
powershell -command "(gc VCL.TMSFNCCust.pas) -replace 'VCL.TMS','FMX.TMS' |Out-file FMX.TMSFNCCust.pas -Encoding utf8"
With these units created, we can compile the packages and install our FNC custom control for use from VCL, FMX and LCL applications in Lazarus.


The full source of this sample FNC custom control can be downloaded here. This sample can be used with the latest version of the TMS FNC UI Pack.

We hope this already whets your appetite for exploring FNC and the power of writing code for UI controls once for use in 3 frameworks. See also this blog article for a more general coverage of what is available in the TMS FNC UI Pack. In a next article, we'll go deeper in compound control creation and also the TTMSFNCGraphics library that offers a vast range of functions, going from drawing text, polygons, polylines, images in various formats, controls like checkboxes, radiobuttons, buttons, ... and much more.

Bruno Fierens


Bookmarks: 

This blog post has received 7 comments. Add a comment.




Previous  |  Next  |  Index