Smart Mobile Studio
  • News
  • Forums
  • Download
  • Store
  • Showcases
    • Featured demos
    • The Smart Contest 2013, Round 1 – Graphics
  • Documentation
    • Get the book
    • System requirements
    • Prerequisites
    • Getting started
      • Introduction
      • Application architecture
      • The application object
      • Forms and navigation
      • Message dialogs
      • Themes and styles
    • Project types
      • Visual project
      • Game project
      • Console project
    • Layout manager
    • Networking
      • TW3HttpRequest
      • TW3JSONP
      • Loading files
  • About

OP4JS: Project file format

Posted on 29.11.2011 by Jon Lennart Posted in Developers log 3 Comments
Embed or reference, now you chose

Embed or reference, now you chose

In the olden days of 16 bit computing, most programming languages saved their projects in a single binary format. In short: all the files pertaining to your project was housed in a single file. The benefits were of-course that making backups was easier, and it was also easier to keep track of a project.

This is something that I have really missed in the age of modern computing. I have had some experiences with Delphi where i misplaced packages and source files and actually lost quite a bit of work. I don’t blame Delphi for this of-course, it has been completely my own fault and it all has to do with keeping 5 Mac’s and 3 PC’s in sync 😛

But still, i do miss being able to save an entire project – and I mean everything – in a single file. It was so easy when sending a project to a friend to just ship one single file (today we use SVN naturally but still), and also so much easier when making backups. You have a projects folder that contain X number of project-files, rather than a folder containing thousands of files, including the SVN revisions.

You can clearly see what file is on disk and which is resident

You can clearly see what file is on disk and which is resident by it's glyph

With OP4JS I’m bringing this old trend back. So you can finally mix and match between the “normal” way of organizing your project (one file per unit + project file + dependencies) or the old school “packaged” way (all files stored inside the project file). You can also keep some files resident and others external. Good if you want to share a unit with someone or just downloaded something from the net.

Import versus reference

Under vanilla Delphi you don’t import files, you reference them (explicit or implicit). I made a small twist to this concept so that if your project contains a file with the same name as an RTL file – it will always use that instead. If you chose to open an RTL file you are always given the option to create a duplicate – inside the project file. That way you can create your very own version of the RTL file without screwing up the system. It’s also invaluable during the development of new RTL files and bug-fixing the system.

Or good fun if you want to “mod” the RTL 🙂

delphi OP4JS

Asm sections? You betcha!

Posted on 28.11.2011 by Jon Lennart Posted in Developers log 6 Comments
OP4JS about to go Alpha

OP4JS about to go Alpha

I posted a picture of the OP4JS pre-Alpha testbed to my Facebook group, and a member found it interesting that it had an ASM section in the code. How can there be an ASM section in a system that targets JavaScript you wonder?

Well, assembler for OP4JS is basically what assembler would be to a real Delphi application. In this case: raw JavaScript. Eric Grange, my friend and author of our compiler, has done a great job on transposing classical Object Pascal terminology onto the (let’s face it) bewildering typology of JavaScript.

Take this simple procedure for instance:

procedure TMyObject.Testing;
var
  mRef: TObject;
begin
  mRef := tagRef;
  asm
    (@mRef).style.width=100 + "px";
  end;
end;

What we do here is to first get a handle to the our tag (the tagRef is a public property of TW3TagObject, the class TW3CustomControl inherits from). We then enter the ASM section, use that reference to access and alter the width style property. Ofcourse you dont have to deal with this stuff unless you want to, because OP4JS will ship with a rich set of controls ready to be used. And rolling your own controls is so simple it’s almost ridicules.

The squiglies

But why the @ prefix you wonder? Well, when we obfuscate our code (make it unreadable, or less “stealable” for the average hacker), all the names of variables and methods are altered. As such, the compiler needs to be able to quickly figure out if you are using a JS based variable or an Object Pascal variable. So all Object Pascal variables have to be prefixed with the @ character. Due to the nature of Javascript you also need to isolate direct references to object fields and native fields inside ( [ .. ] ) sections, like in this example:

asm
  (@self.FWidth) = parseInt( (@mRef).style.width );
end;

Where did my pointers go?

JavaScript don’t have pointers, at least not in the proper sense of addresses and memory buffers. What it does have are object references and data references (it also has a weak reference counted garbage collector). So under OP4JS we dont have a type called “pointer” because it would screw up the reality of compiling to JavaScript. Instead, TObject serves the function of a universal object reference, and variant serves as a universal data reference. Variants are special however, because we dont have any operators dealing with it directly (so you cant write: A:=1 + someVariant). The variant type is just used to transport data from one method to another.

But, all the standard types are there: string, boolean, float, integer and so on. You also have records, interfaces and enumerations to play with. It really is a neat system once you get the hang of it.

  function getSomeData: Variant;
  begin
    asm
      /* return a data structure */
      @result = {first:"hello",second:"hello2"}
    end;
  end;

  procedure handleSomeData(aValue: Variant);
  begin
    asm
      /* access the data structure passed in */
      alert(@aValue.first); //will show "hello"
    end;
  end;

Super simple custom control

To demonstrate how extremely simple it is to create your own controls under OP4JS, let’s make a scroll-text. As you probably know HTML have a tag called marquee that scrolls text in a variety of ways. It has been called an evil tag because it consumes a lot of CPU speed (and that part is very true), but just for the hell of it – let’s make a super-simple OP4JS version of it:


unit myscroller;

interface

uses w3system, w3components;

type

TW3Marquee = Class(TW3CustomControl)
private
  FText:    String;
  procedure SetText(aValue:String);
public
  Property  Text:String read FText write SetText;
End;

implementation

procedure TW3Marquee.SetText(aValue:String);
Begin
  //Keep the text
  Ftext:=aValue;

  // Cheat and inject the tag into our innerHTML
  // This works because TCustomControl has already created
  // a tag for us. So we just inject the content
  innerHtml:='<marquee style="'
  + 'font-family: verdana;'
  + 'width: 100%;'
  + 'height: 100%;'
  + '-webkit-marquee-increment:3px;'
  + '-webkit-marquee-speed:fast;'
  + '-webkit-marquee-direction:backwards;'
  + '-webkit-marquee-repetition:infinite;'
  + '">' + FText + '</marquee>';
end;

end.

Naturally this is just a quick example. A fully functional and quality control would have a slightly different layout. There we would isolate the marquee in it’s own tag object. But the approach is perfectly valid, although a bit slap-dash 🙂

OP4JS does not work by injecting text into the DOM, that is to slow. We create tag objects via the Javascript API and access our objects by reference. This is why OP4JS apps are much faster than those produced by other JS compilers. We try to avoid the use of getElementById() because it results in poor performance.

Console and gaming applications under OP4JS

Posted on 10.11.2011 by Jon Lennart Posted in Developers log 5 Comments
A simple console app

A simple console app

OP4JS is getting near to completion for each day that passes. We are currently implementing the final project types which are: console and gaming. Yes you read right – console.

Console

A console application under OP4JS is basically a visual project, but where an instance of TW3Console occupies the majority of the screen. It is meant for testing purposes (for now) where you want a quick and easy project type just to test out theories and play around with routines that doesn’t require forms.

We do have more plans for the console in future versions of OP4JS:

  • Command registration (think TActions but with params)
  • Built in REST command for testing http services
  • Pipe output to email

At present the console application supports WriteLn() which outputs both to the screen and to the actual console javascript object. This is handy because it means you can use XCode to see the output “live” if you want to (or any other remote debugger).

Gaming

The generic gaming project type is very simple, basically it puts safari mobile into full-screen, plasters a canvas in the view-port and uses a high-speed timer to force maximum redraw-rate. It is up to you to load in pictures and draw them using the methods in the canvas object.

Since i have coded a lot of 2d platform games earlier, you can expect to see a game library coming out as soon as the product has shipped. In fact it’s one of the things i’m eagerly looking forward to working on.

 

Console HTTP Log OP4JS REST

Hardware accelerated webkit animations

Posted on 30.10.2011 by Jon Lennart Posted in Developers log

Working with hardware accelerated webkit animations under vanilla Javascript can be daunting. First of all it takes a while to understand the interrupt driven nature of the webkit engine (or “trigger” based is perhaps a more familiar word to us Delphians) and secondly because there are actually two types of animations (transitions), explicit and non-explicit (animations), which adds to the complexities.

Under OP4JS we have started out by supporting animations only, which basically means that you can trigger a pre-defined animation using either TNamedAnimation or any of our ready-made animation classes. If you wish you can trigger non-explicit animations (or transitions) as much as you like, but you will have to set the tag properties and css values yourself. The heart of our animation system resides in the W3Effects.pas file that is going to ship with the RTL – and you can expect it to grow once we start to issue updates and service packs.

Let me show you how easy it is to setup a hardware acellerated animation and play it:

[sourcecode language=”delphi”]
Procedure TForm1.HandleEffectDone(Sender:TObject);
Begin
TW3NamedAnimation(sender).free;
end;

Procedure TForm1.MoveHeader;
Begin
FEffect:=TW3NamedAnimation.Create;
FEffect.AnimationName:=’HEADER-MOVE’;
FEffect.Duration:=0.80;
FEffect.ExecuteEx(FHeader,NIL,HandleEffectDone);
end;
[/sourcecode]

And in our CSS file we define our animation (this will be automated in a future version of OP4JS):

[sourcecode language=”CSS”]
@-webkit-keyframes HEADER-MOVE {
from {
left: 100%;
top: 0px;
} to {
left: 0px;
top: 0px;
}
}
[/sourcecode]

Voila. That’s all it takes to make a control references by FHeader (or any control you want) to fly across the top of the screen using hardware acceleration (when available, not all platforms supports it directly and resort to software).

Keep it simple

It’s easy to go overboard with effects like this so try to keep in mind that every phone model is unique and have different performance levels. I am currently using 2 hardware accelerated “movers” to navigate between forms, and the difference between the iPhone 3GS and 4G is quite dramatic. It seems 3GS does not support hardware unless your control is placed directly on the document. So while it’s easy to spin things around – we must be prudent in when we use these things. Nothing is worse than an app where the effects get in the way of the actual substance.

 

Animations CSS3 hardware OP4JS webkit

TApplication coming to a close

Posted on 28.10.2011 by Jon Lennart Posted in Developers log
Always when you least need it

Always when you least need it

Yes, I know. This month was meant to be a very active time for OP4JS but sadly Norwegian weather brings with it complications like colds and the flu. So in short i have spent nearly 3 weeks off the grid with nothing but fevers, allergies and sneezing. So to those of you eagerly awaiting the Alpha release of OP4JS I am sad to inform you that we might have to push the date forward to make up for lost time.

Be that as it may my health is finally picking up after the onslaught of germs, viruses and weather up here – so for the past week I have been eagerly working on the object model, in this case: TApplication.

Much like under Objective C (which is the official language you use to create iOS applications, although you can now use alternatives) TApplication is the root controller object. It is in charge of creating a visible screen, kick-starting your application code, which in turn creates forms and register them, which is ultimately injected into the viewport. The viewport (or visible area) being a child object of TScreen – the place where forms do their thing.

Why go to so much trouble you ask? Well, it has to do with several aspects of HTML5 but first and foremost it deals with clipping and scrolling. You want your forms to slide in without problems under any webkit based browser (be it Safari Mobile or Chrome for Android). Secondly, we are trying to avoid having different TApplication models for each of our project types. We are currently aiming for 3 project types:

  • Graphical application (“form” based”)
  • Console application (for test purposes)
  • Game application
The nested layout made visible

The nested layout made visible

TApplication have to be dynamic enough to suit all 3 variations – and we also want to safeguard ourselves for the future where more project types come into play (libraries being on top of the list).

It also have to manage the forms you add to your application correctly, which means taking care of transitions, pre-positioning forms prior to movement and many more details. But thankfully we found a solution that is simple, elegant and robust. And no external dependency either. We might even drop jQuery soon because quite frankly: we dont need it.

On your right is view of how we organize things. The white color is from the actual HTML5 document, the red color is TScreen – which in turn has a child TCustomControl called viewport (green).

The benefits of this layout is that you can (if you want to) add a global header directly to the TScreen object. So instead of each form descending from TW3HeaderForm (which as the TW3Header control built into it) you can just create one header for the whole app. Of-course this means that your forms have to change the title and deal with the back and next buttons directly – but that’s just as easy as it would be in ordinary Delphi.

The second benefit is more or less the same, except for the footer. Many native apps have main view controller that introduces a fixed header and footer, typically containing a tab-bar at the bottom and a toolbar on top. We want to support this because it solves a lot of problems (and also makes you apps faster. The less objects the faster it runs, that’s how it works in Delphi as well).

Well — I better get back to work!

Upcoming features

Your first OP4JS custom control

Posted on 05.10.2011 by Jon Lennart Posted in Documentation 1 Comment
There is a lot of work behind OP4JS

About 0.1% of the total OP4JS RTL system

Since the basic framework is nearing completion at high speed (although some modifications might appear) I thought it could be interesting to demonstrate how to create your very own custom control under OP4JS.

In the Delphi world there are two archetypal programmers: Those that stick to the high level interface of Delphi, meaning that they only use pre-made controls and rarely go beneath the bonnet so to speak – and the second group which create components, packages and love to fiddle around with low-level coding. This type of stereotyping is something more or less unique to RAD languages (which would include Delphi, Lazarus, Visual Basic, Real Basic and languages that are “design” based). In more mature languages like C++, Delphi (yes delphi is just as low level as the C++) or C# low-level work is almost unavoidable. But with Object Pascal you at least have a choice (!)

With OP4JS we have tried to retain much of the HLA (high level abstraction) of Delphi, but the system demands that if you want something unique – you have to create your own controls in order to stand out. If not, you might as well go with the many template-based “app machines” out there that produce programs that all look and feel the same.

The basics of a control

There are two types of controls you can create under OP4JS: Graphical controls and ordinary parent/child controls (like you are used to from Delphi). A graphical control is an object that contains a HTML5 graphics context and canvas, which means you have to draw it yourself. This is good for things like games, charts or anything that cant be represented using “normal” html.

The second type, which is the one 90% of all the standard controls that ship with OP4JS derive from, is TCustomControl. So let’s have a look at how setting up a fancy iPhone header looks like:


type

TW3HeaderControl = Class(TCustomControl)
private
  FLabel:     TLabel;
  FBackBtn:   TW3ToolButton;
  FNextBtn:   TW3ToolButton;
Protected
  Procedure   Resize;Override;
protected
  Procedure   InitializeObject;override;
  Procedure   FinalizeObject;override;
  Procedure   StyleTagObject;override;
End;

Under Delphi you would probably expect to see a constructor and destructor in the above code, but under OP4JS we try to synchronize the number of steps taken to establish a control (i.e number of resize and position operations). So to solve this we have introduced 3 new methods: InitializeObject, FinalizeObject and StyleTagObject. As the names imply you create any sub-controls and initialize your variables in InitializeObject (just think of it as your constructor), you destroy those instances in FinalizeObject, and you apply any extra styling or property alteration in the StyleTagObject method.

Clever styling

When a control is in the state of creation, it automatically set it’s own style class (think html here) to the name of it’s class. So in order to give our little control a nice look – we edit the default style sheet (this is automatically created when you create a new application) and make it look like a true iPhone header. The rule of thumb is: The name of the CSS class always matches the name of the OP4JS control:

.TW3HeaderControl
{
	background-image:-webkit-gradient(linear, left top, left bottom,
		from(#b2bbca),
		color-stop(0.25, #a7b0c3),
		color-stop(0.5, #909cb3),
		color-stop(0.5, #8593ac),
		color-stop(0.75, #7c8ba5),
		to(#73839f));
	border-top: 1px solid #cdd5df;
	border-bottom: 1px solid #2d3642;
	-webkit-box-shadow: rgba(33, 33, 33, 0.2) 0px 1px 1px;
}

Adding behavior

If you don’t know anything about CSS or HTML, don’t worry, you can always copy a style you like from the default skin, and there are plenty of examples around the Internet to learn from (or just get a good book, that would save you a lot of time). OK now we need to add some code to our unit to make it come alive:

Procedure TW3HeaderControl.InitializeObject;
Begin
  inherited;
  FLabel:=TLabel.Create(self);
  FLabel.BorderStyle:=bsDotted;
end;

Procedure TW3HeaderControl.FinalizeObject;
Begin
  FLabel.free;

  if assigned(FBackBtn) then
  FBackBtn.free;

  if assigned(FNextBtn) then
  FNextBtn.free;

  inherited;
end;

Procedure TW3HeaderControl.StyleTagObject;
Begin
  inherited StyleTagObject;
end;

Procedure TW3HeaderControl.Resize;
var
  wd,hd:  Integer;
  mTemp:  Integer;
  dx:     Integer;
Begin
  wd:=Width;
  hd:=Height;

  mTemp:=wd;
  dx:=4;
  dec(mTemp,4); //left margin
  dec(mTemp,4); //Right margin

  if  assigned(FBackBtn)
  and (FBackBtn.Visible) then
  Begin
    //space between "back" & label
    dec(mTemp,FBackBtn.width);
    dec(mTemp,2);

    //offset the left edge of the label
    inc(dx,FBackBtn.Width);
    inc(dx,2);

    // position the back-button
    FBackBtn.Left:=4;
    FBackBtn.Top:=4;
  end;

  if  assigned(FNextBtn)
  and (FNextBtn.Visible) then
  Begin
    //space between label & "next" button
    dec(mTemp,FNextBtn.width);
    dec(mTemp,2);
    FNextBtn.Left:=mTemp;
    FNextBtn.Top:=4;
  end;

  FLabel.left:=dx;
  FLabel.top:=4;
  FLabel.Width:=mTemp;
  FLabel.Height:=Height-8;
end;

Why all that code? First of all because it’s just a quick example and secondly, because a typical iPhone header have 3 parts: A back button, a next button and some text in the middle. The above code checks to see if you actually have created a back or next button and shrinks the text area accordingly. Let’s see how it looks so far:

That was easy enough

That was easy enough

I have set the label to have a dotted frame just to make it easier to work with, we will of-course remove the frame all together later. But now, let’s add some more methods to the class interface. We want to expose the label object to give the user access to it’s full capabilities (caption, font, background, orientation and all the rest), and we also want both back and next buttons.

But, we want to keep resources to a bare minimum, so we will use the old “need” trick and only create the buttons when asked for. So the buttons will only be created when you access them:

TW3HeaderControl = Class(TCustomControl)
private
  FLabel:     TLabel;
  FBackBtn:   TW3ToolButton;
  FNextBtn:   TW3ToolButton;
  procedure   ReleaseButtons;
  Procedure   NeedBackButton;
  Procedure   NeedNextButton;
  function    getBackButton:TW3ToolButton;
  function    getNextButton:TW3ToolButton;
protected
  Procedure   Resize;Override;
protected
  Procedure   InitializeObject;override;
  Procedure   FinalizeObject;override;
  Procedure   StyleTagObject;override;
public
  Property    BackButton:TW3ToolButton read getBackButton;
  Property    NextButton:TW3ToolButton read getNextButton;
  property    Title:TLabel read FLabel;
  Property    Options:TW3HeaderButtonOptions read FOptions write setOptions;
End;

And the implementation for our new methods are (this is just a quick example):

Procedure TW3HeaderControl.NeedBackButton;
Begin
  // Create object on the fly if required
  if not assigned(FBackBtn) then
  Begin
    BeginUpdate;
    FBackBtn:=TW3ToolButton.Create(Self);
    SetReSized;
    EndUpdate;
  end;
end;

Procedure TW3HeaderControl.NeedNextButton;
Begin
  // Create object on the fly if required
  if not assigned(FNextbtn) then
  Begin
    BeginUpdate;
    FNextbtn:=TW3ToolButton.Create(Self);
    SetReSized;
    EndUpdate;
  end;
end;

function TW3HeaderControl.getBackButton:TW3ToolButton;
Begin
  NeedBackButton;
  result:=FBackBtn;
end;

function TW3HeaderControl.getNextButton:TW3ToolButton;
Begin
  NeedNextButton;
  result:=FNextBtn;
end;

procedure TW3HeaderControl.ReleaseButtons;
Begin
  if assigned(FBackBtn) then
  Begin
    FBackBtn.free;
    FBackBtn:=NIL;
  end;

  if assigned(FBackBtn) then
  Begin
    FNextBtn.free;
    FNextBtn:=NIL;
  end;
end;

The final product

To use our new control, all we have to write (in our Form’s InitializeObject for instance) is something like:

FMyCoolHeader:=TW3HeaderControl.Create(self);
FMyCoolHeader.BackButton.Caption:='Back';
FMyCoolHeader.BackButton.onClick:=HandleBackButtonClicked;
FMyCoolHeader.Title.Caption:='My cool header!';

And voila – we have a nifty iPhone header that looks and feels like the real thing 🙂

Easy but effective

Easy but effective

Notes and addendum

This example is very, very simple. It was put together in 5 minutes just to demonstrate how easy it is to get going and is in no-way an example of code quality or approach. I can think of 1000 ways of making a better header control (the one that ships with OP4JS has a lot more code and does not create buttons this way, and yes — exceptions and error handling is a must).

CSS graphics iOS Smart Mobile Studio tutorial

Control complexity and mobile resource management

Posted on 04.10.2011 by Jon Lennart Posted in News and articles 2 Comments
This is not just a picture, but actually the background set for a picture

This is not just a picture, but actually a multi layered view. The buddha is a background for an image placeholder. Quite dynamic and neat

Products like Embarcadero Delphi comes with a rich set of controls ready for use in your applications. If we compare the resource demands of these controls today (Delphi XE or XE2) to those that once shipped with Delphi 1 – or Delphi 7 even, the amount of resources a well designed form consumes has grown exponentially over the years.

As the operative system was grown more complex both in terms for functionality, responsiveness, mobility and the developers need for modern features, the amount of methods and auxiliary classes connected to a single control has become very large. As a result, the amount of memory and CPU requirements have grown with it.

The mobile scene

One of my primary concerns when we sat down to talk about OP4JS control library was simply that it would be over-kill to even attempt to emulate the VCL under javascript. In my notes the primary points were:

  • The amount of JavaScript generated would exceed the restrictions of these devices
  • The HTML5 architecture is incompatible with classical VCL programming
  • The controls would be to slow for practical use

Thankfully my worries were unfounded on all accounts, because we have more or less built a VCL clone. It is and has been quite a challenge. As you may know HTML5 introduces a high-level interface onto ordinary html. It is different not so much in terms of syntax, but rather in philosophy, inspired no doubt by the MVC (model view controller) paradigm imposed on the world by Apple computers. In short, the CSS styling represents the “view” part, the actual html tags the “model” and Javascript the controlling factor. Javascript is what provides behavior to otherwise empty, stateless constructs.

Getting these things to even resemble the VCL has been, well, let’s just say I havent played with my kids in a few weeks.

Doing the math

CSS transitions and events

CSS transitions and events

Luckily, the complexity versus efficiency argument is turning in our favour. Delphi developers like myself have a tendency to over-think the actual needs of our customers, and inside our own heads we are always trying to outsmart other programmers that may – or in most cases – may not be going over our code with a fine tooth comb. This can either drive us to excel at what we do or into obsessive nerds that polishes a piece of code so long – that the platform is dead if he ever finishes.

So, once in a while it’s wise to do a sanity check on your code-base (and your own expectations). Fact is that mobile apps are for the most part quite lightweight. If we for sake of argument say that a mobile app has 10 forms (or views if you prefer) and each of these views is populated by 20 controls. Some controls are composite, meaning that they have child controls (like a toolbar which uses a buttons) while other are vanilla, run of the mill stuff like labels and lists. You may also have a database running under the hood as well.

Adaptable and suitable

So an app consisting of 200 javascript objects is really not that huge. It would result in quite a bit of generated code of-course, but the browser chews through this like it was nothing at all. And you wouldn’t even be close to the limitations set down by Apple or Google regarding size. Strange as it may seem – my test app written in Op4JS both loads and executes faster than it’s native counterpart written in C# (which compiles to a single binary on iOS). The only exception being complex graphics (which you would normally use a DIB library for) and heavy-duty number crunching. But those are things you don’t want to have on your phone anyways. It’s possible of-course, but not practical.

To me at least, mobile development is about information and communication and presentation. It’s about getting or storing data and presenting it on a portable device in a practical manner. It’s also about using the format in a way that makes sense to the consumer.

External resources

  • Model View Controller – Wikipedia article
  • C# Mono Touch – Xamarin website
  • HTML5, A vocabulary and associated APIs for HTML and XHTML, WC3 reference
  • Embarcadero Delphi website
HTML5 javascript Smart Mobile Studio

Focus, callstack and recursive processing

Posted on 29.09.2011 by Jon Lennart Posted in Documentation 6 Comments
Call stack limitations

Call stack limitations

The world of mobile computing is getting better and better, but there are some limitations when dealing with smart gadgets running iOS or Android. The first thing is obviously the speed, which doesn’t even come close to what an average home computer can muster. Even my 5 year old test machine can outrun any mobile device without making so much as a dent in the cpu-o-meter.

The second limitation people are going to discover, depending of-course on the line of work you do, is that mobile devices is the proverbial banker when it comes to memory – implying that your call stack is but a microbial-fraction of what we are used to. What does this mean? Well every time you call a method under Javascript, you eat up one call-slot. If this procedure in turns calls another, and another (and so on) it quickly gobbles up the meager call stack limit. The size of the call stack is varied and depends on the vendor, as of writing iOS is sticking to it’s near obsolete range of 100 recursive calls while Android is said (I couldn’t find any official information on this) to have a call stack of about 800.

To kiss or not to kiss, that is the question

Kiss (keep it simple stupid) is one way to go when it comes to mobile development. But there are times when you must resort to classical speed mechanisms to reach the full potential of a system. As such I am in the process of optimizing the base-classes for speed and simplicity (some form of balance preferably). The method is really simple and it’s known as loop expansion (or just “unrolling”). Let’s for sake of argument say you have a control with a lot of child objects, like a grid or a list. Instead of doing a simple for/next loop, like this:

[sourcecode language=”delphi”]
Procedure TMyObject.DoSomething;
var
x:Integer;
Begin
for x:=0 to FChildren.Count-1 do
Begin
process(FChildren[x]);
end;
end;
[/sourcecode]

The above example is perfectly valid, but it’s quite slow depending on the data-load you expect. A list control could be expected to handle hundreds if not thousands of elements – so we want to speed things up and minimize loop time:

[sourcecode language=”delphi”]
Procedure TMyObject.DoSomething;
var
mLongs:Integer;
mShort:Integer;
mCount:Integer;
mIndex:Integer;
begin
mCount:=FChildren.Count;
mLongs:=mCount shr 3;
mShort:=mCount mod 8;

while mLongs>0 do
Begin
process(FChildren[mIndex]);inc(mIndex);
process(FChildren[mIndex]);inc(mIndex);
process(FChildren[mIndex]);inc(mIndex);
process(FChildren[mIndex]);inc(mIndex);
process(FChildren[mIndex]);inc(mIndex);
process(FChildren[mIndex]);inc(mIndex);
process(FChildren[mIndex]);inc(mIndex);
process(FChildren[mIndex]);inc(mIndex);
dec(mLongs);
end;

while mShort>0 do
Begin
process(FChildren[mIndex]);inc(mIndex);
dec(mShort);
end;
end;
[/sourcecode]

Speed-wise, at least when it comes to crunching fixed data like pixels or typed JS arrays, is nearly incomparable to the first approach. It obviously produce more code – but the benefits are just to good to ignore (roughly 4 times as fast).

As long as your final build does not exceed 10 megabytes, which is Apple’s limit on single javascript files, it’s not a problem (and that would be a huge, huge project if you ask me).

Men first, women and children last

When doing recursive calls that affect an entire object model you have to deal with the men first, meaning of-course those elements that does not have children attach to them (oh this is gonna get me into so much trouble if my wife reads it). Why? Because we want to minimize the number of recursive calls (or steps taken) a control has to make. Let’s use the simple formula to demonstrate (this would also be loop expanded in the final release):

[sourcecode language=”delphi”]
Procedure TMyObject.DoSomething;
var
x:Integer;
mCount:Integer;
mStack: TObjectList;
mObj: TObject;
Begin
//avoid multiple calls to getCount in FChildren array
mCount:=FChildren.Count-1;
for x:=0 to mCount do
Begin
//minimize call to getItem in FChildren array
mObj:=FChildren[x];
if mObj.count=0 then
// No kids? Do singles first
process(mObj) else
Begin
//kids? Ok, we’ll handle that later
if mStack=NIL then
mStack:=TobjectList.Create;
mStack.add(mObj);
end;
end;

if mStack<>NIL then
Begin
mCount:=mStack.Count;
while mCount>0 do
Begin
mObj:=mStack[mCount-1];
process(mObj);
dec(mCount);
end;
mStack.free;
end;
end;
[/sourcecode]

And last but not least, the “process” method should be inlined if possible, thats 50% of the point here. If you can avoid a secondary call – then avoid it, that’s how you cut down on call-stack overload and as a nice benefit you get a speed boost.

Notes

#1 [29.09.11, 18:31]: Eric Grange pointed out (as did two readers on this page) that the same effect will happen if we apply FChildren.Count-1 and start from zero. That would be slightly faster to since we dont execute a continous subtraction of the index. A clear error on my part.

#2 [29.09.11, 18:31]: Interestingly, the -1 trick was originally used for string processing (hence starting at 1) and has nothing to do with speed per-see, except that you save an “if FChildren.Count>0 then” in some languages. But this tiny advantage is indeed lost by the use of [-1] in the loop itself. Some basic compilers will execute the code even if FChildren.count =0. This is an old habit from the days of Amiga BlitzBasic programming.

#3 [29.09.11, 18:35]: Also the “process()” call should only be concidered pseudo code. It’s the loop expansion that’s being demonstrated. Preferably you would work with the data directly at this point rather than call another proc, since the whole point is to limit the number of calls while speeding up a process. It’s not meant as a literal example, but as the bare-bones of a technique.

General programming Smart Mobile Studio tutorial

The elegance of Javascript

Posted on 24.09.2011 by Jon Lennart Posted in News and articles

Two year ago I used to laugh at Javascript, but the more I play with it these days, I find myself enjoying the experience. It cant be compared to Delphi on any level, but there are some features that just blows your mind. I find myself spending a lot of time in Besen, a javascript interpreter and bytecode compiler written in Delphi – just for the sheer fun of it.I like the way dynamic parameters (what we would call array of const) are implemented and that they remain hidden to the entrypoint. This allows you to do do a form of undercover overloading. Unless the method is aware of _the calling interface_ (not the other way around like we are used to) then it could support only a sub-set of the intended functionality. By patching the original function and chaining to it you basically can “emulate” overloading based on condition rather than explicit call. This opens up for some clever API designs.I love the ability to pick values based on conditions, but compacted into a single line without having to invoke a equating entity:[sourcecode language=”javascript”]someValue = (backwards ? (100-percent) : (percent-100)) + "%";[/sourcecode]Having said that there are some aspects of javascript that makes me ponder the collective wisdom of W3C. As a fail-safe i usually add an “if” section to thoughts like this, because otherwise mother nature will go out of her way to disprove me. I can only imagine the work of cleaning up after Netscape and Microsoft, trying to play ball with Opera while Webkit came sneaking in the back door.

Media mayhem

The factors are many, yet the organization of the latest HTML5 multimedia functions is neither fish nor foul. It’s not truly object(ive) in the C++/Delphi sort of way, nor is it linear like basic or old school pascal. It’s both, and none of them at the same time . which makes it difficult to set up generic rules that would apply everywhere in our object model. The only solution is to let go of what the W3C has marked as “legacy features”. Which is hard to do when they produce results so easily 🙂

Threading, security and overkill

Another feature that seems like overkill, is the javascript notion of threads (read: blue threads), referred to as web-workers in the W3C specs for HTML5 (actually better info on Apple’s docs for safari). Im not sure what i was expecting, but i was sort of hoping to use threads to crunch pixel data. You can do that, but you are unable to hook the reference since it runs in a different context.

  • All communication between a worker and the DOM is through a message pipe
  • The only datatype you can pass to and from is a blob
  • All bindings are late-binding
  • Worker code cannot reside in the main document

Thankfully I found a “loophole”, I’ll document it later – but it wont make it into OP4JS because it’s basically a hack. You can use TW3GlobalStorage (one of our classes) as a mirror cache for the data – and it’s actually faster than creating, populating and moving a blob into the thread context. Although it does require initialization ofcourse. But i suspect that loophole will be closed in the next release.

External references

  • Besen – SourceForge project page 
  • Web workers – W3C documentation
javascript

Snippets and comments, simple but effective

Posted on 23.09.2011 by Jon Lennart Posted in Developers log 2 Comments

The OP4JS IDE (integrated development environment) aims to be simple, neat and clean. There are two reasons for this: First of all there is no point trying to catch up with products that have been in development for nearly two decades – and secondly because we don’t necessarily agree with the route some companies have taken with regards to their IDE’s.

Delphi 7, the most popular IDE ever

Delphi 7, the most popular IDE ever

If you ask a Delphi developer what his all-time favorite IDE is, chances are he is going to put the finger somewhere between Delphi 5 and Delphi 7. The environments back then were responsive, lightweight and easy to work with. The interface was so intuitive that even without formal training it required little effort to learn how to use the it. For me personally Delphi 7 is the undisputed king of IDE’s with one exception, like XCode it was a multi windowed environment which is a feature that messes up your work-space.

So for our IDE we turned the idea on it’s head. Since we are starting from scratch – why not use this opportunity to simplify things again? We have neither the time or manpower to catch up with the likes of Delphi, XCode or MonoDevelop. But what we do have is a keen eye on details and a desire to keep things effective.

Back to basics

What are the basics of a good IDE? What do we need to get our work done quickly and efficiently? What do I need?

  • Tabbed source editing
  • Syntax highlighting
  • Method proposal (press “.”)
  • Parameter hints
  • Project tree-view
  • Unit tree-view
  • Property inspector
  • Form designer
  • A snippet library
  • A proper note system
  • A help system designed for human beings
  • CTRL + mouse to quickly locate a symbol (or equivalent functionality)

Text matters

Use notes as your scrap book

Use notes as your scrap book

If you are anything like me you probably have a desktop littered with notes, books, gadgets and coffey mugs. Once a week I give my desk a run over, clean out the thrash and try to organize my notes in a logical, easy to use fashion. I also have a couple of huge whiteboards with important things kept in check by magnets. Fact is, text matters. It is through words that we formulate and transfer ideas.

Sadly the important of text and keeping our ideas organized havent really been implemented in most development environments. Delphi has a skinny “to do” list which is added to the project. I know a couple of people that use it – but let’s be honest: it’s pretty meager stuff. I mean, if I want to generate some form of documentation from my source-code, wouldn’t it be better to keep my notes in one place and my code in another? I’m not suggesting that we should stop commenting code, far from it, I’m simply saying that code-comments is more than enough for the code part. Adding documentation, ideas, who-did-what, credits and examples in the code is a bit excessive.

In short, OP4JS supports comments for every element belonging to the project. You can even comment on images if you like. But it’s not a simple text field or a memo – it’s a full editor. The view will actually split to make room for your notes and as such you can jot down everything (or just use it as a scrap-book when trying out new ideas). The comment editor has proven instrumental when porting Javascript to Object Pascal, because I can paste the JS code in the comment editor and convert it method by method with both sources in plain view. It’s also very handy when it comes to keeping track of who did what and where you last worked, just in case you forget between sessions.

Snippets as a resource

A snippet is just a piece of code that you use often or that you found online. Handy enough to keep but not essential enough to deserve it’s own unit. I haven’t really used snippets before but after implementing it – it’s quite addictive (!) Whenever I go online to search for a solution or study a particular task – the snippet library functions as my extended clipboard, if that makes any sense.

Snippets is an underestimated resource

Snippets is an underestimated resource

borland delphi ide

Inline graphics, orientation and animations

Posted on 20.09.2011 by Jon Lennart Posted in News and articles 5 Comments
CSS based chevrons

CSS based chevrons

This week we are seeing some very cool ideas finally maturing onto the visual canvas. First and foremost: inline graphics. Under the traditional HTML paradigm resources such as images or soundfiles were always losely bound external entities. So before an image could be used it naturally had to download its content from a webserver or read it from a local file. But under HTML5 all of that goes out the window, because now you can embed your graphics as Base64 encoded characters. In short: transform your graphics into text and they can be applied anywhere.

So today our TW3MenuListItem class got automatic support for inline glyphs. The default glyph is of-course the ordinary iPhone chevron picture, but when TImageList is done you will be able to apply just about anything. Since this is HTML5 you can also make use of your styles to add further “bling” to your elements – but we will leave that part up to you. Our job is to deliver a system with the basic iOS widgets ready – but object pascal style, which means easy to use, easy to work with and as little fluff as possible.

Orientation

Angles should be used prudently

Angles should be used prudently

Another cool feature that is now going through the test phase is the Angle property. All components that derive from TCustomControl have this property, and as the name suggests you can use it to rotate the control as you see fit. While it’s not the biggest feature in the world it does open up for a more colorful expression in the user interface. Want a yellow price banner over a product? Put a label on it, set the color and put -30 in the degree property.

Animations

This feature is my favorite, but it’s also the most complex to capture under object pascal. Webkit allows you to define animation sequences, which can then be applied to a html element or a style. You then use a trigger rule to activate the animation. The cool part is of-course that most of these effects have hardware support – so they run smoothly and without any flicker what so ever.

Since Javascript is not the fastest horse in the stable, at least not on devices like iPhone 3GS – it’s very important to use hardware accelerated animations as much as possible. You don’t want to rotate a picture by manipulating the degree property under a timer. It works of-course, but the results cant be compared to the effects produced by hardware accelerated CSS3 animations.

But of-course, under OP4JS you don’t have to worry about that

 External references

  • CSS Backgrounds and Borders Module Level 3 – www.w3.org
  • The document object model – www.w3.org
animation CSS HTML5

Something is coming…

Posted on 01.09.2011 by Jørn E. Angeltveit Posted in News

This website is currently under construction. Over the next days and weeks more and more material will become available here – so stay tuned for a very exciting product 🙂

Pages

  • About
  • Feature Matrix
  • Forums
  • News
  • Release History
  • Download
  • Showcases
    • The Smart Contest 2013, Round 1 – Graphics
  • Store
  • Documentation
    • Creating your own controls
    • Debugging, exceptions and error handling
    • Differences between Delphi and Smart
    • Get the book
    • Getting started
      • Introduction
      • Local storage, session storage and global storage
      • Application architecture
      • The application object
      • Forms and navigation
      • Message dialogs
      • pmSmart Box Model
      • Themes and styles
    • Layout manager
    • Networking
      • Loading files
      • TW3HttpRequest
      • TW3JSONP
    • Prerequisites
    • Real data, talking to sqLite
    • System requirements
    • Project types
      • Visual project
      • Game project
      • Console project

Archives

  • December 2019
  • December 2018
  • November 2018
  • July 2018
  • June 2018
  • February 2018
  • September 2017
  • April 2017
  • November 2016
  • October 2016
  • September 2016
  • April 2016
  • March 2016
  • January 2016
  • October 2015
  • September 2015
  • July 2015
  • April 2015
  • January 2015
  • December 2014
  • October 2014
  • September 2014
  • August 2014
  • July 2014
  • June 2014
  • March 2014
  • February 2014
  • January 2014
  • December 2013
  • November 2013
  • October 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • August 2012
  • July 2012
  • June 2012
  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • November 2011
  • October 2011
  • September 2011

Categories

  • Announcements (25)
  • Developers log (119)
  • Documentation (26)
  • News (104)
  • News and articles (16)

WordPress

  • Register
  • Log in
  • WordPress

Subscribe

  • Entries (RSS)
  • Comments (RSS)
  • Prev
  • 1
  • …
  • 11
  • 12
  • 13
© Optimale Systemer AS