[Release] wrt-installer_0.1.29
[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::backupIconFiles()
403 {
404     LogInfo("Backup Icon Files");
405
406     std::ostringstream b_icon_dir;
407     b_icon_dir << backup_dir.str() << "icons";
408
409     LogDebug("Create icon backup folder : " << b_icon_dir.str());
410     WrtUtilMakeDir(b_icon_dir.str());
411
412     std::list<std::string> fileList;
413     getFileList(GlobalConfig::GetUserWidgetDesktopIconPath(), fileList);
414     std::string appid = DPL::ToUTF8String(m_context.widgetConfig.tzAppid);
415
416     FOREACH(it, fileList)
417     {
418         if (0 == (strncmp((*it).c_str(), appid.c_str(),
419                           strlen(appid.c_str()))))
420         {
421             std::ostringstream icon_file, backup_icon;
422             icon_file << GlobalConfig::GetUserWidgetDesktopIconPath();
423             icon_file << "/" << (*it);
424
425             backup_icon << b_icon_dir.str() << "/" << (*it);
426
427             LogDebug("Backup icon file " << icon_file.str() << " to " <<
428                      backup_icon.str());
429             Try
430             {
431                 DPL::FileInput input(icon_file.str());
432                 DPL::FileOutput output(backup_icon.str());
433                 DPL::Copy(&input, &output);
434             }
435             Catch(DPL::FileInput::Exception::Base)
436             {
437                 LogError("Backup Desktop File Failed.");
438                 ReThrowMsg(Exceptions::BackupFailed, icon_file.str());
439             }
440
441             Catch(DPL::FileOutput::Exception::Base)
442             {
443                 LogError("Backup Desktop File Failed.");
444                 ReThrowMsg(Exceptions::BackupFailed, backup_icon.str());
445             }
446             Catch(DPL::CopyFailed)
447             {
448                 LogError("Backup Desktop File Failed.");
449                 ReThrowMsg(Exceptions::BackupFailed, backup_icon.str());
450             }
451             unlink((*it).c_str());
452         }
453     }
454 }
455
456 void TaskManifestFile::getFileList(const char* path,
457                                    std::list<std::string> &list)
458 {
459     DIR* dir = opendir(path);
460     if (!dir) {
461         LogError("icon directory doesn't exist");
462         ThrowMsg(Exceptions::FileOperationFailed, path);
463     }
464
465     struct dirent entry;
466     struct dirent *result;
467     int return_code;
468     errno = 0;
469     for (return_code = readdir_r(dir, &entry, &result);
470             result != NULL && return_code == 0;
471             return_code = readdir_r(dir, &entry, &result))
472     {
473         if (strcmp(entry.d_name, ".") == 0 ||
474             strcmp(entry.d_name, "..") == 0)
475         {
476             continue;
477         }
478         std::string file_name = entry.d_name;
479         list.push_back(file_name);
480     }
481
482     if (return_code != 0 || errno != 0) {
483         LogError("readdir_r() failed with " << DPL::GetErrnoString());
484     }
485
486     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
487         LogError("Failed to close dir: " << path << " with error: "
488                                          << DPL::GetErrnoString());
489     }
490 }
491
492 void TaskManifestFile::stepGenerateManifest()
493 {
494     TizenPkgId pkgid = m_context.widgetConfig.tzPkgid;
495     manifest_name = pkgid + L".xml";
496     manifest_file += L"/tmp/" + manifest_name;
497
498     //libxml - init and check
499     LibxmlSingleton::Instance().init();
500
501     writeManifest(manifest_file);
502
503     m_context.job->UpdateProgress(
504         InstallerContext::INSTALL_CREATE_MANIFEST,
505         "Widget Manifest Creation Finished");
506 }
507
508 void TaskManifestFile::stepParseManifest()
509 {
510     int code = pkgmgr_parser_parse_manifest_for_installation(
511             DPL::ToUTF8String(manifest_file).c_str(), NULL);
512
513     if (code != 0) {
514         LogError("Manifest parser error: " << code);
515         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
516     }
517
518     m_context.job->UpdateProgress(
519         InstallerContext::INSTALL_CREATE_MANIFEST,
520         "Widget Manifest Parsing Finished");
521     LogDebug("Manifest parsed");
522 }
523
524 void TaskManifestFile::stepParseUpgradedManifest()
525 {
526     int code = pkgmgr_parser_parse_manifest_for_upgrade(
527             DPL::ToUTF8String(manifest_file).c_str(), NULL);
528
529     if (code != 0) {
530         LogError("Manifest parser error: " << code);
531         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
532     }
533
534     m_context.job->UpdateProgress(
535         InstallerContext::INSTALL_CREATE_MANIFEST,
536         "Widget Manifest Parsing Finished");
537     LogDebug("Manifest parsed");
538 }
539
540 void TaskManifestFile::commitManifest()
541 {
542     LogDebug("Commiting manifest file : " << manifest_file);
543
544     std::ostringstream destFile;
545     destFile << "/opt/share/packages" << "/"; //TODO constant with path
546     destFile << DPL::ToUTF8String(manifest_name);
547     LogInfo("cp " << manifest_file << " " << destFile.str());
548
549     DPL::FileInput input(DPL::ToUTF8String(manifest_file));
550     DPL::FileOutput output(destFile.str());
551     DPL::Copy(&input, &output);
552     LogDebug("Manifest writen to: " << destFile.str());
553
554     //removing temp file
555     unlink((DPL::ToUTF8String(manifest_file)).c_str());
556     manifest_file = DPL::FromUTF8String(destFile.str().c_str());
557 }
558
559 void TaskManifestFile::writeManifest(const DPL::String & path)
560 {
561     LogDebug("Generating manifest file : " << path);
562     Manifest manifest;
563     UiApplication uiApp;
564
565     //default widget content
566     setWidgetExecPath(uiApp);
567     setWidgetName(manifest, uiApp);
568     setWidgetIds(manifest, uiApp);
569     setWidgetIcons(uiApp);
570     setWidgetManifest(manifest);
571     setWidgetOtherInfo(uiApp);
572 #ifndef MULTIPROCESS_SERVICE_SUPPORT
573     setAppServicesInfo(uiApp);
574     setAppControlsInfo(uiApp);
575 #endif
576     setAppCategory(uiApp);
577     setLiveBoxInfo(manifest);
578     setAccount(manifest);
579     setPrivilege(manifest);
580
581     manifest.addUiApplication(uiApp);
582 #ifdef MULTIPROCESS_SERVICE_SUPPORT
583     //services AppControl tag
584     ConfigParserData::AppControlInfoList appControlList =
585         m_context.widgetConfig.configInfo.appControlList;
586     unsigned count = 0;
587
588     FOREACH(it, appControlList) {
589         it->m_index = count;
590         UiApplication uiApp;
591
592         uiApp.setTaskmanage(true);
593         uiApp.setNodisplay(true);
594 #ifdef MULTIPROCESS_SERVICE_SUPPORT_INLINE
595         uiApp.setTaskmanage(ConfigParserData::AppControlInfo::Disposition::INLINE != it->m_disposition);
596         uiApp.setMultiple(ConfigParserData::AppControlInfo::Disposition::INLINE == it->m_disposition);
597 #endif
598         std::stringstream postfix;
599         postfix << "-__SERVICE_PROCESS__" << count++;
600
601         setWidgetExecPath(uiApp, postfix.str());
602         setWidgetName(manifest, uiApp);
603         setWidgetIds(manifest, uiApp, postfix.str());
604         setWidgetIcons(uiApp);
605         setAppControlInfo(uiApp, *it);
606         setAppCategory(uiApp);
607         setAccount(manifest);
608         setPrivilege(manifest);
609
610         manifest.addUiApplication(uiApp);
611     }
612     //TODO: AppService tag will be removed
613     //services AppService tag
614     WrtDB::ConfigParserData::ServiceInfoList appServiceList =
615         m_context.widgetConfig.configInfo.appServiceList;
616     FOREACH(it, appServiceList) {
617         it->m_index = count;
618         UiApplication uiApp;
619
620         uiApp.setTaskmanage(true);
621         uiApp.setNodisplay(true);
622 #ifdef MULTIPROCESS_SERVICE_SUPPORT_INLINE
623         uiApp.setTaskmanage(ConfigParserData::ServiceInfo::Disposition::INLINE != it->m_disposition);
624         uiApp.setMultiple(ConfigParserData::ServiceInfo::Disposition::INLINE == it->m_disposition);
625 #endif
626
627         std::stringstream postfix;
628         postfix << "-__SERVICE_PROCESS__" << count++;
629
630         setWidgetExecPath(uiApp, postfix.str());
631         setWidgetName(manifest, uiApp);
632         setWidgetIds(manifest, uiApp, postfix.str());
633         setWidgetIcons(uiApp);
634         setAppServiceInfo(uiApp, *it);
635         setAppCategory(uiApp);
636         setAccount(manifest);
637         setPrivilege(manifest);
638
639         manifest.addUiApplication(uiApp);
640     }
641 #endif
642     manifest.generate(path);
643     LogDebug("Manifest file serialized");
644 }
645
646 void TaskManifestFile::setWidgetExecPath(UiApplication & uiApp,
647                                          const std::string &postfix)
648 {
649     std::string exec = m_context.locations->getExecFile();
650     if (!postfix.empty()) {
651         exec.append(postfix);
652     }
653     LogDebug("exec = " << exec);
654     uiApp.setExec(DPL::FromASCIIString(exec));
655 }
656
657 void TaskManifestFile::setWidgetName(Manifest & manifest,
658                                      UiApplication & uiApp)
659 {
660     bool defaultNameSaved = false;
661
662     DPL::OptionalString defaultLocale =
663         m_context.widgetConfig.configInfo.defaultlocale;
664     std::pair<DPL::String,
665               WrtDB::ConfigParserData::LocalizedData> defaultLocalizedData;
666     //labels
667     FOREACH(localizedData, m_context.widgetConfig.configInfo.localizedDataSet)
668     {
669         Locale i = localizedData->first;
670         DPL::OptionalString tag = getLangTag(i); // translate en -> en_US etc
671         if (tag.IsNull()) {
672             tag = i;
673         }
674         DPL::OptionalString name = localizedData->second.name;
675         generateWidgetName(manifest, uiApp, tag, name, defaultNameSaved);
676
677         //store default locale localized data
678         if (!!defaultLocale && defaultLocale == i) {
679             defaultLocalizedData = *localizedData;
680         }
681     }
682
683     if (!!defaultLocale && !defaultNameSaved) {
684         DPL::OptionalString name = defaultLocalizedData.second.name;
685         generateWidgetName(manifest,
686                            uiApp,
687                            DPL::OptionalString::Null,
688                            name,
689                            defaultNameSaved);
690     }
691 }
692
693 void TaskManifestFile::setWidgetIds(Manifest & manifest,
694                                     UiApplication & uiApp,
695                                     const std::string &postfix)
696 {
697     //appid
698     TizenAppId appid = m_context.widgetConfig.tzAppid;
699     if (!postfix.empty()) {
700         appid = DPL::FromUTF8String(DPL::ToUTF8String(appid).append(postfix));
701     }
702     uiApp.setAppid(appid);
703
704     //extraid
705     if (!!m_context.widgetConfig.guid) {
706         uiApp.setExtraid(*m_context.widgetConfig.guid);
707     } else {
708         if (!appid.empty()) {
709             uiApp.setExtraid(DPL::String(L"http://") + appid);
710         }
711     }
712
713     //type
714     uiApp.setType(DPL::FromASCIIString("webapp"));
715     manifest.setType(L"wgt");
716 }
717
718 void TaskManifestFile::generateWidgetName(Manifest & manifest,
719                                           UiApplication &uiApp,
720                                           const DPL::OptionalString& tag,
721                                           DPL::OptionalString name,
722                                           bool & defaultNameSaved)
723 {
724     if (!!name) {
725         if (!!tag) {
726             DPL::String locale =
727                 LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
728
729             if (!locale.empty()) {
730                 uiApp.addLabel(LabelType(*name, *tag));
731             } else {
732                 uiApp.addLabel(LabelType(*name));
733                 manifest.addLabel(LabelType(*name));
734             }
735         } else {
736             defaultNameSaved = true;
737             uiApp.addLabel(LabelType(*name));
738             manifest.addLabel(LabelType(*name));
739         }
740     }
741 }
742
743 void TaskManifestFile::setWidgetIcons(UiApplication & uiApp)
744 {
745     //TODO this file will need to be updated when user locale preferences
746     //changes.
747     bool defaultIconSaved = false;
748
749     DPL::OptionalString defaultLocale =
750         m_context.widgetConfig.configInfo.defaultlocale;
751
752     std::vector<Locale> generatedLocales;
753     WrtDB::WidgetRegisterInfo::LocalizedIconList & icons =
754         m_context.widgetConfig.localizationData.icons;
755
756     //reversed: last <icon> has highest priority to be writen to manifest if it
757     // has given locale (TODO: why was that working that way?)
758     for (WrtDB::WidgetRegisterInfo::LocalizedIconList::const_reverse_iterator
759          icon = icons.rbegin();
760          icon != icons.rend();
761          ++icon)
762     {
763         FOREACH(locale, icon->availableLocales)
764         {
765             if (std::find(generatedLocales.begin(), generatedLocales.end(),
766                           *locale) != generatedLocales.end())
767             {
768                 LogDebug("Skipping - has that locale - already in manifest");
769                 continue;
770             } else {
771                 generatedLocales.push_back(*locale);
772             }
773
774             DPL::OptionalString tag = getLangTag(*locale); // translate en ->
775                                                            // en_US etc
776             if (tag.IsNull()) {
777                 tag = *locale;
778             }
779
780             generateWidgetIcon(uiApp, tag, *locale, defaultIconSaved);
781         }
782     }
783     if (!!defaultLocale && !defaultIconSaved) {
784         generateWidgetIcon(uiApp, DPL::OptionalString::Null,
785                            DPL::String(),
786                            defaultIconSaved);
787     }
788 }
789
790 void TaskManifestFile::generateWidgetIcon(UiApplication & uiApp,
791                                           const DPL::OptionalString& tag,
792                                           const DPL::String& language,
793                                           bool & defaultIconSaved)
794 {
795     DPL::String locale;
796     if (!!tag) {
797         locale = LanguageTagsProvider::BCP47LanguageTagToLocale(*tag);
798     } else {
799         defaultIconSaved = true;
800     }
801
802     DPL::String iconText;
803     iconText += getIconTargetFilename(language);
804
805     if (!locale.empty()) {
806         uiApp.addIcon(IconType(iconText, locale));
807     } else {
808         uiApp.addIcon(IconType(iconText));
809     }
810     std::ostringstream iconPath;
811     iconPath << GlobalConfig::GetUserWidgetDesktopIconPath() << "/";
812     iconPath << getIconTargetFilename(locale);
813      m_context.job->SendProgressIconPath(iconPath.str());
814 }
815
816 void TaskManifestFile::setWidgetManifest(Manifest & manifest)
817 {
818     manifest.setPackage(m_context.widgetConfig.tzPkgid);
819
820     if (!!m_context.widgetConfig.version) {
821         manifest.setVersion(*m_context.widgetConfig.version);
822     }
823     DPL::String email = (!!m_context.widgetConfig.configInfo.authorEmail ?
824                          *m_context.widgetConfig.configInfo.authorEmail : L"");
825     DPL::String href = (!!m_context.widgetConfig.configInfo.authorHref ?
826                         *m_context.widgetConfig.configInfo.authorHref : L"");
827     DPL::String name = (!!m_context.widgetConfig.configInfo.authorName ?
828                         *m_context.widgetConfig.configInfo.authorName : L"");
829     manifest.addAuthor(Author(email, href, L"", name));
830 }
831
832 void TaskManifestFile::setWidgetOtherInfo(UiApplication & uiApp)
833 {
834     FOREACH(it, m_context.widgetConfig.configInfo.settingsList)
835     {
836         if (!strcmp(DPL::ToUTF8String(it->m_name).c_str(), ST_NODISPLAY)) {
837             if (!strcmp(DPL::ToUTF8String(it->m_value).c_str(), ST_TRUE)) {
838                 uiApp.setNodisplay(true);
839                 uiApp.setTaskmanage(false);
840             } else {
841                 uiApp.setNodisplay(false);
842                 uiApp.setTaskmanage(true);
843             }
844         }
845     }
846     //TODO
847     //There is no "X-TIZEN-PackageType=wgt"
848     //There is no X-TIZEN-PackageID in manifest "X-TIZEN-PackageID=" <<
849     // DPL::ToUTF8String(*widgetID).c_str()
850     //There is no Comment in pkgmgr "Comment=Widget application"
851     //that were in desktop file
852 }
853
854 void TaskManifestFile::setAppServicesInfo(UiApplication & uiApp)
855 {
856     WrtDB::ConfigParserData::ServiceInfoList appServiceList =
857         m_context.widgetConfig.configInfo.appServiceList;
858
859     if (appServiceList.empty()) {
860         LogInfo("Widget doesn't contain application service");
861         return;
862     }
863
864     // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
865     FOREACH(it, appServiceList) {
866         setAppServiceInfo(uiApp, *it);
867      }
868  }
869
870 void TaskManifestFile::setAppControlsInfo(UiApplication & uiApp)
871 {
872     WrtDB::ConfigParserData::AppControlInfoList appControlList =
873         m_context.widgetConfig.configInfo.appControlList;
874
875     if (appControlList.empty()) {
876         LogInfo("Widget doesn't contain app control");
877         return;
878     }
879
880      // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
881     FOREACH(it, appControlList) {
882         setAppControlInfo(uiApp, *it);
883     }
884 }
885
886 void TaskManifestFile::setAppServiceInfo(UiApplication & uiApp,
887                                          const ConfigParserData::ServiceInfo & service)
888 {
889     AppControl appControl;
890     if (!service.m_operation.empty()) {
891         appControl.addOperation(service.m_operation); //TODO: encapsulation?
892     }
893     if (!service.m_scheme.empty()) {
894         appControl.addUri(service.m_scheme);
895     }
896     if (!service.m_mime.empty()) {
897         appControl.addMime(service.m_mime);
898     }
899     uiApp.addAppControl(appControl);
900 }
901
902 void TaskManifestFile::setAppControlInfo(UiApplication & uiApp,
903                                          const WrtDB::ConfigParserData::AppControlInfo & service)
904 {
905     // x-tizen-svc=http://tizen.org/appcontrol/operation/pick|NULL|image;
906     AppControl appControl;
907     if (!service.m_operation.empty()) {
908         appControl.addOperation(service.m_operation); //TODO: encapsulation?
909     }
910     if (!service.m_uriList.empty()) {
911         FOREACH(uri, service.m_uriList) {
912             appControl.addUri(*uri);
913         }
914     }
915     if (!service.m_mimeList.empty()) {
916         FOREACH(mime, service.m_mimeList) {
917             appControl.addMime(*mime);
918         }
919     }
920     uiApp.addAppControl(appControl);
921 }
922
923 void TaskManifestFile::setAppCategory(UiApplication &uiApp)
924 {
925     WrtDB::ConfigParserData::CategoryList categoryList =
926         m_context.widgetConfig.configInfo.categoryList;
927
928     if (categoryList.empty()) {
929         LogInfo("Widget doesn't contain application category");
930         return;
931     }
932     FOREACH(it, categoryList) {
933         if (!(*it).empty()) {
934             uiApp.addAppCategory(*it);
935         }
936     }
937 }
938
939 void TaskManifestFile::stepAbortParseManifest()
940 {
941     LogError("[Parse Manifest] Abroting....");
942
943     int code = pkgmgr_parser_parse_manifest_for_uninstallation(
944             DPL::ToUTF8String(manifest_file).c_str(), NULL);
945
946     if (0 != code) {
947         LogWarning("Manifest parser error: " << code);
948         ThrowMsg(Exceptions::ManifestInvalid, "Parser returncode: " << code);
949     }
950     int ret = unlink(DPL::ToUTF8String(manifest_file).c_str());
951     if (0 != ret) {
952         LogWarning("No manifest file found: " << manifest_file);
953     }
954 }
955
956 void TaskManifestFile::setLiveBoxInfo(Manifest& manifest)
957 {
958     FOREACH(it, m_context.widgetConfig.configInfo.m_livebox) {
959         LogInfo("setLiveBoxInfo");
960         LiveBoxInfo liveBox;
961         DPL::Optional<WrtDB::ConfigParserData::LiveboxInfo> ConfigInfo = *it;
962         DPL::String appid = m_context.widgetConfig.tzAppid;
963
964         if (ConfigInfo->m_liveboxId != L"") {
965             size_t found = ConfigInfo->m_liveboxId.find_last_of(L".");
966             if (found != std::string::npos) {
967                 if (0 == ConfigInfo->m_liveboxId.compare(0, found, appid)) {
968                     liveBox.setLiveboxId(ConfigInfo->m_liveboxId);
969                 } else {
970                     DPL::String liveboxId =
971                         appid + DPL::String(L".") + ConfigInfo->m_liveboxId;
972                     liveBox.setLiveboxId(liveboxId);
973                 }
974             } else {
975                 DPL::String liveboxId =
976                     appid + DPL::String(L".") + ConfigInfo->m_liveboxId;
977                 liveBox.setLiveboxId(liveboxId);
978             }
979         }
980
981         if (ConfigInfo->m_primary != L"") {
982             liveBox.setPrimary(ConfigInfo->m_primary);
983         }
984
985         if (ConfigInfo->m_updatePeriod != L"") {
986             liveBox.setUpdatePeriod(ConfigInfo->m_updatePeriod);
987         }
988
989         if (ConfigInfo->m_label != L"") {
990             liveBox.setLabel(ConfigInfo->m_label);
991         }
992
993         DPL::String defaultLocale
994             = DPL::FromUTF8String(
995                     m_context.locations->getPackageInstallationDir())
996                 + DPL::String(L"/res/wgt/");
997
998         if (ConfigInfo->m_icon != L"") {
999             liveBox.setIcon(defaultLocale + ConfigInfo->m_icon);
1000         }
1001
1002         if (ConfigInfo->m_boxInfo.m_boxSrc.empty() ||
1003             ConfigInfo->m_boxInfo.m_boxSize.empty())
1004         {
1005             LogInfo("Widget doesn't contain box");
1006             return;
1007         } else {
1008             BoxInfoType box;
1009             if (!ConfigInfo->m_boxInfo.m_boxSrc.empty()) {
1010                 if ((0 == ConfigInfo->m_boxInfo.m_boxSrc.compare(0, 4, L"http"))
1011                     || (0 ==
1012                         ConfigInfo->m_boxInfo.m_boxSrc.compare(0, 5, L"https")))
1013                 {
1014                     box.boxSrc = ConfigInfo->m_boxInfo.m_boxSrc;
1015                 } else {
1016                     box.boxSrc = defaultLocale + ConfigInfo->m_boxInfo.m_boxSrc;
1017                 }
1018             }
1019
1020             if (ConfigInfo->m_boxInfo.m_boxMouseEvent == L"true") {
1021                 box.boxMouseEvent = ConfigInfo->m_boxInfo.m_boxMouseEvent;
1022             } else {
1023                 box.boxMouseEvent = L"false";
1024             }
1025
1026             if (ConfigInfo->m_boxInfo.m_boxTouchEffect == L"true") {
1027                 box.boxTouchEffect = ConfigInfo->m_boxInfo.m_boxTouchEffect;
1028             } else {
1029                 box.boxTouchEffect= L"false";
1030             }
1031
1032             std::list<std::pair<DPL::String, DPL::String> > BoxSizeList
1033                 = ConfigInfo->m_boxInfo.m_boxSize;
1034             FOREACH(im, BoxSizeList) {
1035                 std::pair<DPL::String, DPL::String> boxSize = *im;
1036                 if (!boxSize.second.empty()) {
1037                     boxSize.second = defaultLocale + boxSize.second;
1038                 }
1039                 box.boxSize.push_back(boxSize);
1040             }
1041
1042             if (!ConfigInfo->m_boxInfo.m_pdSrc.empty()
1043                 && !ConfigInfo->m_boxInfo.m_pdWidth.empty()
1044                 && !ConfigInfo->m_boxInfo.m_pdHeight.empty())
1045             {
1046                 if ((0 == ConfigInfo->m_boxInfo.m_pdSrc.compare(0, 4, L"http"))
1047                     || (0 == ConfigInfo->m_boxInfo.m_pdSrc.compare(0, 5, L"https")))
1048                 {
1049                     box.pdSrc = ConfigInfo->m_boxInfo.m_pdSrc;
1050                 } else {
1051                     box.pdSrc = defaultLocale + ConfigInfo->m_boxInfo.m_pdSrc;
1052                 }
1053                 box.pdWidth = ConfigInfo->m_boxInfo.m_pdWidth;
1054                 box.pdHeight = ConfigInfo->m_boxInfo.m_pdHeight;
1055             }
1056             liveBox.setBox(box);
1057         }
1058         manifest.addLivebox(liveBox);
1059     }
1060 }
1061
1062 void TaskManifestFile::setAccount(Manifest& manifest)
1063 {
1064     WrtDB::ConfigParserData::AccountProvider account =
1065         m_context.widgetConfig.configInfo.accountProvider;
1066
1067     AccountProviderType provider;
1068
1069     if (account.m_iconSet.empty()) {
1070         LogInfo("Widget doesn't contain Account");
1071         return;
1072     }
1073     if (account.m_multiAccountSupport) {
1074         provider.multiAccount = L"ture";
1075     } else {
1076         provider.multiAccount = L"false";
1077     }
1078     provider.appid = m_context.widgetConfig.tzAppid;
1079
1080     FOREACH(it, account.m_iconSet) {
1081         std::pair<DPL::String, DPL::String> icon;
1082
1083         if (it->first == ConfigParserData::IconSectionType::DefaultIcon) {
1084             icon.first = L"account";
1085         } else if (it->first == ConfigParserData::IconSectionType::SmallIcon) {
1086             icon.first = L"account-small";
1087         }
1088         icon.second = it->second;
1089
1090         provider.icon.push_back(icon);
1091     }
1092
1093     FOREACH(it, account.m_displayNameSet) {
1094         provider.name.push_back(LabelType(it->second, it->first));
1095     }
1096
1097     FOREACH(it, account.m_capabilityList) {
1098         provider.capability.push_back(*it);
1099     }
1100
1101     Account accountInfo;
1102     accountInfo.addAccountProvider(provider);
1103     manifest.addAccount(accountInfo);
1104 }
1105
1106 void TaskManifestFile::setPrivilege(Manifest& manifest)
1107 {
1108     WrtDB::ConfigParserData::PrivilegeList privileges =
1109         m_context.widgetConfig.configInfo.privilegeList;
1110
1111     PrivilegeType privilege;
1112
1113     FOREACH(it, privileges)
1114     {
1115         privilege.addPrivilegeName(it->name);
1116     }
1117
1118     manifest.addPrivileges(privilege);
1119 }
1120
1121 } //namespace WidgetInstall
1122 } //namespace Jobs