009b315d521b76bf4ab1a762130dcaeab07c7282
[framework/web/wrt-installer.git] / src / jobs / widget_install / task_manifest_file.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (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://www.apache.org/licenses/LICENSE-2.0
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  * @file    task_manifest_file.cpp
18  * @author  Pawel Sikorski (p.sikorski@samgsung.com)
19  * @version
20  * @brief
21  */
22
23 //SYSTEM INCLUDES
24 #include <unistd.h>
25 #include <string>
26 #include <dpl/assert.h>
27 #include <dirent.h>
28 #include <fstream>
29 #include <ail.h>
30
31 //WRT INCLUDES
32 #include <widget_install/task_manifest_file.h>
33 #include <widget_install/job_widget_install.h>
34 #include <widget_install/widget_install_errors.h>
35 #include <widget_install/widget_install_context.h>
36 #include <dpl/wrt-dao-ro/global_config.h>
37 #include <dpl/log/log.h>
38 #include <dpl/file_input.h>
39 #include <dpl/errno_string.h>
40 #include <dpl/file_output.h>
41 #include <dpl/copy.h>
42 #include <dpl/exception.h>
43 #include <dpl/foreach.h>
44 #include <dpl/sstream.h>
45 #include <dpl/string.h>
46 #include <dpl/optional.h>
47 #include <dpl/utils/wrt_utility.h>
48 #include <map>
49 #include <libxml_utils.h>
50 #include <pkgmgr/pkgmgr_parser.h>
51 #include <dpl/localization/LanguageTagsProvider.h>
52
53 #define DEFAULT_ICON_NAME   "icon.png"
54
55 using namespace WrtDB;
56
57 namespace {
58 typedef std::map<DPL::String, DPL::String> LanguageTagMap;
59
60 const char* const ST_TRUE = "true";
61 const char* const ST_NODISPLAY = "nodisplay";
62
63 LanguageTagMap getLanguageTagMap()
64 {
65     LanguageTagMap map;
66
67 #define ADD(tag, l_tag) map.insert(std::make_pair(L###tag, L###l_tag));
68 #include "languages.def"
69 #undef ADD
70
71     return map;
72 }
73
74 DPL::OptionalString getLangTag(const DPL::String& tag)
75 {
76     static LanguageTagMap TagsMap =
77         getLanguageTagMap();
78
79     DPL::String langTag = tag;
80
81     LogDebug("Trying to map language tag: " << langTag);
82     size_t pos = langTag.find_first_of(L'_');
83     if (pos != DPL::String::npos) {
84         langTag.erase(pos);
85     }
86     DPL::OptionalString ret;
87
88     LanguageTagMap::iterator it = TagsMap.find(langTag);
89     if (it != TagsMap.end()) {
90         ret = it->second;
91     }
92     LogDebug("Mapping IANA Language tag to language tag: " <<
93              langTag << " -> " << ret);
94
95     return ret;
96 }
97 }
98
99 namespace Jobs {
100 namespace WidgetInstall {
101 const char * TaskManifestFile::encoding = "UTF-8";
102
103 TaskManifestFile::TaskManifestFile(InstallerContext &inCont) :
104     DPL::TaskDecl<TaskManifestFile>(this),
105     m_context(inCont),
106     writer(NULL)
107 {
108     if (m_context.isUpdateMode) {
109         // for widget update.
110         AddStep(&TaskManifestFile::stepBackupIconFiles);
111         AddStep(&TaskManifestFile::stepCopyIconFiles);
112         AddStep(&TaskManifestFile::stepGenerateManifest);
113         AddStep(&TaskManifestFile::stepParseUpgradedManifest);
114         AddStep(&TaskManifestFile::stepUpdateFinalize);
115
116         AddAbortStep(&TaskManifestFile::stepAbortIconFiles);
117     } else {
118         AddStep(&TaskManifestFile::stepCopyIconFiles);
119         AddStep(&TaskManifestFile::stepCreateExecFile);
120         AddStep(&TaskManifestFile::stepGenerateManifest);
121         AddStep(&TaskManifestFile::stepParseManifest);
122         AddStep(&TaskManifestFile::stepFinalize);
123
124         AddAbortStep(&TaskManifestFile::stepAbortParseManifest);
125     }
126 }
127
128 TaskManifestFile::~TaskManifestFile()
129 {}
130
131 void TaskManifestFile::stepCreateExecFile()
132 {
133     std::string exec = m_context.locations->getExecFile();
134     std::string clientExeStr = GlobalConfig::GetWrtClientExec();
135
136     //default widget
137     LogInfo("link -s " << clientExeStr << " " << exec);
138     errno = 0;
139     if (symlink(clientExeStr.c_str(), exec.c_str()) != 0)
140     {
141         int error = errno;
142         if (error)
143             LogPedantic("Failed to make a symbolic name for a file "
144                     << "[" <<  DPL::GetErrnoString(error) << "]");
145         ThrowMsg(Exceptions::FileOperationFailed,
146                 "Symbolic link creating is not done.");
147     }
148
149 #ifdef MULTIPROCESS_SERVICE_SUPPORT
150     //services
151     std::size_t serviceCount =
152         m_context.widgetConfig.configInfo.appControlList.size();
153     serviceCount += m_context.widgetConfig.configInfo.appServiceList.size();
154     for (std::size_t i = 0; i < serviceCount; ++i) {
155         std::stringstream postfix;
156         postfix << "-__SERVICE_PROCESS__" << i;
157         std::string serviceExec = exec;
158         serviceExec.append(postfix.str());
159         errno = 0;
160         if (symlink(clientExeStr.c_str(), serviceExec.c_str()) != 0)
161         {
162             int error = errno;
163             if (error)
164                 LogPedantic("Failed to make a symbolic name for a file "
165                         << "[" <<  DPL::GetErrnoString(error) << "]");
166             ThrowMsg(Exceptions::FileOperationFailed,
167                     "Symbolic link creating is not done.");
168         }
169
170     }
171 #endif
172
173     m_context.job->UpdateProgress(
174             InstallerContext::INSTALL_CREATE_EXECFILE,
175             "Widget execfile creation Finished");
176 }
177
178 void TaskManifestFile::stepCopyIconFiles()
179 {
180     LogDebug("CopyIconFiles");
181
182     //This function copies icon to desktop icon path. For each locale avaliable
183     //which there is at least one icon in widget for, icon file is copied.
184     //Coping prioritize last positions when coping. If there is several icons
185     //with given locale, the one, that will be copied, will be icon
186     //which is declared by <icon> tag later than the others in config.xml of
187     // widget
188
189     std::vector<Locale> generatedLocales;
190
191     WrtDB::WidgetRegisterInfo::LocalizedIconList & icons =
192         m_context.widgetConfig.localizationData.icons;
193
194     //reversed: last <icon> has highest priority to be copied if it has given
195     // locale (TODO: why was that working that way?)
196     for (WrtDB::WidgetRegisterInfo::LocalizedIconList::const_reverse_iterator
197          icon = icons.rbegin();
198          icon != icons.rend();
199          ++icon)
200     {
201         FOREACH(locale, icon->availableLocales)
202         {
203             DPL::String src = icon->src;
204             LogDebug("Icon for locale: " << *locale << "is : " << src);
205
206             if (std::find(generatedLocales.begin(), generatedLocales.end(),
207                           *locale) != generatedLocales.end())
208             {
209                 LogDebug("Skipping - has that locale");
210                 continue;
211             } else {
212                 generatedLocales.push_back(*locale);
213             }
214
215             std::ostringstream sourceFile;
216             std::ostringstream targetFile;
217
218             sourceFile << m_context.locations->getSourceDir() << "/";
219
220             if (!locale->empty()) {
221                 sourceFile << "locales/" << *locale << "/";
222             }
223
224             sourceFile << src;
225
226             targetFile << GlobalConfig::GetUserWidgetDesktopIconPath() << "/";
227             targetFile << getIconTargetFilename(*locale);
228
229             if (m_context.widgetConfig.packagingType ==
230                 WrtDB::PKG_TYPE_HOSTED_WEB_APP)
231             {
232                 m_context.locations->setIconTargetFilenameForLocale(
233                     targetFile.str());
234             }
235
236             LogDebug("Copying icon: " << sourceFile.str() <<
237                      " -> " << targetFile.str());
238
239             icon_list.push_back(targetFile.str());
240
241             Try
242             {
243                 DPL::FileInput input(sourceFile.str());
244                 DPL::FileOutput output(targetFile.str());
245                 DPL::Copy(&input, &output);
246             }
247
248             Catch(DPL::FileInput::Exception::Base)
249             {
250                 // Error while opening or closing source file
251                 //ReThrowMsg(InstallerException::CopyIconFailed,
252                 // sourceFile.str());
253                 LogError(
254                     "Copying widget's icon failed. Widget's icon will not be" \
255                     "available from Main Screen");
256             }
257
258             Catch(DPL::FileOutput::Exception::Base)
259             {
260                 // Error while opening or closing target file
261                 //ReThrowMsg(InstallerException::CopyIconFailed,
262                 // targetFile.str());
263                 LogError(
264                     "Copying widget's icon failed. Widget's icon will not be" \
265                     "available from Main Screen");
266             }
267
268             Catch(DPL::CopyFailed)
269             {
270                 // Error while copying
271                 //ReThrowMsg(InstallerException::CopyIconFailed,
272                 // targetFile.str());
273                 LogError(
274                     "Copying widget's icon failed. Widget's icon will not be" \
275                     "available from Main Screen");
276             }
277         }
278     }
279
280     m_context.job->UpdateProgress(
281         InstallerContext::INSTALL_COPY_ICONFILE,
282         "Widget iconfile copy Finished");
283 }
284
285 void TaskManifestFile::stepBackupIconFiles()
286 {
287     LogDebug("Backup Icon Files");
288
289     backup_dir << m_context.locations->getPackageInstallationDir();
290     backup_dir << "/" << "backup" << "/";
291
292     backupIconFiles();
293
294     m_context.job->UpdateProgress(
295         InstallerContext::INSTALL_BACKUP_ICONFILE,
296         "New Widget icon file backup Finished");
297 }
298
299 void TaskManifestFile::stepAbortIconFiles()
300 {
301     LogDebug("Abrot Icon Files");
302     FOREACH(it, icon_list)
303     {
304         LogDebug("Remove Update Icon : " << (*it));
305         unlink((*it).c_str());
306     }
307
308     std::ostringstream b_icon_dir;
309     b_icon_dir << backup_dir.str() << "icons";
310
311     std::list<std::string> fileList;
312     getFileList(b_icon_dir.str().c_str(), fileList);
313
314     FOREACH(back_icon, fileList)
315     {
316         std::ostringstream res_file;
317         res_file << GlobalConfig::GetUserWidgetDesktopIconPath();
318         res_file << "/" << (*back_icon);
319
320         std::ostringstream backup_file;
321         backup_file << b_icon_dir.str() << "/" << (*back_icon);
322
323         Try
324         {
325             DPL::FileInput input(backup_file.str());
326             DPL::FileOutput output(res_file.str());
327             DPL::Copy(&input, &output);
328         }
329         Catch(DPL::FileInput::Exception::Base)
330         {
331             LogError("Restoration icon File Failed." << backup_file.str()
332                                                      << " to " << res_file.str());
333         }
334
335         Catch(DPL::FileOutput::Exception::Base)
336         {
337             LogError("Restoration icon File Failed." << backup_file.str()
338                                                      << " to " << res_file.str());
339         }
340         Catch(DPL::CopyFailed)
341         {
342             LogError("Restoration icon File Failed." << backup_file.str()
343                                                      << " to " << res_file.str());
344         }
345     }
346 }
347
348 void TaskManifestFile::stepUpdateFinalize()
349 {
350     commitManifest();
351     LogDebug("Finished Update Desktopfile");
352 }
353
354 DPL::String TaskManifestFile::getIconTargetFilename(
355     const DPL::String& languageTag) const
356 {
357     DPL::OStringStream filename;
358     TizenAppId appid = m_context.widgetConfig.tzAppid;
359
360     filename << DPL::ToUTF8String(appid).c_str();
361
362     if (!languageTag.empty()) {
363         DPL::OptionalString tag = getLangTag(languageTag); // translate en ->
364                                                            // en_US etc
365         if (tag.IsNull()) {
366             tag = languageTag;
367         }
368         DPL::String locale =
369             LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
370
371         if (locale.empty()) {
372             filename << L"." << languageTag;
373         } else {
374             filename << L"." << locale;
375         }
376     }
377
378     filename << L".png";
379     return filename.str();
380 }
381
382 void TaskManifestFile::stepFinalize()
383 {
384     commitManifest();
385     LogInfo("Finished ManifestFile step");
386 }
387
388 void TaskManifestFile::saveLocalizedKey(std::ofstream &file,
389                                         const DPL::String& key,
390                                         const DPL::String& languageTag)
391 {
392     DPL::String locale =
393         LanguageTagsProvider::BCP47LanguageTagToLocale(languageTag);
394
395     file << key;
396     if (!locale.empty()) {
397         file << "[" << locale << "]";
398     }
399     file << "=";
400 }
401
402 void TaskManifestFile::updateAilInfo()
403 {
404     // Update ail for desktop
405     std::string cfgAppid =
406         DPL::ToUTF8String(m_context.widgetConfig.tzAppid);
407     const char* appid = cfgAppid.c_str();
408
409     LogDebug("Update ail desktop : " << appid);
410     ail_appinfo_h ai = NULL;
411     ail_error_e ret;
412
413     ret = ail_get_appinfo(appid, &ai);
414     if (ai) {
415         ail_destroy_appinfo(ai);
416     }
417
418     if (AIL_ERROR_NO_DATA == ret) {
419         if (ail_desktop_add(appid) < 0) {
420             LogWarning("Failed to add ail desktop : " << appid);
421         }
422     } else if (AIL_ERROR_OK == ret) {
423         if (ail_desktop_update(appid) < 0) {
424             LogWarning("Failed to update ail desktop : " << appid);
425         }
426     }
427 }
428
429 void TaskManifestFile::backupIconFiles()
430 {
431     LogInfo("Backup Icon Files");
432
433     std::ostringstream b_icon_dir;
434     b_icon_dir << backup_dir.str() << "icons";
435
436     LogDebug("Create icon backup folder : " << b_icon_dir.str());
437     WrtUtilMakeDir(b_icon_dir.str());
438
439     std::list<std::string> fileList;
440     getFileList(GlobalConfig::GetUserWidgetDesktopIconPath(), fileList);
441     std::string appid = DPL::ToUTF8String(m_context.widgetConfig.tzAppid);
442
443     FOREACH(it, fileList)
444     {
445         if (0 == (strncmp((*it).c_str(), appid.c_str(),
446                           strlen(appid.c_str()))))
447         {
448             std::ostringstream icon_file, backup_icon;
449             icon_file << GlobalConfig::GetUserWidgetDesktopIconPath();
450             icon_file << "/" << (*it);
451
452             backup_icon << b_icon_dir.str() << "/" << (*it);
453
454             LogDebug("Backup icon file " << icon_file.str() << " to " <<
455                      backup_icon.str());
456             Try
457             {
458                 DPL::FileInput input(icon_file.str());
459                 DPL::FileOutput output(backup_icon.str());
460                 DPL::Copy(&input, &output);
461             }
462             Catch(DPL::FileInput::Exception::Base)
463             {
464                 LogError("Backup Desktop File Failed.");
465                 ReThrowMsg(Exceptions::BackupFailed, icon_file.str());
466             }
467
468             Catch(DPL::FileOutput::Exception::Base)
469             {
470                 LogError("Backup Desktop File Failed.");
471                 ReThrowMsg(Exceptions::BackupFailed, backup_icon.str());
472             }
473             Catch(DPL::CopyFailed)
474             {
475                 LogError("Backup Desktop File Failed.");
476                 ReThrowMsg(Exceptions::BackupFailed, backup_icon.str());
477             }
478             unlink((*it).c_str());
479         }
480     }
481 }
482
483 void TaskManifestFile::getFileList(const char* path,
484                                    std::list<std::string> &list)
485 {
486     DIR* dir = opendir(path);
487     if (!dir) {
488         LogError("icon directory doesn't exist");
489         ThrowMsg(Exceptions::FileOperationFailed, path);
490     }
491
492     struct dirent entry;
493     struct dirent *result;
494     int return_code;
495     errno = 0;
496     for (return_code = readdir_r(dir, &entry, &result);
497             result != NULL && return_code == 0;
498             return_code = readdir_r(dir, &entry, &result))
499     {
500         if (strcmp(entry.d_name, ".") == 0 ||
501             strcmp(entry.d_name, "..") == 0)
502         {
503             continue;
504         }
505         std::string file_name = entry.d_name;
506         list.push_back(file_name);
507     }
508
509     if (return_code != 0 || errno != 0) {
510         LogError("readdir_r() failed with " << DPL::GetErrnoString());
511     }
512
513     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
514         LogError("Failed to close dir: " << path << " with error: "
515                                          << DPL::GetErrnoString());
516     }
517 }
518
519 void TaskManifestFile::stepGenerateManifest()
520 {
521     TizenPkgId pkgid = m_context.widgetConfig.tzPkgid;
522     manifest_name = pkgid + L".xml";
523     manifest_file += L"/tmp/" + manifest_name;
524
525     //libxml - init and check
526     LibxmlSingleton::Instance().init();
527
528     writeManifest(manifest_file);
529
530     m_context.job->UpdateProgress(
531         InstallerContext::INSTALL_CREATE_MANIFEST,
532         "Widget Manifest Creation Finished");
533 }
534
535 void TaskManifestFile::stepParseManifest()
536 {
537     int code = pkgmgr_parser_parse_manifest_for_installation(
538             DPL::ToUTF8String(manifest_file).c_str(), NULL);
539
540     if (code != 0) {
541         LogError("Manifest parser error: " << code);
542         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
543     }
544
545     // TODO : It will be removed. AIL update is temporary code request by pkgmgr
546     // team.
547     updateAilInfo();
548
549     m_context.job->UpdateProgress(
550         InstallerContext::INSTALL_CREATE_MANIFEST,
551         "Widget Manifest Parsing Finished");
552     LogDebug("Manifest parsed");
553 }
554
555 void TaskManifestFile::stepParseUpgradedManifest()
556 {
557     int code = pkgmgr_parser_parse_manifest_for_upgrade(
558             DPL::ToUTF8String(manifest_file).c_str(), NULL);
559
560     if (code != 0) {
561         LogError("Manifest parser error: " << code);
562         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
563     }
564
565     // TODO : It will be removed. AIL update is temporary code request by pkgmgr
566     // team.
567     updateAilInfo();
568
569     m_context.job->UpdateProgress(
570         InstallerContext::INSTALL_CREATE_MANIFEST,
571         "Widget Manifest Parsing Finished");
572     LogDebug("Manifest parsed");
573 }
574
575 void TaskManifestFile::commitManifest()
576 {
577     LogDebug("Commiting manifest file : " << manifest_file);
578
579     std::ostringstream destFile;
580     destFile << "/opt/share/packages" << "/"; //TODO constant with path
581     destFile << DPL::ToUTF8String(manifest_name);
582     LogInfo("cp " << manifest_file << " " << destFile.str());
583
584     DPL::FileInput input(DPL::ToUTF8String(manifest_file));
585     DPL::FileOutput output(destFile.str());
586     DPL::Copy(&input, &output);
587     LogDebug("Manifest writen to: " << destFile.str());
588
589     //removing temp file
590     unlink((DPL::ToUTF8String(manifest_file)).c_str());
591     manifest_file = DPL::FromUTF8String(destFile.str().c_str());
592 }
593
594 void TaskManifestFile::writeManifest(const DPL::String & path)
595 {
596     LogDebug("Generating manifest file : " << path);
597     Manifest manifest;
598     UiApplication uiApp;
599
600     //default widget content
601     setWidgetExecPath(uiApp);
602     setWidgetName(manifest, uiApp);
603     setWidgetIds(manifest, uiApp);
604     setWidgetIcons(uiApp);
605     setWidgetManifest(manifest);
606     setWidgetOtherInfo(uiApp);
607 #ifndef MULTIPROCESS_SERVICE_SUPPORT
608     setAppServicesInfo(uiApp);
609     setAppControlsInfo(uiApp);
610 #endif
611     setAppCategory(uiApp);
612     setLiveBoxInfo(manifest);
613     setAccount(manifest);
614     setPrivilege(manifest);
615
616     manifest.addUiApplication(uiApp);
617 #ifdef MULTIPROCESS_SERVICE_SUPPORT
618     //services AppControl tag
619     ConfigParserData::AppControlInfoList appControlList =
620         m_context.widgetConfig.configInfo.appControlList;
621     unsigned count = 0;
622
623     FOREACH(it, appControlList) {
624         it->m_index = count;
625         UiApplication uiApp;
626
627         uiApp.setTaskmanage(true);
628         uiApp.setNodisplay(true);
629 #ifdef MULTIPROCESS_SERVICE_SUPPORT_INLINE
630         uiApp.setTaskmanage(ConfigParserData::AppControlInfo::Disposition::INLINE != it->m_disposition);
631         uiApp.setMultiple(ConfigParserData::AppControlInfo::Disposition::INLINE == it->m_disposition);
632 #endif
633         std::stringstream postfix;
634         postfix << "-__SERVICE_PROCESS__" << count++;
635
636         setWidgetExecPath(uiApp, postfix.str());
637         setWidgetName(manifest, uiApp);
638         setWidgetIds(manifest, uiApp, postfix.str());
639         setWidgetIcons(uiApp);
640         setAppControlInfo(uiApp, *it);
641         setAppCategory(uiApp);
642         setAccount(manifest);
643         setPrivilege(manifest);
644
645         manifest.addUiApplication(uiApp);
646     }
647     //TODO: AppService tag will be removed
648     //services AppService tag
649     WrtDB::ConfigParserData::ServiceInfoList appServiceList =
650         m_context.widgetConfig.configInfo.appServiceList;
651     FOREACH(it, appServiceList) {
652         it->m_index = count;
653         UiApplication uiApp;
654
655         uiApp.setTaskmanage(true);
656         uiApp.setNodisplay(true);
657 #ifdef MULTIPROCESS_SERVICE_SUPPORT_INLINE
658         uiApp.setTaskmanage(ConfigParserData::ServiceInfo::Disposition::INLINE != it->m_disposition);
659         uiApp.setMultiple(ConfigParserData::ServiceInfo::Disposition::INLINE == it->m_disposition);
660 #endif
661
662         std::stringstream postfix;
663         postfix << "-__SERVICE_PROCESS__" << count++;
664
665         setWidgetExecPath(uiApp, postfix.str());
666         setWidgetName(manifest, uiApp);
667         setWidgetIds(manifest, uiApp, postfix.str());
668         setWidgetIcons(uiApp);
669         setAppServiceInfo(uiApp, *it);
670         setAppCategory(uiApp);
671         setAccount(manifest);
672         setPrivilege(manifest);
673
674         manifest.addUiApplication(uiApp);
675     }
676 #endif
677     manifest.generate(path);
678     LogDebug("Manifest file serialized");
679 }
680
681 void TaskManifestFile::setWidgetExecPath(UiApplication & uiApp,
682                                          const std::string &postfix)
683 {
684     std::string exec = m_context.locations->getExecFile();
685     if (!postfix.empty()) {
686         exec.append(postfix);
687     }
688     LogDebug("exec = " << exec);
689     uiApp.setExec(DPL::FromASCIIString(exec));
690 }
691
692 void TaskManifestFile::setWidgetName(Manifest & manifest,
693                                      UiApplication & uiApp)
694 {
695     bool defaultNameSaved = false;
696
697     DPL::OptionalString defaultLocale =
698         m_context.widgetConfig.configInfo.defaultlocale;
699     std::pair<DPL::String,
700               WrtDB::ConfigParserData::LocalizedData> defaultLocalizedData;
701     //labels
702     FOREACH(localizedData, m_context.widgetConfig.configInfo.localizedDataSet)
703     {
704         Locale i = localizedData->first;
705         DPL::OptionalString tag = getLangTag(i); // translate en -> en_US etc
706         if (tag.IsNull()) {
707             tag = i;
708         }
709         DPL::OptionalString name = localizedData->second.name;
710         generateWidgetName(manifest, uiApp, tag, name, defaultNameSaved);
711
712         //store default locale localized data
713         if (!!defaultLocale && defaultLocale == i) {
714             defaultLocalizedData = *localizedData;
715         }
716     }
717
718     if (!!defaultLocale && !defaultNameSaved) {
719         DPL::OptionalString name = defaultLocalizedData.second.name;
720         generateWidgetName(manifest,
721                            uiApp,
722                            DPL::OptionalString::Null,
723                            name,
724                            defaultNameSaved);
725     }
726 }
727
728 void TaskManifestFile::setWidgetIds(Manifest & manifest,
729                                     UiApplication & uiApp,
730                                     const std::string &postfix)
731 {
732     //appid
733     TizenAppId appid = m_context.widgetConfig.tzAppid;
734     if (!postfix.empty()) {
735         appid = DPL::FromUTF8String(DPL::ToUTF8String(appid).append(postfix));
736     }
737     uiApp.setAppid(appid);
738
739     //extraid
740     if (!!m_context.widgetConfig.guid) {
741         uiApp.setExtraid(*m_context.widgetConfig.guid);
742     } else {
743         if (!appid.empty()) {
744             uiApp.setExtraid(DPL::String(L"http://") + appid);
745         }
746     }
747
748     //type
749     uiApp.setType(DPL::FromASCIIString("webapp"));
750     manifest.setType(L"wgt");
751 }
752
753 void TaskManifestFile::generateWidgetName(Manifest & manifest,
754                                           UiApplication &uiApp,
755                                           const DPL::OptionalString& tag,
756                                           DPL::OptionalString name,
757                                           bool & defaultNameSaved)
758 {
759     if (!!name) {
760         if (!!tag) {
761             DPL::String locale =
762                 LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
763
764             if (!locale.empty()) {
765                 uiApp.addLabel(LabelType(*name, *tag));
766             } else {
767                 uiApp.addLabel(LabelType(*name));
768                 manifest.addLabel(LabelType(*name));
769             }
770         } else {
771             defaultNameSaved = true;
772             uiApp.addLabel(LabelType(*name));
773             manifest.addLabel(LabelType(*name));
774         }
775     }
776 }
777
778 void TaskManifestFile::setWidgetIcons(UiApplication & uiApp)
779 {
780     //TODO this file will need to be updated when user locale preferences
781     //changes.
782     bool defaultIconSaved = false;
783
784     DPL::OptionalString defaultLocale =
785         m_context.widgetConfig.configInfo.defaultlocale;
786
787     std::vector<Locale> generatedLocales;
788     WrtDB::WidgetRegisterInfo::LocalizedIconList & icons =
789         m_context.widgetConfig.localizationData.icons;
790
791     //reversed: last <icon> has highest priority to be writen to manifest if it
792     // has given locale (TODO: why was that working that way?)
793     for (WrtDB::WidgetRegisterInfo::LocalizedIconList::const_reverse_iterator
794          icon = icons.rbegin();
795          icon != icons.rend();
796          ++icon)
797     {
798         FOREACH(locale, icon->availableLocales)
799         {
800             if (std::find(generatedLocales.begin(), generatedLocales.end(),
801                           *locale) != generatedLocales.end())
802             {
803                 LogDebug("Skipping - has that locale - already in manifest");
804                 continue;
805             } else {
806                 generatedLocales.push_back(*locale);
807             }
808
809             DPL::OptionalString tag = getLangTag(*locale); // translate en ->
810                                                            // en_US etc
811             if (tag.IsNull()) {
812                 tag = *locale;
813             }
814
815             generateWidgetIcon(uiApp, tag, *locale, defaultIconSaved);
816         }
817     }
818     if (!!defaultLocale && !defaultIconSaved) {
819         generateWidgetIcon(uiApp, DPL::OptionalString::Null,
820                            DPL::String(),
821                            defaultIconSaved);
822     }
823 }
824
825 void TaskManifestFile::generateWidgetIcon(UiApplication & uiApp,
826                                           const DPL::OptionalString& tag,
827                                           const DPL::String& language,
828                                           bool & defaultIconSaved)
829 {
830     DPL::String locale;
831     if (!!tag) {
832         locale = LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
833     } else {
834         defaultIconSaved = true;
835     }
836
837     DPL::String iconText;
838     iconText += getIconTargetFilename(language);
839
840     if (!locale.empty()) {
841         uiApp.addIcon(IconType(iconText, locale));
842     } else {
843         uiApp.addIcon(IconType(iconText));
844     }
845     std::ostringstream iconPath;
846     iconPath << GlobalConfig::GetUserWidgetDesktopIconPath() << "/";
847     iconPath << getIconTargetFilename(locale);
848      m_context.job->SendProgressIconPath(iconPath.str());
849 }
850
851 void TaskManifestFile::setWidgetManifest(Manifest & manifest)
852 {
853     manifest.setPackage(m_context.widgetConfig.tzPkgid);
854
855     if (!!m_context.widgetConfig.version) {
856         manifest.setVersion(*m_context.widgetConfig.version);
857     }
858     DPL::String email = (!!m_context.widgetConfig.configInfo.authorEmail ?
859                          *m_context.widgetConfig.configInfo.authorEmail : L"");
860     DPL::String href = (!!m_context.widgetConfig.configInfo.authorHref ?
861                         *m_context.widgetConfig.configInfo.authorHref : L"");
862     DPL::String name = (!!m_context.widgetConfig.configInfo.authorName ?
863                         *m_context.widgetConfig.configInfo.authorName : L"");
864     manifest.addAuthor(Author(email, href, L"", name));
865 }
866
867 void TaskManifestFile::setWidgetOtherInfo(UiApplication & uiApp)
868 {
869     FOREACH(it, m_context.widgetConfig.configInfo.settingsList)
870     {
871         if (!strcmp(DPL::ToUTF8String(it->m_name).c_str(), ST_NODISPLAY)) {
872             if (!strcmp(DPL::ToUTF8String(it->m_value).c_str(), ST_TRUE)) {
873                 uiApp.setNodisplay(true);
874                 uiApp.setTaskmanage(false);
875             } else {
876                 uiApp.setNodisplay(false);
877                 uiApp.setTaskmanage(true);
878             }
879         }
880     }
881     //TODO
882     //There is no "X-TIZEN-PackageType=wgt"
883     //There is no X-TIZEN-PackageID in manifest "X-TIZEN-PackageID=" <<
884     // DPL::ToUTF8String(*widgetID).c_str()
885     //There is no Comment in pkgmgr "Comment=Widget application"
886     //that were in desktop file
887 }
888
889 void TaskManifestFile::setAppServicesInfo(UiApplication & uiApp)
890 {
891     WrtDB::ConfigParserData::ServiceInfoList appServiceList =
892         m_context.widgetConfig.configInfo.appServiceList;
893
894     if (appServiceList.empty()) {
895         LogInfo("Widget doesn't contain application service");
896         return;
897     }
898
899     // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
900     FOREACH(it, appServiceList) {
901         setAppServiceInfo(uiApp, *it);
902      }
903  }
904
905 void TaskManifestFile::setAppControlsInfo(UiApplication & uiApp)
906 {
907     WrtDB::ConfigParserData::AppControlInfoList appControlList =
908         m_context.widgetConfig.configInfo.appControlList;
909
910     if (appControlList.empty()) {
911         LogInfo("Widget doesn't contain app control");
912         return;
913     }
914
915      // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
916     FOREACH(it, appControlList) {
917         setAppControlInfo(uiApp, *it);
918     }
919 }
920
921 void TaskManifestFile::setAppServiceInfo(UiApplication & uiApp,
922                                          const ConfigParserData::ServiceInfo & service)
923 {
924     AppControl appControl;
925     if (!service.m_operation.empty()) {
926         appControl.addOperation(service.m_operation); //TODO: encapsulation?
927     }
928     if (!service.m_scheme.empty()) {
929         appControl.addUri(service.m_scheme);
930     }
931     if (!service.m_mime.empty()) {
932         appControl.addMime(service.m_mime);
933     }
934     uiApp.addAppControl(appControl);
935 }
936
937 void TaskManifestFile::setAppControlInfo(UiApplication & uiApp,
938                                          const WrtDB::ConfigParserData::AppControlInfo & service)
939 {
940     // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
941     AppControl appControl;
942     if (!service.m_operation.empty()) {
943         appControl.addOperation(service.m_operation); //TODO: encapsulation?
944     }
945     if (!service.m_uriList.empty()) {
946         FOREACH(uri, service.m_uriList) {
947             appControl.addUri(*uri);
948         }
949     }
950     if (!service.m_mimeList.empty()) {
951         FOREACH(mime, service.m_mimeList) {
952             appControl.addMime(*mime);
953         }
954     }
955     uiApp.addAppControl(appControl);
956 }
957
958 void TaskManifestFile::setAppCategory(UiApplication &uiApp)
959 {
960     WrtDB::ConfigParserData::CategoryList categoryList =
961         m_context.widgetConfig.configInfo.categoryList;
962
963     if (categoryList.empty()) {
964         LogInfo("Widget doesn't contain application category");
965         return;
966     }
967     FOREACH(it, categoryList) {
968         if (!(*it).empty()) {
969             uiApp.addAppCategory(*it);
970         }
971     }
972 }
973
974 void TaskManifestFile::stepAbortParseManifest()
975 {
976     LogError("[Parse Manifest] Abroting....");
977
978     int code = pkgmgr_parser_parse_manifest_for_uninstallation(
979             DPL::ToUTF8String(manifest_file).c_str(), NULL);
980
981     if (0 != code) {
982         LogWarning("Manifest parser error: " << code);
983         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
984     }
985     int ret = unlink(DPL::ToUTF8String(manifest_file).c_str());
986     if (0 != ret) {
987         LogWarning("No manifest file found: " << manifest_file);
988     }
989 }
990
991 void TaskManifestFile::setLiveBoxInfo(Manifest& manifest)
992 {
993     FOREACH(it, m_context.widgetConfig.configInfo.m_livebox) {
994         LogInfo("setLiveBoxInfo");
995         LiveBoxInfo liveBox;
996         DPL::Optional<WrtDB::ConfigParserData::LiveboxInfo> ConfigInfo = *it;
997         DPL::String appid = m_context.widgetConfig.tzAppid;
998
999         if (ConfigInfo->m_liveboxId != L"") {
1000             size_t found = ConfigInfo->m_liveboxId.find_last_of(L".");
1001             if (found != std::string::npos) {
1002                 if (0 == ConfigInfo->m_liveboxId.compare(0, found, appid)) {
1003                     liveBox.setLiveboxId(ConfigInfo->m_liveboxId);
1004                 } else {
1005                     DPL::String liveboxId =
1006                         appid + DPL::String(L".") + ConfigInfo->m_liveboxId;
1007                     liveBox.setLiveboxId(liveboxId);
1008                 }
1009             } else {
1010                 DPL::String liveboxId =
1011                     appid + DPL::String(L".") + ConfigInfo->m_liveboxId;
1012                 liveBox.setLiveboxId(liveboxId);
1013             }
1014         }
1015
1016         if (ConfigInfo->m_primary != L"") {
1017             liveBox.setPrimary(ConfigInfo->m_primary);
1018         }
1019
1020         if (ConfigInfo->m_updatePeriod != L"") {
1021             liveBox.setUpdatePeriod(ConfigInfo->m_updatePeriod);
1022         }
1023
1024         if (ConfigInfo->m_label != L"") {
1025             liveBox.setLabel(ConfigInfo->m_label);
1026         }
1027
1028         DPL::String defaultLocale
1029             = DPL::FromUTF8String(
1030                     m_context.locations->getPackageInstallationDir())
1031                 + DPL::String(L"/res/wgt/");
1032
1033         if (ConfigInfo->m_icon != L"") {
1034             liveBox.setIcon(defaultLocale + ConfigInfo->m_icon);
1035         }
1036
1037         if (ConfigInfo->m_boxInfo.m_boxSrc.empty() ||
1038             ConfigInfo->m_boxInfo.m_boxSize.empty())
1039         {
1040             LogInfo("Widget doesn't contain box");
1041             return;
1042         } else {
1043             BoxInfoType box;
1044             if (!ConfigInfo->m_boxInfo.m_boxSrc.empty()) {
1045                 if ((0 == ConfigInfo->m_boxInfo.m_boxSrc.compare(0, 4, L"http"))
1046                     || (0 ==
1047                         ConfigInfo->m_boxInfo.m_boxSrc.compare(0, 5, L"https")))
1048                 {
1049                     box.boxSrc = ConfigInfo->m_boxInfo.m_boxSrc;
1050                 } else {
1051                     box.boxSrc = defaultLocale + ConfigInfo->m_boxInfo.m_boxSrc;
1052                 }
1053             }
1054
1055             if (ConfigInfo->m_boxInfo.m_boxMouseEvent == L"true") {
1056                 box.boxMouseEvent = ConfigInfo->m_boxInfo.m_boxMouseEvent;
1057             } else {
1058                 box.boxMouseEvent = L"false";
1059             }
1060
1061             if (ConfigInfo->m_boxInfo.m_boxTouchEffect == L"true") {
1062                 box.boxTouchEffect = ConfigInfo->m_boxInfo.m_boxTouchEffect;
1063             } else {
1064                 box.boxTouchEffect= L"false";
1065             }
1066
1067             std::list<std::pair<DPL::String, DPL::String> > BoxSizeList
1068                 = ConfigInfo->m_boxInfo.m_boxSize;
1069             FOREACH(im, BoxSizeList) {
1070                 std::pair<DPL::String, DPL::String> boxSize = *im;
1071                 if (!boxSize.second.empty()) {
1072                     boxSize.second = defaultLocale + boxSize.second;
1073                 }
1074                 box.boxSize.push_back(boxSize);
1075             }
1076
1077             if (!ConfigInfo->m_boxInfo.m_pdSrc.empty()
1078                 && !ConfigInfo->m_boxInfo.m_pdWidth.empty()
1079                 && !ConfigInfo->m_boxInfo.m_pdHeight.empty())
1080             {
1081                 if ((0 == ConfigInfo->m_boxInfo.m_pdSrc.compare(0, 4, L"http"))
1082                     || (0 == ConfigInfo->m_boxInfo.m_pdSrc.compare(0, 5, L"https")))
1083                 {
1084                     box.pdSrc = ConfigInfo->m_boxInfo.m_pdSrc;
1085                 } else {
1086                     box.pdSrc = defaultLocale + ConfigInfo->m_boxInfo.m_pdSrc;
1087                 }
1088                 box.pdWidth = ConfigInfo->m_boxInfo.m_pdWidth;
1089                 box.pdHeight = ConfigInfo->m_boxInfo.m_pdHeight;
1090             }
1091             liveBox.setBox(box);
1092         }
1093         manifest.addLivebox(liveBox);
1094     }
1095 }
1096
1097 void TaskManifestFile::setAccount(Manifest& manifest)
1098 {
1099     WrtDB::ConfigParserData::AccountProvider account =
1100         m_context.widgetConfig.configInfo.accountProvider;
1101
1102     AccountProviderType provider;
1103
1104     if (account.m_iconSet.empty()) {
1105         LogInfo("Widget doesn't contain Account");
1106         return;
1107     }
1108     if (account.m_multiAccountSupport) {
1109         provider.multiAccount = L"ture";
1110     } else {
1111         provider.multiAccount = L"false";
1112     }
1113     provider.appid = m_context.widgetConfig.tzAppid;
1114
1115     FOREACH(it, account.m_iconSet) {
1116         std::pair<DPL::String, DPL::String> icon;
1117
1118         if (it->first == ConfigParserData::IconSectionType::DefaultIcon) {
1119             icon.first = L"account";
1120         } else if (it->first == ConfigParserData::IconSectionType::SmallIcon) {
1121             icon.first = L"account-small";
1122         }
1123         icon.second = it->second;
1124
1125         provider.icon.push_back(icon);
1126     }
1127
1128     FOREACH(it, account.m_displayNameSet) {
1129         provider.name.push_back(LabelType(it->second, it->first));
1130     }
1131
1132     FOREACH(it, account.m_capabilityList) {
1133         provider.capability.push_back(*it);
1134     }
1135
1136     Account accountInfo;
1137     accountInfo.addAccountProvider(provider);
1138     manifest.addAccount(accountInfo);
1139 }
1140
1141 void TaskManifestFile::setPrivilege(Manifest& manifest)
1142 {
1143     WrtDB::ConfigParserData::PrivilegeList privileges =
1144         m_context.widgetConfig.configInfo.privilegeList;
1145
1146     PrivilegeType privilege;
1147
1148     FOREACH(it, privileges)
1149     {
1150         privilege.addPrivilegeName(it->name);
1151     }
1152
1153     manifest.addPrivileges(privilege);
1154 }
1155
1156 } //namespace WidgetInstall
1157 } //namespace Jobs