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