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