Статьи

Полное руководство по разработке портативных приложений Tizen

Русский (русский) возможен перевод

Содержание

список рисунков

  1. W3C и другие стандарты
  2. Многоуровневая архитектура Tizen
  3. Браузер и Web Runtime
  4. Снимки экрана библиотеки JavaScript
  5. Расхождение богатых и богатых
  6. Структура установки веб-приложения
  7. Структура файловой системы веб-приложения
  8. Иконки Tizen SDK
  9. Основанная на Eclipse IDE
  10. Пульсирующий WRT симулятор
  11. Динамический анализатор производительности
  12. Samsung сделал устройство Tizen

Списки исходного кода

  1. Декларативное программирование с использованием jQuery Mobile и многостраничной инкапсуляции
  2. Полный Sencha Touch index.html, подходящий даже для больших проектов
  3. Реализация точки входа в приложение Sencha Touch
  4. Небольшое мобильное приложение Dojo, полностью реализованное в index.html
  5. Небольшое приложение Enyo JS, полностью реализованное в index.html
    (образец кода для этой статьи можно скачать здесь: zip , tar )

Абстрактный:

Эта статья дополняет серию онлайн-лекций на ежегодной конференции разработчиков Tizen и в других местах. Эти лекции, озаглавленные «JavaScripting Tizen Web Apps» и «Переносимость приложений Tizen», служат руководством для разработчиков, заинтересованных в Tizen и преимуществах портативных стратегий разработки.

Анализ доступных API Tizen начинается с рассмотрения стандартов и портативных веб-технологий. Рассмотрена архитектура Tizen, и отличие ее веб- и Native Frameworks приводит к проверке подхода развертывания Tizen и того, как он влияет на веб-логику и контент как серверных, так и локально установленных приложений.

При оценке стратегий использования библиотек JavaScript представлен ряд популярных кандидатов. Внимание уделяется встроенной версии Web Framework jQuery Mobile, а также сторонним альтернативам, таким как Sencha Touch, Dojo Mobile и Enyo JS. Наряду с кратким объяснением мостов нативного кода в javascript и их потенциала в области портативного использования API устройства Tizen примеры кода иллюстрируют полезность популярных библиотек JavaScript.

Я представляю тизен

Что касается мобильных операционных систем, Tizen   [Tsg01] , безусловно, новый игрок. Эта уникальная платформа, основанная на партнерстве между Samsung, Intel и Linux Foundation, намерена в скором времени привести в действие множество устройств. По словам Samsung, «мы планируем выпустить новые конкурентоспособные устройства Tizen в течение этого года и будем продолжать расширять линейку в зависимости от условий рынка». [Busweek01] По мере взросления ОС и API Tizen становится ясно одно. Архитекторы Tizen ставят концепцию портативных приложений, построенных на стандартных технологиях, в первую очередь.

В этой статье мы рассмотрим основы того, как API Tizen поддерживают разработку переносимых приложений. Независимо от того, использует ли разработчик официальный комплект разработки программного обеспечения Tizen (SDK) или другие инструменты разработки, приложения, написанные для веб-платформы Tizen [Saxena01] [Tsg02], можно относительно легко переносить на другие платформы, используя веб-стандарты. Будучи новой технологией, Tizen выиграет еще больше от портирования уже существующих веб-приложений [Wang01] .

Мотивация портативной разработки

Хотя разработчики и пользователи одинаково выигрывают от приложений, работающих на различных операционных системах, интересно, что те, кто больше всего влияет на архитектуру Tizen, ценят его переносимость по сравнению с различными пользовательскими интерфейсами, которые появятся в будущих устройствах Tizen. Сунил Саксена утверждает, что «архитектура Tizen делает упор на WebAPI для обеспечения работы приложений на разных архитектурах и разных профилях» [Saxena02], что означает, что навигационный компьютер с низким энергопотреблением будет выполнять и отображать географическое приложение так же, как ноутбук или планшет с большим энергопотреблением. компьютер будет. Портативные API также позволяют многократно использовать программное обеспечение, что может значительно снизить дорогостоящие затраты на разработку.

Принимая во внимание богатую поддержку платформы Tizen для портативной разработки, важно помнить, что Tizen также предоставляет нестандартную, но ценную инфраструктуру. Плюсы лежат между сэндвичем POSIX-дружественного ядра GNU / Linux и средами Tizen. А именно, вместо Qt или Gtk библиотеки Enlightenment Foundation (EFL) предоставляют Tizen виджеты и поддерживают графические строительные блоки. Хотя приложения, связанные с EFL, основаны на Unix-подобных ядрах с использованием переносимого и стандартного ISO C, не стоит ожидать, что они будут работать на Windows Phone, iOS или Blackberry 10 на базе Qnx, если назвать несколько. В этой статье мы сужаем определение разработки портативных приложений, чтобы сосредоточить наше внимание на веб-технологиях, таких как JavaScript, CSS и HTML.

Всемирный суп

Не говоря о гиперпространственных словах, большинство разработчиков современных веб-приложений высоко ценят богатый набор функций, предоставленный недавними достижениями в HTML5, CSS3, JavaScript, а также связанными веб-технологиями, такими как XMLHttpRequest (XHR) или множеством библиотек JavaScript [Bennewitz01] . На самом деле веб-интерфейсы настолько часто смешаны, что многие называют этот новый веб-суп просто состоящим из «HTML5», не говоря уже о том, что HTML5 сам по себе является новым стандартом.

Рисунок 1: С уважением к стандартам,
W3C TSL

Стандартизированные интерфейсы и реализации, такие как HTML, ускорили внедрение веб-технологий, что, в свою очередь, усилило те самые стандарты (W3C, ECMA, IETC, ISO), которые способствуют мобильности. Между тем, сообщества разработчиков опередили темпы разработки стандартов, что привело к появлению ряда баз данных и утилит, полезных для оценки соответствия стандартам, принятия API и общей совместимости веб-технологий. Вот некоторые примеры:

Tizen Architecture

Заявленная цель рабочей группы Tizen при разработке уровней ядра, ядра, инфраструктуры и приложений включает использование «надежных возможностей HTML5 и межплатформенной гибкости» для расширения возможностей разработчиков переносимых приложений. «Tizen SDK и API позволяют разработчикам использовать HTML5 и связанные с ним веб-технологии для написания приложений, которые работают в нескольких сегментах устройств, включая смартфон, планшет, Smart TV, информационно-развлекательную систему в автомобиле и нетбук». [Linux01]

Рисунок 2: Архитектура Tizen SDK 2.0 , CC Attribution 3.0 Unported

Продавцы и устройства сегментов

The construction of Tizen differs from one device segment to the next. Vendors can take advantage of the open nature of Tizen’s development cycle to modify the OS to suit their needs, and several key system components deviate to demonstrate this [Clark01]. For example, Tizen’s official IVI image profile distributes the Qt library alongside EFL. Each finished Tizen image aggregates software packaged in the RPM format corresponding to a specific architecture (like IA32 or ARMv71) and device segment.

What unifies these Tizen variants is the fact that their component diagrams are arranged like a sandwich, with applications resting on the framework layer which in turn lies on the core. Each layer is a collection of components in itself, and even the core consists of the Linux kernel, device drivers, and a variety of low level APIs and subsystems.

Web Runtime and Web Framework

Figure 3: Similarity between the Tizen Browser and Web Runtime, GNU Free Documentation License 1.3

      

One of the most important components is the Tizen Web Runtime, the component that allows web apps to run outside the browser. Tizen users can install and use web apps as if they were standalone applications, and the Web Runtime manages the life cycle, system calls, execution, resources, platform integration, and access control of the web app [Jin01][Mtsc01].

Similarly named, the Web Framework aggregates the Web Runtime along with the W3C API, Device API, and a UI framework containing widgets derived from jQuery Mobile.

By exposing the standard W3C and unique Device APIs, Tizen offers added value to web apps that could otherwise only render HTML and carry out generic JavaScript. The Tizen W3C API implements web standards relating to DOM, styles, device, graphics, media, communication, storage, security, UI, performance, location, and widget. The Device API provides advanced logic employing sensors, file I/O, capturing, telephony, FM radio, speech recognition, HDMI output, and more.

WebKit adoption

To render web content the Tizen Web Runtime employs the WebKit layout engine in a similar fashion as Android, Chrome, Safari, MeeGo, Qt, and a number of other WebKit dependent projects. A consideration when choosing a JavaScript library (see section) is indication of WebKit support as well as support for whichever engine the developed software should be portable on.

GNU/Linux and sources

Rather than blurring the lines of free license by releasing binary blobs of kernel and libc while publishing only sanitizing header files, Tizen’s GNU/Linux kernel and other sources are complete, online, and publicly accessible. Any developer can pull a copy of these sources and build their own Tizen image [Tsg03] ready for installation to hardware. After installed, Tizen is bootstrapped by the U-Boot boot loader as with many low power or embedded systems.

JavaScript Libraries

To maximize portability we focus on the model of Tizen development dependent on a web framework. It’s this model that minimizes system dependencies and empowers development of far ‘reach’ in apps.

Although the Tizen Web Framework incorporates a custom themed JQuery Mobile installation, the competing web frameworks aren’t only useful for porting existing applications. Rather, they’re perfect for original Tizen development as well when leveraging the skill set of a developer already familiar with Dojo, requiring the complex fine tuned JavaScript manipulation for which Sencha Touch is known for, or just reusing code written in a pre dating JavaScript library like Enyo JS.

Figure 4: Praiseworthy cross-platform portability of installable Tizen web apps, GFDL 1.3

JQuery Mobile

This is one of few libraries that support more than WebKit rendering. In fact, jQuery Mobile supports the WebKit, Gecko (Mozilla), Presto (Opera), and Trident (Microsoft) engines as well. With such attention to compatibility it’s no surprise that Tizen already enjoys A-grade support, with a fully enhanced experience and Asynchronous JavaScript and XML (AJAX) based animated page transitions [Jqm01]. This compatibility factor is an advantage when developing Tizen web apps to be portable with Mozilla’s Firefox OS or Microsoft’s Windows Phone.

   <head>
     <link rel="stylesheet" href="//code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.css" />
     <script src="//code.jquery.com/jquery-1.8.2.js"></script>
     <script src="//code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.js"></script>
   <body>
  <div data-role="page" id="firstpage">
    <div data-role="header">
      <h1>Nice header</h1>
    </div>
    <div data-role="content">
      <p>I'm the first page. Click for <a href="#secondpage">Second page</a></p>
    </div>
  </div>
  <div data-role="page" id="secondpage">
    <div data-role="content">
      <p>I'm the second page. Click for <a href="#firstpage">First page</a></p>
    </div>
  </div>
  </body>

Listing 1: Declarative programming with jQuery Mobile and multi page encapsulation

jQuery Mobile’s most unique features is its accommodation of the declarative programming paradigm to best suite those familiar with static web pages. It ingeniously rearranges the DOM when parsing static HTML and avoids page HTTP round trips and page refreshes without developer intervention.

Sencha Touch

This popular JavaScript library differs from declarative alternatives in that its structural nature works almost exclusively with JavaScript. Typical with Sencha Touch apps, the directory index (index.html) looks empty and really just serves as a boot loader to the JavaScript logic that in turn builds the document object model (DOM) dynamically. The user’s browser window layout is constructed by supplying the Sencha Touch library with JavaScript code and JSON data that the library uses in deciding how to construct the ‘view.’ This elegant approach has its advantages, but involves a steeper learning curve than jQuery Mobile.

  <!DOCTYPE html>
  <html>
  <head>
    <title>Simple Sencha</title>
    <link rel="stylesheet" href="//cdn.sencha.com/touch/sencha-touch-2.1.1/resources/css/sencha-touch.css" />
    <script src="//cdn.sencha.com/touch/sencha-touch-2.1.1/sencha-touch.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
    <!-- Nothing here! -->
  </body>
  </html>

Listing 2: A complete Sencha Touch index.html, suitable even for large projects

The entry point of web apps built with Sencha is a handler for the launch (not lunch!) event fired by Sencha logic when the library is loaded. A lot of ‘Ext’ keywords in this and other code reveal that this architecture evolved from the historically significant Sencha ExtJS library.

  Ext.application({
    launch: function() {
      alert('App launched!');
    }
  });

Listing 3: Implementation of the entry point to a Sencha Touch app

Recent developments in Sencha Touch have led to a important release commonly referred to by its main version 2 [Sencha01]. A number of additions were made, including some native-to-JavaScript (see section) bridging on iOS and Android as well as a build infrastructure to produce the corresponding native packages. This is all quite useless to Tizen unfortunately, unless Sencha moves beyond their Android/iOS centric support model.

Dojo Mobile

The Dojo Mobile library is similar to jQuery Mobile in that its cutting edge mobile and touch specific logic extends the mature core of the JavaScript Dojo Toolkit library. It allows the developer to program the DOM declaratively by parsing simple HTML and automatically marshals page data over XHR similar to jQuery Mobile to perform smooth page transitions and effects, but Dojo Mobile is unique for providing a modular loading mechanism and distributing its JavaScript library bundled in modules which implement Dojo APIs responsible for data abstraction and DOM manipulation. It incorporates internationalization (i18n) components by design and offers a lot in terms of abstraction of data from control flow. Dojo Mobile best suits iOS, Android, and Blackberry for their look and feel, but its widget theme adaptation is flexible enough to put Dojo Mobile on par with the other competing portable JavaScript libraries for Tizen web app development as well.

  <!DOCTYPE html>
  <html>
  <head>
    <title>Our Dojo Test</title>
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dojo/dojo.js"></script>
    <script>
      require([
      "dojox/mobile/parser",
      "dojox/mobile",
      "dojox/mobile/deviceTheme"],
      function(parser) {
        parser.parse();
      });
    </script>
  </head>
  <body>
    <div id="settings" data-dojo-type="dojox.mobile.View">
      <h1 data-dojo-type="dojox.mobile.Heading">Tizen App with Dojo Mobile</h1>
    </div>
  </body>
  </html>

Listing 4: A small Dojo Mobile app implemented completely in index.html

Enyo JS

At the heart of Enyo JS is a simple but powerful encapsulation model, which helps to factor application functionality into self-contained building blocks that are easy to reuse and maintain [Enyo01]. One of the appealing factors of this library is its widespread use in plentiful web apps both new and old. Enyo certainly profited from wide distribution of the Linux-based WebOS with the historical Palm and HP devices, in which Enyo was used as the primary web framework.

  <!DOCTYPE html>
  <html>
  <head>
    <title>Our Enyo Test</title>
    <link rel="stylesheet" href="//enyojs.com/enyo-2.2.0/enyo.css" />
    <script src="//enyojs.com/enyo-2.2.0/enyo.js"></script>
  </head>
  <body>
    <script>
      new enyo.Control({content: "Hello From Enyo"}).renderInto(document.body);
    </script>
  </body>
  </html>

Listing 5: A small Enyo JS app implemented completely in index.html

HTML5 Boilerplate

Although the Tizen IDE template for HTML5 Boilerplate projects was removed in the SDK 2.0 release, HTML5 Boilerplate still deserves attention for the utility it provides and broad following among developers. The HTML5 Boilerplate deliverables can be easily merged with any of the web app project templates in the Tizen IDE, and when used wisely, it accelerates development of logic common to the early stages of most web apps. Of particular interest in HTML5 Boilerplate is provision of ‘Modernizr’ browser detection and ‘Normalize’ CSS consistency logic. Other boilerplate files relate to Apache, custom 404 pages, cross-domain, robot indicators, and icons.

Native-to-JavaScript bridges

Figure 5: Divergence of rich and reach in mobile apps, GFDL 1.3

Certain Tizen APIs (even in the Web Framework) feature entry points to unportable constructs responsible for components such as time, settings, connection, contacts, device, file, media, notification, storage, events, camera, and capture. Employing any of these APIs reduces portability of the application in question. To regain lost cross platform portability, it’s good to know about projects implementing native-to-JavaScript bridge technology for hybrid apps.

[Cordova01].

There’s not many other competing hybrid JavaScript frameworks, but the ‘Titanium’ branded tools by Appcelerator are being ported [Muschenetz01] to support Tizen APIs.

Package standard

Tizen web apps are packaged [Shiva01] according to the W3C widget packaging specification [W3C01], just as the Wholesale Applications Community (WAC) mandated.

File boat.wgt:

Figure 6: Example installation structure of a web app file, GFDL 1.3

Figure 7: Corresponding file system layout for example web app ‘boat.wgt,’ GFDL 1.3

Store deployment

Nevertheless, packages are only part of the deployment strategy. After much speculation the official Tizen Store was mentioned during the Mobile World Congress 2013 [Mueller01], but without details of infrastructure nor APIs. Since there’s been no official release of this technology, for the time being packages must be consumed either in the traditional way or by leveraging any of a number of competing yet compatible third party web app servers providing a store-like experience:

Tizen Development Tools

The Tizen SDK is a comprehensive set of tools for developing Web applications, native applications, and the platform component for Tizen. It contains an install manager, IDE, tools, documents, samples, and a platform image [Tsg03]. Once installed, its logical file hierarchy includes: ide, install-manager, library, platforms, and tools.

Figure 8: GUI tools distributed in the Tizen SDK 2.0, GNU Free Documentation License 1.3

Tizen integrated development environment

The Tizen integrated development environment (IDE) is a Eclipse derived program, so it requires a Java runtime to work. Because the Eclipse core provides so much customization and leverages Java APIs to do this, there are special requirements involved. Contrary to the theoretically portable nature of Java, problems arise when using OpenJDK and other alternative Java environments. Particularly, Oracle’s Java v6 JDK (not JRE) or later is required [Tsg04].

Figure 9: The Tizen SDK 2.0 Eclipse-based IDE, GNU Free Documentation License 1.3

Regardless of the installation requirements, developers of the Tizen SDK have chosen wisely in deriving from the Eclipse IDE. It provides plugin infrastructure to support a comfortable method of generating certificates, event injection, validating code, packaging applications, and more.

Other important Tizen SDK deliverables include the Tizen emulator and simulator. While these tools differ internally, they perform similar duties in imitating the run time behavior of the operating system.

Tizen emulator

The Tizen emulator uses the QEMU machine emulator and virtualizer to provide the developer with an fully hardware and GPU (GLES) accelerated environment when the host system (with KVM or HAX) and hardware supports it. A number of convenient options appear once the emulator runs to enable screen rotation and scaling, screen shot manipulation, host keyboard input capturing, ram dump diagnosis, and shell access. The emulator can additionally field system events (battery, ear jack, USB, received signal strength indication, SD card, geolocation, NFC, accelerometer, voice and text telephony, light, motion, and proximity sensors) injected by the Tizen IDE or SDB (described below) for a high degree of extensive testing.

Tizen simulator

Figure 10: The Tizen SDK 2.0 WRT Simulator, GNU Free Documentation License 1.3

Tizen SDK developers have released a special web-based test facility called the Tizen simulator. The simulator is not a independent piece of software however, but is rather a interesting blend of the Apache Ripple web runtime simulator already in use by groups like Cordova, WAC, and WebWorks. Ripple isn’t a binary either. Instead, it is a web app in itself that bootstraps by starting a web browser and loading standard web logic. In order to mitigate problems with XHR cross and null origin access, the Tizen simulator makes assumptions about the installed host web browser, requiring either Google Chromium or Chrome by hard coding start up arguments like ‘allow-file-access-from-files’ and ‘disable-web-security.’

Concerning the Tizen emulator and simulator, release engineers have correctly named these tools in describing their emulating and simulating natures. It follows that the Tizen simulator includes no kernel of its own, exposes no APIs at all, and is useless for testing drivers, security, primitive graphics, and native development of any kind. But before throwing away the piece, it’s important to know one thing. The Tizen simulator is priceless when testing web applications that benefit from a quick edit and test interpretation cycle.

Figure 11: Performance bottlenecks diagnosed using the ‘Dynamic Analyser,’ GFDL 1.3

Packed into the Tizen SDK are a few convenience tools as well as performance boosting diagnosis tools. Of particular interest to software designers and graphical tool enthusiasts are the ‘UI Builder’, ‘UI Effect Builder’, and ‘Dynamic Analyser.’

Summary

While mobile strategy comparisons of web and native app development assume mutually exclusive APIs, Tizen provides a unique Web Framework serving elements of both worlds. Web apps can leverage this to benefit from feature complete and portable standards-based development. Learning the ropes of web app development for Tizen and other mobile platforms makes sense for these reasons.  (You can download the sample code for this article here: zip, tar)

Figure 12: A Samsung made Tizen device presented at Mobile World Congress 2013

Benefits of portability

Devices on which Tizen runs have potential regardless of mobile strategy and it’s likely that many will embrace Tizen’s ability to support native development for good reasons. Nevertheless, advancing both Tizen and developers’ interests in a market of emerging technology by employing standard APIs as provided by Tizen’s Web Framework can be favorable. If the Tizen app landscape is best served by both quality and variety, then developers should turn their attention to portable development of both original and existing (ported from other platforms) web apps. Tizen’s architects have gone to lengths to allow low-level APIs to be leveraged from web apps. Developing portable Tizen apps using web technologies is both practical and effective.

Works Cited

Joel Clark.
Qt/qml or efl in tizen ivi.

http://lists.tizen.org/listinfo/ivi/, June 2012.

About enyo, core concepts.
http://www.enyojs.com/about/, 2012.
Web Applications Working Group.
Packaged web apps (widgets).

http://www.w3.org/TR/widgets/, November 2013.

Ming Jin.
Tizen web runtime.

In
Tizen Developer Conference, San Francisco, California, May 2012.

http://www.tizen.org/events/tizen-developer-conference/2012/conference-schedule#session_180.

Mobile graded browser support.
http://www.jquerymobile.com/gbs/, 2013.
Jungah Lee.
Samsung to sell tizen-based handsets after motorola deal.

Businessweek, January 2013.

http://www.businessweek.com/news/2013-01-03/samsung-to-sell-tizen-based-handsets-after-google-motorola-deal/.

Sdk/docs/1.1/web sdk with wrt.
http://wiki.meego.com/SDK/Docs/1.1/Web_SDK_with_WRT, 2011.
Ingo Muschenetz.
Titanium mobile tizen preview now available.

Web log, Appcelerator Developer Blog, February 2013.

Mirko Müller.
Tizen‘s app-store erstmals gezeigt.

Web log, Tizen Blog, March 2013.

René Pourtier and Luc Yriarte.
Enabling cordova on tizen.

In
Tizen Developer Conference, San Francisco, California, May 2012.

http://www.tizen.org/events/tizen-developer-conference/2012/conference-schedule#session_272.

Sunil Saxena.
Tizen architecture.

In
Tizen Developer Conference, San Francisco, California, May 2012.

http://www.tizen.org/events/tizen-developer-conference/2012/conference-schedule#session_150.

Sunil Saxena.
Tizen architecture overview.

In
Linux Foundation Collaboration Summit, San Francisco, California, April 2012.

https://www.tizen.org/events/2011/linux-foundation-collaboration-summit-2012/.

Accessing native apis with ext.device.
http://docs.sencha.com/touch/2-1/#!/guide/native_apis, February 2013.
Raghavendra Reddy Shiva.
Tizen application packaging overview.

http://developer.tizen.org/documentation/tizen-application-packaging-overview/, December 2012.

Michael Schloh von Bennewitz.
Tizen application portability.

In
Tizen Developer Conference, San Francisco, California, May 2012.

http://www.tizen.org/events/tizen-developer-conference/2012/conference-schedule#session_271.

About apache cordova.
http://cordova.apache.org/, 2012.
Architecture of tizen.
http://developer.tizen.org/help/topic/org.tizen.gettingstarted/html/tizen_overview/tizen_architecture.htm, 2013.
Prerequisites for the tizen sdk.
http://developer.tizen.org/downloads/sdk/installing-sdk/prerequisites-tizen-sdk/, February 2013.
Tizen.
http://www.tizen.org/, March 2013.
Tizen 2.0 release notes.
http://developer.tizen.org/downloads/sdk/2.0-release-notes/, February 2013.
Kevin Wang and Darren Hjung.
Porting guide.

http://wiki.tizen.org/wiki/Porting_Guide, February 2013.

Tizen Workgroup.
Tizen.

http://www.linuxfoundation.org/collaborative-projects/tizen, 2012.

Daniel Juyung Seo (SeoZ)

Samsung RD-PQ Handset Photo.

http://pds27.egloos.com/pds/201303/28/58/a0004058_51531936eb6eb.jpg, March 2013.

(You can download the sample code for this article here: zip, tar)