DDD - 0312 - April 2012
DDD - 0312 - April 2012
APRIL 2012
ALSO INSIDE
Mobile UI
www.drdobbs.com
Previous Next
More on DrDobbs.com
Mastering Threads on MacOS X
Dr. Dobb’s Journal The MacOS X platform has four thread solutions — two of
which are obsolete as of version 10.7. Your choices are now
POSIX threads or Cocoa’s NSThread class. Here’s how
IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Mailbag
Chrome >>
iPhone >> Visual Studio 11 Beta, Flash appreciation, the JVM,
Letters >>
Links >> and CISC/RISC divide
Table of Contents >>
First Look at VS 11 lowed the creative development community to deploy a Flash player
for iDevices, developers would have continued on the path of better,
In response to Andrew Binstock’s editorial
faster, cheaper for software. There is no reason to use a proprietary low-
(http://drdobbs.com/windows/232602205) expressing concern
level language like Objective-C, other than you have to. This sounds like
about the Visual Studio 11 beta release , we received:
the old IBM game that lead to their downfall. They were so big that
The title of the editorial caught my attention: "Verdict on Visual Studio
companies did what they demanded, until companies got smarter and
11 Beta: Not Ready for Prime Time." After reading the article, I thought
did what they wanted, taking advantage of the whole open platform
the title was misleading since the title doesn’t specify only the UI but
world. Companies might follow Apple, too, while they have the control-
implies a broader scope. Perhaps "Verdict on VS2011 Beta: Drab and
ling market share, but nothing lasts forever. Somebody, somewhere is
Ugly" instead.
working on the next new thing, and it is unlikely to require Objective-
— Ryan Van Slooten
C. I want better, faster, and cheaper for my software developers.
On Mobile Driving Language Adoption — Steve Wilfe
Denver, Colorado
In response to the editorial, “The Rise and Fall of Languages in
2011” (http://drdobbs.com/mobile/232400093), which con- The JVM as a Language Incubator
cluded that mobile development was largely driving recent lan-
guage adoption: In response to the editorial discussing the JVM as a fertile plat-
While hardware gets better, faster, and cheaper, application develop- form for the development of new languages
ment productivity is becoming more complicated, slower, and more ex- (http://drdobbs.com/jvm/232600846), and that these languages
pensive. There was a reason Adobe Flash was king. It was better, faster, tend to be entirely new efforts, better versions of Java, or simply
and cheaper for software development. Write it once, deploy it every- ports of other languages to the JVM :
where. That was until the Apple empire became so powerful that they I think that the category mappings in the article don’t really fit. For ex-
could force the end of efficient multiplatform development. If Apple al- ample, NetRexx is really just the JVM version of Rexx as far as I am
aware; wouldn’t it belong in the "ports" category? Additionally, Mirah,
www.drdobbs.com April 2012 3
Previous Next [LETTERS]
while heavily inspired by Ruby, is not trying to be another Ruby; so I’m 99% of the time and save on decode-time for every instruction. The
IN THIS ISSUE
curious as to why it would belong in the "ports" category. I think some original idea was that you could do away with microcode altogether
Guest Editorial >>
Mobile UI >>
people may quibble about whether or not Scala should be in the "bet- and deal with incompatibilities in the compilers…but it did not work-
Chrome >> ter Java" or "its own thing" category. out that way.
iPhone >> I think there is also one notable omission: Rhino — the JavaScript im- Is RISC/CISC a meaningful distinction? No: CISC processors have
Letters >> plementation for the JVM. It has been around for ages. It powers a fair enough transistors to dispense with microcode (if they wanted to) and
Links >>
Table of Contents >> bit of server-side JavaScript on the Web. Common uses include server RISC processors need complex instructions for multicore locking. The
side JavaScript processing for initial page hits. difference between an ARM and an Atom processor is more about
Other interesting omissions: Erjang, and Erlang port, and there are at circuit design than which processor allows a WORD load from an non-
least two versions of PHP ports for the JVM that I’ve heard of. Erlang WORD-aligned address.
has some unique features, and if it could be successfully married to all —Steve Channell
of the rocket science and investment that go into Hotspot, it could pro- To which Andrew Binstock responds: “I don’t disagree with the
duce something very powerful, however unlikely that may be. PHP is second part of your analysis; namely, that CISC vs. RISC is a distinction
worth noting if only for its ubiquity. of diminishing relevance. As to the first point, Intel was definitely do-
I hope you get to Clojure soon. There’s a lot more to it than in many ing RISC instructions at the time I mentioned. Here is the description
of the other languages mentioned in the article. written by Hennessy and Patterson (the fathers of RISC) in Computer
— Bill Robertson Architecture — A Quantitative Approach, 3rd Ed. (http://is.gd/qqitUh):
“The P6 [so, Pentium III — Ed.] translates each IA-32 instruction into a
CISC vs. RISC on Intel Processors series of micro-operations (uops) that are executed by the pipeline:
In response to a comment that appeared in this column on page the uops are similar to typical RISC instructions.” I didn’t and don’t
3 of the March issue, in which Andrew Binstock gave a rough claim that the MUL instruction was implemented in RISC, only that its
time frame for Intel’s adoption of RISC instructions in the inner- ability to execute in half a clock cycle occurred at the same time that
most CPU execution instruction, we received: Intel was using RISC instructions in its processors. I stand by that as-
The response in the “Mailbag” was well wide of the truth, and mis- sertion and all my attempts to find counter arguments suggest that
understands what the distinction between RISC and CISC is. To de- it is in fact correct.”
scribe a CISC MUL instruction as being converted to RISC shift/addi-
tion is to miss the point. CISC vs. RISC was not about circuit design, Have a correction or a thoughtful opinion on Dr. Dobb’s content?
but about reducing instruction decode time by reducing the number Let us know! Write to Andrew Binstock at alb@drdobbs.com. Let-
of instructions to the ones most commonly used. For example, in- ters chosen for publication may be edited for clarity and brevity.
stead of {8,16,32} bit versions of multiply, you reduce to the one used All letters become property of Dr. Dobb’s.
IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Chrome >>
iPhone >>
No Tool or Combination of Tools Can Assure
Letters >>
Links >>
Table of Contents >>
Fail-Safe Code
The government’s analysis of Toyota’s automotive code revealed errors and failures. But
despite extensive overlapping forms of testing and modeling, it could not prove or clear
the software as a contributor to unintended acceleration.
By Ron Wilson
L
ast year, the U.S. National Highway Traffic Safety ation in Toyota Vehicles” (www.nhtsa.gov/UA) could be a case study.
Administration (NHTSA ) released an enormous The NASA team applied static source-code analysis, formal logic
report on its investigation into unintended ac- model checking, and algorithm analysis through simulation. The report
celeration in Toyota cars. It all seems very familiar, states, “The team’s experience is that there is no single analysis tech-
if you remember the Audi 5000. New electronic nique today that can reliably intercept all vulnerabilities, but that it is
throttle control reaches the market. Reports of strongly recommended to deploy a range of different leading tools.”
failure emerge from a few users. The vendor de- For code analysis, the team used Coverity, CodeSonar, and Bell Labs’
nies any problem. A few engineers quietly report having reproduced Uno (http://spinroot.com/uno/) to identify “common coding defects
the problem. But an intensive publicly funded investigation finds and suspicious coding patterns.” They also used CodeSonar to com-
nothing. pare Toyota’s code against a Jet Propulsion Lab coding standard.
What makes this report particularly interesting is that the NHTSA For model checking, the team used open-source Spin (http://spin-
called in an evaluation team from the space agency, NASA, to do the root.com/spin/whatispin.html#A) and its companion tool Swarm
heavy lifting. And that team included a software evaluation group. (http://spinroot.com/swarm/). Here, the tale gets more interesting. To
While the hardware folks were shaking, baking, and irradiating cars and use a formal model checker, you first have to write formal models. The
car parts, the software team had at the Engine Controller Module code team decided to build models only for those software modules they
for the four-cylinder 2005 Camry — all 280K lines of ANSI C. The team’s believed could be culprits — so the formal analysis depended upon
report, included as part of the larger “Report on Unintended Acceler- human judgment of possible fault modes.
www.drdobbs.com April 2012 5
Previous Next [GUEST EDITORIAL ]
IN THIS ISSUE
Guest Editorial >>
Mobile UI >> The algorithm analysis started with — once again — building mod-
Chrome >> els, this time in Matlab. That process was undertaken by reading Toyota
iPhone >>
Letters >> documentation and talking with Toyota engineers. It then progressed
Links >> to analyzing the source code, and finally testing the models against
Table of Contents >> actual Camrys. Once the NASA team was satisfied with the models,
they explored failure scenarios in Simulink and checked delays with
AbsInt aiT.
Instantly Search
Some conclusions suggest themselves. First, there are no silver bul- Terabytes Of Text
lets: Effective debugging means using everything you’ve got. Second,
even when it’s grounded in exhaustive and formal techniques, an eval- • 25+ fielded & full-text search options
uation is circumscribed by the evaluators’ beliefs about the possible • dtSearch’s own file parsers highlight hits in
behavior of the system. Third, there is no certainty. Despite Toyota’s
popular file & email types
great care in developing their code, NASA’s analysis found significant
errors, including serious underestimates of delays in the multiprocess- • Spider supports static & dynamic data
ing system. But the investigation could not link those errors to any pro-
posed mechanism for unintended acceleration. Contrary to what you
• APIs for .NET, Java, C++, SQL, etc.
probably read in the papers, the NASA Executive Summary stated, “Be- • Win / Linux (64-bit & 32-bit)
cause proof that the ETCS-I [that is, the Electronic Throttle Control —
Ed.] caused the reported UAs [unintended accelerations] was not “Lightning Fast” – Redmond Mag
found does not mean it could not occur.”
“Covers all data sources” – eWeek
“Returns results in less than a second”
— Ron Wilson is the guest Editorial director of Embedded.com, EDN, and the Design-
lines at UBM Electronics. This is a slightly revised version of this article, which first ap-
– InfoWorld
peared in EETimes.
www.dtSearch.com
Comment Fully-Functional Evaluations
www.drdobbs.com April 2012 6
Previous Next [COVER STORY]
IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Chrome >>
iPhone >>
Letters >>
Links >>
Table of Contents >>
7 Steps To
A Killer Mobile UI
Here's how to write a successful mobile app
By Tiago Simões
O
dds are, you have a smartphone and without realizing it, 1. Define Your Goals
have developed a special, personal relationship with it. We What are you trying to accomplish with the mobile app? Most impor-
only recently learned that Steve Jobs charged the team he tantly, what will your users want from it? You must define the goals
assembled to create the first iPhone to “Create a phone that your app will address. For this, you need to understand the day-to-day
people will fall in love with.” Whether we admit it or not, all of us have activities of your users related to this app, and their goals and motiva-
a special connection with our iPhone, Blackberry, Android, or Windows tions around it.
Phone. A good technique is to create personas — fictitious characters that
But love is fickle. A recent Harris Interactive study revealed that bad represent your users — and write your specs as agile user stories. This
mobile apps can dramatically damage a brand’s reputation. Almost approach puts you in the correct mindset to state requirements for
one-third of respondents said they told others when they had a bad your app. Something like this: “As a security officer, Johnny Bravo must
experience with a mobile app. Still, more than half say they’ve recom- check-in using his mobile phone to find out the next checkpoint that
mended an app based on a positive experience. he should walk to so he can complete the randomized patrol tour.”
Providing a good user experience in mobile applications is para- This tactic lets you see the application from the user’s point of view.
mount. Here are seven steps to get you on the right path to delivering There are, of course, differences between user stories for mobile
great mobile apps. and desktop applications, particularly when considering the mobile
www.drdobbs.com April 2012 7
Previous Next MOBILE UI [COVER STORY]
IN THIS ISSUE
Guest Editorial >>
Mobile UI >> context. For instance, a mobile user might be walking or using one ter suited for enter-
Chrome >> hand. prise applications. A
iPhone >>
Letters >> After gathering several of these stories, you must prioritize them ac- hybrid approach
Links >> cording to their frequency. I’ll explain why this is important shortly. makes sense if you
Table of Contents >> want mobile Web
2. Analyze Existing Apps apps easy mainte-
If it’s the first time you’re creating a mobile app, take a close look at nance but need
the interfaces of existing ones. Two obvious things stand out: The specific hardware
screen size is much smaller and since many mobile devices use touch capabilities, such as
An early Palm Pilot prototype side by side with the real thing.
screen, the elements on the screen must be larger, so they’re easy to the phone’s camera
touch. or GPS.
The smaller screen and the larger elements mean that you can only Taking advantage of existing frameworks and platforms can be a so-
put a limited number of items on the screen. lution, but whichever option you choose, make sure you can create
It can be a challenge to select what should go on the mobile screen; and modify the UIs quickly, and that you’ll be able to iterate often.
some usability experts even advocate that the mobile version of a
website be created before the desktop version. 4. Prototype Quickly
Prioritizing your user stories can help with this. You’ll want to take a A fast way to test a mobile interface at a project’s start is to use a low-
hard look at the features that your top priority users are using. Figuring fidelity prototype. Before the Palm Pilot’s launch, it’s said that the in-
out the 20% of the features that will be used 80% of the time is the ventor carried around a block of wood the size of the device to see
goal of every usability expert. If you do this correctly with mobile, the how it would feel in his pocket. Later, he’d have several rough versions
desktop will also have its priorities right. of the UI sketched on it.
Prototyping a mobile app is easy: A pencil and paper are all you need,
3. Native App or Mobile Web? and because screens are small, you will not have much to draw. Test
You’ll need to decide whether to use HTML5 or native APIs. This deci- your prototypes by asking users to try to accomplish tasks on them.
sion has more implications for the technical implementation than for See what they do, and ask them what they’re thinking. The results will
the user interface, however. Native apps usually run faster and are the be surprising and help you improve the design. A great design mantra
best option for games, offline, and hardware-intensive apps. Mobile is “Don’t Make Me Think!” If your mobile design fails this test, your app
Web apps are quicker to implement, easier to maintain, and often bet- will fail as well.
www.drdobbs.com April 2012 8
Previous Next MOBILE UI [COVER STORY]
IN THIS ISSUE
Guest Editorial >>
Mobile UI >> 5. Avoid Errors That Ruin the UX you do this, remember to include a back button on your UIs, giving
Chrome >> When people start creating mobile applications, they typically make users an accessible exit option.
iPhone >>
Letters >> some known errors. First, if they’re creating the mobile version of an Remembering user selections across sessions (for example, a recent
Links >> existing website, developers often try to replicate every feature of the items list) is another smart touch that will make the app more context
Table of Contents >> desktop, failing to consider the intent of the mobile user. aware and free users from having to repeat navigation steps. Together,
Another common error is to have a navigation structure with too these usability quick-wins work to make the user’s life easier.
many levels. Deep structures aren’t well suited to mobile; simpler mod-
els work better. Expecting users to be able to easily input text is an- 7. Fail Early, Recover Fast
other mistake: Entering text is much harder on mobile devices, so you’ll Even with a good team of designers and developers, your first attempt
want to minimize the need for input. at creating a mobile app will likely fail. (A recent survey showed that
The applications that work best on mobile let users read content 38% of people are unsatisfied with the branded apps they tried.) The
more than write it. Think about it: Do any of your favorite mobile apps best strategy is to fail early and iterate quickly, learning how people
require you to enter a lot of text? are using your app and improving it continuously. Agile methodolo-
gies are a great way to align the mobile UIs you deliver with what users
6. Add Delightful Details need.
A mobile phone is always with you and knows where you are, which is Making the killer mobile UI is hard, but the strategies outlined in this
why mapping applications are so successful. Phones can hear what article will help. Follow them faithfully, and you’re on your way to writ-
you hear and see what you see, which explains the popularity of apps ing some great mobile apps!
like Shazam and Instagram. Using location, the camera, and the micro-
phone are all smart ways to get the same context as the user, and you
can take advantage of that context in unique ways. — Tiago Simões is a senior software engineer in the R&D group at OutSystems, a
Even if you aren’t using the mobile device hardware, there are several cloud-based application developer.
tricks you can use to delight users. Animations can add excitement to
your application. If you’re creating a mobile Web app, cache static con-
tent, and consider using a content delivery network so pages load
faster.
Another welcome touch for mobile Web apps is to let users add them
to their home screen, making them look and feel like a native app. If Comment
www.drdobbs.com April 2012 9
Previous Next [CHROME]
IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Chrome >>
iPhone >>
Letters >>
Links >>
Writing Chrome Extensions
Table of Contents >>
Extensions to Chrome enable you to extend the browser’s capabilities, change how pages are
rendered, and interact with the server in a controlled manner. For all their power, Chrome
extensions turn out to be comparatively simple to write and build once you know how.
hrome Extensions are the code components used for • One or more JavaScript files (optional).
Before going into the details of the extension’s components, let’s see
and then we provide a sample extension to illustrate the techniques. how to load and view an extension. Assuming you have all the exten-
sion-related files:
The Anatomy of Chrome Extensions
A Chrome extension is a zipped bundle of files — HTML, CSS, • Create a folder anywhere on your system to hold the above files..
JavaScript, images, and related extension files. Extensions are essen- • Go to the Extensions Management page in Chrome by clicking
tially Web pages, and they can use all the APIs that Chrome provides the wrench icon and choosing Tools > Extensions, and click on
to Web pages, from XMLHttpRequest to JSON to HTML5. Developer mode option.
A Chrome extension comprises the following files: • Use the Load unpacked extension button and specify the exten-
sion folder. This step will load the extension.
• A manifest file (mandatory). • If the extension is valid, its icon appears next to the address bar,
• One or more HTML files (mandatory) such as background.html, and information about the extension appears in the extensions
popup.html. page.
www.drdobbs.com April 2012 10
Previous Next [CHROME]
IN THIS ISSUE
Guest Editorial >> The extension is now ready to be used. Clicking on the extension’s "matches": ["<all_urls>"],
Mobile UI >> "js": ["page.js"]
icon (next to the address bar) enables interaction with the extension. }
Chrome >>
iPhone >> Note that this page provides options to Reload/Uninstall options for
"icons" : {
Letters >> the extension. Now, we’ll examine the contents of the extensions. "48": "a_48.jpg",
Links >> "128": "a_128.jpg"
Table of Contents >>
The Manifest File }
The manifest file, called “manifest.json,” provides information about
the extension such as the most important files and the capabilities that The manifest file is the heart of the Chrome extension. It contains
the extension uses. several name-value pairs specifying what functions are to be per-
If you’re not familiar with JSON , it stands for JavaScript Object No- formed by whom. The attribute’s name, version and description are
tation, and it’s a lightweight text-based open standard designed for metadata for the extension, whereas the attribute’s
human-readable data interchange in JavaScript. In this way, it serves background_page, options_page, and content-scripts give in-
as an alternative to XML. It is used for representing simple data struc- formation about the files that will be holding the corresponding logic
tures and associative arrays, called objects. It is language-indepen- (which will be described later).
dent, with parsers available for most languages. JSON files are de- The browser_action attribute, which is a composite JSON object
noted by the extension “.json.” JSON is often used for serializing and (that is, made up of one or more JSON objects), is a way of specifying
transmitting structured data over a network connection. Here’s a typ- the user interface (UI) to the extension. It holds the details of the image
ical manifest file: button or the UI that will be provided to the user to access the exten-
sion: It has the child attribute default_icon that specifies the icon to
manifest.json be used next to the URL in the address bar; and the child attribute
{
"name": "Kz_FACE_LIFT", popup contains the name of the HTML file that will be displayed when
"version": "1.1", you click on the icon in the address bar.
"description": "Kz FACE_LIFT PLUG-IN.",
"background_page": "background.html", The composite attribute icons specify the images that are to be dis-
"options_page": "options.html", played at various places. The child attribute 48 specifies the image/icon
"browser_action": {
"default_icon": "images/clock.png", that is to be displayed during the installation and uninstallation
"popup": "popup.html" process of the extension. The child attribute 128 specifies the
}, image/icon that is to be displayed in the chrome://extensions page
"content_scripts": [ where details of all the installed extensions are listed. The child attrib-
{ ute 16 has the same functionality as the default_icon attribute.
www.drdobbs.com April 2012 11
Previous Next [CHROME]
IN THIS ISSUE
Guest Editorial >>
Mobile UI >> Extensions get the user interface in the following two ways: plays it on click. The manifest.json file specifies which HTML file will
Chrome >> hold the background processing logic. It does this via the attribute
iPhone >>
Letters >> • Browser action: An extension that enhances the functionality of background_page.
Links >> the browser irrespective of the pages. As long as the browser is A sample background.html is shown here:
Table of Contents >> running, the extension will be there. It adds an action item to the
<html>
browser. The action item is added in the browser’s toolbar in the <body>
aforementioned sample manifest file. <script src="script.js"></script>
<script type="text/javascript">
• Page action: An extension that enhances the functionality of the chrome.tabs.onSelectionChanged.addListener(myFun4);
browser depending on the Web page being visited. It will be ac- chrome.tabs.onUpdated.addListener(myFun4);
var val = 10 ; //declare a sample variable
tive as long as that page (or any page from that domain ) is open </script>
in the browser. It adds an action item to some of the pages that </body>
depends on the program logic. The action item is added in the
address bar for valid page addresses. Popup.html
Popup.html is basically a simple view that extracts data from back-
At most, an extension can have either one browser action or one ground pages or content scripts (which are JavaScript files) and dis-
page action. plays them. Thus, it provides a way of displaying the results of the op-
erations performed by the extension or the state of the extension.
Background.html In the manifest.json file, we describe which HTML file will act as the
The main logic of the extension resides in the background.html file. UI using the attribute popup. Note: There are many ways of displaying
When an extension needs to have a single long-running script to per- results to the user. We can use other HTML pages. The only difference
form some task, background pages are the solution. Although it is an is that we need to load those additional pages programmatically as
HTML file, its purpose is not used to add a GUI to the extension. Every- needed, whereas with popup.html, we do not need to write any logic
thing in this file is housed inside a <script> tag or contains a refer- for loading because it is attached with one of the standard Chrome
ence to a JavaScript file that holds the main logic. event “browser action/page action” extensions — whenever we click
This file exists for the lifetime of extension, and only one instance of the icon of the extension, popup.html will be displayed.
it per extension is active at a time. For extensions with only back- A sample popup.html is shown next, which just displays “Hello
ground work to do, the UI is implemented by dumb views. That is, the World” text when the extension icon is clicked ( it extracts data from
view collects any data from the background page as needed and dis- background.html):
www.drdobbs.com April 2012 12
Previous Next [CHROME]
IN THIS ISSUE
Guest Editorial >> <body> be used as the content script using the composite attribute con-
Mobile UI >> <h1>Hello World</h1> tent_scripts. It consists of a child attribute named js that tells
<script>
Chrome >> var newwin = chrome.extension.getBackgroundPage(); which file acts as the content script. The child attribute matches, which
iPhone >> alert(newwin.val);//where val is a var declared in
Letters >> holds a regex-pattern/url-value, tells the extension on which domain
//the background page.
Links >> </script> names and URLs the content script is valid.
Table of Contents >> </body> A sample of content script file is shown next, along with the mes-
sage-passing method of interaction. It sends a request to the back-
The chrome.extension.getBackgroundPage() returns the win- ground.html page passing status=2 as data, and waits for response
dow object of the background page from which we can access all the through the handler in which it displays the counter value from the
variables of the background page that are in the window scope. response received.
There is also an alternative way for the extensions pages to interact.
var payload = {status: 2};
They can use message passing, as will be discussed in the section on chrome.extension.sendRequest(payload,
content scripts . function handler(response) {
var a = response.counter;
alert(a);
Options.html });
This file enables the user to customize the behavior of the extension.
The options page should be included in the manifest.json file. It pro- The background.html file shown next handles the above request
vides a link to the options page from the extensions management sent by the content script.
page at chrome://extensions. In the manifest.json file, you describe
function onRequest(request, sender, sendResponse)
which file will be used as the options page using the attribute op- {
tions_page. var num1 = request.status;
if (num1==2)
{
Content Scripts Num2=20;
A content script is a JavaScript file that executes in the context of a sendResponse({counter:Num2});
}
Web page that’s been loaded into the browser. Think of a content }
script as part of that loaded page, not as part of the extension it was //register this function
chrome.extension.onRequest.addListener(onRequest);
packaged with. It interacts with the Web pages visited by the browser.
It can also interact with the extension pages by exchanging messages When the background page receives the request, it sends a response
(message passing). In the manifest.json file, you describe which file will back if the value received is 2. In addition to the exchange of data with
www.drdobbs.com April 2012 13
Previous Next [CHROME]
IN THIS ISSUE the background page, the content scripts can do much more by ac- bookmarks idle
Guest Editorial >> cessing the data of the loaded Web page, such as the document object
browserAction management
Mobile UI >> and its properties, and also modify them as needed.
Chrome >> contextMenus omnibox
iPhone >> cookies pageAction
Letters >> Chrome API
Links >> In addition to having access to all the APIs that Web pages and apps extension proxy
Table of Contents >> can use, extensions can also use Chrome-only APIs (often called fileBrowserHandler tabs
chrome.* APIs) that allow tight integration with the browser. For ex- history types
ample, any extension or Web app can use the standard il8n windows
window.open() method to open a URL. But if you want to specify
which window that URL should be displayed in, your extension can Table 1: The supported Chrome-specific APIs.
use the Chrome-only chrome.tabs.create() method instead.
pleted all their work. Often, synchronous methods have a return type.
Content.js For example:
Table 1 lists the supported chrome.* APIs.
DOMWindow chrome.extension.getBackgroundPage()
Asynchronous vs. Synchronous Methods This method has no callback and a return type of DOMWindow — it
Most of the methods in the chrome.* APIs are asynchronous: They re- synchronously returns the background page and performs no other
turn control back to the browser/script without waiting for the opera- asynchronous work.
tion to finish and while the operation continues to happen in the
background. To get the outcome of an operation after it is complete, a Using a Callback
callback function is passed upfront to the method, which will be ex- To navigate the user’s currently selected tab to a new URL, the current
ecuted later (potentially much later), after the operation is complete. tab’s ID is acquired (using chrome.tabs.getSelected()) and then
Here’s an example of the signature for an asynchronous method: that tab is directed to the new URL using chrome.tabs.update(). A
synchronous getSelected() could be written as below:
chrome.tabs.create(object createProperties,
function callback)
var tab = chrome.tabs.getSeleceted(null); // WRONG
chrome.tabs.update(tab.id, {url:”http://abc.com”});
Few chrome.* methods are synchronous. Synchronous methods ……………………………
will not have a callback because they don’t return until they’ve com- // THIS CODE DOESN’T WORK
IN THIS ISSUE
Guest Editorial >> This approach fails because getSelected() is asynchronous. It re- Extension Origin
Mobile UI >> turns without waiting for its work to complete, and it doesn’t even return Each running extension exists within its own separate security origin.
Chrome >> a value (although some asynchronous methods do). getSelected(), Without requesting additional privileges, the extension can use XML-
iPhone >>
Letters >> or any method in general, is identified as asynchronous by the presence HttpRequest to get resources within its installation. For example, if
Links >> of the callback parameter in its signature. For example: an extension contains a text file “abc.txt,” the extension can retrieve
Table of Contents >> chrome.tabs.getSelected(integer windowId, function the file’s contents as shown in the following code.
callback).
var xmlUnameRequest = new XMLHttpRequest();
The following code shows how to define a callback function that var url = "/abc.txt";
gets the results from getSelected() (as a parameter named tab) xmlUnameRequest.open("GET", url, true);
xmlUnameRequest.onreadystatechange = handler;
and calls update(). xmlUnameRequest.send(null);
function handler(evtXHR){
chrome.tabs.getSeleceted(null, function(tab){ if (xmlhttp.readyState == 4&&xmlhttp.status == 200) {
chrome.tabs.update(tab.id, {url:”http://abc.com”}); alert(xmlhttp.responseText);
………………………………. }
}); else {
//THIS CODE WORKS FINE alert(“Error ”+xmlhttp.status);
}
The callback function specified to getSelected is called only after }
information about the currently selected tab is available, which is
sometime after getSelected() returns. Also note that although up- If the extension attempts to use a security origin other than itself, say
date() is asynchronous, this example doesn’t use its callback param- http://www.google.com, the browser disallows it unless the extension
eter, as we don’t do anything with the results of the update. has requested the appropriate cross-origin permissions.The same per-
mission can be made available to the extension by specifying those
Cross-Origin XMLHttpRequest host names in the manifest file as below.
Extensions can interact with the outside world using XMLHttpRe-
{
quest objects available in JavaScript. Unlike regular Web pages, which “name” : “Kz_Face_Lift”,
can use XMLHttpRequest to send and receive data from remote “permissions”:[
http://www.google.com/,
servers, but are limited by the same origin policy, extensions aren’t http://*/*,
limited this way. An extension can talk to remote servers outside of https://*/
]
its origin as long as it has requested cross-origin permissions in its }
definition.
www.drdobbs.com April 2012 15
Previous Next [CHROME]
IN THIS ISSUE
Guest Editorial >>
Mobile UI >> A match pattern of http://*/* allows HTTP access to all reachable The .pem file must update the
Chrome >> domains. Match patterns are similar to content script match patterns, extension and upload the exten-
iPhone >>
Letters >> but any path information following the host is ignored. Access is sion to the Chrome Web Store. On
Links >> granted both by host and by scheme. If an extension wants both se- successful packaging of the ex-
Table of Contents >> cure and non-secure HTTP access to a given host or set of hosts, the tension, a dialog box is displayed
permissions must be declared separately with https and http as in providing the information regard- Figure 1: The dialog box confirming
successful packaging of an extension.
the aforementioned example. While using an XmlHttpRequest object ing the location of .crx and .pem
in the plugin pages, you can pass the destination URL files. (Figure 1.)
(http://www.mysite.com/getData) after ensuring the same was speci- Packaging also can be done at the command line by specifying the
fied in the manifest file. folder where the plugin resides; and upon successful packaging, the
same dialog box will pop up.
Packaging and Deployment
chrome.exe --pack-extension= C:\KzExtension\Kz_FaceLift
To deploy the extension, the contents of the folder can be packaged
into a special ZIP file that has a .crx suffix.
Hosting
1. Bring up the extensions management page by going to the fol- The Web server that hosts .crx files must use appropriate HTTP head-
lowing URL: chrome://extensions ers, so that end users can install the file onto their browsers by clicking
2. Go to Developer Mode and Click the pack extension button. A a link to it. Google Chrome considers a file to be installable if the file
dialog appears. has the content type application/x-chrome-extension or the file suffix
3. In the extension root directory field, specify the path to the ex- is .crx and both of the following are true: The file is not served with the
tension’s folder — for example, c:\myext. (Ignore the other field; HTTP header X-Content-Type-Options: nosniff option, and it is
you don’t specify a private key file the first time you package a served with one of these content types:
particular extension.) • empty string
4. Click OK. The packager creates two files: a .crx file, which is the • "text/plain"
actual extension that can be installed; and a .pem file, which con- • "application/octet-stream"
tains the private key. • "unknown/unknown"
5. The .crx file can be hosted on a Web server for the end users to • "application/unknown"
download onto their Chrome browsers. • "*/*"
www.drdobbs.com April 2012 16
Previous Next [CHROME]
IN THIS ISSUE
Guest Editorial >>
Mobile UI >> The most common reason for failing to recognize an installable file http://code.google.com/chrome/extensions/api_index.html
Chrome >> is that the server sends the header XContent-Type-Options: nos- http://www.w3.org/TR/XMLHttpRequest/
iPhone >>
Letters >> niff. The second most common reason is that the server sends an
Links >> unknown content type — one that isn’t in the previous list. To fix an — Kausar Munshi works as a developer in Java and Web Technologies. Basavaraju grad-
Table of Contents >> HTTP header issue, either change the configuration of the server or try uated from IIT Madras and has approximately 15 years of experience in IT.
hosting the .crx file on another server.
With this introduction, you should be well on your way to building
fun and useful extensions to Chrome.
Useful References
http://code.google.com/chrome/extensions/getstarted.html
http://en.wikipedia.org/wiki/JSON Comment
By Tom Thompson
ne of the great challenges facing developers of business ticle consolidates this information and introduces you to UITable-
IN THIS ISSUE
Guest Editorial >> events (typically touches). I have discussed the UIView class and
Mobile UI >> shown how to use it in the Dr. Dobb’s article, “The iPhone Isn’t Easy”
Chrome >>
iPhone >> (http://drdobbs.com/mobile/224200243).
Letters >> I mention the UIView class here because UITableView and
Links >> Figure 1: Comparing plain and group-style tables in iOS.
UITableViewCell subclass it. Therefore, they inherit the ability to dis-
Table of Contents >>
iOS tables come in two styles: plain and grouped. For the plain style, play content and respond to touch events. However, these classes do
a table consists of section headers, followed by rows of content dis- not store data. They only display the data and enable the user to inter-
played as lists. For example, the Mailboxes screen of the iOS Mail app act with the app’s data repository (which is known as the data model).
demonstrates this style. For the grouped style, the sections occupy dis- UITableView is responsible for implementing a table’s layout and
tinct screen regions, with the header and footer content appearing certain behaviors. It uses cell objects (described next) to organize and
above and below them. The Settings app is an example of this style. display the data. As Figure 2 shows, UITableView also inherits from
Figure 1 shows these two table styles, and indicates the sections, UIScrollView, which allows the table to be scrolled. However, the
headers, and footers. Note that while the plain style does support foot- table can scroll vertically only.
ers, they are often not used.
When you first create a table, you specify its style, either directly in the
code or in Interface Builder. Once set, a table’s style cannot be changed.
Table rows (cells) have four predefined styles: default, style1, style2,
and subtitle. These styles vary slightly in the number of built-in text
fields they offer and whether an optional image is displayed. Different
cell styles can appear in a table, and a cell’s style can change on the
fly, as driven by user actions.
Cells can also be customized to present additional text labels or im-
ages, or present controls such as sliders, buttons, and switches. For ex-
ample, in Figure 1 the grouped table (right) has cells that contain a
switch and a segment control.
Table Classes
A key class for managing an iOS device screen is the UIView. It is re-
sponsible for painting content onto the screen and capturing user Figure 2: How the Cocoa Touch objects and protocols interact to lay out a table.
IN THIS ISSUE The UITableViewCell class is responsible for displaying a row and
Guest Editorial >> its content. This class serves as a template that clones as many in-
Mobile UI >>
Chrome >> stances of a cell as is required to make up a section. In this sense,
iPhone >> UITableViewCell functions similarly to a Java factory method. Each
Letters >> cell can have a different style and displays the information that it ref-
Links >>
Table of Contents >> erences in the data model. As mentioned earlier, a cell can display text,
images, or controls. Cells are complex objects with many built-in views,
including several content-specific views, a background view, and an
accessory view. Figure 3 illustrates this. The accessory view displays
controls or optional images that assist in navigating to another screen.
Figure 3: Some of the key views in a cell using the default style.
Table Protocols
In iOS parlance, a protocol defines method declarations and the de- appearance of headers and footers, modify a cell’s height, and specify
sired responses when these methods are invoked. It’s up to the de- a background color or image. All methods in this protocol are optional.
veloper to assign a delegate object that implements the protocol. An A UITableViewController class is a variant of the NUIViewCon-
Objective-C protocol therefore functions like a Java interface. The iOS troller class that’s designed to manage a table. It packages house-
runtime is made aware that a class is a delegate object by the addition keeping functions and provides the stub routines for the data source
of a suitable protocol declaration in the class’s header file. and delegate protocol methods into one convenient view controller
Tables use two protocols: UITableViewDataSource_Protocol, class. This design allows the table’s event handling, data display, data
and UITableViewDelegate_Protocol. The UITableViewData- updates, and custom behavior to be contained in one omnibus object.
Source_Protocol obtains information for UITableView about UITableViewController also performs duties such as loading the
table layout and how to supply data to it for display. For table layout, table’s data, flashing the scroll indicators, and clearing the selection
this protocol defines two required methods. The first, num- choice. It exposes a property, tableview, which allows access to the
berOfRowsInSection, queries the app about the number of rows table view’s elements and properties.
a section has. The second method, cellForRowAtIndexPath, re- A final class, NSIndexPath, which has little to do with tables but is
trieves a specific cell in the table so that it can be matched up to its crucial to their operation, describes a path to a node in a tree of arrays.
data source and the data displayed. Recall that tables are organized as a hierarchy of lists, where each list
The UITableViewDelegate_Protocol describes how the table be- corresponds to an array. For tables, an instance of NSIndexPath pro-
haves and its appearance. This protocol is employed to customize the vides the section and row information that references a specific cell,
www.drdobbs.com April 2012 20
[IPHONE]
Previous Next
IN THIS ISSUE and can be used to also reference its data. Many table view methods where you can add your own code and observe the behavior. Click
Guest Editorial >> described here use NSIndexPath instances as arguments, or they re- Choose, name the project TestTable or something similar, and click
Mobile UI >>
Chrome >> turn results as an NSIndexPath. Save. Xcode generates a basic iOS app template that you can build and
iPhone >> For more information on each class, consult the iOS SDK documen- run. All the app displays at this point is a blank screen, but that’s fine.
Letters >> tation (http://is.gd/4gUK4l). We’re going to add the table as we go, and if something breaks along
Links >>
Table of Contents >>
the way, we’ll know where.
Making a Simple Table Now choose File > New File. In the dialog, select Cocoa Touch class,
Let’s write some code. The first decision is whether to use a NUIView- and NUIViewController subclass for the file’s code template. Under
Controller to manage the instance of UITableView, or a UITable- the options, make sure that UITableViewController subclass is
ViewController. The NUIViewController choice gives you fine- checked, and that With XIB for user interface is unchecked. This choice
grained control over every aspect of the table’s appearance and directs Xcode to add a UITableViewController class to the app’s
operation. However, such flexibility comes at a price: You have to man- template. Since we aren’t including a nib file, we’ll use Interface Builder
age every detail of the table’s operation, such as assigning and imple- to add the UI elements later. Click Next, and name the subclass file
menting the protocol delegate objects. In contrast, UITableViewCon- something descriptive like Table.m. When you build the app this time,
troller manages a lot of these details for you because it assigns itself two errors appear.
as the delegate object for both protocols, and provides some house- These errors flag the data source delegate methods numberOf-
keeping routines. The tradeoff is that some flexibility in table design is SectionsInTableView and numberOfRowsInSection. Xcode has
lost because this class implements certain default behaviors. However, provided stub routines for these data source protocols in the code
I have used UITableViewControllers for data display and in many template, but it can only go so far: You must supply information
cases I was able to customize the tables’ appearance without too much about the table layout. As mentioned previously, num-
effort. Unless you require an extremely customized UI, I would recom- berOfRowsInSection is a required method that requests the
mend starting with a UITableViewController. The example apps number of rows in a section. Oddly, numberOfSectionsInTable-
use UITableViewController for table management, so that is the View, which asks for the number of sections in the table, is not.
class I’ll discuss. We’ll start out simply by presenting a list of existing However, if you fail to provide a value greater than zero for the sec-
Apple products. tion number, the app crashes. For simple tables, you can hard-code
From within Xcode, Apple’s IDE for writing and debugging Mac OS these values, but for greater flexibility their values should be de-
X and iOS apps, choose File > New Project. In the New Project window, rived from the app’s data model. That way when the data model
choose iPhone OS Application and Window-based Application for the changes, so do the tables. Leave these alone for now, since we need
template. These choices will generate a minimalist app framework to create some data to display.
www.drdobbs.com April 2012 21
Previous Next [IPHONE]
IN THIS ISSUE
Guest Editorial >>
Make a new file with Xcode, but this time specify an Objective-C table data arrays so that you can buffer and process sensor informa-
Mobile UI >> class. For the “Subclass of” option, choose NSObject. Name this file tion or download data over the air into them before displaying their
Chrome >> TableData.m. Create a data array productNames, and add data strings contents.
iPhone >> to it, similar to that in Listing One. Now go back to Table.m, uncomment the method viewDidLoad,
Letters >>
Links >> and add code to initialize an instance of TableData called products
Table of Contents >> Listing One and to invoke initProductNames . Edit numberOfSection-
// TableData.m for a plain table sInTableView to return a value of one, and numberOfRowsInSec-
#import "TableData.h" tion to return a count value for the number of elements in the pro-
ductNames array. See the example app project PlainTable for more
//
@implementation TableData detail. If all goes well, the app should build without errors and run.
@synthesize productNames; However, nothing appears on the screen.
-(void) initProductNames {
productNames = [[NSMutableArray alloc] Final Fixes for Data Display
initWithObjects:@"iPhone", @"iPhone 3G", There are reasons for the lack of data on-screen. First, we haven’t done
@"iPhone 3GS", @"iPhone 4", anything about the other required data source method, cellFor-
@"iPod classic", @"iPod nano", @"iPod shuffle",
RowAtIndexPath. Search for that method in Table.m and you’ll find
@"iPod touch",
@"Macbook", @"Macbook Pro", @"Macbook Air", it soon enough. It is mostly stub code, which is why the app builds and
@"iMac", @"Mac mini", @"Mac Pro", executes without errors. This method returns a reference to UITable-
@"Apple TV", @"iPad", nil]; ViewCell, which is the class responsible for creating and displaying a
}
cell. (Listing Two.)
-(void)dealloc {
[productNames release]; Listing Two
[super dealloc];
- (UITableViewCell *)tableView:(UITableView *)tableView
}
@end cellForRowAtIndexPath:(NSIndexPath *)indexPath {
IN THIS ISSUE
Guest Editorial >> Given the rearrangement of the data model, the code in cellFor-
Mobile UI >> RowAtIndexPath must be modified as well. The code to update the
Chrome >> cell’s text content becomes:
iPhone >>
Letters >> cell.textLabel.text = [[listOfRows
Links >> objectAtIndex:indexPath.section]
Table of Contents >> objectAtIndex:indexPath.row];
Finally, to improve on the display of rows in the table, we modify the
table view’s property separatorColor, making it a light gray. This is
done in the numberOfSectionsInTableView method because it is
called only once. Now, when the app is built and run, the screen dis-
plays the products, partitioned into their families.
These examples only scratch the surface of what’s possible with iOS
Table 1: Important classes. tables. Feel free to edit and tinker with the example apps. Try changing
the cell’s style. Or with IB, change the table’s property from plain to
In the table view controller’s viewDidLoad method, we define grouped and observe the results. Such experiments can help expand
another array, listOfRows. Into this array we pack the product your knowledge of how iOS table design is done.
family arrays. See the second example program, SectionTable, Table 1 lists important classes and where they’re described in the
for details. SDK documentation.
For the numberOfSectionsInTableView method, instead of a hard-
coded value of one, we now return the count of the product sections,
like so: — Tom Thompson is a proactive support engineer at Freescale Semiconductor and a
frequent contributor to Dr. Dobb’s.
return [products.productSections count];
IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Chrome >>
This Month on DrDobbs.com
iPhone >>
Letters >>
Links >> Interesting items posted on
Table of Contents >>
www.drdobbs.com over the past
month that you may have missed
PROJECT OF THE MONTH: COJAC, A NUMERICAL of those services that zips up your code, ships it off to a build server in
PROBLEM SNIFFER the cloud, and has your APK file waiting for download somewhere.
Cojac’s runtime analysis of code identifies risky arithmetical operations http://drdobbs.com/blogs/tools/232602118
both in Java bytecode and in native binaries.
http://drdobbs.com/testing/232601564 THE CASE AGAINST INT, PART 3: THE ADVANTAGES
AND PERILS OF UNSIGNED ARITHMETIC
HOT-RODDING WINDOWS AND LINUX APP Integers are often used for counting, and that counting is often
PERFORMANCE WITH CUDA-BASED PLUGINS better suited to unsigned than to signed arithmetic. To that end,
Adding GPU capabilities to existing Windows and Linux apps can C++ defines an unsigned integer type, size_t, that is well-suited
be done simply using plugins and the built-in support found in to storing array indices, or otherwise counting items that can fit in
CUDA. This easy form of dynamic loading enables CUDA to be used the computer’s memory.
selectively to hugely accelerate individual tasks within a larger ap- http://drdobbs.com/blogs/cpp/232602212
plication.
http://drdobbs.com/parallel/232601605 THE SHRINKING EXPANDING WORLD OF CI
Continuous integration is undergoing somewhat of a renaissance
ANDROID ON ANDROID as continuous delivery (and its sidekick, DevOps) begin to find adop-
Android Java IDE, AIDE for short, has been released on the Android Mar- tion in many enterprises. Simultaneously, the number of viable CI
ket and provides a fully native Android application development ex- packages is shrinking quickly.
perience, running entirely on an Android device. And no, this is not one http://drdobbs.com/architecture-and-design/232601132
IN THIS ISSUE
Business Contacts
Guest Editorial >>
Mobile UI >> DR. DOBB’S SALES CONTACTS—EAST Entire contents Copyright © UBM TECHWEB
Chrome >> Sales Director, Michele Hurabiell Midwest, South, Northeast U.S. and Eastern Canada 2012, Techweb/United Busi- Tony L. Uphoff CEO
iPhone >> (415) 378-3540, mhurabiell@techweb.com (Saskatchewan, Ontario, Quebec, New Brunswick) ness Media LLC, except where John Dennehy CFO
Letters >> District Manager, Jenny Hanna otherwise noted. No portion of David Michael CIO
Links >> (516) 562-5116, jhanna@techweb.com this publication may be repro- Joseph Braue Sr. VP, Light Reading
duced, stored, transmitted in Communications Network
Table of Contents >> INFORMATIONWEEK BUSINESS District Manager, Michael Greenhut
any form, including computer Scott Vaughan CMO
(516) 562-5044, mgreenhut@techweb.com
TECHNOLOGY NETWORK retrieval, without written per- Ed Grossman Executive Vice President, Information-
Account Manager, Cori Gordon Week Business Technology Network
CMO, Scott Vaughan mission from the publisher. All
(516) 562-5181, cgordon@techweb.com
(949) 223-3662, svaughan@techweb.com Rights Reserved. Articles ex- John Ecke VP and Group Publisher,
Inside Sales Manager East, Ray Capitelli Financial Technology Network, InformationWeek
EVP of Group Sales, press the opinion of the author Government, InformationWeek Healthcare
(212) 600-3045, rcapitelli@techweb.com
InformationWeek Business Technology Network, and are not necessarily the Martha Schwartz EVP, Group Sales,
Martha Schwartz Sales Assistant, Elyse Cowen opinion of the publisher. Pub- InformationWeek Business Technology Network
(212) 600-3015, mschwartz@techweb.com (212) 600-3051, ecowen@techweb.com lished by Techweb, United Beth Rivera Senior VP, Human Resources
Publisher’s Assistant, Esther Rodriguez Strategic Accounts Business Media, 303 Second David Berlind Chief Content Officer,
(949) 223-3656, erodriguez@techweb.com Street, Suite 900 South Tower, TechWeb, and Editor in Chief, TechWeb.com
District Manager, Mary Hyland
(516) 562-5120, mhyland@techweb.com San Francisco, CA 94107 USA Fritz Nelson VP, Editorial Director,
SALES CONTACTS—WEST InformationWeek Business Technology
Account Manager, Tara Bradeen
415-947-6000.
Western U.S. (Pacific and Mountain states) Network, and Executive Producer, TechWeb TV
and Western Canada (British Columbia, (212) 600-3387, tbradeen@techweb.com
Eric Lundquist VP and Editorial Analyst, Information-
Alberta) Account Manager, Jennifer Gambino Week Business Technology Network
Inside Sales Manager, Vesna Beso (516) 562-5651, jgambino@techweb.com
UNITED BUSINESS MEDIA LLC
(415) 947-6104, vbeso@techweb.com Sales Assistant, Kathleen Jurina Pat Nohilly Sr. VP, Strategic Development and Business
Strategic Accounts (212) 600-3170, kjurina@techweb.com Admin.
Dr. Dobb’s Marie Myers Sr. VP, Manufacturing
Account Director, Sandra Kupiec
(415) 947-6922, skupiec@techweb.com Sales Director, Michele Hurabiell
Sales Assistant, Matthew Cohen-Meyer (415) 378-3540, mhurabiell@techweb.com
(415) 947-6214, mmeyer@techweb.com