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