[HybridWebApp] updated HybridWebApp sources
[samples/web/HybridWebApp.git] / js / main.js
1 /*
2  *      Copyright 2012  Samsung Electronics Co., Ltd
3  *
4  *      Licensed under the Flora License, Version 1.1 (the "License");
5  *      you may not use this file except in compliance with the License.
6  *      You may obtain a copy of the License at
7  *
8  *              http://floralicense.org/license
9  *
10  *      Unless required by applicable law or agreed to in writing, software
11  *      distributed under the License is distributed on an "AS IS" BASIS,
12  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *      See the License for the specific language governing permissions and
14  *      limitations under the License.
15  */
16
17 var app = tizen.application.getCurrentApplication();
18 var gServiceAppId = app.appInfo.packageId + ".HybridServiceApp";
19 var gServicePortName = "SAMPLE_PORT";
20 var gLocalMessagePortName = "SAMPLE_PORT_REPLY";
21
22 var gLocalMessagePort;
23 var gRemoteMessagePort;
24
25 var gLocalMessagePortWatchId;
26
27 var isStarting = false;
28
29 $(document).delegate("#main", "pageinit", function() {
30         $("#btn-start").bind("vclick", function(){
31
32                 if(gLocalMessagePort) {
33                         showAlert("Already running.");
34                 } else if(isStarting){
35                         showAlert("Now starting...");
36                 } else {
37                         isStarting = true;
38                         start();
39                 }
40                 return false;
41         });
42         $("#btn-stop").bind("vclick", function(){
43                 if(gRemoteMessagePort) {
44                         sendCommand("stop");
45                 } else {
46                         showAlert("Not running.");
47                 }
48                 return false;
49         });
50         $("#btn-clear").bind("vclick", function(){
51                 $("#logs").empty().listview("refresh");
52                 return false;
53         });
54         $(window).on('tizenhwkey', function (e) {
55                 if (e.originalEvent.keyName === "back") {
56                         if ($.mobile.activePage.attr('id') === 'main') {
57                                 tizen.application.getCurrentApplication().exit();
58                         } else {
59                                 history.back();
60                         }
61                 }
62         });
63 });
64
65 function startMessagePort() {
66         try {
67                 gLocalMessagePort = tizen.messageport.requestLocalMessagePort(gLocalMessagePortName);
68                 gLocalMessagePortWatchId = gLocalMessagePort.addMessagePortListener( function(data, remote) {
69                         onReceive(data, remote);
70                 });
71         } catch (e) {
72                 writeToScreen(e.name);
73         }
74
75         try {
76                 gRemoteMessagePort = tizen.messageport.requestRemoteMessagePort(gServiceAppId, gServicePortName);
77         } catch (e) {
78                 writeToScreen(e.name);
79         }
80
81         isStarting = false;
82
83         sendCommand("connect");
84 }
85
86 function sendCommand(command){
87         var jsondata = '{"command" : "' + command + '"}';
88
89         gRemoteMessagePort.sendMessage([ { key:"command", value:command } ], gLocalMessagePort);
90         writeToScreen("Sending: " + command);
91 }
92
93 function onReceive(data, remote) {
94         var message;
95
96         for(var i in data) {
97                 if(data[i].key == "server")
98                         message = data[i].value;
99         }
100
101         writeToScreen("Received : " + message);
102
103         if(message == "WELCOME"){
104                 sendCommand("start");
105         }else if(message == "stopped"){
106                 sendCommand("exit");
107         }else if(message == "exit"){
108                 if(gRemoteMessagePort)
109                         gRemoteMessagePort = null;
110                 if(gLocalMessagePort) {
111                         gLocalMessagePort.removeMessagePortListener(gLocalMessagePortWatchId);
112                         gLocalMessagePort = null;
113                 }
114         }
115 }
116
117 function writeToScreen(message) {
118         var today = new Date(),
119                 time = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate() + " "
120                                 + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds() + "." + today.getMilliseconds(),
121                 str = '<li class="ui-li-has-multiline ui-li-text-ellipsis">'
122                                 + message
123                                 + '<span class="ui-li-text-sub">'
124                                 + time
125                                 + '</span></li>';
126
127         $("#logs").append(str).listview("refresh");
128 }
129
130 function start() {
131         try {
132                 tizen.application.getAppsContext(onGetAppsContextSuccess, onGetAppsContextError);
133         } catch (exc) {
134                 writeToScreen("Get AppContext Error");
135         }
136 }
137
138 function onGetAppsContextSuccess(contexts) {
139         for (var i = 0; i < contexts.length; i++) {
140                 var appInfo = tizen.application.getAppInfo(contexts[i].appId);
141                 if(appInfo.id == gServiceAppId){
142                         console.log("Running Service App found");
143                         break;
144                 }
145         }
146         if (i >= contexts.length) {
147                 console.log("Running Service App not found. Trying to launch it");
148                 launchServiceApp();
149                 //listInstalledApps();
150         }else{
151                 startMessagePort();
152         }
153 }
154
155 function onGetAppsContextError(err) {
156         console.log("getAppsContext exc");
157 }
158
159 function listInstalledApps() {
160         try {
161                 tizen.application.getAppsInfo(getAppsInfoSuccessCB, getAppsInfoErrorCB);
162         } catch (exc) {
163                 writeToScreen("Get Installed App Info Error");
164         }
165 }
166
167 function getAppsInfoSuccessCB(apps) {
168         for (var i = 0; i < apps.length; i++) {
169                 if(apps[i].id == gServiceAppId){
170                         console.log("Found installed Service App")
171                         break;
172                 }
173         }
174         if(i >= apps.length){
175                 writeToScreen("Service App not installed");
176                 isStarting = false;
177                 return;
178         }
179         launchServiceApp();
180 }
181
182 function getAppsInfoErrorCB(err) {
183         console.log("getAppsInfo failed");
184         isStarting = false;
185 }
186
187 function launchServiceApp() {
188         function onSuccess() {
189                 console.log("Service App launched successfully!");
190                 console.log("Restart...");
191                 start();
192         }
193
194         function onError(err) {
195                 console.log("Service Applaunch failed");
196                 isStarting = false;
197                 showAlert("Failed to launch HybridServiceApp!");
198         }
199
200         try {
201                 console.log("Launching [" + gServiceAppId + "] ...");
202                 tizen.application.launch(gServiceAppId, onSuccess, onError);
203         } catch (exc) {
204                 showAlert("launch exc:" + exc.message);
205         }
206 }
207
208 function showAlert(message) {
209         var alertPopup = $("#alert-popup");
210         alertPopup.find("#message").text(message);
211         alertPopup.popup("open", {positionTo: "window"});
212 }