Você está na página 1de 100

Application Development Guide for Samsung Smart TV

Version 1.20

Samsung Smart TV

Application Development Guide for Samsung Smart TV


APPLICATION DEVELOPMENT GUIDE FOR SAMSUNG SMART TV .......................................................... 1

PREFACE ............................................................................................................................................................................ 7 1. INTRODUCTION .................................................................................................................................................... 8 1.1. 2. WHAT IS SAMSUNG SMART TV? .......................................................................................................................... 8

SAMSUNG SMART TV ........................................................................................................................................... 9 2.1. 2.2. OPERATING PRINCIPLE ......................................................................................................................................... 9 OPERATING ENVIRONMENT .................................................................................................................................. 9

3.

APPLICATIONS .................................................................................................................................................... 10 3.1. 3.2. 3.3. 3.4. 3.5. 3.6. WHAT ARE APPLICATIONS? ................................................................................................................................. 10 STRUCTURE OF AN APPLICATION ........................................................................................................................ 10 DISPLAY TYPE OF APPLICATIONS ........................................................................................................................ 11 RUNNING AN APPLICATION ................................................................................................................................. 12 APPLICATION MANAGER .................................................................................................................................... 12 FEATURES OF SAMSUNG APPLICATIONS ............................................................................................................. 13

4.

CREATING AN APPLICATION .......................................................................................................................... 14 4.1. 4.2. WHAT YOU NEED TO CREATE AN APPLICATION.................................................................................................... 14 HOW TO MAKE AN APPLICATION ........................................................................................................................ 14 Writing config.xml ..................................................................................................................................... 15 Writing index.html ..................................................................................................................................... 16 Writing JavaScript .................................................................................................................................... 16 Writing a CSS ............................................................................................................................................ 17 Use of the remote control .......................................................................................................................... 18 Complete your work & Sample code......................................................................................................... 20
config.xml ...............................................................................................................................................................20 index.html ...............................................................................................................................................................21 Main.js ....................................................................................................................................................................21 Main.css ..................................................................................................................................................................22

4.2.1. 4.2.2. 4.2.3. 4.2.4. 4.2.5. 4.2.6.


4.2.6.1. 4.2.6.2. 4.2.6.3. 4.2.6.4.

4.3.

CONFIG.XML ....................................................................................................................................................... 23

4.3.1. 4.3.2. 4.4.

Tag information ......................................................................................................................................... 23 Example .................................................................................................................................................... 26

SINGLE-SIGN-ON ............................................................................................................................................... 27 What is Single-Sign-On ............................................................................................................................. 27 Registration of Account Information on Service Sites............................................................................... 28

4.4.1. 4.4.2.

Application Development Guide for Samsung Smart TV


4.4.3. 4.5. How to download account information on service sites in applications ................................................... 30

RESET ................................................................................................................................................................ 32 What is Reset? ........................................................................................................................................... 32 How Reset Works? .................................................................................................................................... 32 Necessary Features Developers Should Realize ....................................................................................... 32 Guide for Config.xml Realization ............................................................................................................. 32 Guide for Module Realization ................................................................................................................... 32

4.5.1. 4.5.2. 4.5.3. 4.5.4. 4.5.5. 4.6. 5.

EXAMPLE FOR XHR COMMUNICATION .............................................................................................................. 34

COMMON MODULES .......................................................................................................................................... 37 5.1. 5.2. 5.3. 5.4. APPLICATION MANAGERS COMMON MODULES ................................................................................................. 37 HOW TO USE COMMON MODULES ....................................................................................................................... 37 TVKEYVALUE ................................................................................................................................................... 37 WIDGET ............................................................................................................................................................. 40 sendReadyEvent() ..................................................................................................................................... 40 sendExitEvent() ......................................................................................................................................... 41 sendReturnEvent() .................................................................................................................................... 41 blockNavigation() ..................................................................................................................................... 41 putInnerHTML() ....................................................................................................................................... 42 getChannelWidgetListPath() ..................................................................................................................... 43 getSearchWidgetListPath() ....................................................................................................................... 43 runSearchWidget() .................................................................................................................................... 44 checkSapTicket () ...................................................................................................................................... 44 requestSapTicket () .................................................................................................................................... 45

5.4.1. 5.4.2. 5.4.3. 5.4.4. 5.4.5. 5.4.6. 5.4.7. 5.4.8. 5.4.9. 5.4.10. 5.5.

PLUGIN .............................................................................................................................................................. 45 setOnWatchDog() ...................................................................................................................................... 47 setOffWatchDog()...................................................................................................................................... 47 setOnOSDState() ....................................................................................................................................... 48 setOffOSDState() ....................................................................................................................................... 48 registKey()................................................................................................................................................. 49 unregistKey()............................................................................................................................................. 49 registIMEKey() ......................................................................................................................................... 49 unregistIMEKey()...................................................................................................................................... 50 registAllKey............................................................................................................................................... 50 unregistAllKey() ........................................................................................................................................ 51 registFullWidgetKey() ............................................................................................................................... 51 registPartWidgetKey() .............................................................................................................................. 52

5.5.1. 5.5.2. 5.5.3. 5.5.4. 5.5.5. 5.5.6. 5.5.7. 5.5.8. 5.5.9. 5.5.10. 5.5.11. 5.5.12.

Application Development Guide for Samsung Smart TV


5.5.13. 5.5.14. 5.5.15. 5.5.16. 5.5.17. 5.5.18. 5.5.19. 5.5.20. 5.5.21. 5.6. SetBannerState() ....................................................................................................................................... 52 ShowTools()............................................................................................................................................... 53 setOnIdleEvent() ....................................................................................................................................... 54 setOffIdleEvent() ....................................................................................................................................... 54 setOnScreenSaver() ................................................................................................................................... 54 setOffScreenSaver()................................................................................................................................... 55 isViewerKey() ............................................................................................................................................ 55 setOnFullScreen () .................................................................................................................................... 56 setOffFullScreen() ..................................................................................................................................... 56

CIMAGEVIEWER ................................................................................................................................................ 57 CImageViewer? ......................................................................................................................................... 57 Specifications ............................................................................................................................................ 57 Basic Instructions ..................................................................................................................................... 57 Transition Effect ........................................................................................................................................ 58
Action Principles of Slideshow ...............................................................................................................................59 How to Realize Transition Effect ............................................................................................................................60 Slideshow Mode and Restrictions ...........................................................................................................................61

5.6.1. 5.6.2. 5.6.3. 5.6.4.


5.6.4.1. 5.6.4.2. 5.6.4.3.

5.6.5. 5.6.6.
5.6.6.1. 5.6.6.2.

Events ........................................................................................................................................................ 62 Play local files .......................................................................................................................................... 62


Play Images in an Application ................................................................................................................................62 Play images in USB ................................................................................................................................................63

5.6.7.
5.6.7.1. 5.6.7.2. 5.6.7.3. 5.6.7.4. 5.6.7.5. 5.6.7.6. 5.6.7.7. 5.6.7.8. 5.6.7.9.

Reference................................................................................................................................................... 64
CImageViewer ........................................................................................................................................................64 Effect ......................................................................................................................................................................65 clearScreen() ...........................................................................................................................................................66 destroy() ..................................................................................................................................................................66 endSlideshow() .......................................................................................................................................................67 getStopFlag() ..........................................................................................................................................................67 hide().......................................................................................................................................................................68 isEffectAvailable() ..................................................................................................................................................68 play().......................................................................................................................................................................68 prepareNext() .....................................................................................................................................................69 setFrameArea() ...................................................................................................................................................70 setOnBufferingComplete() .................................................................................................................................71 setOnBufferingStart() .........................................................................................................................................71 setOnNetworkError() ..........................................................................................................................................72

5.6.7.10. 5.6.7.11. 5.6.7.12. 5.6.7.13. 5.6.7.14.

Application Development Guide for Samsung Smart TV


5.6.7.15. 5.6.7.16. 5.6.7.17. 5.6.7.18. 5.6.7.19. 5.6.7.20. setOnRenderError() ............................................................................................................................................72 setOnRenderingComplete () ...............................................................................................................................73 show().................................................................................................................................................................73 showNow () ........................................................................................................................................................73 startSlideshow () .................................................................................................................................................74 stop () .................................................................................................................................................................75

6.

TIPS FOR APPLICATION DEVELOPERS ........................................................................................................ 76 6.1. 6.2. 6.3. 6.4. 6.5. 6.6. 6.7. 6.8. 6.9. 6.10. 6.11. 6.12. 6.13. 6.14. 6.14.1. 6.14.2. 6.15. 6.16. 6.17. 6.18. 6.19. 6.20. 6.20.1. 6.20.2. 6.20.3. 6.21. FUNCTION NECESSARY TO BE CALLED WHEN YOU OPEN AN APPLICATION .......................................................... 76 ACCESS POINT ................................................................................................................................................... 76 HANDLING REMOTE CONTROL KEY EVENTS ....................................................................................................... 76 REMOTE CONTROL KEYS FOR APPLICATIONS ...................................................................................................... 77 CLOSING AN APPLICATION .................................................................................................................................. 79 PREVENTION OF CLOSING THE TV SCREEN BY THE RETURN OR EXIT KEY.......................................................... 79 ADDITIONAL INFORMATION ............................................................................................................................... 79 WHAT CSS NEED TO CONTAIN ........................................................................................................................... 80 LOADING IMAGES IN ADVANCE .......................................................................................................................... 80 CHARACTER OF THE <INPUT> TAG ................................................................................................................. 81 SCROLL BAR ...................................................................................................................................................... 81 MAKING DYNAMIC WEB PAGES ...................................................................................................................... 81 SETTING FOR LETTER-SPACING ...................................................................................................................... 82 MEMORY MANAGEMENT ................................................................................................................................ 82 Using XMLHttpRequest ............................................................................................................................ 82 Freeing up the memory ............................................................................................................................. 82 WATCH DOG .................................................................................................................................................. 82 PREVENTION FOR OSD DISTORTION............................................................................................................... 83 SUPPORT CSS TEXT-OVERFLOW ..................................................................................................................... 83 DIRECTIONS FOR CREATING VIDEO APPLICATION............................................................................................ 83 USING IME .................................................................................................................................................... 83 MINIMIZING INITIAL ENTRY SPEED OF AN APPLICATION .................................................................................. 83 Load Javascript On-Demand .................................................................................................................... 83 Load CSS Background Image On-Demand ............................................................................................... 84 Separation of Main.onLoad functions ....................................................................................................... 84 DIRECTIONS FOR DYNAMIC LOADING OF CSS ............................................................................................... 85

7.

APP ENGINE .......................................................................................................................................................... 87 7.1. APP ENGINE? ..................................................................................................................................................... 87

Application Development Guide for Samsung Smart TV


7.2. 8. STANDARD SPECIFICATIONS ............................................................................................................................... 87

FILE API ................................................................................................................................................................. 88 8.1. 8.2. FILE API? .......................................................................................................................................................... 88 API .................................................................................................................................................................... 88 FileSystem() .............................................................................................................................................. 88 openCommonFile() ................................................................................................................................... 89 closeCommonFile() ................................................................................................................................... 90 deleteCommonFile() ................................................................................................................................. 90 createCommonDir() .................................................................................................................................. 91 deleteCommonDir() .................................................................................................................................. 91 isValidCommonPath() ............................................................................................................................... 92 readLine() ................................................................................................................................................. 92 writeLine() ................................................................................................................................................ 93 readlAll() ................................................................................................................................................... 93 writeAll() ................................................................................................................................................... 94 readDir() ................................................................................................................................................... 94 openFile() ................................................................................................................................................. 95

8.2.1. 8.2.2. 8.2.3. 8.2.4. 8.2.5. 8.2.6. 8.2.7. 8.2.8. 8.2.9. 8.2.10. 8.2.11. 8.2.12. 8.2.13. 9.

APPENDIX.............................................................................................................................................................. 96 9.1. 9.2. 9.3. 9.4. 9.5. COUNTRY CODE ................................................................................................................................................. 96 LANGAUAGE CODE ............................................................................................................................................ 97 REGION CODE .................................................................................................................................................... 99 PRODUCT CATEGORY ....................................................................................................................................... 100 CAUTION INFORMATION ................................................................................................................................... 100 Character sensitive target device ............................................................................................................ 100

9.5.1.

Application Development Guide for Samsung Smart TV

Preface
Purpose of Document

This document is written to help application developers who enjoy the Samsung Smart TV service by providing an overview of the service and basic knowledge required to be obtained by application developers. Using this document, developers can develop and manage applications for digital TVs. Target Readers

This document is aimed at programmers who have used web development languages such as HTML, CSS and JavaScript. This document will be even more helpful for those who have web development experience.

Application Development Guide for Samsung Smart TV

1. Introduction
This section describes what Samsung Smart TV is, how it is configured and how it works.

1.1. What is Samsung Smart TV?


Samsung Smart TV is a web-based application running on an application engine installed in digital TVs connected to the Internet. The Samsung Smart TV service makes it possible to extend the functions of the TV by applying a variety of web functions to it, so that users can obtain useful information and interesting content on their TV screens. Users can check internet services such as news, weather, stock, UCC with simple operation. With Samsung Smart TV, digital TV users can not only download applications from HubSite and install them in their TVs but also personally develop applications tailored to their needs and install them in their TVs.

Samsung Smart TV

HubSite

Application Development Guide for Samsung Smart TV

2. Samsung Smart TV
This section describes the operating principle and environment of Samsung Smart TV.

2.1. Operating principle


With Samsung Smart TV installed in the TV, users can run Internet-based applications on the TV screen. An application is a special type of web page that is implemented on a web browser and runs on the TV screen. Viewing an application is very much like viewing web pages using a web browser on an ordinary PC. Differences between applications and web pages are made by screen resolution, hardware specifications and remote controller, the user interface for Samsung Smart TV installed TVs.

2.2. Operating environment


Browser TV screen resolution
App Engine 6.0 1280x720 pixel, 960 540 pixel

We will look at App Engine, the browser dedicated to internet TVs manufactured by Samsung, in Chapter 7. App Engine.

Application Development Guide for Samsung Smart TV

3. Applications
This section looks at applications that we will develop for Samsung TVs.

3.1. What are applications?


Applications are web-based small applications that are run in digital TVs connected to the internet. They are installed in TVs via the Internet and are run on App Engine. It is safe to say that they are web pages displayed on the TV screen having the remote control as the only user interface. The Application Manager (N.Navi.) controls installing and removing applications, and performing other works for them. You can exploit the Software development kit (SDK) to develop new applications designed to be run on your TV screen.

3.2. Structure of an application


An application is a web page consisting of HTML, CSS and JavaScript, and for Samsung TVs it is run on App Engine. The HTML page shows the structure of the application, the CSS file does the style, and the JavaScript file controls the behavior of the application. If you want to run an application on the TV screen, you have to create a config.xml file containing information on the operating environment and the version of the application. If you want to get more information about config.xml, see Ch. 4.3 config.xml.

10

Application Development Guide for Samsung Smart TV

3.3. Display type of applications


Display type Description Screen layout

Full-screen application

Fills the entire screen with an application.

Single-wide application

Makes an application displayed only on part of the screen.

Keeps an application on the Ticker screen while you do other things with your TV.

* The application will be launched in Europe must be Full-screen application.

11

Application Development Guide for Samsung Smart TV

3.4. Running an application


In order to start an application, you are required to follow the steps below:

Step
Get the Application Manager started

Instruction description
Press the INTERNET(INFO.L) button on the remote control or go through Menu> Application>Samsung Smart TV to open the application

Select an application

Press arrow button located in the center of the remote control to select an application.

Press the Enter button to implement an application. The Application Manager Implement an application reads the information from the config.xml file of the currently running application to set an operating environment, and reads index.html to implement the application.

3.5. Application Manager


The Application Manager serves as a manager that has the authority to authenticate, install, delete, update, open and finish applications. With the Application Manager, users can install or delete applications, and also register applications theyve developed and run them on the TV. The Application Manager is also an application that is continuously updated via the Internet.

Smart Hub

12

Application Development Guide for Samsung Smart TV

Samsung Apps

Settings

Edit Mode

Sort by

3.6. Features of Samsung applications


Applications for Samsung Smart TV allow you to enjoy functions that only TVs have, unlike general web pages. For example, using plugins, you can volume up or down the application and play video other than broadcasting on the TV screen. In addition, you can use a file storage system. If you want to get detailed information on plug-ins and file storage system, refer to Ch. 7 and 8 File API. The Application Manager provides several JavaScript modules used in applications. This enhances convenience of application development. If you want to get detailed information on use of a common module, see Ch. 5 Common modules.

13

Application Development Guide for Samsung Smart TV

4. Creating an application
This section guides you to create a simple application.

4.1. What you need to create an application


Our final goal is to create applications and run them on the TV screen. To this end, you need a Samsung TV connected to the Internet and an SDK or a text editor with which you can write HTML, JavaScript and CSS files. The SDK is equipped with a simulator with which you can run an application youve created before actually installing it in your TV. So, if you use an SDK, you can make an application in a more convenient way.

4.2. How to make an application


An application should contain at least the following elements: An index.html file. The file serves as the access point of the application. An application configuration file. This is an XML file in the root of the application structure that holds information about setting an application. JavaScript files. These are used for a preview of the application and for controlling the behavior of the application. CSS files. The look of the application is determined by these files. Image files, which are used by your application.

Lets make an application that displays text written in CSS and responds to remote control buttons events. The structure and look of an application we will make now are shown as below.

14

Application Development Guide for Samsung Smart TV

4.2.1. Writing config.xml


The config.xml file is called first among all the files the application has in it. <ver> tag value decides whether to update the application and images designated in <ThumbIcon> tag are shown in thumbnail. For information about other tags, turn to Ch. 4.3. config.xml.

<?xml version="1.0" encoding="UTF-8"?> <widget> <ThumbIcon>Resource/image/icon/picasa_106.png</ThumbIcon> <BigThumbIcon>Resource/image/icon/picasa_115.png</BigThumbIcon> <ListIcon>Resource/image/icon/picasa_85.png</ListIcon> <BigListIcon>Resource/image/icon/picasa_95.png</BigListIcon> <category>lifestyle</category> <autoUpdate>y</autoUpdate> <cpname>MyCP</cpname> <cpauthjs></cpauthjs> <login>y</login> <ver>0.930</ver> <mgrver>1.000</mgrver> <fullwidget>n</fullwidget> <srcctl>n</srcctl> <ticker>n</ticker> <childlock>n</childlock> <audiomute>n</audiomute> <videomute>n</videomute> <dcont>y</dcont> <network>y</network> <hubsite>n</hubsite> <widgetname>HelloWorld</widgetname> <description>Welcome!</description> <width>960</width> <height>540</height> <author> <name>Samsung Electronics Co. Ltd.</name> <email></email> <link>http://www.sec.co.kr/</link> <organization>Samsung Electronics Co. Ltd.</organization> </author> </widget>

15

Application Development Guide for Samsung Smart TV 4.2.2. Writing index.html


What you have to do next is writing index.html which will be the access point of the application. The following example is about HTML code that includes the Main.js file under the JavaScript folder and calls the Main.onLoad() function when the document is loaded. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Hello World!!</title> <script type="text/javascript" language="javascript" src="JavaScript/Main.js"></script> </head> <body onload="Main.onLoad();"> <div>Welcome to Samsung application world!</div> </body> </html>

4.2.3. Writing JavaScript


If the HTML document is loaded, the onLoad() function of the Main object is called, because you registered the Main.onLoad() function in the onload property in the <body> tag. Make a Main object and add the onload function. var Main = { } Main.onLoad = function () { alert("Main.onLoad()"); /** * JavaScript code Here! */ } // called by <body>'s onload event // Main object

If you have done all the work, you will get a debug message of Main.onLoad(). But the Welcome to Samsung application world! that you entered will not appear on the TV screen. If the application is successfully loaded, it has to ask the Application Manager to display itself on the screen using the common module provided by the Application Manager. The common module is a library containing essential functions provided by the Application Manager. For more information, refer to Ch. 5 Common Modules. Add the following code to <head> of index.html.

16

Application Development Guide for Samsung Smart TV


<script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/Widget.js"></script>

If the above code is added, a common module is available to use by JavaScript. Declare the common module as a global variable for Main.js you were working on and call the sendReadyEvent() function. By doing this, you can make the Application Manager display an application on the screen. var Main = { } var widgetAPI = new Common.API.Widget(); Main.onLoad = function () { alert("Main.onLoad()"); widgetAPI.sendReadyEvent(); /** * JavaScript code Here! */ } // Create Common module // called by <body>'s onload event // Send ready message to Application Manager // Main object

Ok, now run the application youve just made. You will see the words Welcome to Samsung application world! that you entered in the index.html file appearing on the screen. Maybe you dont like the look of the application because its font size is too small and font color is just simple black. You may want to make your application more stylish. Then, you can give the application a style using CSS.

4.2.4. Writing a CSS


Add the following string in

<head> in the index.html file.

<link rel='stylesheet' type='text/css' href = 'CSS/Main.css'/>

Assign an ID to <div> in the index.html file.

<div id='welcome'>Welcome to Samsung application world!</div>

Create a file in the CSS folder and enter text as you see in the below box to specify the style of the welcome element. body { margin: 0; padding: 0;

17

Application Development Guide for Samsung Smart TV


background-color: transparent; } #welcome { position: absolute; left: 50px; top: 50px; width: 500px; height: 50px; background-color: #AFAFAF; color: #99FFFF; font-size: 30px; text-align: center; }

4.2.5. Use of the remote control


Now, well make your application respond to the remote control. By pressing any of the five buttons located in the center of the remote control, you can change the words your application displays on the screen. If a button on the remote control is pressed, a keydown event occurs. An element having focus is required to receive the event to the index.html file. Add <a> element and Register a function that will be executed when that event occurs in the onkeydown property. Place focus on <a> and press the remote control key, the function registered previously is executed. Add <a> which executes Main.keyDown() method when a keydown event occurs. <body onload="Main.onLoad();"> <div id='welcome'>Welcome to Samsung application world!</div> <a href='javascript:void(0);' id='anchor' onkeydown='Main.keyDown();'></a> </body> Write a keyDown() method bringing key code value when pressing the remote control key Main.keyDown = function(){ // Key handler var keyCode = event.keyCode; alert("Main Key code : " + keyCode); } In a function processed by keys such as keydown(), each key has its own key code value. The Application Manager provides a common module containing key code values to distinguish keys. Add

18

Application Development Guide for Samsung Smart TV


the below code to <head> in the index.html file to use a common module TVKeyValue.

<script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/TVKeyValue.js"></script>

Modify Main.js in order to change the contents of welcome Div. This creates common module objects, classify keys in keydown() method, and define actions for each key. For detailed information on common modules and key code list, see Chapter 5. Common Modules. var Main = { } var widgetAPI = new Common.API.Widget(); var tvKey = new Common.API.TVKeyValue(); Main.onLoad = function(){ alert("Main.onLoad()"); widgetAPI.sendReadyEvent(); document.getElementById("anchor").focus(); /** * JavaScript code Here! */ } Main.keyDown = function(){ var keyCode = event.keyCode; alert("Main Key code : " + keyCode); // Key handler // Main object // Create Common module // called by <body>'s onload event // Send ready message to Application Manager // Focus to Anchor for handling key inputs // from remote controller

switch (keyCode) { case tvKey.KEY_LEFT: alert("left"); document.getElementById("welcome").innerHTML /** * Code for Left key event! */ break; case tvKey.KEY_RIGHT: alert("right"); document.getElementById("welcome").innerHTML break; case tvKey.KEY_UP: alert("up"); document.getElementById("welcome").innerHTML break; case tvKey.KEY_DOWN: alert("down"); document.getElementById("welcome").innerHTML break; case tvKey.KEY_ENTER:

= "Nice to meet you.";

= "I'm so happy.";

= "I Love you.";

= "Good job.";

19

Application Development Guide for Samsung Smart TV


alert("enter"); break; case tvKey.KEY_RETURN: break; } } You will see the value of the welcome Div tag change as you press the up, down, left or right button.

4.2.6. Complete your work & Sample code


With Samsung Smart TV, you can do almost everything you do on a web page. You can create TVoriented applications with extended functions using many plugins. The below are the codes weve written until now.

4.2.6.1.

config.xml

<?xml version="1.0" encoding="UTF-8"?> <widget> <ThumbIcon>Resource/image/icon/picasa_106.png</ThumbIcon> <BigThumbIcon>Resource/image/icon/picasa_115.png</BigThumbIcon> <ListIcon>Resource/image/icon/picasa_85.png</ListIcon> <BigListIcon>Resource/image/icon/picasa_95.png</BigListIcon> <previewjs>PreviewHelloWorld</previewjs> <cpname>Samsung</cpname> <cplogo>Resource/image/settings_logo.png</cplogo> <cpauthjs></cpauthjs> <ver>0.930</ver> <mgrver>1.000</mgrver> <fullwidget>n</fullwidget> <srcctl>n</srcctl> <ticker>n</ticker> <childlock>n</childlock> <audiomute>n</audiomute> <videomute>n</videomute> <dcont>y</dcont> <network>y</network> <hubsite>n</hubsite> <widgetname>HelloWorld</widgetname> <description>Welcome!</description> <width>960</width> <height>540</height>

20

Application Development Guide for Samsung Smart TV


<author> <name>Samsung</name> <email></email> <link>http://acme-widget.example.com</link> <organization>Acme Examples, Inc.</organization> </author> </widget>

4.2.6.2.
<!DOCTYPE html> <html> <head>

index.html

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Hello World!!</title> <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/Widget.js"></script> <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/TVKeyValue.js"></script> <script type="text/javascript" language="javascript" src="JavaScript/Main.js"></script> <link rel='stylesheet' type='text/css' href = 'CSS/Main.css'/> </head> <body onload="Main.onLoad();"> <div id='welcome'>Welcome to Samsung widget world!</div> <a href='javascript:void(0);' id='anchor' onkeydown='Main.keyDown();'></a> </body> </html>

4.2.6.3.
var Main = { }

Main.js
// Main object // Create Common module // called by <body>'s onload event // Send ready message to Application Manager // Focus to Anchor for handling key inputs // from remote controller

var widgetAPI = new Common.API.Widget(); var tvKey = new Common.API.TVKeyValue(); Main.onLoad = function(){ alert("Main.onLoad()"); widgetAPI.sendReadyEvent(); document.getElementById("anchor").focus(); /** * JavaScript code Here! */ } Main.keyDown = function(){ var keyCode = event.keyCode;

// Key handler

21

Application Development Guide for Samsung Smart TV


alert("Main Key code : " + keyCode); switch (keyCode) { case tvKey.KEY_LEFT: alert("left"); document.getElementById("welcome").innerHTML /** * Code for Left key event! */ break; case tvKey.KEY_RIGHT: alert("right"); document.getElementById("welcome").innerHTML break; case tvKey.KEY_UP: alert("up"); document.getElementById("welcome").innerHTML break; case tvKey.KEY_DOWN: alert("down"); document.getElementById("welcome").innerHTML break; case tvKey.KEY_ENTER: alert("enter"); break; case tvKey.KEY_RETURN: break; } }

= "Nice to meet you.";

= "I'm so happy.";

= "I Love you.";

= "Good job.";

4.2.6.4.
body {

Main.css

margin: 0; padding: 0; background-color: transparent; } #welcome { position: absolute; left: 50px; top: 50px; width: 500px; height: 50px; background-color: #AFAFAF; color: #99FFFF; font-size: 30px; text-align: center; }

22

Application Development Guide for Samsung Smart TV

4.3. config.xml
The config.xml file contains information about the applications execution, update, operating environment setting and other related issues. Depending on that information, the Application Manager controls the version of your application, sets an environment in which your application is run, and creates and manages user accounts. The config.xml file should be located in the directory in which the application is installed, and contain the following elements.

4.3.1. Tag information


Element
<widget> <ThumbIcon>

Description
Indicates that the information is relevant to the application. An icon image displayed in the Application Manager. It is used in case of no focus and its size is 106 x 86pixel. An icon image displayed in the Application Manager.

Value
File path

<BigThumbIcon>

It is used in case that the focus is placed on an image and its size is 115 x 95 pixel.

File path

<ListIcon>

An icon image displayed in the Application Manager. The size is 85 x 70 pixel. An icon image displayed in the Application Manager. The size is 95 x 78 pixel. The category to distinguish applications, available items are video, sports, game, lifestyle, information, others. Decides whether to synchronize with hub site. The application which doesnt need synchronization chooses n. Shows information on contents type 11: HTML + java-script + Flash Player Object

File path

<BigListIcon>

File path

<category>

String

<autoUpdate>

y|n

<apptype>

12: Adobe SWF ( Ver. Flash Lite 3.1 ) 13: Adobe SWF ( Ver. Flash 10.1 ) 14 : Lua Script

Number

File path and name at the initial execution of contents Only the following apptype needs contents tag. <contents> <channelType> <channelRoot> 12: Adobe SWF ( Ver. Flash Lite 3.1 ) 13: Adobe SWF ( Ver. Flash 10.1 ) 14 : Lua Script root | child Application File Path

Channel Bound Service Type(optional) Confirms the relations with root-child clarifying root application ID.

23

Application Development Guide for Samsung Smart TV


(Optional, Only when the channel bound service type is child.) When connected to more than one root, roots are distinguished by ::. Channel information to be executed channel bound <channelName> service (Distinguish each channel using :: Ex AAA::BBB::CCC) (Optional, only if channel bound service type is root.) It decides whether the installed channelbound service is displayed on <channelDisplay> the first main screen or not. (If you want to hide the service in the first main screen, select n.) <previewjs> <cpname> deleted Enter the application provider in this tag. The name of the JavaScript file that allows you to confirm account <cpauthjs> information of application providers. This file has to be written in a defined format. <cplogo> <preIcon> deleted deleted Decides a service is available to signin or not. If you select y, you can <login> enter ID and password in Integrated Sign-in site of Application Manager for sign-in. Validity verification should be preceded in JavaScript file corresponding to <cpauthjs> tag value. Indicates <ver> the application the server version. computer Depending updates on the that version x.xxx y|n File path File path String String String y|n String ID

information, application.

corresponding

<mgrver>

Indicates the Application Managers version that is required to run an application having the config.xml file. Indicates whether the application is a full-screen or a single-wide one.

x.xxx

<fullwidget>

Display type affects the audio policy of the application when its run. Refer to Chapter. 6.4. Using Keys on Remote Control for details. If source conversion is needed, set this tag to y. (ex. YouTube application).

y|n

<srcctl>

If you select y, the TV source automatically switched from current TV channel or external input to the internal media player, and back again when the application is finished.

y|n

<childlock> <audiomute>

Determines whether to use the childLock function. This function enables the user to lock an application. Turns on and off the audio. If you select y, TV broadcasting sound is

y|n y|n

24

Application Development Guide for Samsung Smart TV


not outputted when entering the application. Set y if the application occupies full screen and set n if the application occupies parts of the screen. <videomute> Turns on and off the video. If you select y, TV broadcasting is not on the screen when entering the application. Sets the Disable dynamic contrast function. Dynamic contrast is the function to adjust TV contrast ratio and brighten TV screen by darkening the dark screen and lightening the light screen. <dcont> The screen might get lighter or darker when application is on with Dynamic contrast. y turns off the Dynamic contrast, and N turns on the Dynamic contrast. If the application is occupied on full screen, select y to remove sparkling. If the application is partially occupied, select n. Application playing video files can bring problems as stated below. 1. If a video file is played in a device connected to HDMI port such as DVD Player when executing an application (ex. YouTube) converting sources, sounds can be mixed. y|n y|n

<movie>

2. Sparkling at the entry for appliction due to the difference of Frame rate between the TV image and playing video file. If you select y, you can prevent it from the problem above by ending operating the connected HDMI device when executing the application and fixing the Frame rate.

y|n

<widgetname> <description> <width> <height> <author>

Enter a name of application. Enter a brief description of the application. Enter the screen area that the application will be occupying. Generally, it is recommended to enter 960 * 540 pixels, digital TV specification. Enter a description of the author. This tage is used when needed to check network while operating an application. If the tage value is y and the network test result is fail,

String String Number string

<network>

entry for the application can be blocked with a message indicating the failure. Without any set value, default is y. This tage is used when needed to check whether the hubsite has been

y|n

<hubsite>

authorized or not while operating an application. If the tage value is y, and the hubsite has not been authorized, entry for the application can be blocked with a message indicating the failure.

y|n

25

Application Development Guide for Samsung Smart TV


Without any set value, default is n. <pushNotice> Indicates whether the application provides Push Notification Service. Without any set value, default is n. This tag is reserved for former Push Notification Service. Without any set value, default is n. Indicates whether Push Notification Service is provided for specific user. Without any set value, default is n. This tag should be enabled for application that use embedded flash player object, or stand-alone flash player. y|n

<pushControl>

y|n

<pushUerbinding>

y|n

<flashplayer>

y|n

4.3.2. Example
<?xml version="1.0" encoding="UTF-8"?> <widget> <ThumbIcon>Resource/image/icon/picasa_106.png</ThumbIcon> <BigThumbIcon>Resource/image/icon/picasa_115.png</BigThumbIcon> <ListIcon>Resource/image/icon/picasa_85.png</ListIcon> <BigListIcon>Resource/image/icon/picasa_95.png</BigListIcon> <category>lifestyle</category> <autoUpdate>y</autoUpdate> <cpname>Picasa</cpname> <cpauthjs>Auth11101000000</cpauthjs> <login>y</login> <ver>2.000</ver> <mgrver>1.035</mgrver> <fullwidget>y</fullwidget> <srcctl>n</srcctl> <ticker>n</ticker> <childlock>n</childlock> <audiomute>y</audiomute> <videomute>y</videomute> <dcont>y</dcont> <movie>y</movie> <network>y</network> <hubsite>n</hubsite> <widgetname>Picasa Web Albums</widgetname> <description>View photo albums online</description> <width>960</width> <height>540</height> <author> <name>Samsung Electronics Co. Ltd.</name> <email></email> <link>http://www.sec.co.kr/</link> <organization>Samsung Electronics Co. Ltd.</organization> </author> </widget>

26

Application Development Guide for Samsung Smart TV

4.4. Single-Sign-On
This section describes SSO functions supported by the application manager, how to register account information and get the information from the application.

4.4.1. What is Single-Sign-On


Input of account information via TV remote control is so inconvenient that users could be stressed out if they should enter account information whenever they use the application. To improve this inconvenience, Single-Sign-On (hereinafter referred to as SSO) is provided by application manager. Application manager saves the account information that users have entered and sends it to the application. These enable users not to enter account information repetitively. The account information is encrypted and saved in safe area. SSO operates as stated below. Generate a TV Account It is necessary to create a TV account to use SSO. TV account is an account generated in the Application manager and has four-digit PIN number as a password. You can make the account in Settings->Samsung Smart TV-ID. Register Service Sites Registers account information of service sites (ex: YouTube, Picasa) in the generated TV account. Only when the entered account information is determined valid, the information is registered in the account. Registration can be made in Settings -> Samsung Smart TV ID. Sign-in to TV account You can sign in to the TV account created in pressing Red key on the initial screen. In general, account information on several service sites can be registered in a TV account. Sign-in make you enable to get account information on a service site you want to get in several applications. Execution of an Application At this stage, the application manager decides whether the application SSO is available to sign in or not. If available, the account information is given. Account information should be inputted through the process in .

Use account information on service sites In an application, account information coexists with various circumstances information provided by the

27

Application Development Guide for Samsung Smart TV


application manager. Thus, it is required to use account information after parsing. Following chapter describes modules necessary to be realized in an application to register service sites, how to parse and use the account information received by the application manager.

4.4.2. Registration of Account Information on Service Sites


Registration of account information on service sites can be done through Settings -> Samsung Smart TV ID. If you wish to display the names of the service sites you want to show, configure config.xml as suggested below.

<cpname>YourCompany</cpname> <login>y</login>

Then, you can find YourCompany item in the list of service sites. If you cant, restart TV. Application manager could need to be reloaded. Now, the account information on service site, YourCompany can be entered. However, if there is no module which confirms validity of the entered account information, the registration cannot be completed. You should generate the module in person. Validity Confirmation is to make sure that the entered account information is consistent with the ID and Password which are available to sign-in on the real service site. If sign-in can be made by API in each service site, the information is turned out to be valid. In Google, there is ClientLogin to judge validity. If sign-in is successfully done and auth token is granted, the account information is regarded valid. Refer to the URL states below regarding Client Login. (http://code.google.com/intl/ko/apis/accounts/docs/AuthForInstalledApps.html) The module to confirm validity of account information is drawn up as shown below. Enter the name of js file whose config.xml has a module. Put the name of js file which has a module to confirm account information validity in <cpauthjs> item. If the file name is Auth11101000000.js, put Auth11101000000. The application manager executes the module including the file. File names should be unique for each application. Check the variables such as curWidget.id and write the name distinctively.

28

Application Development Guide for Samsung Smart TV


<cpauthjs>Auth11101000000</cpauthjs>

Create a file Create a js file corresponding to the entered file name in the process of . A module will be written in this file. This file is embedded in the top level directory where index.html exists. Draw up a module which confirms validity of account information. This module is generated in the file made in , the format should be in observance of regulations. Declare the object whose name is the entered value in . Add a method checkAccount to the object. checkAccount method confirms validity of the account information on the service site, and it should deliver the results to the callback function transferred to the factor. Example // Object Generated var Auth11101000000 = { } // checkAccount Method Added Auth11101000000.checkAccount = function (id, pw, fnCallback) { /** * The id and pw inputted from the application manager are transferred to the factor. * Check validity of id and pw, and then operate callback function. */ // ... // Confirmation on Validity // ... // Deliver the results if (isValidAccount) { fnCallback ('TRUE'); } else { fnCallback ('FALSE'); }

29

Application Development Guide for Samsung Smart TV


}

The value transferring to the Callback function and the effect are like below.

Return value
'TRUE'

Description
If the transferred ID and Password are valid, return TRUE. Application manager registers ID and Password in the TV account.

'FALSE'

If the account information is invalid, return FALSE. The application Manager let the user reenter the account information.

'ERROR'

Errors occur while confirming validity, return ERROR. The application manager regards it as an error, after a while, it leads the user to try reusing account information.

Others

Values other than three values above are processed identically with ERROR.

4.4.3. How to download account information on service sites in applications


Applications are able to get account information on service sites. Proceed like the order stated below. Configure config.xml like below. This enables the application manager to understand that this application is available to sign-in and necessary service site is YourCompany.

<cpname>YourCompany</cpname> <login>y</login>

Sign-in to the TV account The account information registered in the account can be available when sign-in process to the TV account is completed. Execution for an application Execute the application. Account information on CP(YourCompany) needs to be registered in the designated TV account in . Generally, several service sites are registered in a TV account, on the other hand, an application can get one service site relevant to the designated CP in . How to parse ID and Password All the conditions are satisfied, ID and Password are transferred to Browser global variable

30

Application Development Guide for Samsung Smart TV


window.location.search. This variable includes circumstances information, and it should be parsed. Refer to 6.7 for further information on window.location.search.

31

Application Development Guide for Samsung Smart TV

4.5. Reset
Reset describes functions to initialize the application.

4.5.1. What is Reset?


The function to execute initial modules realized by applications when deleting or initializing applications in Application Manager.

4.5.2. How Reset Works?


1. Application Manager brings information in config.xml of the installed application when

deleting/initializing. 2. Check if the application needs a module which initializes through the information in config.xml. 3. If the application has the module that initializes, bring information on the module. 4. Execute the module in accordance with rules and try initializing. * Application Manager does not obtain any return value but operate the module to initialize.

4.5.3. Necessary Features Developers Should Realize


1. Peculiar Information on config.xml(Refer to Chapter 4) 2. Initialization Module (Refer to Chapter 5)

4.5.4. Guide for Config.xml Realization


Add xml Element as shown below.

<deleteJS>MyReset</deleteJS>
* Without deleteJS Element, the application does not operate the initialization module.

4.5.5. Guide for Module Realization


1. The file name should be the same as class name. 2. No factor. 3. The name of function is reset.

var MyReset= { } MyReset.reset = function() {

32

Application Development Guide for Samsung Smart TV


... ... alert("Reset Complete!"); }

33

Application Development Guide for Samsung Smart TV

4.6. Example for XHR communication


In this section, well look at an example for XHR communication, which is a key factor comprising AJAX technology. The below example is HTML code that includes XHRExample.js, and executes the XHRExample.onload() function when the load event occurs. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>XHR Example</title> <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/TVKeyValue.js"></script> <script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/Widget.js"></script> <script type="text/javascript" language="javascript" src="XHRExample.js"></script> </head> <body onload="XHRExample.onload()"> <div id='intro'>XHR Example.</div> </body> </html> The below is JavaScript code. XHRExample is has been declared as an object and has the variable of XHRObj in it. If XHRObj already exists, XHRExample calls the destroy() method. We will look at this more specifically later in this chapter. If an XHR object has been successfully created, set it and request data. If the state of XHR changes to 4, which means data reception is completed, recieveData() that you registered in onreadystatechange is executed. var XHRExample = { XHRObj : null } var tvKey = new Common.API.TVKeyValue(); var widgetAPI = new Common.API.Widget(); XHRExample.onload = function () { widgetAPI.sendReadyEvent(); var URL = ""; // Test URL here

34

Application Development Guide for Samsung Smart TV


if (this.XHRObj != null) this.XHRObj.destroy(); this.XHRObj = new XMLHttpRequest(); if (this.XHRObj) { this.XHRObj.onreadystatechange = function () { if (XHRExample.XHRObj.readyState == 4) { XHRExample.recieveData(); } }; this.XHRObj.open("GET", URL, true); this.XHRObj.send(null); } } XHRExample.recieveData = function () { alert(this.XHRObj.responseText); } The above example has two remarkable points. One is that the variable of XHRObj is in the XHRExample object. The other is that the destroy() method is called before an object is assigned to XHRObj. With Samsung TVs, if you run out of the memory by continuing to create and use the XHR object, applications in your TV do not work anymore at a certain time. In order to avoid this kind of situation, you should delete objects you used in the past and assign new ones when you use XHR. To free up objects that had been used, the object pointer should be maintained. For this, developers should memorize and manage the variable dealing with XHR objects. If you want to remove an XHR object from the memory, use the destroy() method of it, and this is the method that App Engine provides to allow you to use the limited memory efficiently.

XHRObjet.destroy
Free up the XHR object you created from the memory. Syntax Parameter Return Value Remarks XHRObject.destroy() None None This function, which is executed to optimize the memory usage, is only provided by

35

Application Development Guide for Samsung Smart TV


App Engine for Samsung TV users. Example if (this.XHRObj != null) this.XHRObj.destroy(); this.XHRObj = new XMLHttpRequest();

In the above example, two common modules provided by the Application Manager are included. For more information, turn to Ch. 5 Common modules.

36

Application Development Guide for Samsung Smart TV

5. Common modules
In this section, we will look at a library shared by all your applications.

5.1. Application Managers common modules


The Application Manager provides object modules that all your applications can use. Those common modules enable your applications to do basic work to be normally running on the screen. Also, using common modules, individual applications can recognize and identify remote control button events, use plugins, and communicate with the Application Manager in more convenient and simpler ways.

5.2. How to use common modules


Include common modules you want to use in the index.html file. In order to prevent occurrence of any parsing order error, it is recommended that you include them at the top of the document. $MANAGER_WIDGET allows your applications to access common modules provided by the Application Manager. * In SDK, $MANAGER_WIDGET points the commonlib folder that SDK installed in.

<script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/TVKeyValue.js"></script>

Create an object.

var tvKey = new Common.API.TVKeyValue();

Use known member variable and method.

alert(tvKey.KEY_LEFT);

5.3. TVKeyValue TVKeyValue


An object that defines TV key code. Library path $MANAGER_WIDGET/Common/API/TVKeyValue.js

37

Application Development Guide for Samsung Smart TV


Syntax Parameter Return Value new Common.API.TVKeyValue() None TVKeyValue object This is an object having key code used by the TV as a member variable, and identifies Remarks remote control keys pressed by the user by referring to member variables. (Since Samsung Smart TV version 2.265) var tvKey = new Common.API.TVKeyValue(); switch (KEY_CODE) { case tvKey.KEY_LEFT: // Do something break; case tvKey.KEY_RIGHT: // Do something break; default: break; } KEY_TOOLS KEY_MUTE KEY_RETURN KEY_UP KEY_DOWN KEY_LEFT KEY_RIGHT KEY_WHEELDOWN KEY_WHEELUP KEY_ENTER Members KEY_INFO KEY_EXIT KEY_RED KEY_GREEN KEY_YELLOW KEY_BLUE KEY_INFOLINK KEY_RW KEY_PAUSE KEY_FF KEY_PLAY

Example

38

Application Development Guide for Samsung Smart TV


KEY_STOP KEY_1 KEY_2 KEY_3 KEY_4 KEY_5 KEY_6 KEY_7 KEY_8 KEY_9 KEY_0 KEY_EMPTY KEY_PRECH KEY_SOURCE KEY_CHLIST KEY_MENU KEY_WLINK KEY_CC KEY_CONTENT KEY_FAVCH KEY_REC KEY_EMODE KEY_DMA KEY_PANEL_CH_UP KEY_PANEL_CH_DOWN KEY_PANEL_VOL_UP KEY_PANEL_VOL_DOWN KEY_PANEL_ENTER KEY_PANEL_SOURCE KEY_PANEL_MENU KEY_PANEL_POWER Methods None

39

Application Development Guide for Samsung Smart TV

5.4. Widget
This is an object that has functions needed for desirable operation of an application. A method that notifies the Application Manager of starting of an application, a method that registers and frees up keys users want to use, and other methods are contained in this object.

Widget
Object having functions needed for desirable operation of an application Library path Syntax Parameter Return Value Remarks Example Members var widgetAPI = new Common.API.Widget(); widgetAPI. sendReadyEvent(); None sendReadyEvent sendExitEvent sendReturnEvent Methods blockNavigation putInnerHTML getChannelWidgetListPath getSearchWidgetListPath runSearchWidget $MANAGER_WIDGET/Common/API/Widget.js new Common.API.Widget() None Widget object (Since Samsung Smart TV version 2.265)

5.4.1. sendReadyEvent()

sendReadyEvent
Notifies the Application Manager that the application is ready to be displayed. This event should be passed to display and run the application on the screen. Syntax Parameter Return Value Remarks sendReadyEvent() None None (Since Samsung Smart TV version 2.265)

40

Application Development Guide for Samsung Smart TV


var widgetAPI = new Common.API.Widget(); widgetAPI.sendReadyEvent(); None

Example Enumeration

5.4.2. sendExitEvent()

sendExitEvent
Brings the same effect as pressing the exit key. Stops the application and goes back to the TV screen. Syntax Parameter Return Value Remarks Example Enumeration var widgetAPI = new Common.API.Widget(); widgetAPI.sendExitEvent (); None sendExitEvent() None None (Since Samsung Smart TV version 2.265)

5.4.3. sendReturnEvent()

sendReturnEvent
Brings the same effect of pressing the Return key. Finishes the application and takes you to the Application Manager. Syntax Parameter Return Value Remarks Example Enumeration var widgetAPI = new Common.API.Widget(); widgetAPI.sendReturnEvent (); None sendReturnEvent() None None (Since Samsung Smart TV version 2.265)

5.4.4. blockNavigation()

blockNavigation

41

Application Development Guide for Samsung Smart TV


Key event cannot be forced to return. Syntax Parameter Return Value blockNavigation(keyEvent) keyEvent: Key event None KEY_RETURN and KEY_EXIT events forcibly close the operating application. The func Remarks prevents forced closure and keep being executing. (Since Samsung Smart TV version 2.265) function keyDown () { switch(event.keyCode) { case this.tvKey.KEY_LEFT: // Do something break; case this.tvKey.KEY_RIGHT: // Do something break; case this.tvKey.KEY_RETURN: widgetAPI.blockNavigation(event); // Not terminated break; case this.tvKey.KEY_EXIT: // Terminated by force break; default: break; } } None

Example

Enumeration

5.4.5. putInnerHTML()

putInnerHTML
innerHTML method to fix memory issues. Syntax Parameter Return Value putInnerHTML(div, contents) div: Div Element to use innerHTML contents: Things to insert in innerHTML None Required to use this method because repetitive use of innerHTML can occur memory Remarks issues. (Since Samsung Smart TV version 2.265) Example var widgetAPI = new Common.API.Widget();

42

Application Development Guide for Samsung Smart TV


var divElement = document.getElementById("divID"); var contents = "Text to change"; widgetAPI.putInnerHTML(divElement, contents); Enumeration None

5.4.6. getChannelWidgetListPath()

getChannelWidgetListPath
Method that brings the path of xml file having the child application list of the current channel bound application Syntax Parameter Return Value getChannelWidgetListPath() None string : xml file path This method is used when the channel bound application needs information on the Remarks currently installed child application. (Since Samsung Smart TV version 2.265) Example Enumeration var widgetAPI = new Common.API.Widget(); var xmlPath = widgetAPI.getChannelWidgetListPath(); None

5.4.7. getSearchWidgetListPath()

getSearchWidgetListPath
Method that brings the path of xml file having the list of applications related Syntax Parameter Return Value getSearchWidgetListPath() None string : xml file path This method is used when a search tag in config.xml requires information on an Remarks application whose search tag is set as y. (Since Samsung Smart TV version 2.265) Example Enumeration var widgetAPI = new Common.API.Widget(); var xmlPath = widgetAPI.getSearchWidgetListPath(); None

43

Application Development Guide for Samsung Smart TV 5.4.8. runSearchWidget()

runSearchWidget
Method called when executing another application in an application Syntax Parameter Return Value runSearchWidget () appID : The application ID you intend to operate extraInfo : The string that transferred to the executing application None This method is used when the channel bound application requires information on the Remarks installed child application at present. (Since Samsung Smart TV version 2.265) Example Enumeration var widgetAPI = new Common.API.Widget(); widgetAPI.runSearchWidget(111011000001,key1=value1&key2=value2); None

5.4.9. checkSapTicket ()

checkSapTicket
Method called when checking to have the valid ticket for current logged-in user. Syntax Parameter Return Value checkSapTicket () None None You should register event handler for passing the return value. If you have valid ticket, the return value is stat=ok&ticket=686a8281-e952-4dccRemarks a67b-57e8f92e5530 Otherwise, it is stat=fail&ticket=null. (Since Samsung Smart TV version 3.037) // Register Event Handler curWidget.onWidgetEvent = AAAA; var widgetAPI = new Common.API.Widget(); widgetAPI.checkSapTicket(); Example function AAAA(event){ if( event.type == Common.API.EVENT_ENUM.PNS_CHECK_TICKET){ // The return value is event.data. // TODO }

44

Application Development Guide for Samsung Smart TV


} Enumeration None

5.4.10.

requestSapTicket ()

requestSapTicket
Method called when requesting new Sap Ticket for Application Server. Syntax Parameter Return Value requestSapTicket () None None You should register event handler for passing the return value. If new ticket is generated normally, the return value is stat=ok&ticket=686a8281Remarks e952-4dcc-a67b-57e8f92e5530 Otherwise, it is stat=fail&ticket=null. (Since Samsung Smart TV version 3.037) // Register Event Handler curWidget.onWidgetEvent = AAAA; var widgetAPI = new Common.API.Widget(); widgetAPI.requestSapTicket(); Example function AAAA(event){ if( event.type == Common.API.EVENT_ENUM.PNS_REQUEST_TICKET){ // The return value is event.data. // TODO } } None

Enumeration

5.5. Plugin
The Application Manager provides a wrapper class that allows you to use some plugin functions in more convenient ways. If you want to take advantage of this class, just insert objects needed for use of plugins in the index.html document. Then, the Application Manager will give you an appropriate class method.

Plugin
Object that is wrapped for convenient use of plugins

45

Application Development Guide for Samsung Smart TV


Library path Syntax Parameter Return Value Remarks Example Members var pluginAPI = new Common.API.Plugin(); pluginAPI.setOnWatchDog(); None Object ID : pluginObjectTVMW setOnWatchDog setOffWatchDog registKey unregistKey registIMEKey unregistIMEKey registAllKey unregistAllKey registFullWidgetKey registPartWidgetKey Object ID : pluginObjectVideo Methods setOnOSDState setOffOSDState Object ID : pluginObjectVideo setOnOSDState setOffOSDState Object ID : pluginObjectNNavi SetBannerState ShowTools setOnIdleEvent setOffIdleEvent setOnScreenSaver setOffScreenSaver Object ID : pluginObjectAppCommon isViewerKey Object list pluginObjectTVMW <OBJECT id='pluginObjectTVMW' border=0 classid='clsid:SAMSUNG-INFOLINK-TVMW' $MANAGER_WIDGET/Common/API/Plugin.js new Common.API.Plugin() None Plugin object (Since Samsung Smart TV version 2.265)

46

Application Development Guide for Samsung Smart TV


style='opacity:0.0;background-color:#000000;width:0px;height:0px;'></OBJECT> pluginObjectVideo <OBJECT id='pluginObjectVideo' border=0 classid='clsid:SAMSUNG-INFOLINK-VIDEO' style='opacity:0.0;background-color:#000000;'></OBJECT> pluginObjectNNavi <OBJECT id='pluginObjectNNavi' classid='clsid:SAMSUNG-INFOLINK-NNAVI' style='opacity:0.0;background-color:#000000;width:0px;height:0px;'></OBJECT> pluginObjectAppCommon <OBJECT id='pluginObjectAppCommon' classid='clsid:SAMSUNG-INFOLINK-APPCOMMON' style='opacity:0.0;background-color:#000000;width:0px;height:0px;'></OBJECT>

5.5.1. setOnWatchDog()

setOnWatchDog
Turns on the Watch dog function. Syntax Parameter Return Value Remarks Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.setOnWatchDog(); None setOnWatchDog() None None (Since Samsung Smart TV version 2.265)

5.5.2. setOffWatchDog()

setOffWatchDog
Turns off the Watch dog function. Syntax Parameter Return Value Remarks Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.setOffWatchDog(); None setOffWatchDog() None None (Since Samsung Smart TV version 2.265)

47

Application Development Guide for Samsung Smart TV

5.5.3. setOnOSDState()

setOnOSDState
Sets the area where OSD is protected. Syntax setOnOSDState(left, top, width, height) left : left coordinate of the area Parameter top : top coordinate of the area width : width of the area height : height of the area Return Value Remarks Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.setOnOSDState(0,0, 330, 540); None None (Since Samsung Smart TV version 2.265)

5.5.4. setOffOSDState()

setOffOSDState
Cancels the previously set OSD area. Syntax setOffOSDState(left, top, width, height) left : left coordinate of the area Parameter top : top coordinate of the area width : width of the area height : height of the area Return Value Remarks Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.setOffOSDState(0,0, 330, 540); None None (Since Samsung Smart TV version 2.265)

48

Application Development Guide for Samsung Smart TV 5.5.5. registKey()

registKey
Lets the Application Manager register specific key Syntax Parameter Return Value registKey(pNumKeyCode) pNumKeyCode: key code None Registration/Unregistration of keys should be done after window.onshow event. Refer Remarks to Chap. 6.4 How to use keys on remote control for more details. (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.registKey(tvKey.KEY_ TOOLS); None

5.5.6. unregistKey()

unregistKey
Lets the Application Manager unregister specific key Syntax Parameter Return Value unregistKey(pNumKeyCode) pNumKeyCode: key code None Registration/Unregistration of keys should be done after window.onshow event. Refer Remarks to Chap. 6.4 How to use keys on remote control for more details. (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.unregistKey(tvKey.KEY_ TOOLS); None

5.5.7. registIMEKey()

registIMEKey
Lets the Application Manager register IME key

49

Application Development Guide for Samsung Smart TV


Syntax Parameter Return Value registIMEKey() None None Registers number keys from 0 to 9, -(hyphen), and previous channel key used in entering IME. Remarks Registration/Unregistration of keys should be done after window.onshow event. Refer to Chap. 6.4 How to use keys on remote control for more details. (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.registIMEKey(); None

5.5.8. unregistIMEKey()

unregistIMEKey
Lets the Application Manager unregister IME key Syntax Parameter Return Value unregistIMEKey() None None Unregisters number keys from 0 to 9, -(hyphen), previous channel key used in entering IME. Remarks Registration/Unregistration of keys should be done after window.onshow event. Refer to Chap. 6.4 How to use keys on remote control for more details. (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.unregistIMEKey(); None

5.5.9. registAllKey

registAllKey
Lets the Application Manager register all keys

50

Application Development Guide for Samsung Smart TV


Syntax Parameter Return Value registAllKey() None None Registers all keys Remarks Registration/Unregistration of keys should be done after window onshow event. Refer to Chap. 6.4 How to use keys on remote control for more details. (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.registAllKey(); None

5.5.10.

unregistAllKey()

unregistAllKey
Lets the Application Manager unregister all keys Syntax Parameter Return Value unregistAllKey() None None Unregisters all keys Remarks Registration/Unregistration of keys should be done after window onshow event. Refer to Chap. 6.4 How to use keys on remote control for more details. (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.unregistAllKey(); None

5.5.11.

registFullWidgetKey()

registFullWidgetKey
Lets the Application Manager register specific key group Syntax Parameter registFullWidgetKey() None

51

Application Development Guide for Samsung Smart TV


Return Value None Registers keys for fullwidget Remarks Registration/Unregistration of keys should be done after window onshow event. Refer to Chap. 6.4 How to use keys on remote control for more details. (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.registFullWidgetKey(); None

5.5.12.

registPartWidgetKey()

registPartWidgetKey
Lets the Application Manager register specific key group Syntax Parameter Return Value registPartWidgetKey () None None Registers keys for part widget Remarks Registration/Unregistration of keys should be done after window onshow event. Refer to Chap. 6.4 How to use keys on remote control for more details. (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI. registPartWidgetKey (); None

5.5.13.

SetBannerState()

SetBannerState
A function using when you want to put volume and channel OSD with the application. Syntax SetBannerState (nState) nState : Defined value on OSD you want to bring with the application. Parameter PL_NNAVI_STATE_BANNER_NONE = 0; PL_NNAVI_STATE_BANNER_VOL = 1; PL_NNAVI_STATE_BANNER_VOL_CH = 2;

52

Application Development Guide for Samsung Smart TV


Return Value None When you intend to bring up volume OSD on the screen, volume key value should be Remarks registered. So does channels. See an example. (Since Samsung Smart TV version 2.265) var PL_NNAVI_STATE_BANNER_NONE = 0; var PL_NNAVI_STATE_BANNER_VOL = 1; var PL_NNAVI_STATE_BANNER_VOL_CH = 2; var pluginAPI = new Common.API.Plugin(); var tvKey = new Common.API.TVKeyValue(); pluginAPI.unregistKey(tvKey.KEY_VOL_UP); pluginAPI.unregistKey(tvKey.KEY_VOL_DOWN); pluginAPI.SetBannerState(PL_NNAVI_STATE_BANNER_VOL); Enumeration None

Example

5.5.14.

ShowTools()

ShowTools
A function to bring popup windows for screen and sound adjustment. Syntax ShowTools (nTool) nTool: Defined value on a popup window you want to bring. Parameter 0 : Sound Setting popup 1 : Picture Setting popup Return Value None You can see the point when the popup window is closed by signing up for Remarks curWidget.onWidgetEvent. (Since Samsung Smart TV version 2.265) curWidget.onWidgetEvent = function(){ // a code that will be executed after closing the popup window Example } var pluginAPI = new Common.API.Plugin(); pluginAPI.ShowTools(1); Enumeration None

53

Application Development Guide for Samsung Smart TV 5.5.15. setOnIdleEvent()

setOnIdleEvent
The function to set idle on to close the application in case that there is no input for a certain time Syntax Parameter Return Value setOnIdleEvent() None None 1. Default is set as Idle ON. Remarks 2. Recall the function when idle process is required after calling setOffIdleEvent method.(ex. When closing image playing) (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.setOnIdleEvent(); None

5.5.16.

setOffIdleEvent()

setOffIdleEvent
The function to set idle off in order not to close the application despite no input for a certain time Syntax Parameter Return Value setOffIdleEvent() None None 1. Default is set as idle ON. Remarks 2. Setting Idle off is needed in case of watching clips for a long time (Since Samsung Smart TV version 2.265) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.setOffIdleEvent(); None

5.5.17.

setOnScreenSaver()

setOnScreenSaver

54

Application Development Guide for Samsung Smart TV


The function to set on screen saver Syntax Parameter Return Value Remarks setOnScreenSaver() None None Screensaver is off when the application is closed. (Since Samsung Smart TV version 2.265) var pluginAPI = new Common.API.Plugin(); pluginAPI.setOnScreenSaver(); None

Example Enumeration

5.5.18.

setOffScreenSaver()

setOffScreenSaver
The function to set off screen saver Syntax Parameter Return Value Remarks setOffScreenSaver() None None Available after calling setOnScreenSaver (Since Samsung Smart TV version 2.265) var pluginAPI = new Common.API.Plugin(); pluginAPI.setOffScreenSaver(); None

Example Enumeration

5.5.19.

isViewerKey()

isViewerKey
The function to decide whether the key value currently entered is for TV View or application Syntax Parameter Return Value isViewerKey (pKeyCode) pKeyCode: entered remote control key value at present True - Key processing by TV Viewer False Key processing by Application When the TV viewer needs to proceed the entered remote control keys, the inputted value in TV viewer is automatically transferred

Remarks

55

Application Development Guide for Samsung Smart TV


(Since Application Manager 2.266) Example Enumeration var pluginAPI = new Common.API.Plugin(); pluginAPI.isViewerKey(KEY_ENTER) None

5.5.20.

setOnFullScreen ()

setOnFullScreen
The function to set on full screen. Syntax Parameter Return Value Remarks setOnFullScreen() None None In case of <fullwidget>y</fullwidget>, it is not necessary to call this function. (Since Samsung Smart TV version 2.306) var pluginAPI = new Common.API.Plugin(); pluginAPI.setOnFullScreen(); None

Example Enumeration

5.5.21.

setOffFullScreen()

setOffFullScreen
The function to set off full screen. Syntax Parameter Return Value Remarks setOffFullScreen() None None Available after calling setOnFullScreen. (Since Samsung Smart TV version 2.306) var pluginAPI = new Common.API.Plugin(); pluginAPI.setOffFullScreen(); None

Example Enumeration

56

Application Development Guide for Samsung Smart TV

5.6. CImageViewer
Introduces a common module ClmageViewer and describes how to use it

5.6.1. CImageViewer?
CImageViewer is a common module that enables JPEG files to be played in SAMSUNG DTV. With this module, Images can be displayed on DTV big screen with high resolution,1920 x 1080 pixels. In addition, images are marked by scaling the size you need at the location you prefer, and transition effect in various manners is available. If you want to utilize CImageViewer, TV source should be designated as a Media source. Source Transition can be made by setting <srcctl> item to y or through SetMediaSource() of TVMW Plugin.

5.6.2. Specifications
Features
1920 x 1080 pixels Resolution Images are displayed in Media source. The display pixel of the application is marked as 960 x 540 pixels, but that of the displaying image in media source is marked as 1920 x 1080 pixels. Supported file format JPEG only Designate the area where an image should be displayed and play it, the Scaling range image is scaled in observance of the area you set. At this stage, resolution should be set over 300 pixels. If it is less than 30 pixels, images can be distorted or flicking. Total 10 modes are provided. Transition Effects (NONE, FADE1, FADE2, BLIND, SPIRAL, CHECKER, LINEAR, STAIRS, WIPE, RANDOM) Refer to 5.6.4. Transition Effect for more information.

Description

5.6.3. Basic Instructions


Appoints locations of images and displays images by scaling Include common module common module is included by putting the code below in the <head> of index.html

57

Application Development Guide for Samsung Smart TV


<script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/CImageViewer.js"></script>

Create instance Create ImageViewer instance. var ImageViewer = new CImageViewer('Common ImageViewer');

Initialize ImageViewer Set the area where images are displayed and functions which will execute each event. show() method shows the area managed by ImageViewer on screen. Area designation via setFrameArea() method is executed based on basic resolution (960x540 pixel). The appointed area operates at 1920x1080 pixel.

ImageViewer.setFrameArea(100, 100, 300, 300); ImageViewer.setOnNetworkError(function(){ alert('Network error occurs!'); }); ImageViewer.show();

Play images Play images. Images remain original proportion at the designated areas and they are indicated by scaling.

ImageViewer.play('$WIDGET/picture.jpg', 640, 480);

Closing the App When the App is closed, ImageViewer should be initialized with calling destroy() method. In case that the application is closed without initialization while playing images in ImageViewer, fatal problems such as TV system pause might occur and there could be toubles using ImageViewer in other applications.

// Run ImageViewer.destroy() method on <body>'s onunload function ImageViewer.destroy();

5.6.4. Transition Effect


The function to give special effects. The effect applies to the whole screen not to the image area. Following describes the process to transfer page 1 to page 2. There are 10 modes available.

58

Application Development Guide for Samsung Smart TV


Effect
NONE FADE1 FADE2 BLIND SPIRAL CHECKER LINEAR STAIRS Transition without effects. Page 1 is faded out and page 2 is faded in. Page 1 is white faded out and page2 is faded in. Page 2 appears with blind effect. Page 2 appears spinning clockwise from the center. Page 2 appears gradually in a grid pattern. Each line of Page 1 is replaced with the lines of page 2 from left to right. The page is transformed to page 2 gradually in the shape of steps from upper left to lower right. WIPE Page transition happens when the central is spread up and down, or upper and down sides are reached to the center. RANDOM Effects above except for NONE are operated randomly.

Description

It is available to refer to variables of Effect members in an instance of CImageViewer or CImageViewer class. var ImageViewer = new CImageViewer('Common ImageViewer'); ImageViewer.Effect.FADE2 or CImageViewer.Effect.FADE2

5.6.4.1.

Action Principles of Slideshow

Slideshow operates as stated below.

Display the first image Prepare the second image Display the second image Prepare the third image

Play the first image through .play(). Buffering complete event occurs while playing, afterward, Rendering complete event which informs that the image are thoroughly scattered on screen takes place. Then, call prepareNext() to prepare next image. The screen has not been changed because preparation is proceeded on background. When the image is ready to show, Buffering complete event informs that. Since this point, Transition Effect is available to see by calling .showNow(). After the Effect is completed, Rendering complete event occurs again to proceed next image.

59

Application Development Guide for Samsung Smart TV

5.6.4.2.

How to Realize Transition Effect

An image display is terminated, the next image is loaded. When loading is completed, Transition effect starts to play. After the Transition effect, the next image is loaded. The points when image display is ended and loading is completed are acknowledged by the Event loaded from ImageViewer. ImageViewer Setup Full screen is designated as area of use for ImageViewer. Register a function to find out the points an image started to be loaded and playing is over.

ImageViewer = new CImageViewer(Common ImageViewer'); ImageViewer.setFrameArea(0, 0, 960, 540); ImageViewer.setOnBufferingComplete(function(){ alert('Image ready!'); }); ImageViewer.setOnRenderingComplete(function(){ alert('You can prepare next image!'); });

Slideshow Mode Setup There are many differences in internal process sequences between general image display and image display by Transition effect. Set a method notifying slideshow mode to enable ImageViewer to execute Transition effect.

ImageViewer.startSlideshow();

Play the first image The first image is played with play() method. Factors such as width and height except URL do not need to

60

Application Development Guide for Samsung Smart TV


be provided because it is not available to designate location of images in slideshow mode.

ImageViewer.play('$WIDGET/picture_1.jpg', 640, 480);

Prepare to load the next image The next image is loaded after the first image is displayed. The moment when the first playing is ended is equal to the point when the registered function via setOnRenderingComplete() begins to execute. Then, location of the image and effects you intend to apply are settled by prepareNext(). After a while, Buffering Completed, which means that the next image is ready for display, occurs.

ImageViewer.prepareNext('$WIDGET/picture_2.jpg ', ImageViewer.Effect.FADE2);

Start Effect Transition effect starts to play once showNow() is called. When Effect animation is completed, Rendering Complete event, which indicates completion of image display, takes place. Successive Transition effect can be realized by reiterating process . Be sure to remember that calling showNow() should be made after Buffering Complete event. End slideshow mode Call endSlideshow() to sneak out of slideshow mode. This method enables next images to display normally.

ImageViewer.endSlideshow();

5.6.4.3.

Slideshow Mode and Restrictions

There are several restrictions in using Transition effect. Scaling is not available.

Transition effect applies to the whole screen, so it is not available to operate with scaling simultaneously. Images should be palyed in full screen (960x540 pixels). Set as shown below.

setFrameArea(0, 0, 960, 540);

Images are displayed at the center of screen in original size. If the size of original image is larger than width 1920 pixels and height 1080 pixels, the image will be downscaled in accordance with aspect ratio, and displayed in the center screen.

61

Application Development Guide for Samsung Smart TV


Do not execute other methods while operating Transition effect.

If other methods are operated while proceeding Transition effect, several problems occur such as troubles on image transition. It is recommended that other operations be done after Rendering complete event indicating that the effect is over. Hardware restrictions

SAMSUNG DTV has several models, but some of them could not support Transition effect due to hardware restrictions. CImageViewer provides isEffectAvailable() method to check the availability.

5.6.5. Events
ImageViewer loads various events in order to control image display more precisely. You can operate events after registering a function to the necessary Event.

Event
Buffering start

Description
If the image you intend to play exists on the internet, this occurs when the image starts to be loaded actually after successful connection with server.

Function
setOnBufferingStart()

Buffering complete Rendering complete

This happens when the image is ready to display after loading. This occurs when an image is completely displayed on the screen. In case of using Transition effect, this happens when Effect animation has been completed. This appears in case that image URL Is not accessed normally. This takes place when image decoding and rendering are failed.

setOnBufferingComplete()

setOnRenderingComplete()

Network error

setOnNetworkError()

Render error

setOnRenderError()

5.6.6. Play local files


ImageViewer displays images in application or USB as well as on the Internet. A special path starting with $ is necessary to display images in application or USB.

5.6.6.1.

Play Images in an Application

The string $WIDGET indicates a directory containing an application. Images in the application can be played by sending strings as shown below to ImageViewer.play().

62

Application Development Guide for Samsung Smart TV


ImageViewer.play('$WIDGET/picture_2.jpg ', 640, 480);

5.6.6.2.

Play images in USB

The string '$USB_DIR' indicates USB. To display images in USB, the location where the USB is mounted in TV is needed because TV has plural USB ports, and mounting path varies for each USB connection. The location can be found via Storage Plugin. Refer to Plugin guide for more details on Storage Plugin. Here, we apply minimum functions to show examples. How to figure out mount route The path to mount USB is found out by Storage plugin. Root directory path of USB is completed by adding the path mounted by the string $USB_DIR which indicates USB.

// Plugin object Designated var eStoragePlugin = document.getElementById('pluginObjectStorage'); // Provided that one USB is connected var deviceId = eStoragePlugin.GetUSBDeviceID(0); // Provided that USB has one partition var mountPath = eStoragePlugin.GetUSBMountPath(deviceId, 0); var USBRootPath = '$USB_DIR/' + mountPath; // USB root directory path

Your TV has more than two USB ports. If you need to control more than two USBs or use USB with divided partitions, other functions in Storage plugin are required. How to create file routes File information in USB is available, using readDir() API of App Engine. readDir() puts file information on the path in an array and returns it. Below shows an example to refer to whether it is a directory or not and file name. Refer to 8. File API for more information.

var fileSystemObj = new FileSystem(); var dirs = new Array(); var files = new Array(); var data = fileSystemObj.readDir(USBRootPath); for (var i = 0; i < data.length; i++) { if (data[i].isDir) { dirs.push(data[i].name); }

// App Engine API

// readDir() returns the array of file information

63

Application Development Guide for Samsung Smart TV


else { files.push(data[i].name); } }

The whole path of image files in USB is created by the file information figured above.

var USBImageFile = USBRootPath +'/'+ directory +'/'+ file;

The actual variable of USBImageFile could be the same as below.

'$USB_DIR/sda1/myphotos/picture_2.jpg'

Image files in USB are displayed.

ImageViewer.play(USBImageFile);

5.6.7. Reference 5.6.7.1. CImageViewer

CImageViewer
A class to play images Library path Syntax $MANAGER_WIDGET/Common/API/CImageViewer.js New CImageViewer(objectName:String) objectName:String Parameter Includes names to distinguish generated objects. The debug message which occurred from ImageViewer has the name on it. Return Value CImageViewer object ImageViewer provided by TV in reality is only one. Therefore, it is urged that one object of CImageViewer be created. Remarks If an image is played via ImageViewer, destroy() should be called when closing the application. (Since Application Manager 2.269)

64

Application Development Guide for Samsung Smart TV


Example Members var ImageViewer = new CImageViewer('Common ImageViewer'); Effect clearScreen destroy endSlideshow getStopFlag hide isEffectAvailable isValidType play prepareNext Methods setDisplayArea setFrameArea setOnBufferingComplete setOnBufferingStart setOnNetworkError setOnRenderError setOnRenderingComplete show showNow startSlideshow stop

5.6.7.2.

Effect

Effect
An object defined by Transition Effect Value Library path Syntax Parameter Return Value Remarks Example $MANAGER_WIDGET/Common/API/CImageViewer.js var ImageViewer = new CImageViewer(objectName:String); ImgeViewer.Effect.VALUE None None INIT is for internal action, do not us it. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer');

65

Application Development Guide for Samsung Smart TV


ImageViewer.Effect.FADE1; NONE FADE1 FADE2 BLIND SPIRAL CHECKER LINEAR STAIRS WIPE RANDOM

Members

Methods

None

5.6.7.3.

clearScreen()

clearScreen
Deletes images displaying on the page Syntax Parameter Return Value Remarks Example Enumeration ImageViewer.clearScreen() None None stop() is not able to remove the playing image. To delete the image, call clearScreen. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); ImageViewer.clearScreen(); None

5.6.7.4.

destroy()

destroy
Pauses the playing image and initializes ImageViewer Syntax Parameter Return Value ImageViewer.destroy() None None If you have used ImageViewer, this function should be called when closing the Remarks application. It is recommended that the function registered onunload function of (Since Application Manager 2.269) <body> element call this method. The function is called when the application ends.

66

Application Development Guide for Samsung Smart TV


Example Enumeration var ImageViewer = new CImageViewer('Common ImageViewer'); ImageViewer.destroy (); None

5.6.7.5.

endSlideshow()

endSlideshow
Ends slideshow mode Syntax Parameter Return Value ImageViewer.endSlideshow() None None Call startSlideshow() to enter slideshow mode which includes transition effect. Remarks prepareNext() and showNow() work only in slideshow mode. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); Example ImageViewer.startSlideshow(); // Use transition effect ImageViewer.endSlideshow(); Enumeration None

5.6.7.6.

getStopFlag()

getStopFlag
Confirms that ImageViewer is stopped or not Syntax Parameter Return Value Remarks Example Enumeration ImageViewer. getStopFlag(); None ImageViewer.getStopFlag(); None Boolean If the ImageViewer is stopped, return true, if it is operating, return false. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer');

67

Application Development Guide for Samsung Smart TV 5.6.7.7. hide()

hide
Hides areas managed by ImageViewer Syntax Parameter Return Value Remarks ImageViewer.show(); Example // Play images! ImageViewer.stop(); ImageViewer.hide(); Enumeration None ImageViewer.hide(); None None (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer');

5.6.7.8.

isEffectAvailable()

isEffectAvailable
Checks if Transition effect is available Syntax Parameter ImageViewer.isEffectAvailable(); None Boolean Return Value If user settings are feasible for Transition effect, return true, if not, return false. (Since Application Manager 2.269) Remarks Example Enumeration Some models do not support Transition effect due to hardware restrictions. In these models, Effect animation is not workable even in slideshow mode. var ImageViewer = new CImageViewer('Common ImageViewer'); ImageViewer.isEffectAvailable(); None

5.6.7.9.

play()

Play
Plays images

68

Application Development Guide for Samsung Smart TV


Syntax ImageViewer.play(url:String, width:Number, height:Number); url:String Available to display image URL, images in Application and USB width:Number Size unit of an image (width, height) is pixel. The image is scaled based on the pixels and displayed in the designated area by setFrameArea(). Slideshow mode does not need this. height:Number Size unit of an image (width, height) is pixel. The image is scaled based on the pixels and displayed in the designated area by setFrameArea(). Slideshow mode does not need this. (Since Application Manager 2.269) Playable image type is JPEG only. var ImageViewer = new CImageViewer('Common ImageViewer'); ImageViewer.setFrameArea(50,50,480,320); ImageViewer.play(image_url, image_width, image_height); Enumeration None

Parameter

Return Value Remarks Example

5.6.7.10.

prepareNext()

prepareNext
Method to load the next image to execute Transition effect in slideshow mode Syntax ImageViewer.prepareNext(url:string, effect:ImageViewer.Effect); url:string Available to display image URL, images in Application and USB Parameter effect:ImageViewer.Effect Refer to Transition effect you intend to apply and Effect variables in the instance of CImageViewer. Return Value None When this method is called, an image is started to be loaded. Effect animation is shown by calling showNow() after Buffering Complete event. Remarks Transition effect might not be supported by several models because of hardware restrictions. Use isEffectAvailable() to find out that Transition effect is available in your TV. (Since Application Manager 2.269) Example var ImageViewer = new CImageViewer('Common ImageViewer'); ImageViewer.setFrameArea(0,0,960,540); ImageViewer.startSlideshow();

69

Application Development Guide for Samsung Smart TV


ImageViewer.play(firstImage, 300, 400); // after Rendering complete event ImageViewer.prepareNext(NextImage, ImageViewer.Effect.FADE1); // after Buffering complete event ImageViewer.shwoNow(); // after finishing slideshow ImageViewer.endSlideshow(); Enumeration None

5.6.7.11.

setFrameArea()

setFrameArea
Sets the area where images are marked. Images are displayed within the area. Syntax ImageViewer.setFrameArea(left:Number, top:Number, width:Number, height:Number); left:Number Left coordinate of the area top:Number Top coordinate of the area Parameter width:Number Width of the area height:Number Height of the area * Unit is pixel. Return Value None For instance, if the image is set as setFrameArea(0,0,225,200), the upper left area of TV screen is transferred to Media source, Images at 450 x 400 pixels are realized Remarks remaining intact. If an image you intend to display is larger than the standard, it is scaled in accordance with aspect ratio and displayed in the area. (Since Application Manager 2.269) Example Enumeration var ImageViewer = new CImageViewer('Common ImageViewer'); ImageViewer.setFrameArea(0,0,480,320); ImageViewer.play(image_url, image_width, image_height); None

70

Application Development Guide for Samsung Smart TV 5.6.7.12. setOnBufferingComplete()

setOnBufferingComplete
Registers a function executed in case of Buffering complete event while loading an image Syntax Parameter Return Value ImageViewer.setOnBufferingComplete(callback:function); callback:function The function executed in the event of Buffering complete event None Buffering complete event occurs after image loading. If this event takes places after Remarks calling prepareNext(), it means that the image is ready for Transition effect. At this stage, calling showNow() begins effect animation. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); Example ImageViewer.setOnBufferingComplete(function(){ // blah blah }); Enumeration None

5.6.7.13.

setOnBufferingStart()

setOnBufferingStart
Registers a function executed in case of Buffering start event Syntax Parameter Return Value ImageViewer.setOnBufferingStart(callback:function); callback:function The function executed in the event of Buffering start event None If the image you intend to play is on the Internet, this event happens when starting to Remarks load actual image data after connecting to the server successfully. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); Example ImageViewer.setOnBufferingStart(function(){ // blah blah }); Enumeration None

71

Application Development Guide for Samsung Smart TV 5.6.7.14. setOnNetworkError()

setOnNetworkError
Registers a function executed in case of Network error event Syntax Parameter Return Value Remarks ImageViewer.setOnNetworkError(callback:function); callback:function The function executed in the event of Network error event None This event occurs in case of network errors while loading images. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); Example ImageViewer.setOnNetworkError(function(){ // blah blah }); Enumeration None

5.6.7.15.

setOnRenderError()

setOnRenderError
Registers a function executed in case of Decoding or Rendering error Syntax Parameter Return Value ImageViewer.setOnRenderError(callback:function); callback:function The function executed in case of Decoding or Rendering error None This event takes place when an error occurs while decoding and rendering after Remarks buffering and when trying playing a format not basically supported. (Image files except for JPEG) (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); Example ImageViewer.setOnRenderError(function(){ // blah blah }); Enumeration None

72

Application Development Guide for Samsung Smart TV 5.6.7.16. setOnRenderingComplete ()

setOnRenderingComplete
Registers a function executed in case of Rendering complete event Syntax Parameter Return Value ImageViewer.setOnRenderingComplete(callback:function); callback:function The function executed in the event of Rendering complete event None This event occurs when the image displays completely on the screen. If Transition Remarks effect is used, the event occurs at the point when Effect animation is ended. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); Example ImageViewer.setOnRenderingComplete(function(){ // blah blah }); Enumeration None

5.6.7.17.

show()

Show
Shows area managed by ImageViewer on screen Syntax Parameter Return Value Remarks ImageViewer.show(); Example // Play images! ImageViewer.stop(); ImageViewer.hide(); Enumeration None ImageViewer.show(); None None (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer');

5.6.7.18.

showNow ()

showNow

73

Application Development Guide for Samsung Smart TV


Transition effect is begun to play. Loading the image should be ended via prepareNext(). Syntax Parameter Return Value ImageViewer.showNow(); None None Transition effect is not provided in several models owing to hardware restrictions. Refer to isEffectAvailable(). Remarks Calling prepareNext() starts to load a image. Effect animation is shown by calling showNow() after Buffering complete event. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); ImageViewer.setFrameArea(0,0,960,540); ImageViewer.startSlideshow(); ImageViewer.play(firstImage, 300, 400); // after Rendering complete event Example ImageViewer.prepareNext(NextImage, ImageViewer.Effect.FADE1); // after Buffering complete event ImageViewer.shwoNow(); // after finishing slideshow ImageViewer.endSlideshow(); Enumeration None

5.6.7.19.

startSlideshow ()

startSlideshow
Starts slideshow mode Syntax Parameter Return Value ImageViewer.startSlideshow() None None If you want to close slideshow mode, call endSlideshow(). Remarks Methods such as prepareNext() and showNow() are available only in slideshow mode. (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); Example ImageViewer.startSlideshow(); // Use transition effect

74

Application Development Guide for Samsung Smart TV


ImageViewer.endSlideshow(); Enumeration None

5.6.7.20.

stop ()

stop
Stops image processing Syntax Parameter Return Value ImageViewer.stop(); None None This does not get rid of playing images on screen. It stops image processing such as Remarks image loading and Transition effect animation. If you want to remove playing images from the screen, refer to clearScreen(). (Since Application Manager 2.269) var ImageViewer = new CImageViewer('Common ImageViewer'); ImageViewer.setFrameArea(50,50,480,320); ImageViewer.play(image_url, image_width, image_height); ImageViewer.stop(); Enumeration None

Example

75

Application Development Guide for Samsung Smart TV

6. Tips for application developers


This section describes several pieces of information that are useful for application developers.

6.1. Function necessary to be called when you open an application


For an application to be run, it should ask the Application Manager to display itself on the screen. Only when the Application Manager is requested to do so, it displays the corresponding application on the screen. Any request should be made through a common module. Call the sendReadyEvent() method of the Widget object in the common module.

var widgetAPI = new Common.API.Widget(); // Create Common module widgetAPI.sendReadyEvent(); // Send ready message to Application Manager

6.2. Access point


Whenever you open an application, the App Engine reads the index.html document. If you implement an application by selecting an application and clicking Enter in the Application Manager, the browser starts to read the index.html document. Register a JavaScript function in the onload property so that when the <body> load event occurs, the application is started. The application must calls sendReadyEvent() of the Widget object in the common module.

<body onload="Main.onLoad();">

6.3. Handling remote control key events


If any button on the remote control is pressed, the keydown event occurs. This event is passed to an element receiving focus at the point of time when the event occurs. If the element has registered a function in the onkeydown property, that function is executed. The function identifies which button is pressed using event.keyCode. You should note that an element that is supposed to respond to the keydown event should be receiving focus. If theres no element receiving focus, there will be no relation on the TV screen even though you press a remote control button. All the remote control keys have been defined by member variables of the tvKeyValue object.

76

Application Development Guide for Samsung Smart TV


Look at the example below. Insert an element that will have focus in index.html.

<a href='javascript:void(0);' id='anchor' onkeydown='Main.keyDown();'></a>

Create a function that will be registered in the onkeydown property. Main.keyDown = function(){ var keyCode = event.keyCode; alert("Main Key code : " + keyCode); switch (keyCode) { case tvKey.KEY_LEFT: /** * Code for Left key event! */ break; case tvKey.KEY_RIGHT: break; case tvKey.KEY_UP: break; case tvKey.KEY_DOWN: break; case tvKey.KEY_ENTER: break; case tvKey.KEY_RETURN: break; } } // Key handler

6.4. Remote control keys for applications


If you access an application, the Application Manager registers basic keys relevant to it. A key event registered in an application occurs, it is loaded to the the application, but a key is not registered in the application, the event is not loaded to the application. If an unregistered key is executed, TV system closes the application and TV functions become available. For example, when an application which has no registered volume key is running, the volume key on remote control is pressed, the working application is forcibly closed and volume banner appears on TV screen. Application Manager registers key sets as stated below in order for the application to use keys. When tag value of <fullwidget> in config.xml is y and the Full-screen Application keyset is n, Single-wide Application is registered.

77

Application Development Guide for Samsung Smart TV


Full- screen Application
KEY_VOL_UP KEY_VOL_DOWN KEY_MUTE KEY_TOOLS KEY_INFO KEY_EMODE KEY_DMA KEY_MENU KEY_SOURCE KEY_PRECH KEY_FAVCH KEY_CHLIST KEY_DMA KEY_TTX_MIX KEY_GUIDE KEY_SUBTITLE KEY_ASPECT KEY_DOLBY_SRR KEY_MTS KEY_PANEL_CH_UP KEY_PANEL_CH_DOWN KEY_PANEL_VOL_UP KEY_PANEL_VOL_DOWN KEY_PANEL_ENTER KEY_PANEL_SOURCE KEY_PANEL_MENU KEY_1 KEY_2 KEY_3 KEY_4 KEY_5 KEY_6 KEY_7 KEY_8 KEY_9 KEY_0 KEY_WHEELDOWN KEY_WHEELUP KEY_RED KEY_GREEN KEY_YELLOW KEY_BLUE KEY_RW KEY_PAUSE KEY_FF KEY_PLAY KEY_STOP KEY_ENTER KEY_RETURN KEY_EXIT

Single-wide Application
KEY_WHEELDOWN KEY_WHEELUP KEY_RED KEY_GREEN KEY_YELLOW KEY_BLUE KEY_RW KEY_PAUSE KEY_FF KEY_PLAY KEY_STOP KEY_ENTER KEY_RETURN KEY_EXIT

Each application registers/unregisters keys additionally by utilizing registKey() of common module, Widget. You should be aware of one thing below. Key registration/unregistration should be done after window.onshow event.

The keys registered/unregistered after window.onshow event are normally processed, but those before window.onshow event could be ignored. Register a function executed in window.onshow prior to calling this method because window.onshow event happens after calling sendReadyEvent() of common module, Widget. Below is an example.

var WIDGET = new Common.API.Widget(); var TVKEY = new Common.API.TVKeyValue(); var PLUGIN = new Common.API.Plugin(); Main.onLoad = function(){ window.onshow = function(){

// For sendReadyEvent() // Remote controller key value object // Plugin common module

// register function will be run onshow event

PLUGIN.registKey(TVKEY.KEY_VOL_UP);

78

Application Development Guide for Samsung Smart TV


PLUGIN.registKey(TVKEY.KEY_VOL_DOWN); } WIDGET.sendReadyEvent(); /** * code */ }

The time of key registration/unregistration after window.onshow event does not matter.

6.5. Closing an application


There are two ways to close your application working on the screen: pressing the Return or Exit button on the remote control or sending an event to the Application Manager. For the latter way, you use the sendExitEvent() and sendReturnEvent() functions of the App which is the common module. For more information, see Ch.5 Common module.

6.6. Prevention of closing the TV screen by the Return or Exit key


Using the Return or Exit key on the remote control, you can close applications. If you press the Return key, you will be taken to the Application Manager, and if you press the Exit key, you will be taken to the TV screen. In order to prevent this from happening, when either Return or Exit is pressed, the blockNavigation() function of the App which is the common module has to be executed. For more information, see Ch.5 Common modules.

6.7. Additional Information


When an application is run, the Application Manager gives you additional information. The application gets such information by referring to window.location.search like below. Entered ID/PW via SSO or TV language information is available.

?country=US&language=1&modelid=Valencia&server=development&remocon=2_35_259&area=USA&product =1&mgrver=3.000&id=ori590e@exxx.com&pw=pxxxx&payload={key1:value2,key2:value2}

79

Application Development Guide for Samsung Smart TV


Attribute
country language modelid server remocon area

Value
Country code Language code Digital TV Model ID development | operating Region Code Chapter 9.1.

Description
Country code that has already been assigned. Refer to

Replaced with 'lang attribute Digital TV Model ID server type: Development Server or Operating Server No use Region code that has already been assigned. Refer to chapter9.3. Id inputted in SSO. It is passed only when entering application

Id

string

after sign-in. It should be used after calling decodeURIComponent(). Pw inputted in SSO. It is passed only when entering

pw

string

application after sign-in. It should be used after calling decodeURIComponent().

product mgrver

Product code Samsung Smart TV version

Refer to 9.4. Product Category If your application is enabled after a specific version of Samsung Smart TV, you should check mgrver. Extra Information for specific service. It is passed only when

payload

string(JSON)

entering application after push notification. It should be used after calling decodeURIComponent().

6.8. What CSS need to contain


The element created in the margin beyond the maximum TV resolution(960 x 540 pixel) can cause the display to scroll. All the element margins and paddings in the index.html document should be defaulted to 0 to prevent the matter resulted from going beyond the area. Your CSS should contain the following strings. body { margin: 0; padding: 0; background-color: transparent; }

6.9. Loading images in advance


The App Engine decodes images to make them displayed normally on your screen. If the browser continues to change images that are displayed at a high speed, it may fail to display images on the screen due to

80

Application Development Guide for Samsung Smart TV


unfinished decoding process. To avoid this, you can load and keep images before you actually use them. By doing this, you can save the time for image decoding.

var imagePreloading = new Image(); imagePreloading.src = "Resource/image/largeNFastChange.png";

By doing the above work, you can make the App Engine decode images. For images that have been decoded once by the browser, they dont have to be decoded again later when they are used elsewhere, so that your TV can display them faster.

6.10. Character of the <input> tag


On App Engine, an object that is created by the <input> tag is not overlapped by other objects. Even if you use z-index, the <input> object is always over other objects.

6.11. Scroll bar


App Engine provides a scrolling function, but you cannot see the actual scroll bar on the screen. You can scroll up or down the content on the screen with buttons on the remote control when the content needs a larger area than that you specified before. If you want to see the actual scroll bar on your TV screen, you should use scrollHeight, scrollTop and offsetHeight to make an actual scrollbar appear on the screen. Put an anchor (<a>) in the content you want to scroll up and down, give it focus and click the up or down button on the remote control, then you can scroll up or down the content. (Picture Source: http://sevencapitalsins.wordpress.com/2007/07/04/javascript-smooth-scroll/)

6.12. Making dynamic web pages


If you want to make dynamic web pages, you can use createElement and innerHTML. The createElement function is the standard method dealing with HTML DOM, but its disadvantage is lower operating speed, compared with innerHTML. It is recommended to use innerHTML because your applications are run in TVs, which provide a less optimized operating environment than personal computers.

81

Application Development Guide for Samsung Smart TV

6.13. Setting for letter-spacing


The value of letter-spacing in App Engine is defaulted -1. In case of Thai language, letters happen to be overlapped when the value is -1. Set the value 0 to prevent this from happening. Include below codes to CSS. *{ letter-spacing: 0px; }

6.14. Memory management


If you keep changing innerHTML and creating the XMLHttpRequest object on an on, your TV memory runs out and applications installed in your TV will not run normally. Of course, you have a garbage collector, but it doesnt work fine. Another problem is limited memory resources, compared to PCs. Therefore, if you want to write optimized applications that normally run, you should take additional measures.

6.14.1.

Using XMLHttpRequest

If you create and use XHR objects repeatedly in Samsung TVs, you will be faced with a problem of your applications working in a wrong way. The solution to this problem is set forth in Ch. 4.5 Example for XHR communication.

6.14.2.

Freeing up the memory

If the content in the tag is replaced with the innerHTML property, the corresponding node in the DOM tree is closed and a new one is created and connected. The closed node remains in the memory. If this procedure occurs repeatedly, you could face memory full. The solution to this problem is to use the putInnerHTML() method of the Widget object in the common module. For more information on this method, refer to Ch. Common modules.

6.15. Watch Dog


SAMSUNG TV periodically checks that the operating applications are working properly. If the application does not react within 20 sec, it closes the application forcibly. This system is called Watch dog. Watch dog turns on and off an application, using setOnWatchDog(), setOffWatchDog() method of common module, Plugin. In application, Network related operation and big data parsing(ex. Stock ) take more than 20 sec, and this

82

Application Development Guide for Samsung Smart TV


will let the Watch dog be forced to close. It is recommended that you turn off Watch dog prior to these actions. After the actions have been completed, turn on the watch dog again. If you keep Watch dog off, TV might stop working.

6.16. Prevention for OSD distortion


Images of an application can be distorted if the movie is playing in the background makes too fast transitions. Operating setOnOSDState(), setOffOSDState() method of common module Plugin prevents the trouble. For more details on using the method, see Chapter 5.5. Plugin. This trouble could appear in Single-wide application and Ticker application. (not in Full-screen application)

6.17. Support CSS text-overflow


App Engine supports CSS1, CSS2. Also, text-overflow which is one of the attributes of CSS3 is supported, this can make the browser cope with contents over the area efficiently.

6.18. Directions for creating video application


Video application using Player(Plugin) should be closed after the player is stopped. If you end application without stop playing, critical problem such that TV is paused can occur. The best way to prevent the problem is to stop Player at the registered function in onunload of <body> tag.

6.19. Using IME


Text input is available via remote control in application. Samsung Smart TV provides a module for utilizing IME(Input Method Editor). This module enables users to enter languages. For more details, refer to IME Tutorial manual distributed separately.

6.20. Minimizing initial entry speed of an application


6.20.1. Load Javascript On-Demand

You can save javascript loading time by minimizing javascript in the initial page. On-Demand Javascript Loading is that Download Javascript when it required, instead of downloading it all in the initial page. Divide a big javascript file into several javascript file. And then only some Javascript files needed to generate the initial page amog others. Therefore you can include javascript files minimally in the initial page. And you can load other javascript files by inserting script element as following.

83

Application Development Guide for Samsung Smart TV


Main.onLoad = function(){ var widgetAPI = new Common.API.Widget(); widgetAPI.sendReadyEvent(); setTimeout('IncludeJavascript()',0); } function IncludeJavascript(){ var head= document.getElementsByTagName('head')[0]; var script = document.createElement('script'); //script tag creation. script.type = 'text/javascript'; script.src = 'test.js'; script.onload = function (){}; head.appendChild(script); //inject a new script element into page }

6.20.2.

Load CSS Background Image On-Demand

App Engine loads an image for an elements background style when its background style matching is invoked. Because deleting background style of some elements not nessasary in initial page can speed the application loading up. You can apply elements background style when it required as follows.

function loadBackgroundImage(eid, url){ document.getElementById(eid).style.backgroundImage = "url("+url+")"; } function loadCSSImage(){ loadBackgroundImage("Full1", "img/Full_1.png"); loadBackgroundImage("Full2", "img/Full_2.png"); loadBackgroundImage("Full3", "img/Full_3.png"); }

6.20.3.

Separation of Main.onLoad functions

If you using setTimeout function properly, a background of initial page can be shown more quikly. Separate Main.onLoad function into two steps. The first step is to generate background of initial page. The second step is to do other works not necessary to generate the background of initial page. Following shows this technique.

84

Application Development Guide for Samsung Smart TV

Main.onLoad = function(){ generate background var widgetAPI = new Common.API.Widget(); widgetAPI.sendReadyEvent(); setTimeout('Main_onLoad2()',0); } function Main_onload2(){ IncludeJavascript(); // refer to 6.20.1 generateDetailPage(); }

6.21. Directions for Dynamic loading of CSS


Dynamic loading of CSS files can be done simply with adding a link nod to <head>. However, CSS should be loaded prior to composition of DOM tree in App Engine. If DOM is configured with loaded CSS files, CSS style applies to the DOM. However, CSS is loaded after DOM configuration. CSS style is not applicable to the DOM. See the example below. Add HTML Elements after dynamic loading of CSS Load red_box.css dynamically, and then add div after three secs. After 3 secs, CSS style is applied, a red box appears on screen because CSS file is loaded before DOM.

var Main = { } var WIDGET = new Common.API.Widget(); Main.onLoad = function() { alert("Main : onLoad()"); WIDGET.sendReadyEvent(); includeCSS ('red_box.css'); setTimeout("insertHTML()", 3000); // // } insertHTML(); setTimeout("includeCSS ('red_box.css')", 3000); // For sendReadyEvent() // The first function

85

Application Development Guide for Samsung Smart TV


function includeCSS(path) { alert('+=====+ includeCSS +=====+'); var linkNode = document.createElement('link'); linkNode.type = 'text/css'; linkNode.rel = 'stylesheet'; linkNode.href = path; document.getElementsByTagName('head')[0].appendChild(linkNode); } function insertHTML() { alert('+=====+ insertHTML +=====+'); var divNode = document.createElement('div'); divNode.id = 'red_box'; document.body.appendChild(divNode); } * red_box.css #red_box { position : absolute; left: 100px; top: 100px; width: 100px; height: 100px; border : 3px solid #FF0000; }

Add HTML Element and load CSS dynamically. Get ride of the annotation from Main.onLoad() in the example above. CSS is loaded 3 secs after HML Div element is added. Therefore, there is no change.

insertHTML(); setTimeout("includeCSS ('red_box.css')", 3000);

86

Application Development Guide for Samsung Smart TV

7. App Engine
This section sets forth the browser for running applications provided with Samsung Smart TV, App Engine.

7.1. App Engine?


Stands for Markup engine Platform for Embedded Systems Browser engine for Consumer Electronics (CE) devices Controls devices using markup tags and script classes

When an application is displayed and behaves on the screen, its image and text generation should be controlled and managed. For Samsung TVs with Samsung Smart TV installed, it is App Engine that performs such work. An applications behaviors and displays are made by App Engine. While Internet Explorer and Firefox are PC-based browsers, App Engine is Samsung TV-based browser.

7.2. Standard Specifications


Supported web standards HTML4.01, XHTML1.0, XML1.0 Markup language specifications HTTP1.0/1.1 CSS1, CSS2, CSS TV Profile 1.0 DOM1, DOM2 JavaScript 1.6 Supported image formats BMP, JPEG, PNG, GIF

87

Application Development Guide for Samsung Smart TV

8. File API
This section introduces the file input/output operation system which the Samsung TV application engine supports.

8.1. File API?


Applications can use the file input/output system supported the Samsung TV application engine. Applications can store data they get while they are still working and read them anytime they want to restore the data. All applications perform file input/output operations in a common area. For this reason, files used in different applications might have same name. To prevent this, create a directory using application ID(curWidget.id) and work on the file in the directory. If multiple applications need to share some data, they should do through a file path that they previously promised to use. File input/output operations are performed by creating a file system object and calling the interface of the object.

8.2. API
The following is a list of interfaces that are provided by the Samsung TV application engine. You can use them in JavaScript.

8.2.1. FileSystem()

FileSystem
Generates file system instance available to be used in an application Syntax Parameter Return Value new FileSystem(); None App Engine FileSystem object This function Returns FileSystem instance defined in App Engine. Through this Remarks operation, reading and writing texts are available. Binary format file is not supported. Example Members var fileSystemObj = new FileSystem(); None

88

Application Development Guide for Samsung Smart TV


openCommonFile closeCommonFile deleteCommonFile createCommonDir deleteCommonDir Methods isValidCommonPath readLine writeLine readlAll writeAll readDir openFile

8.2.2. openCommonFile()

openCommonFile
Opens file in common storage area of an application. Syntax fileSystemObj.openCommonFile(filePath:String, mode:String) filePath:String path including a file name. mode:String r : Open a file for reading. The file must exist. w : Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. a : Append to a file. Writing operations append data at the end of the file. The file is Parameter created if it does not exist. r+ : Open a file for update both reading and writing. The file must exist. w+ : Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. a+ : Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist. Return Value App Engine file object

89

Application Development Guide for Samsung Smart TV


With this method, all the applications operate to input and output files in the same Remarks area. Due to this feature, the case that files used in other applications have the same name happens. It is required to create directories using application ID via curWidget.id and execute file operations in the directory. var fileSystemObj = new FileSystem(); Example var fileObj = fileSystemObj.openCommonFile(curWidget.id + '/testFile.data', 'w'); fileObj.writeAll('something to write.'); fileSystemObj.closeCommonFile(fileObj); Enumeration None

8.2.3. closeCommonFile()

closeCommonFile
Closes files opened by openCommonFile(). Syntax Parameter Return Value Remarks fileSystemObj.closeCommonFile(fileObj:App Engine file object) fileObj: App Engine file object The file instance returned by openCommonFile() Boolean Opened files should be closed. Especially, if a file is outputted by methods such as writeAll(), the output is not saved without closing the file object. var fileSystemObj = new FileSystem(); Example var fileObj = fileSystemObj.openCommonFile(curWidget.id + '/testFile.data', 'w'); fileObj.writeAll('something to write.'); fileSystemObj.closeCommonFile(fileObj); Enumeration None

8.2.4. deleteCommonFile()

deleteCommonFile
Deletes files in Input/Output area Syntax Parameter fileSystemObj.deleteCommonFile(filePath:String) filePath:String path including the name of a file to delete

90

Application Development Guide for Samsung Smart TV


Return Value Remarks Example Enumeration Boolean None var fileSystemObj = new FileSystem(); var bResult = fileSystemObj.deleteCommonFile(curWidget.id + '/testFile.data'); None

8.2.5. createCommonDir()

createCommonDir
Creates directories in file input/output area Syntax Parameter Return Value Remarks fileSystemObj.createCommonDir(directoryPath:String) directoryPath:String path including the name of a directory to create Boolean Creating a directory named curWidget.id to avoid crash between file names in other applications. var fileSystemObj = new FileSystem(); var bResult = fileSystemObj.createCommonDir(curWidget.id); None

Example Enumeration

8.2.6. deleteCommonDir()

deleteCommonDir
Deletes directories in file input/out area Syntax Parameter Return Value Remarks Example Enumeration fileSystemObj.deleteCommonDir(directoryPath:String) directoryPath:String path including a name of directory to delete Boolean None var fileSystemObj = new FileSystem(); var bResult = fileSystemObj.deleteCommonDir(curWidget.id); None

91

Application Development Guide for Samsung Smart TV 8.2.7. isValidCommonPath()

isValidCommonPath
Checks if there is a directory Syntax Parameter fileSystemObj.isValidCommonPath(directoryPath:String) directoryPath:String path including a name of directory to confirm its existence Int Return Value 0 : JS function failed 1 : valid 2 : invalid Remarks None var fileSystemObj = new FileSystem(); var bValid = fileSystemObj.isValidCommonPath(curWidget.id); Example if (!bValid) { fileSystemObj.createCommonDir(curWidget.id); } Enumeration None

8.2.8. readLine()

readLine
Reads a line in an opened file Syntax Parameter fileObj.readLine() None String Return Value Returns a line ranging to line feed character as a result. If there is nothing to read, return null. Remarks None var fileSystemObj = new FileSystem(); Example var fileObj = fileSystemObj.openCommonFile(curWidget.id + '/testFile.data', 'r'); var strLine = ''; var arrResult = new Array();

92

Application Development Guide for Samsung Smart TV


while((strLine=fileObj.readLine())) { arrResult.push(strLine); } Enumeration None

8.2.9. writeLine()

writeLine
Writes a line in an opened file Syntax Parameter Return Value Remarks fileObj.writeLine(text:String) text:String text to write in a file Boolean None var fileSystemObj = new FileSystem(); Example var fileObj = fileSystemObj.openCommonFile(curWidget.id + '/testFile.data', 'w'); fileObj.writeLine('something to write.'); fileSystemObj.closeCommonFile(fileObj); Enumeration None

8.2.10.

readlAll()

readAll
Reads whole of the opened file Syntax Parameter Return Value Remarks fileObj.readAll() None String Whole contents of the file None var fileSystemObj = new FileSystem(); Example var fileObj = fileSystemObj.openCommonFile(curWidget.id + '/testFile.data', 'r'); var strResult = fileObj.readAll(); alert(strResult); Enumeration None

93

Application Development Guide for Samsung Smart TV

8.2.11.

writeAll()

writeAll
Writes several lines in the opened file Syntax Parameter Return Value Remarks fileObj.writeAll(text:String) text:String test to write in a file Boolean None var fileSystemObj = new FileSystem(); Example var fileObj = fileSystemObj.openCommonFile(curWidget.id + '/testFile.data', 'w'); fileObj.writeAll('something to write.'); fileSystemObj.closeCommonFile(fileObj); Enumeration None

8.2.12.

readDir()

readDir
Able to see file information in USB Syntax Parameter fileSystemObj.readDir(directoryPath:String) directoryPath:String Path of a directory that you want to see. Wors only for USB directory Array The Array containing file information. Each element has file information in a directory. Able to get information by referring to variables below. name : file name Return Value isDir : If a file is a directory, true, if not, false size : File Size (byte) atime : The time when to open a file or access time to a directory with cd command mtime : The time when file contents are changed ctime : The time when file information is changed If there is no directoryPath, return false.

94

Application Development Guide for Samsung Smart TV


File information in USB can be brought by $USB_DIR. For the way to find out mounted path of USB, refer to storage plugin of Plugin guide. var fileSystemObj = new FileSystem(); var usbPath = '$USB_DIR' + usb_mount_path; var arrFiles = fileSystemObj.readDir(usbPath); if (arrFiles) { Example for (var i=0; i < arrFiles.length; i++) { alert(arrFiles[i].name); alert(arrFiles[i].isDir); } } Enumeration None

Remarks

8.2.13.

openFile()

openFile
Opens files in an application Syntax fileSystemObj.openFile(filePath:String, mode:String) filePath:String path including a file name Parameter mode:String r : Open a file for reading. The file must exist. *only r mode is available. App Engine file object Return Value Returns file object defined in App Engine. Character strings are read By calling readLine(), readAll() methods that file object has. openCommonFile() enablies files to input and output in common area of all Remarks applications, on the other hand, openFile() is only able to read files in directory where an application is installed. var fileSystemObj = new FileSystem(); Example var fileObj = fileSystemObj.openFile('index.html', 'r'); alert(fileObj.readAll()); fileSystemObj.closeFile(fileObj); Enumeration None

95

Application Development Guide for Samsung Smart TV

9. Appendix
9.1. Country Code
You can get this code from Application Manager. Refer ch. 6.7, for more details.

Nations
ALBANIA ANDORRA AUSTRIA BELGIUM BOSNIA BULGARIA CIS CROATIA CYPRUS CZECH DENMARK FINLAND FRANCE GERMANY GREECE HUNGRARY ICELAND IRELAND ITALY LUXEMBOURG MACEDONIA MONTENEGRO NETHERLAND NORWAY POLAND

Code
AL AD AT BE BA BG RU HR CY CZ DK FI FR DE GR HU IS IE IT LU MK ME NL NO PL PORTUGAL ROMANIA SERBIA SLOVAKIA SLOVENIA SPAIN SWEDEN SWITZERLAND UK AMERICA CANADA MEXICO ARGENTINA CHILE PERU THAILAND VIETNAM MALAYSIA INDONESIA PHILIPPINES BRAZIL ALGERIA MOROCCO TUNISIA

Nations

Code
PT RO RS SK SI ES SE CH GB US CA MX AR CL PE TH VN MY ID PH BR DZ MA TN

96

Application Development Guide for Samsung Smart TV

9.2. Langauage Code


These codes are obtained from application manager while the application is operating. These are made by parsing value of window.location.search, and value stated below is delivered to lang attribute. Tamil and Hindi are not provided in App Engine 5.1, the code for them is en-GB. Refer to Chapter 6.7 for more information on window.location.search.

Nations
Afrikaans Amharic Arabic Bulgarian Chinese Croatian Czech Danish Dutch English English(GB) Estonian Finnish French French(America) German Greek, Modern Hausa Hebrew Hindi (Not provided) Hongkong Hungarian Igbo Indonesian Italian Korean

Code
af am ar bg zh-CN hr cs da nl en en-GB et fi fr fr-US de el ha he en-GB zh-HK hu ig id it ko Latvian Lithuanian Lithuanian Norwegian Persian Polish Portuguese

Nations

Code
lv lt lt no fa pl pt pt-US ro ru sr sk es es-US sw sv zh-TW en-GB th tr ur vi xh yo zu

Portuguese(America) Romany Russian Serbian Slovak Spanish Spanish(America) Swahili Swedish Taiwan Tamil (Not provided) Thai Turkish Urdu Vietnamese Xhosa Yoruba Zulu

97

Application Development Guide for Samsung Smart TV


The table stated below shows the codes delivered from language attribute. language attribute is replaced with lang. language attribute is planned to be erased. Do not use it further.

Language
Korean English Spanish(America) French(America) Portuguese(America) Bulgarian Croatian Czech Danish Dutch Finnish French German Modern Greek Hungarian Italian Norwegian English(GB) Polish Portuguese Romany Russian Serbian Slovak

Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Spanish Swedish Turkish Chinese Hongkong Taiwan Japanese Maori CMN YUE Hindi Estonian Latvian Lithuanian Arabic Persian QAA AD Catalan VAL Hebrew OTHER Thai

Language

Code
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

98

Application Development Guide for Samsung Smart TV

9.3. Region Code


You can get this code from Application Manager. Refer ch. 6.7, for more details.

Code
KOR USA BRA PANEURO CHI HKG ARB PANNORDIG SOUTHEASTASIA Korea USA/Canada/Mexico

Region

Brazil, Paraguay, Uruguay, Argentine Europe China Hong Kong Arab Nordic South-East Asia (Vietnam, Thailand, India, China, Iran, Israel, Central Asia, East Asia, Africa)

ASIA_ATV

South-East Asia (Vietnam, Thailand, India, China, Iran, Israel, Central Asia, East Asia, Africa)

ASIA_DTV TW NORTHAFRICA EA_DTV CIS PHI S_AFR_DTV

Australia , New Zealand, Singapore Taiwan, Columbia TURKEY, MOROCCO, TUNISIA Indonesia, Malaysia, Republic of South Africa, Vietnam CIS Philippine South Africa DTV

99

Application Development Guide for Samsung Smart TV

9.4. Product Category


These codes can be obtained from application manager while the application is operating. For more details, refer to chapter 6.7.

Code
0 1 2 TV Monitor Blue-ray Disk

Region

9.5. Caution information


9.5.1. Character sensitive target device
Broadcom Target is the case sensitive system. So, making the matching name is important. For example, if you have player.js file, but in index.html, you write like below, there willl be error in Broadcom target. <script language="javascript" type="text/javascript" src="Javascript/Player.js"></script>

100

Você também pode gostar