Titanium Ninja

App and module development with Titanium Mobile

tiConf 2013 and New Titanium Modules

@oliviermorandi Discusses native module creation
Courtesy Tipsy & Tumbler Ltd

Almost two weeks ago I had the pleasure to attend tiConf 2013 in Valencia, where, besides getting in touch with lots of awesome developers from all over the world, I held a workshop on native module development for Titanium on both iOS and Android platforms. Here’s the presentation:


During the talk I gave a quick tour on how to start creating modules, with an emphasis on how JS-to-native bindings are structured in the Titanium framework, presenting a set of real-world use cases. Among the others, I mentioned a module for offloading to native code the conversion of XML documents into JSON structures, which wasn’t yet published.

I had this module lying around for several months, so in the past few days I took some time to polish the iOS version and I published it on GitHub here: github.com/omorandi/TiXml2Json. I think it represents a very good start for understanding some of the concepts around Titanium native module creation.

But why shall we need such kind of functionality implemented in native code in the first place? Actually, parsing XML structures through the DOM API is somewhat cumbersome and inefficient, while working with JSON structures is more easily manageable. For doing this we could use any of the JavaScript modules available, like the good XMLTools from David Bankier, however, when the size of the XML string is relevant, the parsing phase can be very slow, thus blocking the execution of our app for a significant and noticeable amount of time. A possible solution is then to do the conversion in native land, achieving better performance. In some cases this may still not be enough, so I also implemented an asynchronous version of the conversion method, which offloads the conversion process on a separate thread, keeping the JavaScript thread free to continue its normal flow, thus adding responsiveness to the client application.

The module exports a very simple API with just two methods:

  • convert(xml)
  • convertAsync(xml, callback)

The former takes an xml string or blob argument and returns the corresponding JSON representation as a JS object. The latter implements the asynchronous version described above, which takes an additional argument for the callback function that will be invoked with the resulting JS object at the end of the process. Internally, the conversion methods use the XML to NSDictionary converter code from Troy Brant.

This week I also published another iOS module: TiAssetsLibrary, which wraps the iOS AssetsLibrary framework with an almost 1 to 1 mapping between the JS and the native API. This module deserves another post where I’d like to talk about performance implications of API design.

That’s all for now. See you all at the next tiConf.

Introducing TiProfiler for iOS

Around four months ago I started experimenting with some custom modifications to the JavaScriptCore library, which is the JavaScript engine used by the Titanium Mobile SDK for executing Titanium applications on iOS. After succeeding in enabling the profiler component provided by JSCore and extracting some relevant profiling data from running applications, I wanted a tool that would allow me to show such information in a manageable way, like the Web Inspector and Developer tools allow to do in Safari or Chrome.

My basic requirements were the following:

  • The tool needed to be able to start and stop the profiler running alongside a Titanium Mobile application executed on the iOS Simulator, as well as to retrieve the collected profiling data
  • The GUI app should be very simple and quick and easy to develop: a web app would be good enough
  • I wanted to be able to show the profiling data (i.e. a function call tree showing the amount of time spent in each function) in the typical expandable tree grid
  • I wanted to be able to quickly show the source code of every referenced function, in order to better understand the data every time an anonymous function was reported

So I started creating a very simple web-based GUI and a node.js server component providing a proxy between the client app and the profiler, and today I’m able to introduce some results, with the following demo screencast:

TiProfiler demo from Olivier Morandi on Vimeo.

This has been possible thanks to the following technologies/libraries:

  • Ext JS: General GUI layout & tree-grid
  • ACE editor: for showing the original source code of the selected application files
  • socket.io: for event-based communication between all the components

The screencast showcases the usage of the three main components involved:

  • The node-based server, used for serving the client app files and for communicating with both the profiler and the GUI
  • The GUI app itself
  • The Titanium Mobile application, built and executed through a custom version of the 2.1.0.GA Titanium SDK, with all the required additions to make the magic possible

The node server gets notified when the Titanium application and the profiler are started, re-broadcasting such events. The web-app, on the other side, issues start & stop commands to the node server, which reflects them to the profiler running inside of the Ti app.

At the core of the system lies a custom version of the TiJSCore library, and some very limited additions to the inner workings of the Titanium Kroll bridge. In particular, besides the basic modifications already mentioned in the previous post, it has been necessary to do the following:

  • modifying the code managing the CommonJS require() function, in order to make both the JS interpreter and the profiler aware of the names of the files being loaded through it
  • decorating the calls to methods of Titanium proxy objects with a representation of their real name, in order to highlight them with something more meaningful than (Function oject). For example a call to Ti.UI.Window.open() now it’s reported as [object TiUIWindow].open: not exactly the JavaScript signature, but quite similar, indeed
  • building a bit of infrastructure in order to allow the profiler to communicate remotely, either for receiving start and stop commands, either for sending the recorded profiling data. Using the iOS port of the socket.io library helped a lot in this context.
  • other minor adjustments (e.g. converting profiling data returned by the JSCore profiler to JSon)

At the moment I’m not planning to release these modifications and additions as open source. I’m still thinking about what to do about them. Actually it would be nice if at some point they could be integrated into the Titanium SDK.

Anyway, I’m willing to share this tool with the Titanium community, letting interested folks to play with it, and report any kind of feedback, so I’ve created a repository on github hosting both the node server and the client app source code.

Originally I was aiming to keep all the modifications to the JSCore library, as well as the corresponding hooks inside the Titanium SDK completely self-contained in a single binary, in order to be able to provide just a simple drop-in replacement for the libTiCore.a library, to be plugged in a standard distribution of the Ti SDK. However, after integrating socket.io on the iOS side, things are a bit more complicated, since socket.io requires the target app to be linked with the Security framework, which is not linked by default in the standard Titanium Xcode template. For this reason, in order to keep things super-simple for anyone interested in this project, I’ve prepared a package containing a custom version of the 2.1.0.GA Titanium SDK that can coexist side by side with the official SDKs provided by Appcelerator already present in the system.

Anybody wanting to follow all the steps, without using the prebuilt package, can download a custom build of the libTiCore.a library, copy it in the ${TI_SDK}/iphone directory of a 2.X.X version of the Ti SDK (where ${TI_SDK} for example is /Library/Application\ Support/Titanium/mobilesdk/osx/2.1.0.GA, open the ${TI_SDK}/iphone/iphone/Titanium.xcodeproj) and add there a reference to the Security framework.

The custom SDK can be used for building, executing and profiling any Titanium application on iOS, with the following, and maybe more, limitations:

  • It doesn’t work for Android targets
  • It can be used only with apps running inside the iOS Simulator: apps should be able to execute on device, but at the moment, no profiling data can be exchanged with the node.js server component. Results of building and running Ti apps on device with such SDK are currently undefined
  • The client app is currently very limited

Wrap up

Where do we go from here?

I have a bunch of things I’d like to improve/work on in the very near future. Here are some:

  • Replace the currently very limited web-app with the client from the Node Inspector project. This is actually a fork of the WebKit Web Inspector that can be used to debug and experimentally profile node.js applications. Modifying this to work with my server should be fairly easy
  • Improve the way in which anonymous functions are reported. It is true that these functions are actually unnamed, but in most cases they’re usually referenced through a variable or an object member. I’d like to leverage the features of the super-cool Esprima JavaScript parser in order to extract such information directly from source files, reporting the name of the referencing variable/member when possible
  • Make things work on device
  • Start studying how to do something similar on V8 for android targets

Any comment is well accepted, either here, or on twitter. This project is needing some love, especially on the GUI component and node server side. Feel free to fork it on github and make pull requests.

Testing Titanium Mobile Applications With Jasmine and Sinon (Part I)

As the code base of an application grows, manual testing becomes very quickly a cumbersome and highly error prone activity. Moreover, when fixing bugs or refactoring portions of the app, there’s no way for telling if a fix is breaking something that was previously working. In order to mitigate such drawbacks, automatic unit testing tools come at help, allowing to describe how each single component of an application must behave, and testing in a systematic way if the imposed requirements and expectations are met.

During the last year, which I mainly spent developing and maintaining a quite large and complex Ti Mobile application, I tried to investigate which were the available options for gradually introducing automatic testing in my development workflow. There is plenty of tools and frameworks for Javascript testing, and although most of them are obviously targeted to the web development world, some of them have been more or less successfully made available for testing Titanium Mobile applications.

JS dynamic nature makes it an ideal language for automatic testing: you can easily modify objects at runtime, and provide fake implementations around the code that needs to be tested. So testing JS applications, and in particular Ti Mobile applications is super easy, right? Wrong! Or better, it can be, provided that you use the right tools and that you write your code in a way that makes it easily testable. For instance, every time we use state variables and functions hidden inside closures (e.g. even just using either CommonJS, or the omni-present module pattern), we are creating code that can be hard to test. An interesting take on this problem can be found here.

In this short series of post I’d like to talk about some tools and patterns I’ve found useful for introducing automatic testing in my coding/refactoring habits.

The tools

There are quite a lot JavaScript testing frameworks available, some of which are dependent on the presence of a DOM, so they’re only suitable for in-browser testing and cannot be used in Titanium. Among those that are framework-independent I’ve found Jasmine.js very interesting. Jasmine is a self-contained Behaviour-Driven Development (BDD) framework for Javascript, where tests express the “expected behaviour” for our code. I won’t go into detail on the philosophy behind this kind of Test-Driven Development practice, but those willing to dig deeper will find the “RSpec Book” quite useful.

There exist a bunch of attempts bring BDD testing with Jasmine to Titanium:

I have tried each of these approaches and none satisfied me. In particular, the second solution, which is probably the most used among the Ti community and is based on running tests directly in the target simulator, dissatisfied me for the following reasons:

  • Testing in the simulator is very slow, while TDD is based on quick red/green/refactor iterations, where you first write the test for your code, you make it fail, you refactor and iterate until you get a green light. Even if, like me, you don’t follow religiously this practice, you quickly lose your patience waiting for the simulator to start every time
  • I think that testing in the simulator, while surely necessary at some point (mainly while doing integration and acceptance testing), allows taking short paths that quickly lead to writing poorly testable code (more on this later)

Actually what I was looking for was a solution allowing me to write and execute my tests in the quickest and simplest way possible. Enter Jasmine-Node, which is a Node.js module, providing a cli for running Jasmine tests through node.

Jasmine-node: setup & execution

Supposing you already have Node.js and npm in place, installing jasmine-node is just a matter of typing:

$ sudo npm install jasmine-node -g

Now you can start executing your tests (also called specs), whose JS files should reside all in the same directory tree. For example, let’s consider the following directory tree, which could be part of a Ti Mobile project:

project/
|     
+---- Resources/
|     |
|     +---- app.js
|     |
|     +---- app-modules/
|           |
|           +---- backend.js
|           |
|           +---- ui.js
|
+---- spec/
      |
      +---- backend_spec.js
      |
      +---- ui_spec.js

In Resources we have the application code, contained in a couple of CommonJS modules. Our tests reside in the spec directory. Please note that each file in this directory contain the spec string in its name, allowing jasmine-node to recognize it as a file to be evaluated by the test runner.

Having in mind this directory structure, we can execute our tests (e.g. from inside the project dir):

$ jasmine-node spec
.............

Finished in 0.013 seconds
13 tests, 15 assertions, 0 failures

the command argument is simply the path of the directory containing our tests.

Let’s write some code and some tests

Now, we can write our code and our tests. For example, suppose in our app we have a module with some silly utility functions:

project/Resources/app-modules/util.js:
--------------------------

exports.computeSum = function(a, b) {
    return a + b;
};

we can write our Jasmine spec like this:

project/spec/util_spec.js:
--------------------------

var util = require('../Resources/app-modules/util');
describe('util tests', function() {

    it('should compute the sum between 1 & 2', function(){
        var sum = util.computeSum(1, 2);
        expect(sum).toEqual(3);
    });

});

let’s run the spec:

jasmine-node spec
.

Finished in 0.007 seconds
1 test, 1 assertion, 0 failures

I don’t enter in further details on how to write Jasmine tests, as this will be covered in the second part of this post (still to come);

We need to remember that specs must be written as Node.js modules and obviously the Titanium Mobile API objects won’t be available. So how can we test our Titanium modules if they make use of the Titanium API? We need to provide our tests with fake implementations of it. This subject leads to the concept of mocks and stubs and dependency injection, which I’ll cover in the next episode.

Caveats

In this post we’ve just touched the basics about how to setup our environment for testing with node-jasmine and Titanium, however there are some somewhat hidden issues that need to be taken into account. In particular, it turns out that the Titanium implementation of CommonJS require() is buggy and doesn’t correctly support relative paths. This represents a major problem when trying to integrate jasmine-node test runners in projects with even minimally complex directory trees.

A possible solution to the issue is to not use relative paths in require() in Titanium (but you are free to use them in your jasmine specs run through node). Instead of relative paths we need to use full paths with Resources as the root directory.

For example, taking into account the directory tree laid out before, let’s suppose the backend.js module is dependent from the util.js module, we’ll need to write the require() in this way:

project/Resources/app-modules/backend.js:
--------------------------

require('app-modules/util');

//...

In our jasmine specs we’ll use relative paths as usual.

Now the trick is to set the NODE_PATH environment variable to point to the Resources directory of the Ti Project, just like:

export NODE_PATH="${PROJECT_DIR}/Resources"
jasmine-node spec   

This will instruct the Node.js environment to search for modules in the Resources directory, allowing them to be found by the test runner.

These two lines can obviously be encapsulated in a shell script or makefile.

What next?

In the next episode of this series, we’ll see how to write our application modules in Titanium, in order to make them easily testable. We’ll also expand our use of available testing frameworks, discussing how to use Sinon.js for creating mocks and stubs.

Titanium Mobile: Flexibility vs. Performance

Last week I had the pleasure to give a talk at the WhyMCA Italian Mobile Developer Conference. The title of the talk is “Titanium Mobile: Flexibility vs. Performance”. Despite being structured as a quite technical speech, at it’s heart I consider it a “philosophical” one, since its message is highly related to why I think the approach to cross platform mobile development and code portability provided by Titanium is, albeit always perfectible, the right one. In this post I’d like to expand a bit on the motivations behind this line of thinking.

Titanium isn’t a write-once-run-everywhere platform. As Appcelerator’s guys use to say, its aim is to be a write-once-adapt-everywhere tool, since, while using a common high level language and API, it enables the exploitment of platform specific features when needed. This philosophy is clearly visible in the API, as we have entire sub-namespaces dedicated to either iOS, or Android. This allows adapting our mobile applications to the platforms where they’re executed, thus avoiding a write once, suck everywhere effect. Moreover, the possibility to develop custom native extensions to the framework opens up a wide range of development scenarios, ideally allowing us to create user experiences that are practically undistinguishable from those of applications developed with native SDKs.

My point of view on this kind of approach to cross platform portability has its roots in the work I took over during 5 years as a researcher, where I explored the boundaries of flexibility (in terms of ease of development and cross platform portability) and performance in the field of network processing architectures. If you really have nothing better to do, you can check out my PhD dissertation thesis dating back to the beginning of 2009 for additional details.

While at a completely different scale, in mobile application development we face challenges that are very similar to those that passionated me during my research:

  • heterogeneous and incompatible mobile device platforms and OSs
  • while native capabilities are quite homogeneous across platforms, UIs are not
  • each platform must be programmed with it’s own SDK, each one based on a different language (e.g. Java for Android, objective-c for iOS, and so on) - code reuse and portability is impossible
  • we have stringent constraints on the User Experience: apps with a poor UX fail to gain wide adoption

In this scenario, the approach proposed by Titanium is very interesting:

  • It’s based on a high level language that abstracts away the different programming models of the target platforms
  • It provides a very wide and flexible high level API (in contrast to other technologies, like the very recent RubyMotion, which provides just Ruby wrappers around the classes of the iOS Cocoa Touch framework)
  • It’s extensible through natively coded modules for leveraging native features of the target platform

Titanium applications are native by all means anyway, since even if written in JavaScript, they directly rely on native functionality. However, as its API is very general and flexible, allowing to adapt the same macro components to very disparate uses, in some cases this may cause slow downs and not so slick user experiences. It’s quite simple to explain why this happens: when the code implementing an UI component (e.g. a TableView), must be able to adapt to every possible use, we are introducing some amount of overhead, with the result of trading off performance in favor of flexibility.

So, in my presentation, I tried to propose two main lines of thought based on the realistic scenario of performance problems related to the creation and scrolling of a table view. The first line of thought tries to make the point that when we face a performance problem, which in mobile development is frequently a UX problem, we need to go to the root of the issue, by understanding what is causing it. This means the following things:

  • we need to know how the tools we’re using actually work under the hood: Titanium doesn’t use the same JS engine on both iOS and Android. In particular, JavaScriptCore and V8 are very different implementations of JS, the latter being an optimizing JIT compiler, while the former is actually a bytecode interpreter, as JIT compilations is forbidden by iOS
  • As a corollary, relying on some old school micro-optimizations, like caching the length of an array while iterating over it in a for loop, may be actually useless, since if the body of the loop is “fat” enough, I’m quite sure you’re not wasting time in that check. Moreover, if that loop is “hot” enough, V8 will automatically optimize it anyway, by hoisting the access to the array length outside of the loop (check out this video from JSConf 2012: “One day of life in V8” by Vyacheslav Egorov)
  • We need to measure, at first even just in a rough way, in order to find where we are loosing time

This last point raises an alert on the lack of accurate profiling tools that we can productively use for measuring the actual performance of our code. My extensions to Titanium for leveraging the JavaScriptCore profiler are still work in progress, and I’ll hopefully post an update on that story soon.

The other line of thought I pursued, is related to what we can do for increasing the scrolling performance of our table view component. Table views are a critical component in most applications, and those presenting complex row layouts can result in choppy scrolling animations for several reasons. Complex row layouts are actually a problem also when developed natively, however, in Titanium we have much less opportunities for optimizations, as we obviously need to rely on the provided API implementation, which is crafted in a way that enhances flexibility and ease of use for the developer.

In my presentation I propose a short investigation on the reasons that underly a lack of scrolling performance, by using the Instruments Core Animation profiling tools provided with Xcode. Scrolling issues are usually caused by transparent, or non-opaque views, like labels, which make the rendering engine do extra work for computing how superimposed views blend together. Another major pain point (often more important than the former) is represented by views with rounded corners, which need more iterations to be rendered. In this case, a very simple solution is to use image masks: a semi transparent image to be superimposed to the view that needs rounded corners. If the view is an ImageView, the Ti.UI.MaskedImage component does just the right job.

There’s an interesting session from Apple’s WWDC 2010 where these kinds of performance issues are analyzed. The talk is titled “Performance Optimization on iPhone OS”. If you are registered as an Apple developer you can download the video from https://developer.apple.com/videos/wwdc/2010/.

So we come to the center point of my reasoning. If we are not able to fulfill our performance goals by tweaking our use of the standard API, Titanium allows us to implement our performance-critical components as native modules. In other words, we can trade flexibility for gaining performance. For doing so, we must give up some amount of generality and the possibility to reuse our code in other applications by implementing an optimized component that exposes an application-specific semantic: both the API and the implementation of the module will be tailored on the peculiar application and it’s performance requirements.

Following the table view example, on iOS this translates into having tableview rows with a hardcoded layout, possibly with sub-views whose opaque property is set to true on iOS, and so on. Would we still be dissatisfied with the result, we can always rely on the concept of fast-cells, which are tableview cells actually composed by a single view, where all information to be shown is laid out by using low level CoreGraphics drawing primitives. Check out the iOS Boilerplate project and this coding example from Apple for additional information.

Summarizing, what does all this mean? That Titanium Mobile is a tool allowing us to create very complex cross platform mobile applications in a fraction of the time needed to make parallel developments using native SDKs. The possibility to extend the framework with native modules opens up a wide range of development scenarios, enabling both the reuse of existing native libraries, and the optimization of performance-critical portions of the app, when needed.

Is it a panacea? Not really, IMHO. I use Titanium since version 0.8, and despite a visible effort in making it better release after release, even now that version 2.0 is out I think it’s still a bit immature. I still see it somewhat a platform made for hackers, rather than for developers, as without a deep knowledge of its internals it’s often impractical to overcome even trivial issues like a failed build. A quick look at most of the questions on the Q&A forum will suffice to support my point of view on this.

That said, even taking into account the problems, I think Titanium is the right tool every time we are dealing with an application that needs to support both iOS and Android platforms, whose value resides in a rather complex business logic, instead of just in the presentation layer. In these cases, we don’t want to develop, test, debug, and maintain different implementations of the same solution across different platforms. Moreover, being based on a high level abstraction layer (JS language + very flexible API), Titanium allows very quick iterations in the solution space, which is an invaluable feature when we are trying to validate business ideas against unkown markets.

Finally, here you find the slides of my presentation:

Bash One-liner for Renaming High-res Image Files to @2x

This tip may be useful to iOS developers when they’re given a bunch of high-resolution files and they need to rename them with the @2x filename suffix.

Supposing the files are all in the same directory (containing only the files you need to rename), just do this in the terminal:

for file in *; do mv "$file" "${file%.*}@2x.${file##*.}"; done

As a result, the files will all be renamed following the pattern <name>@2x.<extension>.