All posts by Stephen Ball

Stephen is a Charted IT Professional and the Associate Product Manager for InterBase at Embarcadero. He is also a Product Evangelist for RAD Studio, regularly speaking across EMEA. @DelphiABall

Expanding FireMonkey TPlatformServices

Over this post, I want to introduce the concept of an Interface and then look at how using Interfaces allows you to expand the FireMonkey TPlatformServices in XE7 – using an example of adding custom support for FullScreen mode on iOS, where it currently isn’t supported out the box.

Interfaces & OOP – Quick Introduction.

For those of you who are aware of what an interface is, you way want to skip the first sections.

Delphi & AppMethod are built on top of the Object Pascal programming language which, as its name suggests is an Object Orientated Programming language – OOP.

Part of OOP is the concept of Interfaces;  Interfaces are in short a contract that classes can then implement and support. Unlike object inheritance (where you can only descend from a single object), an object can introduce and support multiple interfaces at the same time. The great thing about Interfaces is the ability to ask an object if it supports a specific Interface, and if it does, telling it to go do a specific supported method.

Example of an Interface – ISteeringWheel

I am sure we all know what a steering wheel is so lets imagine we have defined in our code an interface ISteeringWheel that can be turned left and turned right with two method TurnLeft and TurnRight

type 
  ISteeringWheel = Interface
  ['{F4F8536B-FCA6-48D1-B3D4-AF4EE9B90964}']
    procedure TurnLeft;
    procedure TurnRight;
  end;

But where are we going to use this SteeringWheel? It could be on a TCar or a TBoat or even a TAirplane.

The job of implementing the code and what happens when you call a method of an Interface is down to the object that supports that interface.

TCar = class(TInterfacedObject, ISteeringWheel)
public
  // Turns wheels
  procedure TurnLeft;
  procedure TurnRight;
end;

TBoat = class(TInterfacedObject, ISteeringWheel)
public
  // Changes the rudder
  procedure TurnLeft;
  procedure TurnRight;
end;

How does this relate to Platform Services?

If we think about phones, tablets, laptops etc, not all devices support the same capabilities; e.g. my iPad doesn’t have a sim card so doesn’t support making calls.  FireMonkey works with this complexity by defining Interfaces that can be queried at run time to determine if a device supports specific capabilities.  By having a contract in code, the platforms are then able to provide to you an object that supports the platform, but also the Interface.

Using our example above, lets imagine, TCar and TBoat are like Android and iOS, and the SteeringWheel is a compass, then you would start to understand that by asking at run time if the compass is supported, we get an iOS or Android object that we know how to talk to as it supports the appropriate interface, but under the hood calls the platform specific API’s.

TPlatformServices and IFMXFullScreenWindowService

So now we understand about Interfaces and how to use them, lets look into a real implementation and how we can use this to update the way the system works by providing a supported Interface.

The IFMXFullScreenWindowService interface supports 3 methods that allow you to find out if the application is running in FullScreen mode (Get), or put it into FullScreen mode (Set) and also define if the Icon is seen.

(I’ve removed the parameters here to make it more readable)

IFMXFullScreenWindowService = interface(IInterface)
  ['{103EB4B7-E899-4684-8174-2EEEE24F1E58}']
  procedure SetFullScreen(....);
  function GetFullScreen(....): Boolean;
  procedure SetShowFullScreenIcon(....);
end;

This Interface has been used by TCommonCustomForm and descendants (of which TForm is the one you will probably be using) and wrapped up into an easy to call property – FullScreen.

To change between full screen and non full screen at run time is as simple as

procedure TForm1.Button1Click(Sender: TObject);
begin
  FullScreen := not FullScreen;
end;

This property was introduced in RAD Studio XE7 / Appmethod September 2014 release and works on Windows, Mac OS X, and Android (Immersive mode). However, there is not an implementation for iOS.

While each platform behaves differently according to its design and platform norms, I want to show you how you can add support for iOS without having to change the common code that works on the other platforms.

Under the hood – FullScreen & TPlatformServices

So first, before we add the service I also want to cover for other examples how you check for a supported PlatformService Interface.

FireMonkey’s TPlatformServices (defined in FMX.Platform)  exposes the instance of TPlatformServices using the Current property.

TPlatformServices.Current

Once you have the Current TPlatformServices instance it can be queried for support of specific interfaces. One of those new interfaces is the IFMXFullScreenWindowService. To find out if it is supported we need to create a variable to point to the service and then ask if its supported. e.g.

var 
  FFullScreenSrvice: IFMXFullScreenWindowService;
begin
  TPlatformServices.Current.SupportsPlatformService(IFMXFullScreenWindowService, FFullScreenSrvice);
  if FFullScreenSrvice <> nil then 
    // its supported - make full screen
    FFullScreenSrvice.SetFullScreen(True);
end;

Once you have an instance of the Interface, you can then just call its methods. There is no need to free an interface as they are reference counted on all platforms.

Adding a new Interface implementation to TPlatformServices

To add a new platform service we again go back to TPlatformServices. There is a method called AddPlatformService. This takes 2 parameters, Firstly the interface you want to add and secondly the instance of an class supporting that Interface.

Using what we learned earlier about creating an object that supports and interface we first need to define a class (TFullScreenServiceiOS) defined  as a TInterfacedObject supporting the desired interface (IFMXFullScreenWindowService).

Full code can be downloaded from code central so you can see how GetFullScreen and SetFullScreen were fully implemented in code.

TFullScreenServiceiOS = class(TInterfacedObject,   IFMXFullScreenWindowService)
public
  function GetFullScreen(....): Boolean;
  procedure SetFullScreen(....);
  procedure SetShowFullScreenIcon(....);
end;

WIth the object defined and implemented, you can then register an instance with the application at run time.  As I only want this to register for iOS, one approach is to use IFDEF’s to call a register procedure during the initialisation of the application.

procedure RegisterFullScreenServiceiOS;
begin
  FullScreeniOS := TFullScreenServiceiOS.Create;
  TPlatformServices.Current.AddPlatformService(
     IFMXFullScreenWindowService, FullScreeniOS);
end;

{$IFDEF IOS}
initialization
  RegisterFullScreenServiceiOS;
{$ENDIF}

With this code in place, it is now possible to run the same application code on iOS and see the FullScreen := not FullScreen move the application in and out of FullScreen mode as it is now supported in iOS.

Summary

Thats it! –  Creating a new class that implements code and supports the interface and registering the class to the TPlatformServices is all you need to do to expand and modify the TPlatformServices.

The full source code for the TPlatformServices and IFMXFullScreenWIndowServices example can be downloaded from code central  http://cc.embarcadero.com/item/30023

Mobile Development Lessons – Delphi & C++

Free series of mobile development lessons for Android and iOS based on C++ and Object Pascal.

Earlier in the year the 2nd edition of the mobile development summer school was run by David I and Jim McKeeth. It was great fun doing the first edition and its amazing to see how some of the tech has moved on further in the year since we first ran summer school. This years was more popular than ever and has been made available on YouTube

YouTube Playlist for video replays

https://www.youtube.com/playlist?list=PLwUPJvR9mZHhLj-gegxc0KpGE0wL2zVBo

Blogs for slides and samples:

To get started is easy!

Download your free trial of RAD Studio https://downloads.embarcadero.com/free/rad_studio

or your FREE edition of Appmethod (C++ Free for Android mobile)
http://www.appmethod.com 

Happy Coding!

Parallel Programming Thread Pool

In my Parallel Programming introduction post I explored how to easily get performance gains when running loop code by using the TParallel.For() loop construct. A key part of the Parallel Programming Library engine is the new ThreadPool that manages some of the complexity behind the scenes when using this syntax, but more on that later.

Following on from this first post I want to explore a common question I have heard. Is it possible to manage the Parallel Programming library thread pool Size? and if so how?

In short Yes, but I want to pose another question: Should you? – Lets explore this below.

Parallel programming thread pool

The Parallel programming thread pool is very smart! It automatically grows and shrinks based on CPU demand when your application runs and requires its use; it also throttles growth as your CPU usage rises ensuring it doesn’t over cook your CPU and ensuring you don’t lock up your machine. This inbuilt intelligence makes it very efficient and courteous out the box. All of this, without ANY management from us developers! 🙂 So why would you want to change this?

Thats not to say you can’t use a custom(ised) pool. If you do want to limit the size of a pool then you can override the defaults of  a TThreadPool.

TThreadPool Defaults

Defined in System.Threading, TThreadPool initiates with a default of 25 threads per CPU.

MaxThreadsPerCPU = 25;

TThreadPool multiplies the MaxThreadsPerCPU with the number of CPU’s on the machine (it gets this form calling TThread.ProcessorCount) and exposes the result via a read only property TThreadPool.MaxWorkerThreads.

To query the default pool size on your machine at runtime you can use TThreadPool’s handy class method that returns the default pool. With this pool you can then query the MaxWorkerThreads. e.g.

var
  i : integer;
begin
  i := TThreadPool.Default.MaxWorkerThreads;
  ShowMessage('Pool size = '+i.ToString());
end;

On my Windows VM running 2 cores I see 50, but on my Mac OS X with 8 cores, this code returns 200.

Customising a TThreadPool

Let me start this section by saying, modifying the default TThreadPool properties is not recommended. 

While possible, it is not recommended to modify the Default TThreadPool options as this is a global instance that is used throughout the application, and you never can be sure where and when its being used. You can however create your own instance of a TThreadPool that you modify and use and this is a better approach.

Creating and modifiying a TThreadPool

Creating a TThreadPool is as simple as declaring the variable and calling the constructor.

With an instance of a TThreadPool, you can then modify the MaxWorkerThreads by overriding the value using the method SetMaxWorkerThreads() which takes in an Integer. This sets it at a flat number regardless of the number of CPU’s you have available.  e.g. the following code reports 10 as the Max size on both my Windows and Mac OSX machines mentioned above.

var
  FPool : TThreadPool;

...

if Pool = nil then begin
  Pool := TThreadPool.Create;
  Pool.SetMaxWorkerThreads(10);
end;

Note, the MaxWorkerThreads number must always be greater than the MinimumWorkerThreads value that (by default) is set from TThread.ProcessorCount.

A word of caution..

Creating a new TThreadPool come with an overhead. From an initial test where I creating a new TThreadPool for running a small TParallel.For() loop, and then disposing it afterwards it actually decrease performance on your application compared to a traditional for loop. For this reason alone, I would always use a global TThreadPool. When the pool was created globally, the speed performance was immediately backup compared to the create and destroy on demand idea.

 Example of using a custom TThreadPool

Below is an example where Pool is a global TThreadPool.  When the button is selected to run a TThreadPool with a maximum of 10 WorkerThreads. The only adjustments from the example in the previous tutorials is that we now pass in Pool as a paramater to the For loop, note however that this is not being created and free’ed each time in this code.

var
  Pool: TThreadPool;

procedure TForm5.Button1Click(Sender: TObject);
var
 Tot: Integer;
 SW: TStopwatch;
begin
 // counts the prime numbers below a given value
 Tot := 0;
 SW := TStopWatch.Create;
 SW.Start;

 if Pool = nil then begin 
   Pool := TThreadPool.Create;
   Pool.SetMaxWorkerThreads(10);
 end;
 TParallel.For(1, Max, procedure (I: Integer)
   begin
     if IsPrime (I) then
       TInterlocked.Increment (Tot);
   end,Pool);
 SW.Stop;
 Memo1.Lines.Add (Format (
 'Parallel (Custom Pool) for loop: %d - %d', [SW.ElapsedMilliseconds, Tot]));
end;

I would say that while this gives me a sense of control, I actually don’t like the fact that I am messing with something that is highly tuned. I would personally conclude that a ThreadPool should be created as the application has initialised and that you use this. Ideally I would say use the default one, as it behaviour is very good already, but if you really want to make more work for yourself, then you can always set the properties of a new pool and use it.

 A thank you to Allen Bauer for his input while writing this post.

In-app purchase on Android and iOS

Jim Mckeeth recently recorded a developer skill sprint showing how to use In App purchase on Android and iOS.

Using the Capitals Quiz demo that ships with RAD Studio and Appmethod, he covered common scenarios of how to use in-app purchases to disable adverts, to purchase additional items, restore purchases that had been made on another device and also consume a purchased item, all using common code that works across Android and iOS.

There are loads of great notes on in App Purchase on docwiki

A summary of key steps

On Android

You need / see

  • An application license key ID (which is very long and may need splitting over two lines) – You need to upload your app to the Google Play store first (recommended as alpha) to get this key and then you can re-upload later on.
  • Unique product ID’s – which point to Managed products online
  • To create a key store and set this to be used in the Project Options.
  • (and also a number of other steps.. e.g setting up merchant account)

On iOS (iTunes)

You need / see

  • From the developer portal, you need the AppID (non wild card version) and need to ensure the App has InApp purchases enabled.
  • Use iTunes connect to create the purchase item, including setting price Tier
  • Add language and display name for the purchase, and also add in screen shots to show what happens.

Once setup you can call

  • InAppPurchase.PurchaseProduct() and pass in the ID for the product to purchase a product.
  • Define an InAppPurchase.OnPurchaseComplete event to define what happens once an item is purchased.
  • Query InAppPurchase.IsProductPurchased etc..

Other Resources

He does also mention that setting applications live can take a few hours.

Watch the replay here:

NFC in Android from Delphi / Objective Pascal

One great thing about developing with Embarcadero’s RAD Studio, Delphi, C++ Builder and AppMethod is the component development model. Developing with components allows you to write code once that works across all platforms as the components take care of the platform specific API mappings. e.g. Talking to the camera, accelerometer, compass etc.

There are however times when a component doesn’t exist (yet). This is normally when something is platform specific as it doesn’t make sense to have a component that is platform specific when you can still call the API’s of that platform. e.g. prior to the announcements from Apple on the iPhone 6, NFC was on Android but not iOS. 

So what do you need to do when you don’t have a component ready to go? – Well it depends on what you want to call. With regards to accessing NFC, then Brian Long and Danny Magin, both Embarcadero MVP’s, have recently blogged about working through importing the Java libraries required, setting up the intents to collect the message from NFC, setting your application so Android knows it can deal with messages from NFC and then using them. Pretty cool 🙂

If your interested further in calling platform API’s then check out the replays from the Skills Sprints for accessing Android and iOS API’s directly.

TTask.IFuture from the Parallel Programming Library

In my last post I spoke about TTask and how it enables us developers to quickly run multiple tasks at the same time with limited bottleneck in our applications. Moving on from that I want to explore IFuture which impletements ITask.

IFuture

IFuture , provides TTask with a structure us developers can use to creating a function that returns a specific type (defined using Generics, thats the <T> bit you see in code sometimes).  Using an instance of IFuture, the process can run and then allow us to get other stuff done, until such point as we need the result. This allows us to prioritise code blocks to run in the order we want them to, but still ensure we get the value we need at the point we need it!

Example

To get a value in the future, you first need to define what type of value, set it running and then go call it. To view this, below I am using a totally pointless (but shows how to use this feature) block of code, which I will break down step by step afterwards.

procedure TFormThreading.Button3Click(Sender: TObject);
var
 OneValue: IFuture <Integer>;
 OtherValue: Integer;
 Total: Integer;
begin
 OneValue := TTask.Future<Integer>(function: Integer
   begin
     Result := ComputeSomething;
     Sleep(1000); // delay to show status
   end);

 Memo1.Lines.Add(TRttiEnumerationType.
 GetName<TTaskStatus>(OneValue.Status));

 OtherValue := ComputeSomething;

 Memo1.Lines.Add(TRttiEnumerationType.
 GetName<TTaskStatus>(OneValue.Status));

 Total := OtherValue + OneValue.Value;

 Memo1.Lines.Add(TRttiEnumerationType.
 GetName<TTaskStatus>(OneValue.Status));

 // result
 Memo1.Lines.Add(Total.ToString);
end;

The output of this code looks something like this..

IFutures

Key points in the code

The first step, is using TTask.Future<T> to define the type to be returned, and then pass in the anonymous method to return the instance of that value. (Here we are getting an Integer from ComputeSomething so we use Integer as the type)

The output of calling TTask.Future is an instance of IFuture into the OneValue variable defined.

 OneValue := TTask.Future<Integer>(function: Integer
   begin
     Result := ComputeSomething;
     Sleep(1000); // delay to show status
   end);

OK, so putting a Sleep command in the anonymous method here is kind of pointless, but it does allow when running this demo code to see the result of the call to OneValue.Status change from WaitingToRun, to Running, to Completed.

As you read down further, you will see OneValue being queried for its current status. The code for converting our Future’s Status to a string is the same as any other Enumeration type, pass in the type you want to convert and the value to GetName.

TRttiEnumerationType.
 GetName<TTaskStatus>(OneValue.Status)

The first value returned will be WaitingToRun as everything is prepared. Following the first status query, we call the same ComputeSomething task

 OtherValue := ComputeSomething;

Afterwards, we can check the status of OneValue and see that (due to the sleep taking longer than the ComputeSomething call) its now reporting as running.

So hold on! Does that mean we need to check the status to see if its OK to get the value? Well actually NO 🙂

 Total := OtherValue + OneValue.Value;

This line asks OneValue for its Value. If it is done, it will have the value ready for you, if not (as in this case) it will block and wait for IFuture to finish before executing the code making life very easy on us developers.

So thats IFuture, its a process that you can set running, but will return at the point it is ready. Another way to save time and speed up your application code.

Using TTask from the Parallel programming library

In my last post on using Parallel Programming and the TParallel.For construct we learned about the new System.Threading unit and how to use TParallel to make looping faster.  There are however times when you need to run multiple tasks that are not loops, but these can run in parallel.

Running a number of processes in tandem has been greatly simplified with System.Threading.TTask and System.Threading.ITask

TTask provides a class to create & manage interaction with instances of ITask. You can choose to WaitForAll or WaitForAny to finish before proceeding in code.

To give an example. Imagine you have two tasks. A and B.
If A takes 3 seconds and B takes 5 seconds how long does it take to get a result to a user?

  • Sequentially (without TTask / ITask) = 8 seconds.
  • Using TTask.WaitForAll = 5 seconds
  • Using TTask.WaitForAny = 3 seconds

Depending on what your doing, the speed for return can be dramatically quicker. So lets look at a code example for WaitForAll.

procedure TFormThreading.MyButtonClick(Sender: TObject);
var
 tasks: array of ITask;
 value: Integer;
begin
 Setlength (tasks ,2);
 value := 0;

 tasks[0] := TTask.Create (procedure ()
   begin
     sleep (3000); // 3 seconds
     TInterlocked.Add (value, 3000);
   end);
 tasks[0].Start;

 tasks[1] := TTask.Create (procedure ()
   begin
     sleep (5000); // 5 seconds
     TInterlocked.Add (value, 5000);
   end);
 tasks[1].Start;

 TTask.WaitForAll(tasks);
 ShowMessage ('All done: ' + value.ToString);
end

The above example uses an Array of ITask to process a set of tasks. The result returned is 8000, but despite 8 seconds worth of sleep commands, the first 3 seconds run in parallel, leaving the second task to finish before returning 2 seconds later, which equates to a 3 second gain on sequentially running the two tasks; and all of this without having to create your own custom threads and managing them return. 🙂

While speeding up a task to run before returning is good, you can also use TTask to prevent the user interface locking up if you want to start something in the background.  To do this, you can just run a single task and start it, for example

procedure TFormThreading.Button1Click(Sender: TObject);
var
 aTask: ITask;
begin
 // not a thread safe snippet
 aTask := TTask.Create (procedure ()
   begin
     sleep (3000); // 3 seconds
     ShowMessage ('Hello');
   end);
 aTask.Start;
end;

This second example, if used, would allow the user to press the button multiple times resulting in multiple ShowMessage calls, however, used with care this is a powerful way to run task. This is also an example of asynchronous programming where you can start the Task, get on with other stuff, and then deal with the result as it returns.

ITask

ITasks provide a range of methods and properties to Start, Wait, Cancel and also a property for Status (Created, WaitingToRun, Running, Completed, WaitingForChildren, Canceled, Exception)

As ITask is an interface, you can always create your own classes that use ITask if you so wish, providing great flexibility to the frame work.

Parallel Programming with Delphi XE7; a quick introduction

Everyone knows that typically device / computers today have multiple CPU’s, even my phone has 4! But when it comes to programming to get full benefits of working across those cores its often been a little tricky or time consuming and extra code overhead to manage.  Well… that is until now with Parallel Programming with Delphi!

Starting with Delphi, C++ Builder and RAD Studio XE7, there is a new library that simplifies the effort needed to get tasks running in parallel, aptly named the Parallel Programming Library.

The Parallel Programming Library lives within the System.Threading unit and is made up of a number of new helpful features that can be easily introduced into new and also existing projects. There are also loads of overloaded arguments for fine tuning and supporting C++ working with this as well as Object Pascal.

These features include a new Parallel for loop that is easy to uses, along side a number of more advanced features for running tasks, joining tasks, waiting on groups of tasks etc to process. Under the hood there is a thread pool that self tunes itself automatically (based on the load on the CPU’s).

To give you an idea about how easily this is to plug in, lets take a simple example where you want to work out if a number is a prime number.

function IsPrime (N: Integer): Boolean;
var
 Test: Integer;
begin
 IsPrime := True;
 for Test := 2 to N - 1 do
   if (N mod Test) = 0 then
   begin
     IsPrime := False;
     break; {jump out of the for loop}
   end;
end;

The traditional way to loop  and check for the number of prime numbers between 1 to X value would be to do something like this where each number is checked in sequence and the total stored into a variable (here Tot is an integer)

const
 Max = 50000; // 50K

for I := 1 to Max do
 begin
   if IsPrime (I) then
     Inc (Tot);
 end;

Using the new Parallel library, this can be achieved by replaces the “for” command with a call to the class function TParallel.For passing in the code to be run as an anonymous method.

In addition, to avoid clashes with multiple threads running, you can call TInterlocked.Increment.

TParallel.For(1, Max, procedure (I: Integer)
 begin
   if IsPrime (I) then
     TInterlocked.Increment (Tot);
 end);

So what difference does this make?

Using TStopWatch from System.Diagnostics we are able to test the time to run each version of the loop above. Even on my VM running only 2 cores the time drops from 415ms for the standard for loop down to 192ms using the Parallel programming library version. On my Mac where there are more cores available it goes from 382ms down to 90ms for the same test!

What I love about this, is this is a really easy solution to plug into existing code as its part of the language and framework.

The great thing about writing native code is that we can take advantage of all the cores on a device. 🙂 Including Mobiles! However, as a word of caution, use it only where you need to on mobile as it will use more battery if you are running multiple threads heavily.

Samples

An other example that can help get your head around how to use the Parallel Programming library is a sample of Conways game of life for both Object Pascal and C++ in the samples directory shipped with XE7, located in the RTL samples. e.g.

C:\Users\Public\Documents\Embarcadero\Studio\15.0\Samples\Object Pascal\RTL\Parallel Library
C:\Users\Public\Documents\Embarcadero\Studio\15.0\Samples\CPP\RTL\Parallel Library

Not sure about you, but I’m off to speed up some processing in some old projects I have 🙂 Happy coding!