./ 0000755 0000156 0000165 00000000000 12702745452 011105 5 ustar jenkins jenkins ./libertine/ 0000755 0000156 0000165 00000000000 12702745452 013062 5 ustar jenkins jenkins ./libertine/ContainerConfigList.h 0000644 0000156 0000165 00000012532 12702745452 017142 0 ustar jenkins jenkins /**
* @file ContainerConfigList.h
* @brief Libertine Manager list of containers configurations
*/
/*
* Copyright 2015-2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#ifndef CONTAINER_CONTAINERCONFIGLIST_H
#define CONTAINER_CONTAINERCONFIGLIST_H
#include
#include
#include
class ContainerApps;
class ContainerArchives;
class ContainerConfig;
class LibertineConfig;
/**
* The runtime configuration of the Libertine tools.
*/
class ContainerConfigList
: public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(QString defaultContainerId
READ default_container_id
WRITE default_container_id
NOTIFY defaultContainerChanged)
public:
using ConfigList = QList;
using iterator = ConfigList::iterator;
using size_type = ConfigList::size_type;
static const QString Json_container_list;
static const QString Json_default_container;
/**
* Display roles for a container config.
*/
enum class DataRole
: int
{
ContainerId = Qt::UserRole + 1, /**< The container ID */
ContainerName, /**< The container name */
ContainerType, /**< The type of container - lxc or chroot */
DistroSeries, /**< The distro from which the container was built */
InstallStatus, /**< Current container install status */
Error /**< last role (error) */
};
public:
/**
* Constructs a default-initialized (empty) list.
*/
explicit
ContainerConfigList(QObject* parent = nullptr);
/**
* Constructs a container config list from an (in-memory) JSON string.
*/
ContainerConfigList(QJsonObject const& json_object,
QObject* parent = nullptr);
/**
* Constructs a container config list from a container config.
*/
ContainerConfigList(LibertineConfig const* config,
QObject* parent = nullptr);
/**
* Tears dow the container config list.
*/
~ContainerConfigList();
Q_INVOKABLE void
reloadContainerList();
Q_INVOKABLE QString
addNewContainer(QString const& type,
QString name);
Q_INVOKABLE void
deleteContainer();
QList *
getAppsForContainer(QString const& container_id);
Q_INVOKABLE bool
isAppInstalled(QString const& container_id,
QString const& package_name);
Q_INVOKABLE QString
getAppStatus(QString const& container_id,
QString const& package_name);
Q_INVOKABLE QString
getAppVersion(QString const& app_info);
Q_INVOKABLE bool
isValidDebianPackage(QString const& package_string);
Q_INVOKABLE QString
getDebianPackageName(QString const& package_path);
Q_INVOKABLE QString
getDownloadsLocation();
Q_INVOKABLE QStringList
getDebianPackageFiles();
QList *
getArchivesForContainer(QString const& container_id);
Q_INVOKABLE QString
getContainerType(QString const& container_id);
Q_INVOKABLE QString
getContainerDistro(QString const& container_id);
Q_INVOKABLE QString
getContainerMultiarchSupport(QString const& container_id);
Q_INVOKABLE QString
getContainerName(QString const& container_id);
Q_INVOKABLE QString
getContainerStatus(QString const& container_id);
Q_INVOKABLE QString
getHostArchitecture();
void
reloadConfigs();
QJsonObject
toJson() const;
QString const&
default_container_id() const;
void
default_container_id(QString const& container_id);
/**
* @addtogroup Standard container interface
* @{
*/
/**
* Indicates if the list of available containers is empty.
*/
Q_INVOKABLE bool
empty() const noexcept;
/**
* Gets the number of container configs in the list.
*/
size_type
size() const noexcept;
/** @} */
/**
* @addtogroup QML interface
* @{
*/
/**
* Gets the number of rows in the data model.
*/
int
rowCount(QModelIndex const& parent = QModelIndex()) const;
/**
* Gets the names of the various display roles.
*/
QHash
roleNames() const;
/**
* Gets the column data for a row by role.
*/
QVariant
data(QModelIndex const& index, int role = Qt::DisplayRole) const;
/** @} */
signals:
void
defaultContainerChanged();
void
configChanged();
private:
/**
* Generates a bis (suffix) that can be used to distinguish between otherwise
* identical container ids and names.
*/
int
generate_bis(QString const& distro_series);
void
clear_config();
void
load_config();
QString
getHostDistroCodename();
QString
getHostDistroDescription();
private:
LibertineConfig const* config_;
ConfigList configs_;
QString default_container_id_;
};
#endif /* CONTAINER_CONTAINERCONFIGLIST_H */
./libertine/libertine.h 0000644 0000156 0000165 00000003255 12702745445 015217 0 ustar jenkins jenkins /**
* @file libertine.h
* @brief Libertine app wrapper
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#ifndef LIBERTINE_LIBERTINE_H
#define LIBERTINE_LIBERTINE_H
#include
#include
#include
#include
#include
class ContainerConfigList;
class LibertineConfig;
class PasswordHelper;
class ContainerAppsList;
class ContainerArchivesList;
class Libertine
: public QGuiApplication
{
Q_OBJECT
public:
Libertine(int argc, char* argv[]);
~Libertine();
private:
void
initialize_view();
private slots:
void
reload_config(const QString& path);
private:
QString main_qml_source_file_;
QScopedPointer config_;
QFileSystemWatcher watcher_;
ContainerConfigList* containers_;
ContainerAppsList* container_apps_;
ContainerArchivesList* container_archives_;
PasswordHelper* password_helper_;
QQuickView view_;
};
#endif /* LIBERTINE_LIBERTINE_H */
./libertine/ContainerManager.h 0000644 0000156 0000165 00000011106 12702745452 016447 0 ustar jenkins jenkins /**
* @file ContainerManager.h
* @brief Threaded Libertine container manager
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#ifndef CONTAINER_CONTAINERMANAGER_H_
#define CONTAINER_CONTAINERMANAGER_H_
#include
#include
#include
#include
class ContainerManagerWorker
: public QThread
{
Q_OBJECT
Q_ENUMS(ContainerAction)
Q_PROPERTY(ContainerAction containerAction READ container_action WRITE container_action NOTIFY containerActionChanged)
Q_PROPERTY(QString containerId READ container_id WRITE container_id NOTIFY containerIdChanged)
Q_PROPERTY(QString containerType READ container_type WRITE container_type NOTIFY containerTypeChanged)
Q_PROPERTY(QString containerDistro READ container_distro WRITE container_distro NOTIFY containerDistroChanged)
Q_PROPERTY(QString containerName READ container_name WRITE container_name NOTIFY containerNameChanged)
Q_PROPERTY(bool containerMultiarch READ container_multiarch WRITE container_multiarch)
Q_PROPERTY(QString data READ data WRITE data NOTIFY dataChanged)
Q_PROPERTY(QStringList data_list READ data_list WRITE data_list NOTIFY dataListChanged)
public:
static const QString libertine_container_manager_tool;
enum class ContainerAction
: int
{
Create,
Destroy,
Install,
Remove,
Search,
Update,
Exec,
Configure
};
public:
ContainerManagerWorker();
ContainerManagerWorker(ContainerAction container_action,
QString const& container_id,
QString const& container_type);
ContainerManagerWorker(ContainerAction container_action,
QString const& container_id,
QString const& container_type,
QString const& data);
ContainerManagerWorker(ContainerAction container_action,
QString const& container_id,
QString const& container_type,
QStringList data_list);
~ContainerManagerWorker();
ContainerAction
container_action() const;
void
container_action(ContainerAction container_action);
QString const&
container_id() const;
void
container_id(QString const& container_id);
QString const&
container_type() const;
void
container_type(QString const& container_type);
QString const&
container_distro() const;
void
container_distro(QString const& container_distro);
QString const&
container_name() const;
void
container_name(QString const& container_name);
bool
container_multiarch();
void
container_multiarch(bool container_multiarch);
QString const&
data() const;
void
data(QString const& data);
QStringList
data_list();
void
data_list(QStringList data_list);
protected:
void run() Q_DECL_OVERRIDE;
private:
void createContainer(QString const& password);
void destroyContainer();
void installPackage(QString const& package_name);
void removePackage(QString const& package_name);
void searchPackageCache(QString const& search_string);
void updateContainer();
void runCommand(QString const& command_line);
void configureContainer(QStringList configure_command);
private:
ContainerAction container_action_;
QString container_id_;
QString container_type_;
QString container_distro_;
QString container_name_;
bool container_multiarch_;
QString data_;
QStringList data_list_;
signals:
void containerActionChanged();
void containerIdChanged();
void containerTypeChanged();
void containerDistroChanged();
void containerNameChanged();
void dataChanged();
void dataListChanged();
void finished();
void finishedDestroy(QString const& container_id);
void finishedInstall(bool result, QString const& error_msg);
void finishedRemove(bool result, QString const& error_msg);
void finishedSearch(bool result, QList packageList);
void finishedCommand(QString const& command_output);
void finishedConfigure(bool result, QString const& error_msg);
};
#endif /* CONTAINER_CONTAINERMANAGER_H_ */
./libertine/ContainerAppsList.cpp 0000644 0000156 0000165 00000004367 12702745452 017202 0 ustar jenkins jenkins /**
* @file ContainerAppsList.cpp
* @brief Libertine Manager list of container applications
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "libertine/ContainerAppsList.h"
#include "libertine/ContainerConfigList.h"
ContainerAppsList::
ContainerAppsList(ContainerConfigList* container_config_list,
QObject* parent)
: QAbstractListModel(parent)
, container_config_list_(container_config_list)
{ }
ContainerAppsList::
~ContainerAppsList()
{ }
void ContainerAppsList::
setContainerApps(QString const& container_id)
{
apps_ = container_config_list_->getAppsForContainer(container_id);
reloadAppsList();
}
void ContainerAppsList::
reloadAppsList()
{
beginResetModel();
endResetModel();
}
bool ContainerAppsList::
empty() const noexcept
{ return apps_->empty(); }
ContainerAppsList::size_type ContainerAppsList::
size() const noexcept
{ return apps_->count(); }
int ContainerAppsList::
rowCount(QModelIndex const&) const
{
return this->size();
}
QHash ContainerAppsList::
roleNames() const
{
QHash roles;
roles[static_cast(DataRole::PackageName)] = "packageName";
roles[static_cast(DataRole::AppStatus)] = "appStatus";
return roles;
}
QVariant ContainerAppsList::
data(QModelIndex const& index, int role) const
{
QVariant result;
if (index.isValid() && index.row() <= apps_->count())
{
switch (static_cast(role))
{
case DataRole::PackageName:
result = (*apps_)[index.row()]->package_name();
break;
case DataRole::AppStatus:
result = (*apps_)[index.row()]->app_status();
break;
case DataRole::Error:
break;
}
}
return result;
}
./libertine/main.cpp 0000644 0000156 0000165 00000001503 12702745445 014513 0 ustar jenkins jenkins /**
* @file main.cpp
* @brief Libertine app mainline driver.
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "libertine/config.h"
#include "libertine/libertine.h"
int
main(int argc, char* argv[])
{
Libertine app(argc, argv);
return app.exec();
}
./libertine/qml/ 0000755 0000156 0000165 00000000000 12702745452 013653 5 ustar jenkins jenkins ./libertine/qml/libertine.qml 0000644 0000156 0000165 00000002750 12702745445 016351 0 ustar jenkins jenkins /**
* @file libertine.qml
* @brief Libertine app main view.
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import QtQuick 2.4
import Ubuntu.Components 1.2
MainView {
id: mainView
objectName: "mainView"
applicationName: "libertine"
width: units.gu(90)
height: units.gu(75)
property var currentContainer: undefined
property var currentPackage: undefined
PageStack {
id: pageStack
}
Component.onCompleted: {
mainView.currentContainer = containerConfigList.defaultContainerId
if (mainView.currentContainer) {
containerAppsList.setContainerApps(mainView.currentContainer)
pageStack.push(Qt.resolvedUrl("HomeView.qml"))
}
else if (!containerConfigList.empty()) {
pageStack.push(Qt.resolvedUrl("ContainersView.qml"))
}
else {
pageStack.push(Qt.resolvedUrl("WelcomeView.qml"))
}
}
}
./libertine/qml/ContainerPasswordDialog.qml 0000644 0000156 0000165 00000006322 12702745452 021156 0 ustar jenkins jenkins /**
* @file ContainerPasswordDialog.qml
* @brief Libertine container password dialog
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import Libertine 1.0
import QtQuick 2.4
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
Dialog {
id: passwordDialog
title: i18n.tr("Authentication required")
text: i18n.tr("Password is required to create a Libertine container")
property var enableMultiarch: false
property var containerName: null
property var switchPage: false
Label {
id: invalidPasswordText
visible: false
text: i18n.tr("Invalid password entered")
}
TextField {
id: passwordInput
placeholderText: i18n.tr("password")
echoMode: TextInput.Password
onAccepted: okButton.clicked()
}
Row {
spacing: units.gu(1)
Button {
id: okButton
text: i18n.tr("OK")
color: UbuntuColors.green
width: (parent.width - parent.spacing) / 2
onClicked: {
if (passwordHelper.VerifyUserPassword(passwordInput.text)) {
passwordAccepted(text)
switchPage = true
PopupUtils.close(passwordDialog)
}
else {
invalidPasswordText.visible = true
}
passwordInput.text = ""
}
}
Button {
id: cancelButton
text: i18n.tr("Cancel")
color: UbuntuColors.red
width: (parent.width - parent.spacing) / 2
onClicked: PopupUtils.close(passwordDialog)
}
}
Component.onCompleted: passwordInput.forceActiveFocus()
Component.onDestruction: {
if (switchPage) {
pageStack.clear()
pageStack.push(Qt.resolvedUrl("ContainersView.qml"))
}
}
function passwordAccepted(password) {
var container_id = containerConfigList.addNewContainer("lxc", containerName)
var comp = Qt.createComponent("ContainerManager.qml")
var worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Create,
"containerId": container_id,
"containerType": null,
"data": password})
worker.containerDistro = containerConfigList.getContainerDistro(container_id)
worker.containerName = containerConfigList.getContainerName(container_id)
worker.containerMultiarch = enableMultiarch
mainView.currentContainer = container_id
worker.start()
}
}
./libertine/qml/SearchResultsView.qml 0000644 0000156 0000165 00000010042 12702745452 020005 0 ustar jenkins jenkins /**
* @file SearchResultsView.qml
* @brief Libertine search packages results view
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import Libertine 1.0
import QtQuick 2.4
import QtQuick.Layouts 1.0
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
Page {
id: searchResultsView
title: i18n.tr("Package Search Results")
objectName: "searchResultsView"
property var search_string: null
property var search_comp: null
property var search_obj: null
signal doSearch
head.actions: [
Action {
iconName: "search"
text: i18n.tr("Search")
description: i18n.tr("Search for packages")
onTriggered: doSearch()
}
]
Component {
id: noResultsPopup
Dialog {
id: noResultsDialog
title: i18n.tr("No Search Results Found")
property var returnHome: false
Button {
id: searchAgain
text: i18n.tr("Search Again")
color: UbuntuColors.green
onClicked: {
PopupUtils.close(noResultsDialog)
PopupUtils.open(Qt.resolvedUrl("SearchPackagesDialog.qml"))
}
}
Button {
id: returnToHomeView
text: i18n.tr("Return to Apps Page")
onClicked: {
noResultsDialog.returnHome = true
PopupUtils.close(noResultsDialog)
}
}
Component.onDestruction: {
if (returnHome) {
pageStack.pop()
}
}
}
}
ActivityIndicator {
id: searchActivity
visible: false
running: searchActivity.visible
anchors {
top: parent.top
topMargin: units.gu(2)
}
}
Label {
id: searchLabel
text: i18n.tr("Searching for packages…")
visible: searchActivity.running
anchors {
left: searchActivity.right
top: parent.top
leftMargin: units.gu(2)
topMargin: units.gu(2)
}
}
ListModel {
id: packageListModel
}
Component.onCompleted: {
searchForPackages(search_string)
}
function searchForPackages(search_string) {
searchActivity.visible = true
if (search_obj) {
search_obj.destroy()
}
packageListModel.clear()
var comp = Qt.createComponent("ContainerManager.qml")
var worker = comp.createObject()
worker.containerAction = ContainerManagerWorker.Search
worker.containerId = mainView.currentContainer
worker.data = search_string
worker.finishedSearch.connect(finishedSearch)
worker.start()
}
function finishedSearch(result, packageList) {
searchActivity.visible = false
if (result) {
for (var i = 0; i < packageList.length; ++i)
{
packageListModel.append({"package_desc": packageList[i], "package_name": packageList[i].split(' ')[0]})
}
if (!search_comp) {
search_comp = Qt.createComponent("SearchResults.qml")
}
search_obj = search_comp.createObject(searchResultsView, {"model": packageListModel})
}
else {
PopupUtils.open(noResultsPopup)
}
}
onDoSearch: PopupUtils.open(Qt.resolvedUrl("SearchPackagesDialog.qml"))
}
./libertine/qml/ConfigureContainer.qml 0000644 0000156 0000165 00000005622 12702745452 020157 0 ustar jenkins jenkins /**
* @file ConfigureContainer.qml
* @brief Libertine configure container view
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import Libertine 1.0
import QtQuick 2.4
import Ubuntu.Components 1.2
import Ubuntu.Components.ListItems 1.2 as ListItem
Page {
id: configureView
title: i18n.tr("Configure %1").arg(mainView.currentContainer)
Column {
anchors.left: parent.left
anchors.right: parent.right
ListItem.Standard {
visible: containerConfigList.getHostArchitecture() == 'x86_64' ? true : false
control: CheckBox {
checked: containerConfigList.getContainerMultiarchSupport(mainView.currentContainer) == 'enabled' ? true : false
onClicked: {
var comp = Qt.createComponent("ContainerManager.qml")
if (checked) {
var worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Configure,
"containerId": mainView.currentContainer,
"containerType": containerConfigList.getContainerType(mainView.currentContainer),
"data_list": ["--multiarch", "enable"]})
worker.start()
}
else {
var worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Configure,
"containerId": mainView.currentContainer,
"containerType": containerConfigList.getContainerType(mainView.currentContainer),
"data_list": ["--multiarch", "disable"]})
worker.start()
}
}
}
text: i18n.tr("i386 multiarch support")
}
ListItem.SingleValue {
text: i18n.tr("Additional archives and PPAs")
progression: true
onClicked: {
containerArchivesList.setContainerArchives(mainView.currentContainer)
pageStack.push(Qt.resolvedUrl("ExtraArchivesView.qml"))
}
}
}
}
./libertine/qml/HomeView.qml 0000644 0000156 0000165 00000020740 12702745452 016114 0 ustar jenkins jenkins /**
* @file HomeView.qml
* @brief Libertine container apps view
*/
/*
* Copyright 2015-2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import Libertine 1.0
import QtQuick 2.4
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
Page {
id: homeView
title: i18n.tr("Classic Apps - %1").arg(mainView.currentContainer)
head.actions: [
Action {
iconName: "add"
onTriggered: PopupUtils.open(addAppsMenu, homeView)
},
Action {
id: settingsButton
iconName: "settings"
onTriggered: PopupUtils.open(settingsMenu, homeView)
}
]
Component {
id: enterPackagePopup
Dialog {
id: enterPackageDialog
title: i18n.tr("Install new package")
text: i18n.tr("Enter exact package name or full path to a Debian package file")
Label {
id: appExistsWarning
wrapMode: Text.Wrap
visible: false
}
TextField {
id: enterPackageInput
placeholderText: i18n.tr("Package name or Debian package path")
onAccepted: okButton.clicked()
}
Row {
spacing: units.gu(1)
Button {
id: okButton
text: i18n.tr("OK")
color: UbuntuColors.green
width: (parent.width - parent.spacing) / 2
onClicked: {
if (enterPackageInput.text != "") {
if (!containerConfigList.isAppInstalled(mainView.currentContainer, enterPackageInput.text)) {
installPackage(enterPackageInput.text)
mainView.currentPackage = enterPackageInput.text
PopupUtils.close(enterPackageDialog)
}
else {
appExistsWarning.text = i18n.tr("The %1 package is already installed. Please try a different package name.").arg(enterPackageInput.text)
appExistsWarning.visible = true
enterPackageInput.text = ""
}
}
}
}
Button {
id: cancelButton
text: i18n.tr("Cancel")
color: UbuntuColors.red
width: (parent.width - parent.spacing) / 2
onClicked: PopupUtils.close(enterPackageDialog)
}
}
Component.onCompleted: enterPackageInput.forceActiveFocus()
}
}
Component {
id: settingsMenu
ActionSelectionPopover {
actions: ActionList {
Action {
text: i18n.tr("Configure Container")
onTriggered: {
pageStack.push(Qt.resolvedUrl("ConfigureContainer.qml"))
}
}
Action {
text: i18n.tr("Update Container")
onTriggered: {
updateContainer()
}
}
Action {
text: i18n.tr("Switch Container")
onTriggered: {
pageStack.pop()
pageStack.push(Qt.resolvedUrl("ContainersView.qml"))
}
}
}
}
}
Component {
id: addAppsMenu
ActionSelectionPopover {
id: addAppsActions
actions: ActionList {
Action {
text: i18n.tr("Enter package name or Debian file")
onTriggered: {
PopupUtils.open(enterPackagePopup)
}
}
Action {
text: i18n.tr("Choose Debian package to install")
onTriggered: {
var packages = containerConfigList.getDebianPackageFiles()
pageStack.push(Qt.resolvedUrl("DebianPackagePicker.qml"), {packageList: packages})
}
}
Action {
text: i18n.tr("Search archives for a package")
onTriggered: {
PopupUtils.open(Qt.resolvedUrl("SearchPackagesDialog.qml"))
}
}
}
}
}
Component.onCompleted: {
containerConfigList.configChanged.connect(reloadAppList)
}
Component.onDestruction: {
containerConfigList.configChanged.disconnect(reloadAppList)
}
function reloadAppList() {
containerAppsList.setContainerApps(mainView.currentContainer)
}
UbuntuListView {
anchors.fill: parent
model: containerAppsList
delegate: ListItem {
ActivityIndicator {
id: appActivity
anchors.verticalCenter: parent.verticalCenter
visible: (appStatus === i18n.tr("installing") ||
appStatus === i18n.tr("removing")) ? true : false
running: appActivity.visible
}
Label {
text: packageName
anchors {
verticalCenter: parent.verticalCenter
left: appActivity.running ? appActivity.right : parent.left
leftMargin: units.gu(2)
}
}
leadingActions: ListItemActions {
actions: [
Action {
iconName: "delete"
text: i18n.tr("delete")
description: i18n.tr("Remove Package")
onTriggered: {
mainView.currentPackage = packageName
removePackage(packageName)
pageStack.push(Qt.resolvedUrl("PackageInfoView.qml"))
}
}
]
}
trailingActions: ListItemActions {
actions: [
Action {
iconName: "info"
text: i18n.tr("info")
description: i18n.tr("Package Info")
onTriggered: {
mainView.currentPackage = packageName
pageStack.push(Qt.resolvedUrl("PackageInfoView.qml"))
}
}
]
}
}
}
function updateContainer() {
var comp = Qt.createComponent("ContainerManager.qml")
var worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Update,
"containerId": mainView.currentContainer,
"containerType": containerConfigList.getContainerType(mainView.currentContainer)})
worker.start()
}
function installPackage(package_name) {
var comp = Qt.createComponent("ContainerManager.qml")
var worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Install,
"containerId": mainView.currentContainer,
"containerType": containerConfigList.getContainerType(mainView.currentContainer),
"data": package_name})
worker.start()
}
function removePackage(packageName) {
var comp = Qt.createComponent("ContainerManager.qml")
var worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Remove,
"containerId": mainView.currentContainer,
"containerType": containerConfigList.getContainerType(mainView.currentContainer),
"data": packageName})
worker.start()
}
}
./libertine/qml/ContainersView.qml 0000644 0000156 0000165 00000010722 12702745452 017330 0 ustar jenkins jenkins /**
* @file ContainersView.qml
* @brief Libertine containers view
*/
/*
* Copyright 2015-2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import Libertine 1.0
import QtQuick 2.4
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
/**
* View providing a list of available containers and their (possibly animated)
* states.
*/
Page {
id: containersView
title: i18n.tr("My Containers")
head.actions: [
Action {
iconName: "add"
onTriggered: {
var popup = PopupUtils.open(Qt.resolvedUrl("ContainerOptionsDialog.qml"))
popup.passwordDialogSignal.connect(showPasswordDialog)
}
}
]
UbuntuListView {
anchors.fill: parent
model: containerConfigList
delegate: ListItem {
ActivityIndicator {
id: containerActivity
anchors.verticalCenter: parent.verticalCenter
visible: (installStatus === i18n.tr("installing") ||
installStatus === i18n.tr("removing")) ? true : false
running: containerActivity.visible
}
Label {
text: name
anchors {
verticalCenter: parent.verticalCenter
left: containerActivity.running ? containerActivity.right : parent.left
leftMargin: units.gu(2)
}
}
leadingActions: ListItemActions {
actions: [
Action {
iconName: "delete"
text: i18n.tr("delete")
description: i18n.tr("Delete Container")
onTriggered: {
var comp = Qt.createComponent("ContainerManager.qml")
var worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Destroy,
"containerId": containerId,
"containerType": containerConfigList.getContainerType(containerId)})
worker.start()
mainView.currentContainer = containerId
}
}
]
}
trailingActions: ListItemActions {
actions: [
Action {
iconName: "info"
text: i18n.tr("info")
description: i18n.tr("Container Info")
onTriggered: {
mainView.currentContainer = containerId
pageStack.push(Qt.resolvedUrl("ContainerInfoView.qml"))
}
},
Action {
iconName: "edit"
text: i18n.tr("edit")
description: i18n.tr("Container Apps")
onTriggered: {
mainView.currentContainer = containerId
containerAppsList.setContainerApps(mainView.currentContainer)
pageStack.pop()
pageStack.push(Qt.resolvedUrl("HomeView.qml"))
}
}
]
}
}
}
Component.onCompleted: {
containerConfigList.configChanged.connect(updateContainerList)
}
Component.onDestruction: {
containerConfigList.configChanged.disconnect(updateContainerList)
}
function updateContainerList() {
containerConfigList.reloadContainerList()
}
function showPasswordDialog(enableMultiarch, containerName) {
PopupUtils.open(Qt.resolvedUrl("ContainerPasswordDialog.qml"), null, {"enableMultiarch": enableMultiarch, "containerName": containerName})
}
}
./libertine/qml/ContainerManager.qml 0000644 0000156 0000165 00000000121 12702745445 017577 0 ustar jenkins jenkins import Libertine 1.0
import QtQuick 2.4
ContainerManagerWorker {
id: worker
}
./libertine/qml/DebianPackagePicker.qml 0000644 0000156 0000165 00000004647 12702745452 020175 0 ustar jenkins jenkins /**
* @file DebianPackagePicker.qml
* @brief Libertine container Debian package picker view
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import QtQuick 2.4
import Ubuntu.Components 1.2
Page {
id: debianPackagePicker
title: i18n.tr("Available Debian Packages to Install")
property var packageList: null
ListModel {
id: packageListModel
}
UbuntuListView {
id: listView
anchors.fill: parent
model: packageListModel
visible: packageList.length > 0 ? true : false
delegate: ListItem {
id: packageItem
Label {
text: model.file_name
anchors {
verticalCenter: parent.verticalCenter
left: parent.left
leftMargin: units.gu(2)
}
}
trailingActions: ListItemActions {
actions: [
Action {
iconName: "select"
description: i18n.tr("Install Package")
onTriggered: {
var package_path = containerConfigList.getDownloadsLocation() + "/" + model.file_name
pageStack.pop()
pageStack.currentPage.installPackage(package_path)
}
}
]
}
}
}
Label {
id: emptyLabel
anchors.centerIn: parent
visible: packageList.length == 0 ? true : false
wrapMode: Text.Wrap
width: parent.width
horizontalAlignment: Text.AlignHCenter
text: i18n.tr("No Debian packages available")
}
Component.onCompleted: {
for (var i = 0; i < packageList.length; ++i)
{
packageListModel.append({"file_name": packageList[i]})
}
}
}
./libertine/qml/PackageExistsDialog.qml 0000644 0000156 0000165 00000003037 12702745452 020244 0 ustar jenkins jenkins /**
* @file PackageExistsDialog.qml
* @brief Libertine search packages dialog
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import QtQuick 2.4
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
Dialog {
id: packageExistsDialog
property var package_name: null
property var search_again: false
title: i18n.tr("The %1 package is already installed.").arg(package_name)
text: i18n.tr("Search again or return to search results.")
Button {
id: searchAgain
text: i18n.tr("Search again")
color: UbuntuColors.green
onClicked: {
search_again = true
PopupUtils.close(packageExistsDialog)
}
}
Button {
id: returnToResults
text: i18n.tr("Return to search results")
onClicked: {
PopupUtils.close(packageExistsDialog)
}
}
Component.onDestruction: {
if (search_again) {
pageStack.currentPage.doSearch()
}
}
}
./libertine/qml/WelcomeView.qml 0000644 0000156 0000165 00000004353 12702745452 016621 0 ustar jenkins jenkins /**
* @file WelcomeView.qml
* @brief Libertine default welcome view
*/
/*
* Copyright 2015-2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import QtQuick 2.4
import QtQuick.Layouts 1.0
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
Page {
id: welcomeView
title: i18n.tr("Welcome")
ColumnLayout {
spacing: units.gu(2)
anchors {
fill: parent
margins: units.gu(4)
}
Label {
id: welcomeMessage
Layout.fillWidth: true
wrapMode: Text.Wrap
horizontalAlignment: Text.AlignHCenter
text: i18n.tr("Welcome to the Ubuntu Legacy Application Support Manager.")
}
Label {
id: warningMessage
Layout.fillWidth: true
wrapMode: Text.Wrap
horizontalAlignment: Text.AlignHCenter
text: i18n.tr("You do not have Legacy Application Support configured at this time. Downloading and setting up the required environment takes some time and network bandwidth.")
}
Button {
id: installButton
Layout.alignment: Qt.AlignCenter
Layout.maximumWidth: units.gu(12)
text: i18n.tr("Install")
color: UbuntuColors.green
onClicked: {
var popup = PopupUtils.open(Qt.resolvedUrl("ContainerOptionsDialog.qml"))
popup.passwordDialogSignal.connect(showPasswordDialog)
}
}
}
function showPasswordDialog(enableMultiarch, containerName) {
PopupUtils.open(Qt.resolvedUrl("ContainerPasswordDialog.qml"), null, {"enableMultiarch": enableMultiarch, "containerName": containerName})
}
}
./libertine/qml/SearchPackagesDialog.qml 0000644 0000156 0000165 00000004152 12702745452 020354 0 ustar jenkins jenkins /**
* @file SearchPackagesDialog.qml
* @brief Libertine search packages dialog
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import QtQuick 2.4
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
Dialog {
id: searchPackageDialog
title: i18n.tr("Search for packages")
text: i18n.tr("Search archives for packages")
TextField {
id: searchPackageInput
placeholderText: i18n.tr("search")
onAccepted: okButton.clicked()
}
Row {
spacing: units.gu(1)
Button {
id: okButton
text: i18n.tr("OK")
color: UbuntuColors.green
width: (parent.width - parent.spacing) / 2
onClicked: {
if (searchPackageInput.text != "") {
PopupUtils.close(searchPackageDialog)
if (pageStack.currentPage.objectName == "searchResultsView") {
pageStack.currentPage.searchForPackages(searchPackageInput.text)
}
else {
pageStack.push(Qt.resolvedUrl("SearchResultsView.qml"), {search_string : searchPackageInput.text})
}
}
}
}
Button {
id: cancelButton
text: i18n.tr("Cancel")
color: UbuntuColors.red
width: (parent.width - parent.spacing) / 2
onClicked: {
PopupUtils.close(searchPackageDialog)
}
}
}
Component.onCompleted: searchPackageInput.forceActiveFocus()
}
./libertine/qml/ContainerOptionsDialog.qml 0000644 0000156 0000165 00000005037 12702745452 021011 0 ustar jenkins jenkins /**
* @file ContainerOptionsDialog.qml
* @brief Libertine container options dialog
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import Libertine 1.0
import QtQuick 2.4
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
import Ubuntu.Components.ListItems 1.2 as ListItem
Dialog {
id: containerOptionsDialog
title: i18n.tr("Container Options")
text: i18n.tr("Configure options for container creation.")
property var showPasswordDialog: false
signal passwordDialogSignal(var enableMultiarch, var containerName)
Row {
spacing: units.gu(1)
CheckBox {
id: enableMultiarchCheckbox
}
Label {
id: enableMultiarchText
text: i18n.tr("i386 multiarch support")
anchors {
leftMargin: units.gu(2)
verticalCenter: enableMultiarchCheckbox.verticalCenter
}
}
}
Label {
id: containerNameText
text: i18n.tr("Enter or name for the container or leave blank for default name")
wrapMode: Text.Wrap
}
TextField {
id: containerNameInput
placeholderText: i18n.tr("container name")
onAccepted: okButton.clicked()
}
Row {
spacing: units.gu(1)
Button {
id: okButton
text: i18n.tr("OK")
color: UbuntuColors.green
width: (parent.width - parent.spacing) / 2
onClicked: {
showPasswordDialog = true
PopupUtils.close(containerOptionsDialog)
}
}
Button {
id: cancelButton
text: i18n.tr("Cancel")
color: UbuntuColors.red
width: (parent.width - parent.spacing) / 2
onClicked: PopupUtils.close(containerOptionsDialog)
}
}
Component.onDestruction: {
if (showPasswordDialog) {
passwordDialogSignal(enableMultiarchCheckbox.checked, containerNameInput.text)
}
}
}
./libertine/qml/SearchResults.qml 0000644 0000156 0000165 00000003552 12702745452 017162 0 ustar jenkins jenkins /**
* @file SearchResults.qml
* @brief Libertine search results list view component
*/
/*
* Copyright 2015-2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import QtQuick 2.4
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
UbuntuListView {
id: listView
anchors.fill: parent
delegate: ListItem {
id: packageItem
Label {
text: model.package_desc
anchors {
verticalCenter: parent.verticalCenter
left: parent.left
leftMargin: units.gu(2)
}
}
trailingActions: ListItemActions {
actions: [
Action {
iconName: "select"
description: i18n.tr("Install Package")
onTriggered: {
if (!containerConfigList.isAppInstalled(mainView.currentContainer, model.package_name)) {
pageStack.pop()
pageStack.currentPage.installPackage(model.package_name)
}
else {
PopupUtils.open(Qt.resolvedUrl("PackageExistsDialog.qml"), null, {"package_name": model.package_name})
}
}
}
]
}
}
}
./libertine/qml/ContainerApps.qml 0000644 0000156 0000165 00000001520 12702745445 017134 0 ustar jenkins jenkins /**
* @file ContainerApps.qml
* @brief Libertine container apps data source
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import QtQuick 2.4
Item {
function are_apps_installed(containerId) {
var documentIds = {}
return documentIds.length > 0
}
}
./libertine/qml/ContainerInfoView.qml 0000644 0000156 0000165 00000005545 12702745452 017770 0 ustar jenkins jenkins /**
* @file ContainerInfoView.qml
* @brief Container info view
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import Libertine 1.0
import QtQuick 2.4
import QtQuick.Layouts 1.0
import Ubuntu.Components 1.2
import Ubuntu.Components.ListItems 1.2 as ListItem
Page {
id: containerInfoView
title: i18n.tr("Container information for %1").arg(mainView.currentContainer)
property string currentContainer: mainView.currentContainer
property string containerDistroText: containerConfigList.getContainerDistro(currentContainer)
property string containerNameText: containerConfigList.getContainerName(currentContainer)
property string containerIdText: currentContainer
property var statusText: containerConfigList.getContainerStatus(currentContainer)
Flickable {
anchors.fill: parent
contentHeight: contentItem.childrenRect.height
boundsBehavior: (contentHeight > containerInfoView.height) ?
Flickable.DragAndOvershootBounds :
Flickable.StopAtBounds
flickableDirection: Flickable.VerticalFlick
Column {
anchors.left: parent.left
anchors.right: parent.right
ListItem.Standard {
text: i18n.tr("ID")
control: Label {
text: containerIdText
}
}
ListItem.Standard {
text: i18n.tr("Name")
control: Label {
text: containerNameText
}
}
ListItem.Standard {
text: i18n.tr("Distribution")
control: Label {
text: containerDistroText
}
}
ListItem.Standard {
text: i18n.tr("Status")
control: Label {
text: statusText
}
}
}
}
Component.onCompleted: {
containerConfigList.configChanged.connect(reloadStatus)
}
Component.onDestruction: {
containerConfigList.configChanged.disconnect(reloadStatus)
}
function reloadStatus() {
statusText = containerConfigList.getContainerStatus(currentContainer)
if (!statusText) {
statusText = i18n.tr("removed")
}
}
}
./libertine/qml/ExtraArchivesView.qml 0000644 0000156 0000165 00000013115 12702745445 017774 0 ustar jenkins jenkins /**
* @file ExtraArchiveView.qml
* @brief Libertine container add archive view
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import Libertine 1.0
import QtQuick 2.4
import Ubuntu.Components 1.2
import Ubuntu.Components.Popups 1.2
Page {
id: extraArchiveView
title: i18n.tr("Additional Archives and PPAs")
property var archive_name: null
property var worker: null
head.actions: [
Action {
iconName: "add"
text: i18n.tr("add")
description: i18n.tr("Add a new PPA")
onTriggered: PopupUtils.open(addArchivePopup)
}
]
Component {
id: addArchivePopup
Dialog {
id: addArchiveDialog
title: i18n.tr("Add additional PPA")
text: i18n.tr("Enter name of PPA in the form ppa:user/ppa-name:")
TextField {
id: extraArchiveString
onAccepted: {
PopupUtils.close(addArchiveDialog)
addArchive(text)
}
}
Button {
text: i18n.tr("OK")
color: UbuntuColors.green
onClicked: {
PopupUtils.close(addArchiveDialog)
addArchive(extraArchiveString.text)
}
}
Button {
text: i18n.tr("Cancel")
color: UbuntuColors.red
onClicked: PopupUtils.close(addArchiveDialog)
}
Component.onCompleted: {
extraArchiveString.forceActiveFocus()
}
}
}
UbuntuListView {
id: extraArchiveList
anchors.fill: parent
model: containerArchivesList
delegate: ListItem {
ActivityIndicator {
id: extraArchiveActivity
anchors.verticalCenter: parent.verticalCenter
visible: (archiveStatus === i18n.tr("installing") ||
archiveStatus === i18n.tr("removing")) ? true : false
running: extraArchiveActivity.visible
}
Label {
anchors {
verticalCenter: parent.verticalCenter
left: extraArchiveActivity.running ? extraArchiveActivity.right : parent.left
leftMargin: units.gu(2)
}
text: archiveName
}
leadingActions: ListItemActions {
actions: [
Action {
iconName: "delete"
text: i18n.tr("remove")
description: i18n.tr("Remove extra archive")
onTriggered: {
deleteArchive(archiveName)
}
}
]
}
}
}
function addArchive(archive) {
var comp = Qt.createComponent("ContainerManager.qml")
worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Configure,
"containerId": mainView.currentContainer,
"containerType": containerConfigList.getContainerType(mainView.currentContainer),
"data_list": ["--add-archive", archive]})
worker.finishedConfigure.connect(finishedConfigure)
worker.start()
}
function deleteArchive(archive) {
var comp = Qt.createComponent("ContainerManager.qml")
worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Configure,
"containerId": mainView.currentContainer,
"containerType": containerConfigList.getContainerType(mainView.currentContainer),
"data_list": ["--delete-archive", archive]})
worker.finishedConfigure.connect(finishedConfigure)
worker.start()
}
Component {
id: addFailedPopup
Dialog {
property var error_msg: null
id: addFailedDialog
title: i18n.tr("Adding archive failed")
text: error_msg
Button {
text: i18n.tr("Dismiss")
onClicked: PopupUtils.close(addFailedDialog)
}
}
}
Component.onCompleted: {
containerConfigList.configChanged.connect(reloadArchives)
}
Component.onDestruction: {
containerConfigList.configChanged.disconnect(reloadArchives)
if (worker) {
worker.finishedConfigure.disconnect(finishedConfigure)
}
}
function reloadArchives() {
containerArchivesList.setContainerArchives(mainView.currentContainer)
}
function finishedConfigure(result, error_msg) {
if (result) {
containerArchivesList.setContainerArchives(mainView.currentContainer)
}
else {
PopupUtils.open(addFailedPopup, null, {'error_msg': error_msg})
}
}
}
./libertine/qml/PackageInfoView.qml 0000644 0000156 0000165 00000010462 12702745452 017373 0 ustar jenkins jenkins /**
* @file PackageInfoView.qml
* @brief Container package info view
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
import Libertine 1.0
import QtQuick 2.4
import QtQuick.Layouts 1.0
import Ubuntu.Components 1.2
import Ubuntu.Components.ListItems 1.2 as ListItem
Page {
id: packageInfoView
title: i18n.tr("Information for the %1 package").arg(mainView.currentPackage)
property string currentContainer: mainView.currentContainer
property var currentPackage: mainView.currentPackage
property var statusText: containerConfigList.getAppStatus(currentContainer, currentPackage)
property var failureReasonText: ""
property var packageVersionText: i18n.tr("Obtaining package version…")
property var worker: null
property var install_signal: null
Flickable {
anchors.fill: parent
contentHeight: contentItem.childrenRect.height
boundsBehavior: (contentHeight > packageInfoView.height) ?
Flickable.DragAndOvershootBounds :
Flickable.StopAtBounds
flickableDirection: Flickable.VerticalFlick
Column {
anchors.left: parent.left
anchors.right: parent.right
ListItem.Standard {
text: i18n.tr("Package version")
control: Label {
text: packageVersionText
}
}
ListItem.Standard {
text: i18n.tr("Install status")
control: Label {
text: statusText
}
}
ListItem.Standard {
id: failureReason
text: i18n.tr("Failure reason")
visible: false
control: Label {
text: failureReasonText
wrapMode: Text.Wrap
width: parent.parent.width/2
horizontalAlignment: Qt.AlignRight
onHeightChanged: updateFailureReasonHeight()
}
}
}
}
Component.onCompleted: {
if (install_signal) {
install_signal.connect(installFinished)
}
containerConfigList.configChanged.connect(reloadStatus)
var command = "apt-cache policy " + currentPackage
var comp = Qt.createComponent("ContainerManager.qml")
worker = comp.createObject(mainView, {"containerAction": ContainerManagerWorker.Exec,
"containerId": mainView.currentContainer,
"containerType": containerConfigList.getContainerType(mainView.currentContainer),
"data": command })
worker.finishedCommand.connect(getPackageVersion)
worker.start()
}
Component.onDestruction: {
containerConfigList.configChanged.disconnect(reloadStatus)
worker.finishedCommand.disconnect(getPackageVersion)
if (install_signal) {
install_signal.disconnect(installFinished)
}
}
function updateFailureReasonHeight() {
failureReason.height = Math.max(failureReason.control.height + 10, 48)
}
function reloadStatus() {
statusText = containerConfigList.getAppStatus(currentContainer, currentPackage)
if (!statusText) {
statusText = i18n.tr("removed")
}
}
function getPackageVersion(command_output) {
packageVersionText = containerConfigList.getAppVersion(command_output)
}
function installFinished(success, error_msg) {
if (!success) {
statusText = i18n.tr("failed")
failureReasonText = error_msg
failureReason.visible = true
}
install_signal.disconnect(installFinished)
}
}
./libertine/ContainerManager.cpp 0000644 0000156 0000165 00000022303 12702745452 017003 0 ustar jenkins jenkins /**
* @file ContainerManager.cpp
* @brief Threaded Libertine container manager
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "libertine/ContainerManager.h"
#include
const QString ContainerManagerWorker::libertine_container_manager_tool = "libertine-container-manager";
ContainerManagerWorker::
ContainerManagerWorker()
{ }
ContainerManagerWorker::
ContainerManagerWorker(ContainerAction container_action,
QString const& container_id,
QString const& container_type)
: container_action_(container_action)
, container_id_(container_id)
, container_type_(container_type)
{ }
ContainerManagerWorker::
ContainerManagerWorker(ContainerAction container_action,
QString const& container_id,
QString const& container_type,
QString const& data)
: container_action_(container_action)
, container_id_(container_id)
, container_type_(container_type)
, data_(data)
{ }
ContainerManagerWorker::
ContainerManagerWorker(ContainerAction container_action,
QString const& container_id,
QString const& container_type,
QStringList data_list)
: container_action_(container_action)
, container_id_(container_id)
, container_type_(container_type)
, data_list_(data_list)
{ }
ContainerManagerWorker::
~ContainerManagerWorker()
{ }
ContainerManagerWorker::ContainerAction ContainerManagerWorker::
container_action() const
{ return container_action_; }
void ContainerManagerWorker::
container_action(ContainerAction container_action)
{
container_action_ = container_action;
}
QString const& ContainerManagerWorker::
container_id() const
{ return container_id_; }
void ContainerManagerWorker::
container_id(QString const& container_id)
{
container_id_ = container_id;
}
QString const& ContainerManagerWorker::
container_type() const
{ return container_type_; }
void ContainerManagerWorker::
container_type(QString const& container_type)
{
container_type_ = container_type;
}
QString const& ContainerManagerWorker::
container_distro() const
{ return container_distro_; }
void ContainerManagerWorker::
container_distro(QString const& container_distro)
{
if (container_distro != container_distro_)
{
container_distro_ = container_distro;
}
}
QString const& ContainerManagerWorker::
container_name() const
{ return container_name_; }
void ContainerManagerWorker::
container_name(QString const& container_name)
{
if (container_name != container_name_)
{
container_name_ = container_name;
}
}
bool ContainerManagerWorker::
container_multiarch()
{ return container_multiarch_; }
void ContainerManagerWorker::
container_multiarch(bool container_multiarch)
{
if (container_multiarch != container_multiarch_)
{
container_multiarch_ = container_multiarch;
}
}
QString const& ContainerManagerWorker::
data() const
{ return data_; }
void ContainerManagerWorker::
data(QString const& data)
{
data_ = data;
}
QStringList ContainerManagerWorker::
data_list()
{ return data_list_; }
void ContainerManagerWorker::
data_list(QStringList data_list)
{
data_list_ = data_list;
}
void ContainerManagerWorker::
run()
{
switch(container_action_)
{
case ContainerAction::Create:
createContainer(data_);
break;
case ContainerAction::Destroy:
destroyContainer();
break;
case ContainerAction::Install:
installPackage(data_);
break;
case ContainerAction::Remove:
removePackage(data_);
break;
case ContainerAction::Search:
searchPackageCache(data_);
break;
case ContainerAction::Update:
updateContainer();
break;
case ContainerAction::Exec:
runCommand(data_);
break;
case ContainerAction::Configure:
configureContainer(data_list_);
break;
default:
break;
}
}
void ContainerManagerWorker::
createContainer(QString const& password)
{
QProcess libertine_cli_tool;
QString exec_line = libertine_container_manager_tool;
QStringList args;
args << "create" << "-i" << container_id_ << "-d" << container_distro_ << "-n" << container_name_;
if (container_multiarch_)
args << "-m";
libertine_cli_tool.start(exec_line, args);
if (!libertine_cli_tool.waitForStarted())
quit();
libertine_cli_tool.write(password.toStdString().c_str());
libertine_cli_tool.closeWriteChannel();
libertine_cli_tool.waitForFinished(-1);
emit finished();
quit();
}
void ContainerManagerWorker::
destroyContainer()
{
QProcess libertine_cli_tool;
QString exec_line = libertine_container_manager_tool;
QStringList args;
args << "destroy" << "-i" << container_id_;
libertine_cli_tool.start(exec_line, args);
if (!libertine_cli_tool.waitForStarted())
quit();
libertine_cli_tool.waitForFinished(-1);
emit finishedDestroy(container_id_);
emit finished();
quit();
}
void ContainerManagerWorker::
installPackage(QString const& package_name)
{
QByteArray error_msg;
bool result = true;
QProcess libertine_cli_tool;
QString exec_line = libertine_container_manager_tool;
QStringList args;
args << "install-package" << "-i" << container_id_ << "-p" << package_name;
libertine_cli_tool.start(exec_line, args);
if (!libertine_cli_tool.waitForStarted())
quit();
libertine_cli_tool.waitForFinished(-1);
if (libertine_cli_tool.exitCode() != 0)
{
error_msg = libertine_cli_tool.readAllStandardError();
result = false;
}
emit finishedInstall(result, QString(error_msg));
emit finished();
quit();
}
void ContainerManagerWorker::
removePackage(QString const& package_name)
{
QByteArray error_msg;
bool result = true;
QProcess libertine_cli_tool;
QString exec_line = libertine_container_manager_tool;
QStringList args;
args << "remove-package" << "-i" << container_id_ << "-p" << package_name;
libertine_cli_tool.start(exec_line, args);
if (!libertine_cli_tool.waitForStarted())
quit();
libertine_cli_tool.waitForFinished(-1);
if (libertine_cli_tool.exitCode() != 0)
{
error_msg = libertine_cli_tool.readAllStandardError();
result = false;
}
emit finishedRemove(result, QString(error_msg));
emit finished();
quit();
}
void ContainerManagerWorker::
searchPackageCache(QString const& search_string)
{
QProcess libertine_cli_tool;
QString exec_line = libertine_container_manager_tool;
QStringList args;
QByteArray search_output;
QList packageList;
bool result = true;
args << "search-cache" << "-i" << container_id_ << "-s" << search_string;
libertine_cli_tool.start(exec_line, args);
if (!libertine_cli_tool.waitForStarted())
quit();
libertine_cli_tool.waitForFinished(-1);
search_output = libertine_cli_tool.readAllStandardOutput();
if (search_output.isEmpty())
{
result = false;
}
else
{
QList packages = search_output.split('\n');
foreach (const QByteArray &package, packages)
{
packageList.append(QString(package));
}
}
emit finishedSearch(result, packageList);
emit finished();
quit();
}
void ContainerManagerWorker::
updateContainer()
{
QProcess libertine_cli_tool;
QString exec_line = libertine_container_manager_tool;
QStringList args;
args << "update" << "-i" << container_id_;
libertine_cli_tool.start(exec_line, args);
if (!libertine_cli_tool.waitForStarted())
quit();
libertine_cli_tool.waitForFinished(-1);
emit finished();
quit();
}
void ContainerManagerWorker::
runCommand(QString const& command_line)
{
QProcess libertine_cli_tool;
QString exec_line = libertine_container_manager_tool;
QStringList args;
QByteArray command_output;
args << "exec" << "-i" << container_id_ << "-c" << command_line;
libertine_cli_tool.start(exec_line, args);
if (!libertine_cli_tool.waitForStarted())
quit();
libertine_cli_tool.waitForFinished(-1);
command_output = libertine_cli_tool.readAllStandardOutput();
emit finishedCommand(QString(command_output));
quit();
}
void ContainerManagerWorker::
configureContainer(QStringList configure_command)
{
QByteArray error_msg;
bool result = true;
QProcess libertine_cli_tool;
QString exec_line = libertine_container_manager_tool;
QStringList args;
args << "configure" << "-i" << container_id_ << configure_command.at(0) << configure_command.mid(1);
libertine_cli_tool.start(exec_line, args);
if (!libertine_cli_tool.waitForStarted())
quit();
libertine_cli_tool.waitForFinished(-1);
if (libertine_cli_tool.exitCode() != 0)
{
error_msg = libertine_cli_tool.readAllStandardOutput();
result = false;
}
emit finishedConfigure(result, QString(error_msg));
emit finished();
quit();
}
./libertine/config.h.in 0000644 0000156 0000165 00000001547 12702745445 015116 0 ustar jenkins jenkins /**
* @file config.h.in
* @brief Libertine app configuraiton file.
*
* This file is a template used to generate the actual config.h file.
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#define LIBERTINE_APPLICATION_NAME "@PROJECT_NAME@"
#define LIBERTINE_VERSION "@PROJECT_VERSION@"
./libertine/LibertineConfig.h 0000644 0000156 0000165 00000002135 12702745445 016301 0 ustar jenkins jenkins /**
* @file LibertineConfig.cpp
* @brief Libertine Manager application-wide configuration module
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#ifndef LIBERTINE_LIBERTINECONFIG_H
#define LIBERTINE_LIBERTINECONFIG_H
#include
class Libertine;
/**
* The runtime configuration of the Libertine tools.
*/
class LibertineConfig
{
public:
LibertineConfig(Libertine const& libertine);
LibertineConfig();
~LibertineConfig();
QString
containers_config_file_name() const;
};
#endif /* LIBERTINE_LIBERTINECONFIG_H */
./libertine/PasswordHelper.cpp 0000644 0000156 0000165 00000004620 12702745445 016534 0 ustar jenkins jenkins /**
* @file PasswordHelper.cpp
* @brief Helper class for managing password entry
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "libertine/PasswordHelper.h"
#include
#include
#include
using namespace std;
namespace
{
struct pam_response *reply;
int function_conversation(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
{
*resp = reply;
return PAM_SUCCESS;
}
void set_stdin_echo(bool enable = true)
{
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
if (!enable)
tty.c_lflag &= ~ECHO;
else
tty.c_lflag |= ECHO;
(void) tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
} // anonymous namespace
PasswordHelper::
PasswordHelper()
{
}
PasswordHelper::
~PasswordHelper()
{
}
QString PasswordHelper::
GetPassword()
{
string password;
cout << "Please enter your password:" << endl;
set_stdin_echo(false);
getline(cin, password);
set_stdin_echo(true);
if (cin.fail() || cin.eof())
{
return nullptr;
}
else
{
return QString::fromStdString(password);
}
}
bool PasswordHelper::
VerifyUserPassword(QString const& password)
{
char *username = getenv("USER");
int retval;
const struct pam_conv local_conversation = { function_conversation, NULL };
pam_handle_t *local_auth_handle = NULL;
retval = pam_start("common_auth", username, &local_conversation, &local_auth_handle);
if (retval != PAM_SUCCESS)
{
return false;
}
reply = (struct pam_response *)malloc(sizeof(struct pam_response));
reply[0].resp = strdup(password.toStdString().c_str());
reply[0].resp_retcode = 0;
retval = pam_authenticate(local_auth_handle, 0);
if (retval != PAM_SUCCESS)
{
return false;
}
retval = pam_end(local_auth_handle, retval);
if (retval != PAM_SUCCESS)
{
return false;
}
return true;
}
./libertine/libertine.cpp 0000644 0000156 0000165 00000010727 12702745445 015554 0 ustar jenkins jenkins /**
* @file libertine.cpp
* @brief Libertine app wrapper
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "libertine/config.h"
#include
#include "libertine/ContainerManager.h"
#include "libertine/ContainerAppsList.h"
#include "libertine/ContainerArchivesList.h"
#include "libertine/ContainerConfig.h"
#include "libertine/ContainerConfigList.h"
#include "libertine/libertine.h"
#include "libertine/LibertineConfig.h"
#include "libertine/PasswordHelper.h"
#include
#include
#include
#include
#include
#include
#include
#include
namespace
{
static QString const s_main_QML_source_file = "qml/libertine.qml";
/**
* Searches for the main QML source file.
*
* The actual QML sources could be in any of a number of places depending on if
* the program was invoked from within the developer's source tree, a DEB, a
* click, a clack, a snap or a snood. Gotta check 'em all, in some semblance
* of a priority order in which the developer's source tree is highest priority
* and the system installation places are lowest.
*
* @returns the source file path or an empty string if no source file was found.
*/
static QString
find_main_qml_source_file()
{
static const QStringList sub_paths = { "", "libertine/" };
QStringList paths = QStandardPaths::standardLocations(QStandardPaths::DataLocation);
paths.prepend(QDir::currentPath());
paths.prepend(QCoreApplication::applicationDirPath());
for (auto const& path: paths)
{
for (auto const& sub: sub_paths)
{
QFileInfo fi(path + "/" + sub + s_main_QML_source_file);
if (fi.exists())
{
return fi.filePath();
}
}
}
return QString();
}
} // anonymous namespace
/**
* Constraucts a Libertine application wrapper object.
* @param[in] argc The count of the number of command-line arguments.
* @param[in] argv A vector of command-line arguments.
*
* Sets up the Libertine application from the command-line arguments,
* environment variables, and configurations files and displays the GUI.
*/
Libertine::
Libertine(int argc, char* argv[])
: QGuiApplication(argc, argv)
, main_qml_source_file_(find_main_qml_source_file())
{
setApplicationName(LIBERTINE_APPLICATION_NAME);
setApplicationVersion(LIBERTINE_VERSION);
config_.reset(new LibertineConfig(*this));
qmlRegisterType("Libertine", 1, 0, "ContainerConfig");
qmlRegisterType("Libertine", 1, 0, "ContainerManagerWorker");
qmlRegisterType("Libertine", 1, 0, "PasswordHelper");
watcher_.addPath(config_.data()->containers_config_file_name());
connect(&watcher_, SIGNAL(fileChanged(QString)), SLOT(reload_config(QString)));
if (main_qml_source_file_.isEmpty())
{
qWarning() << "Can not locate " << s_main_QML_source_file;
}
containers_ = new ContainerConfigList(config_.data(), this);
container_apps_ = new ContainerAppsList(containers_, this);
container_archives_ = new ContainerArchivesList(containers_, this);
password_helper_ = new PasswordHelper();
initialize_view();
view_.show();
}
/**
* Tears down the Libertine application wrapper object.
*/
Libertine::
~Libertine()
{
}
/**
* Initializes the main QML view.
*/
void Libertine::
initialize_view()
{
view_.setResizeMode(QQuickView::SizeRootObjectToView);
QQmlContext* ctxt = view_.rootContext();
ctxt->setContextProperty("containerConfigList", containers_);
ctxt->setContextProperty("containerAppsList", container_apps_);
ctxt->setContextProperty("containerArchivesList", container_archives_);
ctxt->setContextProperty("passwordHelper", password_helper_);
view_.setSource(QUrl::fromLocalFile(main_qml_source_file_));
connect(view_.engine(), SIGNAL(quit()), SLOT(quit()));
}
void Libertine::
reload_config(const QString& path)
{
Q_UNUSED(path)
containers_->reloadConfigs();
}
./libertine/ContainerConfig.cpp 0000644 0000156 0000165 00000031472 12702745445 016647 0 ustar jenkins jenkins /**
* @file ContainerConfig.cpp
* @brief Libertine Manager containers configuration module
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "libertine/ContainerConfig.h"
#include
#include
#include
#include
#include
namespace {
/**
* Extracts the container id from a JSON object.
*
* The container id must exist and be non-empty.
*/
QString
extract_container_id_from_json(QJsonObject const& json_object)
{
QJsonValue value = json_object["id"];
if (value == QJsonValue::Undefined)
{
throw std::runtime_error("container id not found in JSON object");
}
QJsonValue::Type value_type = value.type();
if (value_type != QJsonValue::String)
{
throw std::runtime_error("container id not valid type in JSON object");
}
QString id = value.toString();
if (id.length() == 0)
{
throw std::runtime_error("container id empty in JSON object");
}
return id;
}
QString
extract_container_name_from_json(QJsonObject const& json_object,
QString const& container_id)
{
QString name = container_id;
QJsonValue value = json_object["name"];
if (value != QJsonValue::Undefined)
{
QJsonValue::Type value_type = value.type();
if (value_type == QJsonValue::String)
{
QString s = value.toString();
if (s.length() > 0)
{
name = s;
}
}
}
return name;
}
QString
extract_container_type_from_json(QJsonObject const& json_object,
QString const& container_id)
{
QString type = container_id;
QJsonValue value = json_object["type"];
if (value != QJsonValue::Undefined)
{
QJsonValue::Type value_type = value.type();
if (value_type == QJsonValue::String)
{
QString s = value.toString();
if (s.length() > 0)
{
type = s;
}
}
}
return type;
}
QString
extract_distro_series_from_json(QJsonObject const& json_object,
QString const& container_id)
{
QString distro_series = container_id;
QJsonValue value = json_object["distro"];
if (value != QJsonValue::Undefined)
{
QJsonValue::Type value_type = value.type();
if (value_type == QJsonValue::String)
{
QString s = value.toString();
if (s.length() > 0)
{
distro_series = s;
}
}
}
return distro_series;
}
QString
extract_multiarch_support_from_json(QJsonObject const& json_object)
{
QString multiarch_support("disabled");
QJsonValue value = json_object["multiarch"];
if (value != QJsonValue::Undefined)
{
QJsonValue::Type value_type = value.type();
if (value_type == QJsonValue::String)
{
QString s = value.toString();
if (s.length() > 0)
{
multiarch_support = s;
}
}
}
return multiarch_support;
}
const static struct { QString string; ContainerConfig::InstallStatus enumeration; } install_status_names[] =
{
{ QObject::tr("new"), ContainerConfig::InstallStatus::New },
{ QObject::tr("installing"), ContainerConfig::InstallStatus::Installing },
{ QObject::tr("ready"), ContainerConfig::InstallStatus::Ready },
{ QObject::tr("removing"), ContainerConfig::InstallStatus::Removing },
{ QObject::tr("removed"), ContainerConfig::InstallStatus::Removed },
{ QObject::tr("failed"), ContainerConfig::InstallStatus::Failed },
{ QString(), ContainerConfig::InstallStatus::New }
};
ContainerConfig::InstallStatus
extract_install_status_from_json(QJsonObject const& json_object)
{
QJsonValue value = json_object["installStatus"];
if (value != QJsonValue::Undefined)
{
QJsonValue::Type value_type = value.type();
if (value_type == QJsonValue::String)
{
QString s = value.toString();
if (s.length() > 0)
{
for (auto const& name: install_status_names)
{
if (0 == s.compare(name.string, Qt::CaseInsensitive))
{
return name.enumeration;
}
}
}
}
}
return ContainerConfig::InstallStatus::New;
}
const static struct { QString string; CurrentStatus enumeration; } status_names[] =
{
{ QObject::tr("new"), CurrentStatus::New },
{ QObject::tr("installing"), CurrentStatus::Installing },
{ QObject::tr("installed"), CurrentStatus::Installed },
{ QObject::tr("failed"), CurrentStatus::Failed },
{ QObject::tr("removing"), CurrentStatus::Removing },
{ QObject::tr("removed"), CurrentStatus::Removed },
{ QString(), CurrentStatus::New }
};
QString
extract_package_name_from_json(QJsonObject const& json_object)
{
QString package_name;
QJsonValue value = json_object["packageName"];
if (value != QJsonValue::Undefined)
{
QJsonValue::Type value_type = value.type();
if (value_type == QJsonValue::String)
{
package_name = value.toString();
}
}
return package_name;
}
CurrentStatus
extract_app_status_from_json(QJsonObject const& json_object)
{
CurrentStatus app_status = CurrentStatus::New;
QJsonValue value = json_object["appStatus"];
if (value != QJsonValue::Undefined)
{
QJsonValue::Type value_type = value.type();
if (value_type == QJsonValue::String)
{
QString s = value.toString();
if (s.length() > 0)
{
for (auto const& name: status_names)
{
if (0 == s.compare(name.string, Qt::CaseInsensitive))
{
app_status = name.enumeration;
break;
}
}
}
}
}
return app_status;
}
QList
extract_container_apps_from_json(QJsonObject const& json_object)
{
QList container_apps;
QString package_name;
CurrentStatus app_status;
QJsonArray installed_apps = json_object["installedApps"].toArray();
for (auto const& app: installed_apps)
{
package_name = extract_package_name_from_json(app.toObject());
app_status = extract_app_status_from_json(app.toObject());
container_apps.append(new ContainerApps(package_name, app_status));
}
return container_apps;
}
QString
extract_archive_name_from_json(QJsonObject const& json_object)
{
QString archive_name;
QJsonValue value = json_object["archiveName"];
if (value != QJsonValue::Undefined)
{
QJsonValue::Type value_type = value.type();
if (value_type == QJsonValue::String)
{
archive_name = value.toString();
}
}
return archive_name;
}
CurrentStatus
extract_archive_status_from_json(QJsonObject const& json_object)
{
CurrentStatus archive_status = CurrentStatus::New;
QJsonValue value = json_object["archiveStatus"];
if (value != QJsonValue::Undefined)
{
QJsonValue::Type value_type = value.type();
if (value_type == QJsonValue::String)
{
QString s = value.toString();
if (s.length() > 0)
{
for (auto const& name: status_names)
{
if (0 == s.compare(name.string, Qt::CaseInsensitive))
{
archive_status = name.enumeration;
break;
}
}
}
}
}
return archive_status;
}
QList
extract_container_archives_from_json(QJsonObject const& json_object)
{
QList container_archives;
QString archive_name;
CurrentStatus archive_status;
QJsonArray extra_archives = json_object["extraArchives"].toArray();
for (auto const& archive: extra_archives)
{
archive_name = extract_archive_name_from_json(archive.toObject());
archive_status = extract_archive_status_from_json(archive.toObject());
container_archives.append(new ContainerArchives(archive_name, archive_status));
}
return container_archives;
}
} // anonymous namespace
ContainerApps::
ContainerApps(QString const& package_name,
CurrentStatus app_status,
QObject* parent)
: QObject(parent)
, package_name_(package_name)
, app_status_(app_status)
{ }
ContainerApps::
~ContainerApps()
{ }
QString const& ContainerApps::
package_name() const
{ return package_name_; }
QString const& ContainerApps::
app_status() const
{ return status_names[(int)app_status_].string; }
ContainerArchives::
ContainerArchives(QString const& archive_name,
CurrentStatus archive_status,
QObject* parent)
: QObject(parent)
, archive_name_(archive_name)
, archive_status_(archive_status)
{ }
ContainerArchives::
~ContainerArchives()
{ }
QString const& ContainerArchives::
archive_name() const
{ return archive_name_; }
QString const& ContainerArchives::
archive_status() const
{ return status_names[(int)archive_status_].string; }
ContainerConfig::
ContainerConfig(QObject* parent)
: QObject(parent)
{ }
ContainerConfig::
ContainerConfig(QString const& container_id,
QString const& container_name,
QString const& container_type,
QString const& distro_series,
QObject* parent)
: QObject(parent)
, container_id_(container_id)
, container_name_(container_name)
, container_type_(container_type)
, distro_series_(distro_series)
, install_status_(InstallStatus::New)
{ }
ContainerConfig::
ContainerConfig(QJsonObject const& json_object,
QObject* parent)
: QObject(parent)
, container_id_(extract_container_id_from_json(json_object))
, container_name_(extract_container_name_from_json(json_object, container_id_))
, container_type_(extract_container_type_from_json(json_object, container_id_))
, distro_series_(extract_distro_series_from_json(json_object, container_id_))
, multiarch_support_(extract_multiarch_support_from_json(json_object))
, install_status_(extract_install_status_from_json(json_object))
, container_apps_(extract_container_apps_from_json(json_object))
, container_archives_(extract_container_archives_from_json(json_object))
{ }
ContainerConfig::
~ContainerConfig()
{ }
QString const& ContainerConfig::
container_id() const
{ return container_id_; }
QString const& ContainerConfig::
name() const
{ return container_name_; }
void ContainerConfig::
name(QString const& name)
{
container_name_ = name;
emit nameChanged();
}
QString const& ContainerConfig::
container_type() const
{ return container_type_; }
QString const& ContainerConfig::
distro_series() const
{ return distro_series_; }
QString const& ContainerConfig::
multiarch_support() const
{ return multiarch_support_; }
QString const& ContainerConfig::
install_status() const
{ return install_status_names[(int)install_status_].string; }
void ContainerConfig::
install_status(InstallStatus install_status)
{
install_status_ = install_status;
emit installStatusChanged();
}
QList & ContainerConfig::
container_apps()
{ return container_apps_; }
QList & ContainerConfig::
container_archives()
{ return container_archives_; }
QJsonObject ContainerConfig::
toJson() const
{
QJsonObject json_object,
app_object,
archive_object;
QJsonArray apps,
archives;
json_object["id"] = container_id_;
json_object["name"] = container_name_;
json_object["type"] = container_type_;
json_object["distro"] = distro_series_;
for (auto const& name: install_status_names)
{
if (install_status_ == name.enumeration)
{
json_object["installStatus"] = name.string;
break;
}
}
for (auto const& container_app: container_apps_)
{
app_object["packageName"] = container_app->package_name();
app_object["appStatus"] = status_names[0].string;
apps.append(app_object);
}
json_object["installedApps"] = apps;
for (auto const& container_archive: container_archives_)
{
archive_object["archiveName"] = container_archive->archive_name();
archives.append(archive_object);
}
json_object["extraArchives"] = archives;
return json_object;
}
./libertine/ContainerConfig.h 0000644 0000156 0000165 00000006747 12702745445 016323 0 ustar jenkins jenkins /**
* @file ContainerConfig.h
* @brief Libertine Manager containers configuration module
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#ifndef CONTAINER_CONTAINERCONFIG_H
#define CONTAINER_CONTAINERCONFIG_H
#include
#include
#include
enum class CurrentStatus { New, Installing, Installed, Failed, Removing, Removed };
class ContainerApps
: public QObject
{
Q_OBJECT
public:
ContainerApps(QString const& package_name,
CurrentStatus app_status,
QObject* parent = nullptr);
~ContainerApps();
QString const&
package_name() const;
QString const&
app_status() const;
private:
QString package_name_;
CurrentStatus app_status_;
};
class ContainerArchives
: public QObject
{
Q_OBJECT
public:
ContainerArchives(QString const& archive_name,
CurrentStatus archive_status,
QObject* parent = nullptr);
~ContainerArchives();
QString const&
archive_name() const;
QString const&
archive_status() const;
private:
QString archive_name_;
CurrentStatus archive_status_;
};
/**
* The runtime configuration of the Libertine tools.
*/
class ContainerConfig
: public QObject
{
Q_OBJECT
Q_ENUMS(InstallStatus)
Q_PROPERTY(QString containerId READ container_id)
Q_PROPERTY(QString name READ name WRITE name NOTIFY nameChanged)
Q_PROPERTY(QString distroSeries READ distro_series)
public:
/** The container's current install state. */
enum class InstallStatus
{ New, Installing, Ready, Removing, Removed, Failed };
public:
ContainerConfig(QObject* parent = nullptr);
ContainerConfig(QString const& container_id,
QString const& container_name,
QString const& container_type,
QString const& distro_series,
QObject* parent = nullptr);
ContainerConfig(QJsonObject const& json_object,
QObject* parent = nullptr);
~ContainerConfig();
QString const&
container_id() const;
QString const&
name() const;
void
name(QString const& name);
QString const&
container_type() const;
QString const&
distro_series() const;
QString const&
multiarch_support() const;
QString const&
install_status() const;
void
install_status(InstallStatus install_status);
QList &
container_apps();
QList &
container_archives();
QJsonObject
toJson() const;
signals:
void nameChanged();
void installStatusChanged();
private:
QString container_id_;
QString container_name_;
QString container_type_;
QString distro_series_;
QString multiarch_support_;
InstallStatus install_status_;
QList container_apps_;
QList container_archives_;
};
#endif /* CONTAINER_CONTAINERCONFIG_H */
./libertine/PasswordHelper.h 0000644 0000156 0000165 00000002142 12702745445 016176 0 ustar jenkins jenkins /**
* @file PasswordHelper.h
* @brief Helper class for managing password entry
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#ifndef LIBERTINE_PASSWORD_HELPER_H_
#define LIBERTINE_PASSWORD_HELPER_H_
#include
#include
#include
#include
class PasswordHelper
: public QObject
{
Q_OBJECT
public:
PasswordHelper();
~PasswordHelper();
QString
GetPassword();
Q_INVOKABLE bool
VerifyUserPassword(QString const& password);
};
#endif /* LIBERTINE_PASSWORD_HELPER_H_ */
./libertine/CMakeLists.txt 0000644 0000156 0000165 00000000657 12702745445 015634 0 ustar jenkins jenkins configure_file(config.h.in config.h)
file(GLOB_RECURSE QML_SRC *.qml *.js *.json)
set(libertine_SRC
libertine.cpp
main.cpp
${QML_SRC}
)
add_executable(libertine ${libertine_SRC})
target_link_libraries(libertine libertine-common Qt5::Core Qt5::Quick Qt5::Gui)
install(DIRECTORY qml DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${CMAKE_PROJECT_NAME})
install(TARGETS libertine RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
./libertine/ContainerConfigList.cpp 0000644 0000156 0000165 00000026503 12702745452 017500 0 ustar jenkins jenkins /**
* @file ContainerConfigList.cpp
* @brief Libertine Manager list of containers configurations
*/
/*
* Copyright 2015-2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "libertine/ContainerManager.h"
#include "libertine/ContainerConfigList.h"
#include "libertine/LibertineConfig.h"
#include
#include "libertine/ContainerConfig.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
const QString ContainerConfigList::Json_container_list = "containerList";
const QString ContainerConfigList::Json_default_container = "defaultContainer";
ContainerConfigList::
ContainerConfigList(QObject* parent)
: QAbstractListModel(parent)
{ }
ContainerConfigList::
ContainerConfigList(QJsonObject const& json_object,
QObject* parent)
: QAbstractListModel(parent)
{
if (!json_object.empty())
{
default_container_id_ = json_object[Json_default_container].toString();
QJsonArray container_list = json_object[Json_container_list].toArray();
for (auto const& config: container_list)
{
QJsonObject containerConfig = config.toObject();
configs_.append(new ContainerConfig(containerConfig, this));
}
}
}
ContainerConfigList::
ContainerConfigList(LibertineConfig const* config,
QObject* parent)
: QAbstractListModel(parent)
, config_(config)
{
load_config();
}
ContainerConfigList::
~ContainerConfigList()
{ }
void ContainerConfigList::
reloadContainerList()
{
beginResetModel();
endResetModel();
}
QString ContainerConfigList::
addNewContainer(QString const& type, QString name)
{
QString distro_series = getHostDistroCodename();
QString container_id = distro_series;
int bis = generate_bis(container_id);
if (bis > 0)
{
container_id = QString("%1-%2").arg(container_id).arg(bis);
if (name.isEmpty())
{
name = getHostDistroDescription();
name = QString("%1 (%2)").arg(name).arg(bis);
}
}
configs_.append(new ContainerConfig(container_id, name, type, distro_series, this));
if (this->size() == 1)
default_container_id_ = container_id;
return container_id;
}
void ContainerConfigList::
deleteContainer()
{
beginResetModel();
endResetModel();
}
QList * ContainerConfigList::
getAppsForContainer(QString const& container_id)
{
for (auto const& config: configs_)
{
if (config->container_id() == container_id)
{
return &(config->container_apps());
}
}
return nullptr;
}
bool ContainerConfigList::
isAppInstalled(QString const& container_id, QString const& package_name)
{
for (auto const& config: configs_)
{
if (config->container_id() == container_id)
{
for (auto const& app: config->container_apps())
{
if (app->package_name() == package_name)
{
return true;
}
}
}
}
return false;
}
QString ContainerConfigList::
getAppStatus(QString const& container_id, QString const& package_name)
{
for (auto const& config: configs_)
{
if (config->container_id() == container_id)
{
for (auto const& app: config->container_apps())
{
if (app->package_name() == package_name)
{
return app->app_status();
}
}
}
}
return nullptr;
}
QString ContainerConfigList::
getAppVersion(QString const& app_info)
{
if (app_info.startsWith("N:") || app_info.isEmpty())
{
return QString("Cannot determine package version.");
}
else
{
QStringList info = app_info.split('\n');
return info.at(1).section(": ", 1, 1);
}
}
bool ContainerConfigList::
isValidDebianPackage(QString const& package_string)
{
return (package_string.endsWith(".deb") &&
QFile::exists(package_string));
}
QString ContainerConfigList::
getDebianPackageName(QString const& package_path)
{
QProcess cmd;
QString exec_line("dpkg-deb");
QStringList args;
QByteArray package_name;
args << "-f" << package_path << "Package";
cmd.start(exec_line, args);
if (!cmd.waitForStarted())
return QString(package_name);
cmd.waitForFinished(-1);
package_name = cmd.readAllStandardOutput();
return QString(package_name.trimmed());
}
QString ContainerConfigList::
getDownloadsLocation()
{
return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
}
QStringList ContainerConfigList::
getDebianPackageFiles()
{
QStringList filters;
QDir downloads(getDownloadsLocation());
filters << "*.deb";
return downloads.entryList(filters);
}
QList * ContainerConfigList::
getArchivesForContainer(QString const& container_id)
{
for (auto const& config: configs_)
{
if (config->container_id() == container_id)
{
return &(config->container_archives());
}
}
return nullptr;
}
QString ContainerConfigList::
getContainerType(QString const& container_id)
{
QString default_type("lxc");
for (auto const& config: configs_)
{
if (config->container_id() == container_id)
{
return config->container_type();
}
}
return default_type;
}
QString ContainerConfigList::
getContainerDistro(QString const& container_id)
{
for (auto const& config: configs_)
{
if (config->container_id() == container_id)
{
return config->distro_series();
}
}
return nullptr;
}
QString ContainerConfigList::
getContainerName(QString const& container_id)
{
for (auto const& config: configs_)
{
if (config->container_id() == container_id)
{
return config->name();
}
}
return nullptr;
}
QString ContainerConfigList::
getContainerMultiarchSupport(QString const& container_id)
{
for (auto const& config: configs_)
{
if (config->container_id() == container_id)
{
return config->multiarch_support();
}
}
return nullptr;
}
QString ContainerConfigList::
getContainerStatus(QString const& container_id)
{
for (auto const& config: configs_)
{
if (config->container_id() == container_id)
{
return config->install_status();
}
}
return nullptr;
}
QString ContainerConfigList::
getHostArchitecture()
{
return QSysInfo::currentCpuArchitecture();
}
QString ContainerConfigList::
getHostDistroCodename()
{
QSettings distro_info("/etc/lsb-release", QSettings::NativeFormat);
return distro_info.value("DISTRIB_CODENAME").toString();
}
QString ContainerConfigList::
getHostDistroDescription()
{
QSettings distro_info("/etc/lsb-release", QSettings::NativeFormat);
return distro_info.value("DISTRIB_DESCRIPTION").toString().section(' ', 0, 2);
}
void ContainerConfigList::
reloadConfigs()
{
load_config();
emit configChanged();
}
QJsonObject ContainerConfigList::
toJson() const
{
QJsonObject json_object;
json_object[Json_default_container] = default_container_id_;
QJsonArray contents;
for (auto const& config: configs_)
{
contents.append(config->toJson());
}
json_object[Json_container_list] = contents;
return json_object;
}
QString const& ContainerConfigList::
default_container_id() const
{ return default_container_id_; }
void ContainerConfigList::
default_container_id(QString const& container_id)
{ default_container_id_ = container_id; }
bool ContainerConfigList::
empty() const noexcept
{ return configs_.empty(); }
ContainerConfigList::size_type ContainerConfigList::
size() const noexcept
{ return configs_.count(); }
int ContainerConfigList::
rowCount(QModelIndex const&) const
{
return this->size();
}
QHash ContainerConfigList::
roleNames() const
{
QHash roles;
roles[static_cast(DataRole::ContainerId)] = "containerId";
roles[static_cast(DataRole::ContainerName)] = "name";
roles[static_cast(DataRole::ContainerType)] = "type";
roles[static_cast(DataRole::DistroSeries)] = "distroSeries";
roles[static_cast(DataRole::InstallStatus)] = "installStatus";
return roles;
}
QVariant ContainerConfigList::
data(QModelIndex const& index, int role) const
{
QVariant result;
if (index.isValid() && index.row() <= configs_.count())
{
switch (static_cast(role))
{
case DataRole::ContainerId:
result = configs_[index.row()]->container_id();
break;
case DataRole::ContainerName:
result = configs_[index.row()]->name();
break;
case DataRole::ContainerType:
result = configs_[index.row()]->container_type();
break;
case DataRole::DistroSeries:
result = configs_[index.row()]->distro_series();
break;
case DataRole::InstallStatus:
result = configs_[index.row()]->install_status();
break;
case DataRole::Error:
break;
}
}
return result;
}
int ContainerConfigList::
generate_bis(QString const& id)
{
int bis = 0;
int max = 0;
QRegExp re = QRegExp("^(\\w*)(?:-(\\d+))?$", Qt::CaseInsensitive);
for (auto const& config: configs_)
{
int found = re.indexIn(config->container_id());
if (found >= 0 && re.cap(1) == id)
{
++bis;
bool ok;
int val = re.cap(2).toInt(&ok);
if (ok && val > 0)
max = std::max(bis, val);
}
}
if (bis > 0)
bis = std::max(bis, max) + 1;
return bis;
}
void ContainerConfigList::
clear_config()
{
for (auto const& config: configs_)
{
qDeleteAll(config->container_apps());
config->container_apps().clear();
}
qDeleteAll(configs_);
configs_.clear();
}
void ContainerConfigList::
load_config()
{
QFile config_file(config_->containers_config_file_name());
if (config_file.exists())
{
if (!config_file.open(QIODevice::ReadOnly))
{
qWarning() << "could not open containers config file " << config_file.fileName();
}
else if (config_file.size() != 0)
{
QJsonParseError parse_error;
flock(config_file.handle(), LOCK_EX);
QJsonDocument json = QJsonDocument::fromJson(config_file.readAll(), &parse_error);
flock(config_file.handle(), LOCK_UN);
if (parse_error.error)
{
qWarning() << "error parsing containers config file: " << parse_error.errorString();
}
if (!json.object().empty())
{
default_container_id_ = json.object()[Json_default_container].toString();
if (!configs_.empty())
{
clear_config();
}
QJsonArray container_list = json.object()[Json_container_list].toArray();
for (auto const& config: container_list)
{
QJsonObject containerConfig = config.toObject();
configs_.append(new ContainerConfig(containerConfig, this));
}
}
}
}
}
./libertine/LibertineConfig.cpp 0000644 0000156 0000165 00000003371 12702745452 016635 0 ustar jenkins jenkins /**
* @file LibertineConfig.cpp
* @brief Libertine Manager application-wide configuration module
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "libertine/LibertineConfig.h"
#include "libertine/libertine.h"
#include
#include
#include
#include
LibertineConfig::
LibertineConfig(Libertine const& libertine)
{
QCommandLineParser commandlineParser;
commandlineParser.setApplicationDescription("manage sandboxes for running legacy DEB-packaged X11-based applications");
commandlineParser.addHelpOption();
commandlineParser.addVersionOption();
commandlineParser.process(libertine);
}
LibertineConfig::
LibertineConfig()
{
}
LibertineConfig::
~LibertineConfig()
{
}
QString LibertineConfig::
containers_config_file_name() const
{
QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/libertine";
QDir dir(path);
if (!dir.exists())
{
dir.mkpath(path);
}
QString file_name = path + "/ContainersConfig.json";
if (!QFile::exists(file_name))
{
QFile file(file_name);
file.open(QIODevice::WriteOnly);
file.close();
}
return file_name;
}
./libertine/ContainerArchivesList.cpp 0000644 0000156 0000165 00000004446 12702745445 020043 0 ustar jenkins jenkins /**
* @file ContainerArchivesList.cpp
* @brief Libertine Manager list of extra container archives, ie, PPAs
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "libertine/ContainerArchivesList.h"
#include "libertine/ContainerConfigList.h"
ContainerArchivesList::
ContainerArchivesList(ContainerConfigList* container_config_list,
QObject* parent)
: QAbstractListModel(parent)
, container_config_list_(container_config_list)
{ }
ContainerArchivesList::
~ContainerArchivesList()
{ }
void ContainerArchivesList::
setContainerArchives(QString const& container_id)
{
archives_ = container_config_list_->getArchivesForContainer(container_id);
beginResetModel();
endResetModel();
}
bool ContainerArchivesList::
empty() const noexcept
{ return archives_->empty(); }
ContainerArchivesList::size_type ContainerArchivesList::
size() const noexcept
{ return archives_->count(); }
int ContainerArchivesList::
rowCount(QModelIndex const&) const
{
return this->size();
}
QHash ContainerArchivesList::
roleNames() const
{
QHash roles;
roles[static_cast(DataRole::ArchiveName)] = "archiveName";
roles[static_cast(DataRole::ArchiveStatus)] = "archiveStatus";
return roles;
}
QVariant ContainerArchivesList::
data(QModelIndex const& index, int role) const
{
QVariant result;
if (index.isValid() && index.row() <= archives_->count())
{
switch (static_cast(role))
{
case DataRole::ArchiveName:
result = (*archives_)[index.row()]->archive_name();
break;
case DataRole::ArchiveStatus:
result = (*archives_)[index.row()]->archive_status();
break;
case DataRole::Error:
break;
}
}
return result;
}
./libertine/ContainerAppsList.h 0000644 0000156 0000165 00000003637 12702745452 016646 0 ustar jenkins jenkins /**
* @file ContainerAppsList.h
* @brief Libertine Manager list of container applications
*/
/*
* Copyright 2015 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#ifndef _CONTAINER_APPS_LIST_H_
#define _CONTAINER_APPS_LIST_H_
#include "libertine/ContainerConfig.h"
#include
#include
#include
#include
class ContainerApps;
class ContainerConfigList;
class ContainerAppsList
: public QAbstractListModel
{
Q_OBJECT
public:
using AppsList = QList;
using iterator = AppsList::iterator;
using size_type = AppsList::size_type;
enum class DataRole
: int
{
PackageName = Qt::UserRole + 1,
AppStatus,
Error
};
public:
explicit
ContainerAppsList(ContainerConfigList* container_config_list,
QObject* parent = nullptr);
~ContainerAppsList();
Q_INVOKABLE void
setContainerApps(QString const& container_id);
Q_INVOKABLE void
reloadAppsList();
Q_INVOKABLE bool
empty() const noexcept;
size_type
size() const noexcept;
int
rowCount(QModelIndex const& parent = QModelIndex()) const;
QHash
roleNames() const;
QVariant
data(QModelIndex const& index, int role = Qt::DisplayRole) const;
private:
ContainerConfigList* container_config_list_;
AppsList* apps_;
};
#endif /* _CONTAINER_APPS_LIST_H_ */
./libertine/ContainerArchivesList.h 0000644 0000156 0000165 00000003700 12702745445 017500 0 ustar jenkins jenkins /**
* @file ContainerArchivesList.h
* @brief Libertine Manager list of extra container archives (PPAs)
*/
/*
* Copyright 2016 Canonical Ltd
*
* Libertine is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* Libertine is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#ifndef _CONTAINER_ARCHIVES_LIST_H_
#define _CONTAINER_ARCHIVES_LIST_H_
#include "libertine/ContainerConfig.h"
#include
#include
#include
#include
class ContainerArchives;
class ContainerConfigList;
class ContainerArchivesList
: public QAbstractListModel
{
Q_OBJECT
public:
using ArchivesList = QList;
using iterator = ArchivesList::iterator;
using size_type = ArchivesList::size_type;
enum class DataRole
: int
{
ArchiveName = Qt::UserRole + 1,
ArchiveStatus,
Error
};
public:
explicit
ContainerArchivesList(ContainerConfigList* container_config_list,
QObject* parent = nullptr);
~ContainerArchivesList();
Q_INVOKABLE void
setContainerArchives(QString const& container_id);
Q_INVOKABLE bool
empty() const noexcept;
size_type
size() const noexcept;
int
rowCount(QModelIndex const& parent = QModelIndex()) const;
QHash
roleNames() const;
QVariant
data(QModelIndex const& index, int role = Qt::DisplayRole) const;
private:
ContainerConfigList* container_config_list_;
ArchivesList* archives_;
};
#endif /* _CONTAINER_ARCHIVES_LIST_H_ */
./liblibertine/ 0000755 0000156 0000165 00000000000 12702745445 013553 5 ustar jenkins jenkins ./liblibertine/libertine.h 0000644 0000156 0000165 00000004435 12702745445 015707 0 ustar jenkins jenkins /*
* Copyright 2015 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include
#ifndef _LIBERTINE_COMMON_H_
#define _LIBERTINE_COMMON_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* libertine_list_containers:
*
* Gets the list of existing containers for the user.
*
* Return value: (transfer full): A NULL terminated list of
* container IDs. Should be free'd with g_strfreev().
*/
gchar ** libertine_list_containers(void);
/**
* libertine_container_path:
* @container_id: ID of the container
*
* Calculates the full path to the rootfs of @container_id.
*
* Return value: Path to the rootfs or NULL if it is not found.
* Should be free'd with g_free().
*/
gchar * libertine_container_path(const gchar * container_id);
/**
* libertine_container_home_path:
* @container_id: ID of the container
*
* Calculates the path to the mapped home dir of @container_id.
*
* Return value: Path to the mapped home dir or NULL if it is not found.
* Should be free'd with g_free().
*/
gchar * libertine_container_home_path(const gchar * container_id);
/**
* libertine_container_name:
* @container_id: ID of the container
*
* Gets the human readable name of @container_id.
*
* Return value: Human readable string for @container_id.
* Should be free'd with g_free().
*/
gchar * libertine_container_name(const gchar * container_id);
/**
* libertine_list_apps_for_container:
* @container_id: ID of the container
*
* Gets the list of existing apps installed in a container.
*
* Return value: (transfer full): A NULL terminated list of
* app IDs. Should be free'd with g_strfreev().
*/
gchar ** libertine_list_apps_for_container(const gchar * container_id);
#ifdef __cplusplus
}
#endif
#endif /* _LIBERTINE_COMMON_H_ */
./liblibertine/libertine.cpp 0000644 0000156 0000165 00000007651 12702745445 016245 0 ustar jenkins jenkins /**
* @file libertine_common.cpp
* @brief The Libertine Common shared library
*/
/*
* Copyright 2015 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "liblibertine/libertine.h"
#include "libertine/ContainerConfigList.h"
#include "libertine/LibertineConfig.h"
gchar **
libertine_list_apps_for_container(const gchar * container_id)
{
g_return_val_if_fail(container_id != NULL, NULL);
gchar * path = NULL;
path = libertine_container_path(container_id);
GArray * apps = g_array_new(TRUE, TRUE, sizeof(gchar *));
GError **error = NULL;
gchar * fullpath = g_strjoin("/", g_strdup(path), "usr/share/applications", NULL);
GDir * dir = g_dir_open(fullpath, 0, error);
g_return_val_if_fail(dir != NULL, NULL);
const gchar * files;
while ((files = g_dir_read_name(dir)) != NULL)
{
gchar *file = g_build_filename(fullpath, files, NULL);
if (g_file_test(file, G_FILE_TEST_IS_REGULAR))
{
gchar * basename = g_path_get_basename(file);
gchar ** name = g_strsplit(basename, ".", 0);
gchar * app_id = g_strjoin("_", g_strdup(container_id), name[0], "0.0", NULL);
g_array_append_val(apps, app_id);
g_strfreev(name);
g_free(basename);
}
g_free(file);
}
g_dir_close(dir);
g_free(path);
return (gchar **)g_array_free(apps, FALSE);
}
gchar **
libertine_list_containers(void)
{
guint container_count;
guint i;
LibertineConfig config;
ContainerConfigList container_list(&config);
GArray * containers = g_array_new(TRUE, TRUE, sizeof(gchar *));
QVariant id;
container_count = (guint)container_list.size();
for (i = 0; i < container_count; ++i)
{
id = container_list.data(container_list.index(i, 0), (int)ContainerConfigList::DataRole::ContainerId);
gchar * container_id = g_strdup((gchar *)id.toString().toStdString().c_str());
g_array_append_val(containers, container_id);
}
return (gchar **)g_array_free(containers, FALSE);
}
gchar *
libertine_container_path(const gchar * container_id)
{
gchar * path = NULL;
g_return_val_if_fail(container_id != NULL, NULL);
path = g_build_filename(g_get_user_cache_dir(), "libertine-container", container_id, "rootfs", NULL);
if (g_file_test(path, G_FILE_TEST_EXISTS))
{
return path;
}
else
{
g_free(path);
return NULL;
}
}
gchar *
libertine_container_home_path(const gchar * container_id)
{
gchar * path = NULL;
g_return_val_if_fail(container_id != NULL, NULL);
path = g_build_filename(g_get_user_data_dir(), "libertine-container", "user-data", container_id, NULL);
if (g_file_test(path, G_FILE_TEST_EXISTS))
{
return path;
}
else
{
g_free(path);
return NULL;
}
}
gchar *
libertine_container_name(const gchar * container_id)
{
guint container_count;
guint i;
gchar * container_name = NULL;
LibertineConfig config;
ContainerConfigList container_list(&config);
QVariant id;
container_count = (guint)container_list.size();
for (i = 0; i < container_count; ++i)
{
id = container_list.data(container_list.index(i, 0), (int)ContainerConfigList::DataRole::ContainerId);
if (g_strcmp0((gchar *)id.toString().toStdString().c_str(), container_id) == 0)
{
QVariant name = container_list.data(container_list.index(i, 0), (int)ContainerConfigList::DataRole::ContainerName);
container_name = g_strdup(name.toString().toStdString().c_str());
break;
}
}
return container_name;
}
./liblibertine/libertine.pc.in 0000644 0000156 0000165 00000000436 12702745445 016464 0 ustar jenkins jenkins prefix=@CMAKE_INSTALL_FULL_PREFIX@
exec_prefix=${prefix}
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
Name: libertine
Description: Libertine legacy application sandbox
Version: @PROJECT_VERSION@
Requires: @LIBERTINE_REQUIRES@
Libs: -L${libdir} -llibertine
Cflags: -I@liblibertine_headers_path@
./liblibertine/CMakeLists.txt 0000644 0000156 0000165 00000003555 12702745445 016323 0 ustar jenkins jenkins set(API_VERSION 1)
set(ABI_VERSION 1)
set(libertine_src ${CMAKE_SOURCE_DIR}/libertine)
add_library(
libertine-common SHARED
libertine.cpp
${libertine_src}/ContainerConfigList.cpp
${libertine_src}/LibertineConfig.cpp
${libertine_src}/ContainerConfig.cpp
${libertine_src}/ContainerManager.cpp
${libertine_src}/ContainerAppsList.cpp
${libertine_src}/ContainerArchivesList.cpp
${libertine_src}/PasswordHelper.cpp
)
set_target_properties(libertine-common PROPERTIES
VERSION ${ABI_VERSION}.0.0
SOVERSION ${ABI_VERSION}
OUTPUT_NAME "libertine"
)
target_link_libraries(libertine-common
${GLIB2_LIBRARIES}
${PYTHON3_LIBRARIES}
Qt5::Core
pam
)
set(liblibertine_headers_path "${CMAKE_INSTALL_FULL_INCLUDEDIR}/liblibertine")
install(FILES libertine.h DESTINATION ${liblibertine_headers_path})
install(TARGETS libertine-common LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
configure_file(libertine.pc.in ${CMAKE_BINARY_DIR}/libertine.pc @ONLY)
install(FILES ${CMAKE_BINARY_DIR}/libertine.pc
DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
##########################
# Introspection
##########################
include(UseGObjectIntrospection)
set(INTROSPECTION_GIRS)
set(_introspection_files libertine.h)
set(Libertine_1_gir "libertine")
set(Libertine_1_gir_INCLUDES GObject-2.0)
gir_get_cflags(_cflags)
set(Libertine_1_gir_CFLAGS ${c_flags})
set(Libertine_1_gir_LIBS libertine)
list_make_absolute(_abs_introspection_files _introspection_files "${CMAKE_CURRENT_SOURCE_DIR}/")
set(Libertine_1_gir_FILES ${_abs_introspection_files})
set(Libertine_1_gir_SCANNERFLAGS --c-include "libertine.h")
set(Libertine_1_gir_EXPORT_PACKAGES "libertine-${API_VERSION}")
list(APPEND INTROSPECTION_GIRS Libertine-1.gir)
gir_add_introspections(INTROSPECTION_GIRS)
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/Libertine-1.typelib" DESTINATION "${CMAKE_INSTALL_LIBDIR}/girepository-1.0")
./cmake/ 0000755 0000156 0000165 00000000000 12702745445 012167 5 ustar jenkins jenkins ./cmake/UseGObjectIntrospection.cmake 0000644 0000156 0000165 00000007516 12702745445 017755 0 ustar jenkins jenkins # Copyright (C) 2010, Pino Toscano,
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
include(ListOperations)
macro(_gir_list_prefix _outvar _listvar _prefix)
set(${_outvar})
foreach(_item IN LISTS ${_listvar})
list(APPEND ${_outvar} ${_prefix}${_item})
endforeach()
endmacro(_gir_list_prefix)
macro(gir_add_introspections introspections_girs)
foreach(gir IN LISTS ${introspections_girs})
set(_gir_name "${gir}")
## Transform the gir filename to something which can reference through a variable
## without automake/make complaining, eg Gtk-2.0.gir -> Gtk_2_0_gir
string(REPLACE "-" "_" _gir_name "${_gir_name}")
string(REPLACE "." "_" _gir_name "${_gir_name}")
# Namespace and Version is either fetched from the gir filename
# or the _NAMESPACE/_VERSION variable combo
set(_gir_namespace "${${_gir_name}_NAMESPACE}")
if (_gir_namespace STREQUAL "")
string(REGEX REPLACE "([^-]+)-.*" "\\1" _gir_namespace "${gir}")
endif ()
set(_gir_version "${${_gir_name}_VERSION}")
if (_gir_version STREQUAL "")
string(REGEX REPLACE ".*-([^-]+).gir" "\\1" _gir_version "${gir}")
endif ()
# _PROGRAM is an optional variable which needs it's own --program argument
set(_gir_program "${${_gir_name}_PROGRAM}")
if (NOT _gir_program STREQUAL "")
set(_gir_program "--program=${_gir_program}")
endif ()
# Variables which provides a list of things
_gir_list_prefix(_gir_libraries ${_gir_name}_LIBS "--library=")
_gir_list_prefix(_gir_packages ${_gir_name}_PACKAGES "--pkg=")
_gir_list_prefix(_gir_includes ${_gir_name}_INCLUDES "--include=")
_gir_list_prefix(_gir_export_packages ${_gir_name}_EXPORT_PACKAGES "--pkg-export=")
# Reuse the LIBTOOL variable from by automake if it's set
set(_gir_libtool "--no-libtool")
add_custom_command(
COMMAND ${INTROSPECTION_SCANNER}
${INTROSPECTION_SCANNER_ARGS}
--quiet
--warn-all
--namespace=${_gir_namespace}
--nsversion=${_gir_version}
${_gir_libtool}
${_gir_program}
${_gir_libraries}
${_gir_packages}
${_gir_includes}
${_gir_export_packages}
${${_gir_name}_SCANNERFLAGS}
${${_gir_name}_CFLAGS}
${${_gir_name}_FILES}
--output ${CMAKE_CURRENT_BINARY_DIR}/${gir}
DEPENDS ${${_gir_name}_FILES}
${${_gir_name}_LIBS}
OUTPUT ${gir}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
VERBATIM
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${gir} DESTINATION share/gir-1.0)
string(REPLACE ".gir" ".typelib" _typelib "${gir}")
add_custom_command(
COMMAND ${INTROSPECTION_COMPILER}
${INTROSPECTION_COMPILER_ARGS}
--includedir=.
${CMAKE_CURRENT_BINARY_DIR}/${gir}
-o ${CMAKE_CURRENT_BINARY_DIR}/${_typelib}
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${gir}
OUTPUT ${_typelib}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${_typelib} DESTINATION ${CMAKE_INSTALL_LIBDIR}/girepository-1.0)
add_custom_target(gir-${gir} ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${gir})
add_custom_target(gir-typelibs-${_typelib} ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${_typelib})
endforeach()
endmacro(gir_add_introspections)
macro(gir_get_cflags _output)
get_directory_property(_tmp_includes INCLUDE_DIRECTORIES)
list_prefix(_includes _tmp_includes "-I")
get_directory_property(_tmp_compile_definitions COMPILE_DEFINITIONS)
list_prefix(_compile_definitions _tmp_compile_definitions "-D")
set(${_output} ${_includes} ${_compile_definitions})
endmacro(gir_get_cflags)
./cmake/FindGObjectIntrospection.cmake 0000644 0000156 0000165 00000003765 12702745445 020103 0 ustar jenkins jenkins # - try to find gobject-introspection
#
# Once done this will define
#
# INTROSPECTION_FOUND - system has gobject-introspection
# INTROSPECTION_SCANNER - the gobject-introspection scanner, g-ir-scanner
# INTROSPECTION_COMPILER - the gobject-introspection compiler, g-ir-compiler
# INTROSPECTION_GENERATE - the gobject-introspection generate, g-ir-generate
# INTROSPECTION_GIRDIR
# INTROSPECTION_TYPELIBDIR
# INTROSPECTION_CFLAGS
# INTROSPECTION_LIBS
#
# Copyright (C) 2010, Pino Toscano,
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
macro(_GIR_GET_PKGCONFIG_VAR _outvar _varname)
execute_process(
COMMAND ${PKG_CONFIG_EXECUTABLE} --variable=${_varname} gobject-introspection-1.0
OUTPUT_VARIABLE _result
RESULT_VARIABLE _null
)
if (_null)
else()
string(REGEX REPLACE "[\r\n]" " " _result "${_result}")
string(REGEX REPLACE " +$" "" _result "${_result}")
separate_arguments(_result)
set(${_outvar} ${_result} CACHE INTERNAL "")
endif()
endmacro(_GIR_GET_PKGCONFIG_VAR)
find_package(PkgConfig)
if(PKG_CONFIG_FOUND)
if(PACKAGE_FIND_VERSION_COUNT GREATER 0)
set(_gir_version_cmp ">=${PACKAGE_FIND_VERSION}")
endif()
pkg_check_modules(_pc_gir gobject-introspection-1.0${_gir_version_cmp})
if(_pc_gir_FOUND)
set(INTROSPECTION_FOUND TRUE)
_gir_get_pkgconfig_var(INTROSPECTION_SCANNER "g_ir_scanner")
_gir_get_pkgconfig_var(INTROSPECTION_COMPILER "g_ir_compiler")
_gir_get_pkgconfig_var(INTROSPECTION_GENERATE "g_ir_generate")
_gir_get_pkgconfig_var(INTROSPECTION_GIRDIR "girdir")
_gir_get_pkgconfig_var(INTROSPECTION_TYPELIBDIR "typelibdir")
set(INTROSPECTION_CFLAGS "${_pc_gir_CFLAGS}")
set(INTROSPECTION_LIBS "${_pc_gir_LIBS}")
endif()
endif()
mark_as_advanced(
INTROSPECTION_SCANNER
INTROSPECTION_COMPILER
INTROSPECTION_GENERATE
INTROSPECTION_GIRDIR
INTROSPECTION_TYPELIBDIR
INTROSPECTION_CFLAGS
INTROSPECTION_LIBS
)
./cmake/ListOperations.cmake 0000644 0000156 0000165 00000000735 12702745445 016155 0 ustar jenkins jenkins
macro(list_prefix _outvar _listvar _prefix)
set(${_outvar})
foreach(_item IN LISTS ${_listvar})
list(APPEND ${_outvar} ${_prefix}${_item})
endforeach()
endmacro(list_prefix)
macro(list_make_absolute _outvar _listvar _prefix)
set(${_outvar})
foreach(_item IN LISTS ${_listvar})
if(IS_ABSOLUTE ${_item})
list(APPEND ${_outvar} ${_item})
else()
list(APPEND ${_outvar} ${_prefix}${_item})
endif()
endforeach()
endmacro(list_make_absolute)
./tests/ 0000755 0000156 0000165 00000000000 12702745445 012251 5 ustar jenkins jenkins ./tests/mocks/ 0000755 0000156 0000165 00000000000 12702745445 013365 5 ustar jenkins jenkins ./tests/mocks/mock_app 0000755 0000156 0000165 00000000047 12702745445 015105 0 ustar jenkins jenkins #!/bin/sh
touch $XDG_RUNTIME_DIR/mock
./tests/unit/ 0000755 0000156 0000165 00000000000 12702745445 013230 5 ustar jenkins jenkins ./tests/unit/ContainerConfigListTests.cpp 0000644 0000156 0000165 00000004340 12702745445 020664 0 ustar jenkins jenkins /**
* @file tests/unit/ContainerConfigLIstTests.cpp
* @brief Verify the ContainerConfig class
*/
/*
* Copyright 2015 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include
#include "libertine/ContainerConfigList.h"
#include
#include
#include
/** Verify constructing a New containerConfig DTRT. */
TEST(LibertineContainerConfigList, constructDefault)
{
ContainerConfigList container_configs;
EXPECT_EQ(container_configs.empty(), true);
EXPECT_EQ(container_configs.size(), 0);
}
/** Verify constructing a ContainerConfig from JSON DTRT. */
TEST(LibertineContainerConfigList, constructFromJson)
{
QByteArray raw_json(
"{"
"\"containerList\": ["
"{"
"\"id\": \"wily\","
"\"name\": \"Wily Werewolf\","
"\"distro\": \"wily\","
"\"installedApps\": ["
"],"
"\"installStatus\": \"ready\""
"},"
"{"
"\"id\": \"wily1\","
"\"name\": \"Wily Werewolf\","
"\"distro\": \"wily\","
"\"installedApps\": ["
"],"
"\"installStatus\": \"new\""
"}"
"],"
"\"defaultContainer\": \"wily\""
"}"
);
QJsonParseError parse_error;
QJsonDocument json = QJsonDocument::fromJson(raw_json, &parse_error);
ASSERT_EQ(parse_error.error, 0) << parse_error.errorString().toStdString();
ContainerConfigList container_configs(json.object());
EXPECT_EQ(container_configs.empty(), false);
EXPECT_EQ(container_configs.size(), 2);
EXPECT_EQ(container_configs.default_container_id().toStdString(), "wily");
}
./tests/unit/libertine_public_gir_tests.py 0000755 0000156 0000165 00000005027 12702745445 021207 0 ustar jenkins jenkins # Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
import os
from testtools import TestCase
from testtools.matchers import Equals
from gi.repository import Libertine
class TestLibertineGir(TestCase):
def setUp(self):
super(TestLibertineGir, self).setUp()
self.cmake_source_dir = os.environ['CMAKE_SOURCE_DIR']
def test_list_containers(self):
os.environ['XDG_DATA_HOME'] = self.cmake_source_dir + '/libertine-config'
containers = Libertine.list_containers()
self.assertThat(containers[0], Equals('wily'))
self.assertThat(containers[1], Equals('wily-2'))
def test_container_path(self):
container_id = 'wily'
os.environ['XDG_CACHE_HOME'] = self.cmake_source_dir + '/libertine-data'
container_path = Libertine.container_path(container_id)
self.assertThat(container_path, Equals(self.cmake_source_dir + '/libertine-data/libertine-container/wily/rootfs'))
def test_container_home_path(self):
container_id = 'wily'
os.environ['XDG_DATA_HOME'] = self.cmake_source_dir + '/libertine-home'
container_home_path = Libertine.container_home_path(container_id)
self.assertThat(container_home_path, Equals(self.cmake_source_dir + '/libertine-home/libertine-container/user-data/wily'))
def test_container_name(self):
container_id = 'wily'
os.environ['XDG_DATA_HOME'] = self.cmake_source_dir + '/libertine-config'
container_name = Libertine.container_name(container_id)
self.assertThat(container_name, Equals("Ubuntu 'Wily Werewolf'"))
container_id = 'wily-2'
container_name = Libertine.container_name(container_id)
self.assertThat(container_name, Equals("Ubuntu 'Wily Werewolf' (2)"))
def test_list_apps_for_container(self):
os.environ['XDG_DATA_HOME'] = self.cmake_source_dir + '/libertine-config'
apps = Libertine.list_apps_for_container('wily')
self.assertThat(len(apps), Equals(0))
./tests/unit/libertine-data/ 0000755 0000156 0000165 00000000000 12702745445 016114 5 ustar jenkins jenkins ./tests/unit/libertine-data/libertine-container/ 0000755 0000156 0000165 00000000000 12702745445 022051 5 ustar jenkins jenkins ./tests/unit/libertine-data/libertine-container/wily/ 0000755 0000156 0000165 00000000000 12702745445 023035 5 ustar jenkins jenkins ./tests/unit/libertine-data/libertine-container/wily/rootfs/ 0000755 0000156 0000165 00000000000 12702745445 024351 5 ustar jenkins jenkins ./tests/unit/libertine-config/ 0000755 0000156 0000165 00000000000 12702745445 016450 5 ustar jenkins jenkins ./tests/unit/libertine-config/libertine/ 0000755 0000156 0000165 00000000000 12702745445 020425 5 ustar jenkins jenkins ./tests/unit/libertine-config/libertine/ContainersConfig.json 0000644 0000156 0000165 00000001025 12702745445 024551 0 ustar jenkins jenkins {
"containerList": [
{
"id": "wily",
"image": "wily",
"installStatus": "new",
"installedApps": [
],
"name": "Ubuntu 'Wily Werewolf'",
"type": "lxc"
},
{
"id": "wily-2",
"image": "wily",
"installStatus": "new",
"installedApps": [
],
"name": "Ubuntu 'Wily Werewolf' (2)",
"type": "chroot"
}
],
"defaultContainer": "wily"
}
./tests/unit/test_libertine_container.py 0000644 0000156 0000165 00000004264 12702745445 020666 0 ustar jenkins jenkins """Unit tests for the LibertineContainer interface."""
# Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
from libertine import Libertine
from testtools import TestCase
from testtools.matchers import Equals
import os
import shutil
import tempfile
class TestLibertineContainer(TestCase):
def setUp(self):
super().setUp()
self._working_dir = tempfile.mkdtemp()
os.environ['XDG_CACHE_HOME'] = self._working_dir
os.environ['XDG_DATA_HOME'] = self._working_dir
def tearDown(self):
shutil.rmtree(self._working_dir)
super().tearDown()
def test_container_id(self):
container_id = "test-id-1"
container = Libertine.LibertineContainer(container_id)
self.assertThat(container.container_id, Equals(container_id))
def test_container_type_default(self):
container_id = "test-id-2"
container = Libertine.LibertineContainer(container_id)
self.assertThat(container.container_type, Equals("lxc"))
def test_container_name_default(self):
container_id = "test-id-3"
container = Libertine.LibertineContainer(container_id)
self.assertThat(container.name, Equals("Unknown"))
def test_container_root_path(self):
container_id = "test-id-4"
container = Libertine.LibertineContainer(container_id)
expected_root_path = os.path.join(self._working_dir,
"libertine-container",
container_id,
"rootfs")
self.assertThat(container.root_path, Equals(expected_root_path))
./tests/unit/libertine_launch_tests.py 0000755 0000156 0000165 00000007123 12702745445 020341 0 ustar jenkins jenkins # Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
import os
import shlex
import shutil
import subprocess
import tempfile
from testtools import TestCase
from testtools.matchers import Equals, NotEquals
class TestLibertineLaunch(TestCase):
def setUp(self):
super(TestLibertineLaunch, self).setUp()
self.cmake_source_dir = os.environ['CMAKE_SOURCE_DIR']
self.cmake_binary_dir = os.environ['CMAKE_BINARY_DIR']
# Set the paths to the config file
container_config_path = os.path.join(self.cmake_binary_dir, 'tests', 'unit', 'libertine-config')
container_config_file = os.path.join(container_config_path, 'libertine', 'ContainersConfig.json')
# Set necessary enviroment variables
os.environ['XDG_DATA_HOME'] = container_config_path
os.environ['XDG_RUNTIME_DIR'] = tempfile.mkdtemp()
os.environ['DISPLAY'] = ':0'
os.environ['PATH'] = (self.cmake_source_dir + '/tests/mocks:' +
self.cmake_source_dir + '/tools:' + os.environ['PATH'])
self.addCleanup(self.cleanup)
# Make a mock container
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager create -i test -n Test -t mock'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
def cleanup(self):
shutil.rmtree(os.environ['XDG_RUNTIME_DIR'])
def test_launch_app_existing_container(self):
'''
Base line test to ensure launching an app in an existing container works.
'''
cli_cmd = self.cmake_source_dir + '/tools/libertine-launch test true'
args = shlex.split(cli_cmd)
p = subprocess.Popen(args)
p.wait()
self.assertThat(p.returncode, Equals(0))
def test_launch_app_nonexistent_container(self):
'''
Test to make sure that things gracefully handle a non-existing container.
'''
cli_cmd = self.cmake_source_dir + '/tools/libertine-launch test1 true'
args = shlex.split(cli_cmd)
p = subprocess.Popen(args)
p.wait()
# Should fail due to nonexistent container
self.assertThat(p.returncode, Equals(1))
def test_launch_good_app(self):
'''
Test to make sure that launching an app actually works.
'''
cli_cmd = self.cmake_source_dir + '/tools/libertine-launch test mock_app'
args = shlex.split(cli_cmd)
p = subprocess.Popen(args)
p.wait()
self.assertThat(p.returncode, Equals(0))
self.assertThat(os.path.exists(os.path.join(os.environ['XDG_RUNTIME_DIR'], 'mock')), Equals(True))
os.remove(os.path.join(os.path.join(os.environ['XDG_RUNTIME_DIR'], 'mock')))
def test_launch_bad_app(self):
'''
Test to make sure launching an app that doesn't exist doesn't break things
'''
cli_cmd = self.cmake_source_dir + '/tools/libertine-launch test foo'
args = shlex.split(cli_cmd)
p = subprocess.Popen(args)
p.wait()
self.assertThat(p.returncode, Equals(1))
./tests/unit/libertine-home/ 0000755 0000156 0000165 00000000000 12702745445 016133 5 ustar jenkins jenkins ./tests/unit/libertine-home/libertine-container/ 0000755 0000156 0000165 00000000000 12702745445 022070 5 ustar jenkins jenkins ./tests/unit/libertine-home/libertine-container/user-data/ 0000755 0000156 0000165 00000000000 12702745445 023755 5 ustar jenkins jenkins ./tests/unit/libertine-home/libertine-container/user-data/wily/ 0000755 0000156 0000165 00000000000 12702745445 024741 5 ustar jenkins jenkins ./tests/unit/test_app_discovery.py 0000644 0000156 0000165 00000003630 12702745445 017512 0 ustar jenkins jenkins """Unit tests for the AppLauncher module."""
# Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
from libertine.AppDiscovery import IconCache
from testtools import TestCase
from testtools.matchers import Equals
class TestIconSearching(TestCase):
def mock_file_loader(self, root_path):
return [
"/some/path/128x128/icon.png",
"/somepath/icon.png",
"/somepath/testme.png"
];
def test_full_path(self):
some_root = "/some_root"
icon_cache = IconCache(some_root, file_loader=self.mock_file_loader)
some_full_path = "/this/is/a/full/path"
self.assertThat(icon_cache.expand_icons(some_full_path)[0],
Equals(some_full_path))
def test_icon_name(self):
some_root = "/some_root"
icon_cache = IconCache(some_root, file_loader=self.mock_file_loader)
some_icon_list = "testme"
self.assertThat(icon_cache.expand_icons(some_icon_list)[0],
Equals("/somepath/testme.png"))
def test_edge_case_relative_file_name(self):
some_root = "/some_root"
icon_cache = IconCache(some_root, file_loader=self.mock_file_loader)
some_icon_list = "testme.png"
self.assertThat(icon_cache.expand_icons(some_icon_list)[0],
Equals("/somepath/testme.png"))
./tests/unit/ContainerConfigTests.cpp 0000644 0000156 0000165 00000010600 12702745445 020024 0 ustar jenkins jenkins /**
* @file tests/unit/ContainerConfigTests.cpp
* @brief Verify the COntainerConfig class
*/
/*
* Copyright 2015 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include
#include "libertine/ContainerConfig.h"
#include
#include
#include
/** Verify constructing a New containerConfig DTRT. */
TEST(LibertineContainerConfig, constructFromScalars)
{
ContainerConfig container_config("id", "name", "type", "distro");
EXPECT_EQ(container_config.container_id(), "id");
EXPECT_EQ(container_config.name(), "name");
EXPECT_EQ(container_config.container_type(), "type");
EXPECT_EQ(container_config.distro_series(), "distro");
EXPECT_EQ(container_config.install_status(), "new");
}
/** Verify constructing a ContainerConfig from JSON DTRT. */
TEST(LibertineContainerConfig, constructFromJson)
{
QByteArray raw_json(
"{"
"\"id\": \"wily3\","
"\"name\": \"Wily Werewolf\","
"\"type\": \"lxc\","
"\"distro\": \"wily\","
"\"installedApps\": ["
"],"
"\"installStatus\": \"ready\""
"}"
);
QJsonParseError parse_error;
QJsonDocument json = QJsonDocument::fromJson(raw_json, &parse_error);
ASSERT_EQ(parse_error.error, 0) << parse_error.errorString().toStdString();
ContainerConfig container_config(json.object());
EXPECT_EQ(container_config.container_id().toStdString(), "wily3");
EXPECT_EQ(container_config.name().toStdString(), "Wily Werewolf");
EXPECT_EQ(container_config.distro_series().toStdString(), "wily");
EXPECT_EQ(container_config.install_status(), "ready");
EXPECT_EQ(container_config.container_apps().empty(), true);
}
TEST(LibertineContainerConfig, constructFromJsonWithOneApp)
{
QByteArray raw_json(
"{"
"\"id\": \"wily3\","
"\"name\": \"Wily Werewolf\","
"\"type\": \"lxc\","
"\"distro\": \"wily\","
"\"installedApps\": ["
"{"
"\"packageName\": \"firefox\","
"\"appStatus\": \"installed\""
"}"
"],"
"\"installStatus\": \"ready\""
"}"
);
QJsonParseError parse_error;
QJsonDocument json = QJsonDocument::fromJson(raw_json, &parse_error);
ASSERT_EQ(parse_error.error, 0) << parse_error.errorString().toStdString();
ContainerConfig container_config(json.object());
EXPECT_EQ(container_config.container_apps().empty(), false);
EXPECT_EQ(container_config.container_apps()[0]->package_name(), "firefox");
EXPECT_EQ(container_config.container_apps()[0]->app_status(), "installed");
}
TEST(LibertineContainerConfig, constructFromJsonWithTwoApps)
{
QByteArray raw_json(
"{"
"\"id\": \"wily3\","
"\"name\": \"Wily Werewolf\","
"\"type\": \"lxc\","
"\"distro\": \"wily\","
"\"installedApps\": ["
"{"
"\"packageName\": \"firefox\","
"\"appStatus\": \"installed\""
"},"
"{"
"\"packageName\": \"xterm\","
"\"appStatus\": \"new\""
"}"
"],"
"\"installStatus\": \"ready\""
"}"
);
QJsonParseError parse_error;
QJsonDocument json = QJsonDocument::fromJson(raw_json, &parse_error);
ASSERT_EQ(parse_error.error, 0) << parse_error.errorString().toStdString();
ContainerConfig container_config(json.object());
EXPECT_EQ(container_config.container_apps().empty(), false);
EXPECT_EQ(container_config.container_apps()[0]->package_name(), "firefox");
EXPECT_EQ(container_config.container_apps()[0]->app_status(), "installed");
EXPECT_EQ(container_config.container_apps()[1]->package_name(), "xterm");
EXPECT_EQ(container_config.container_apps()[1]->app_status(), "new");
}
./tests/unit/CMakeLists.txt 0000644 0000156 0000165 00000004571 12702745445 015777 0 ustar jenkins jenkins set(GTEST_ROOT /usr/src/gtest)
add_subdirectory(${GTEST_ROOT} ${CMAKE_CURRENT_BINARY_DIR}/gtest)
add_definitions ( -DCMAKE_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}" )
add_executable(
test_container_config
ContainerConfigTests.cpp
ContainerConfigListTests.cpp
)
target_link_libraries(
test_container_config
libertine-common
gtest gtest_main
Qt5::Core
)
add_test(test_container_config
test_container_config
)
add_test(test_libertine_public_gir
"/usr/bin/python3" "-m" "testtools.run" "libertine_public_gir_tests"
)
set_tests_properties(test_libertine_public_gir
PROPERTIES
ENVIRONMENT
"GI_TYPELIB_PATH=${CMAKE_BINARY_DIR}/liblibertine;LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}/liblibertine:${LD_LIBRARY_PATH};CMAKE_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR};PYTHONPATH=${CMAKE_CURRENT_SOURCE_DIR}")
set_tests_properties(test_libertine_public_gir
PROPERTIES
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
add_test(test_libertine "/usr/bin/python3" "-m" "testtools.run" "discover" "-s" "${CMAKE_CURRENT_SOURCE_DIR}")
set_tests_properties(test_libertine
PROPERTIES
ENVIRONMENT
"GI_TYPELIB_PATH=${CMAKE_BINARY_DIR}/liblibertine;LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}/liblibertine:${LD_LIBRARY_PATH};PYTHONPATH=${CMAKE_SOURCE_DIR}/python")
add_test(test_libertine_container_manager
"/usr/bin/python3" "-m" "testtools.run" "libertine_container_manager_tests"
)
set_tests_properties(test_libertine_container_manager
PROPERTIES
ENVIRONMENT
"GI_TYPELIB_PATH=${CMAKE_BINARY_DIR}/liblibertine;LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}/liblibertine:${LD_LIBRARY_PATH};CMAKE_BINARY_DIR=${CMAKE_BINARY_DIR};PYTHONPATH=${CMAKE_CURRENT_SOURCE_DIR}:${CMAKE_SOURCE_DIR}/python;CMAKE_SOURCE_DIR=${CMAKE_SOURCE_DIR}")
add_test(test_libertine_launch
"/usr/bin/python3" "-m" "testtools.run" "libertine_launch_tests"
)
set_tests_properties(test_libertine_launch
PROPERTIES
ENVIRONMENT
"GI_TYPELIB_PATH=${CMAKE_BINARY_DIR}/liblibertine;LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}/liblibertine:${LD_LIBRARY_PATH};CMAKE_BINARY_DIR=${CMAKE_BINARY_DIR};PYTHONPATH=${CMAKE_CURRENT_SOURCE_DIR}:${CMAKE_SOURCE_DIR}/python;CMAKE_SOURCE_DIR=${CMAKE_SOURCE_DIR}")
./tests/unit/libertine_container_manager_tests.py 0000755 0000156 0000165 00000020476 12702745445 022551 0 ustar jenkins jenkins # Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
import json
import os
import shlex
import shutil
import subprocess
from testtools import TestCase
from testtools.matchers import Equals, NotEquals
class TestLibertineCLI(TestCase):
def setUp(self):
super(TestLibertineCLI, self).setUp()
self.cmake_source_dir = os.environ['CMAKE_SOURCE_DIR']
self.cmake_binary_dir = os.environ['CMAKE_BINARY_DIR']
def get_container_config_path(self):
return os.path.join(self.cmake_binary_dir, 'tests', 'unit', 'libertine-config')
def get_container_config_file(self):
return os.path.join(self.get_container_config_path(), 'libertine', 'ContainersConfig.json')
def get_container_json_object(self):
container_list = {}
container_config_file = self.get_container_config_file()
if os.path.exists(container_config_file):
with open(container_config_file, 'r') as fd:
container_list = json.load(fd)
fd.close()
return container_list
def test_01_create_initial_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
if os.path.exists(self.get_container_config_file()):
shutil.rmtree(self.get_container_config_path())
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager create -i test -n Test -t mock'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
container_list = self.get_container_json_object()
self.assertThat(len(container_list), NotEquals(0))
self.assertThat(len(container_list['containerList']), Equals(1))
self.assertThat(container_list['containerList'][0]['id'], Equals('test'))
self.assertThat(container_list['containerList'][0]['name'], Equals('Test'))
self.assertThat(container_list['defaultContainer'], Equals('test'))
def test_02_create_second_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager create -i test2 -n Test2 -t mock'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
container_list = self.get_container_json_object()
self.assertThat(len(container_list), NotEquals(0))
self.assertThat(len(container_list['containerList']), Equals(2))
self.assertThat(container_list['containerList'][1]['id'], Equals('test2'))
self.assertThat(container_list['containerList'][1]['name'], Equals('Test2'))
self.assertThat(container_list['defaultContainer'], Equals('test'))
def test_03_create_existing_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager create -i test -n Test -t mock'
args = shlex.split(cli_cmd)
p = subprocess.Popen(args)
p.wait()
# Return code of 1 indicates the cli found the container already exists.
self.assertThat(p.returncode, Equals(1))
def test_04_add_package_to_initial_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager install-package -i test -p firefox'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
container_list = self.get_container_json_object()
self.assertThat(len(container_list), NotEquals(0))
self.assertThat(len(container_list['containerList'][0]['installedApps']), NotEquals(0))
self.assertThat(container_list['containerList'][0]['installedApps'][0]['packageName'], Equals('firefox'))
def test_05_add_second_package_to_initial_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager install-package -i test -p libreoffice'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
container_list = self.get_container_json_object()
self.assertThat(len(container_list), NotEquals(0))
self.assertThat(len(container_list['containerList'][0]['installedApps']), NotEquals(0))
self.assertThat(container_list['containerList'][0]['installedApps'][1]['packageName'], Equals('libreoffice'))
def test_06_add_package_to_second_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager install-package -i test2 -p gedit'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
container_list = self.get_container_json_object()
self.assertThat(len(container_list), NotEquals(0))
self.assertThat(len(container_list['containerList'][1]['installedApps']), NotEquals(0))
self.assertThat(container_list['containerList'][1]['installedApps'][0]['packageName'], Equals('gedit'))
def test_07_add_existing_package_to_initial_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager install-package -i test -p firefox'
args = shlex.split(cli_cmd)
p = subprocess.Popen(args)
p.wait()
# Return code of 1 indicates the cli found the package already exists.
self.assertThat(p.returncode, Equals(1))
def test_08_remove_package_from_second_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager remove-package -i test2 -p gedit'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
container_list = self.get_container_json_object()
self.assertThat(len(container_list), NotEquals(0))
self.assertThat(len(container_list['containerList'][1]['installedApps']), Equals(0))
def test_09_remove_package_from_initial_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager remove-package -i test -p firefox'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
container_list = self.get_container_json_object()
self.assertThat(len(container_list), NotEquals(0))
self.assertThat(len(container_list['containerList'][0]['installedApps']), Equals(1))
self.assertThat(container_list['containerList'][0]['installedApps'][0]['packageName'], Equals('libreoffice'))
def test_10_remove_initial_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager destroy -i test'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
container_list = self.get_container_json_object()
self.assertThat(len(container_list), NotEquals(0))
self.assertThat(container_list['containerList'][0]['id'], Equals('test2'))
self.assertThat(container_list['containerList'][0]['name'], Equals('Test2'))
self.assertThat(container_list['defaultContainer'], Equals('test2'))
def test_11_remove_last_container(self):
os.environ['XDG_DATA_HOME'] = self.get_container_config_path()
cli_cmd = self.cmake_source_dir + '/tools/libertine-container-manager destroy -i test2'
args = shlex.split(cli_cmd)
subprocess.Popen(args).wait()
container_list = self.get_container_json_object()
self.assertThat(len(container_list), NotEquals(0))
self.assertThat(len(container_list['containerList']), Equals(0))
self.assertThat('defaultContainer' not in container_list, Equals(True))
./tests/CMakeLists.txt 0000644 0000156 0000165 00000000027 12702745445 015010 0 ustar jenkins jenkins add_subdirectory(unit)
./po/ 0000755 0000156 0000165 00000000000 12702745452 011523 5 ustar jenkins jenkins ./po/POTFILES.in.in 0000644 0000156 0000165 00000000051 12702745452 013701 0 ustar jenkins jenkins [type: gettext/ini] @GENERATED_POTFILES@
./po/en_US.po 0000644 0000156 0000165 00000023466 12702745452 013107 0 ustar jenkins jenkins # English translations for libertine package.
# Copyright (C) 2016 Canonical Ltd.
# This file is distributed under the same license as the PACKAGE package.
# Chris Townsend , 2016.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-04-08 16:01-0400\n"
"PO-Revision-Date: 2016-03-21 10:21-0400\n"
"Last-Translator: Chris Townsend \n"
"Language-Team: English\n"
"Language: en_US\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: ../libertine/qml/ExtraArchivesView.qml:34
msgid "Add a new PPA"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:43
msgid "Add additional PPA"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:133
msgid "Adding archive failed"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:26
msgid "Additional Archives and PPAs"
msgstr ""
#: ../libertine/qml/ConfigureContainer.qml:59
msgid "Additional archives and PPAs"
msgstr ""
#: ../libertine/qml/ContainerPasswordDialog.qml:27
msgid "Authentication required"
msgstr ""
#: ../libertine/qml/DebianPackagePicker.qml:7
msgid "Available Debian Packages to Install"
msgstr ""
#: ../libertine/qml/SearchPackagesDialog.qml:57
#: ../libertine/qml/ContainerPasswordDialog.qml:70
#: ../libertine/qml/HomeView.qml:86 ../libertine/qml/ExtraArchivesView.qml:62
#: ../libertine/qml/ContainerOptionsDialog.qml:75
msgid "Cancel"
msgstr ""
#: ../libertine/qml/HomeView.qml:136
msgid "Choose Debian package to install"
msgstr ""
#: ../libertine/qml/HomeView.qml:27
msgid "Classic Apps - %1"
msgstr "Classic Apps - %1"
#: ../libertine/qml/ConfigureContainer.qml:27
msgid "Configure %1"
msgstr "Configure %1"
#: ../libertine/qml/HomeView.qml:102
msgid "Configure Container"
msgstr "Configure Container"
#: ../libertine/qml/ContainerOptionsDialog.qml:28
#, fuzzy
msgid "Configure options for container creation."
msgstr "Configure Container"
#: ../libertine/qml/ContainersView.qml:96
msgid "Container Apps"
msgstr "Container Apps"
#: ../libertine/qml/ContainersView.qml:87
msgid "Container Info"
msgstr "Container Info"
#: ../libertine/qml/ContainerOptionsDialog.qml:27
#, fuzzy
msgid "Container Options"
msgstr "Container Apps"
#: ../libertine/qml/ContainerInfoView.qml:28
msgid "Container information for %1"
msgstr "Container information for %1"
#: ../libertine/qml/ContainersView.qml:69
msgid "Delete Container"
msgstr "Delete Container"
#: ../libertine/qml/ExtraArchivesView.qml:137
msgid "Dismiss"
msgstr ""
#: ../libertine/qml/ContainerInfoView.qml:62
#, fuzzy
msgid "Distribution"
msgstr "Distribution: %1"
#: ../libertine/qml/HomeView.qml:46
#, fuzzy
msgid "Enter exact package name or full path to a Debian package file"
msgstr "Please enter the exact package name of the app to install:"
#: ../libertine/qml/ExtraArchivesView.qml:44
msgid "Enter name of PPA in the form ppa:user/ppa-name:"
msgstr ""
#: ../libertine/qml/ContainerOptionsDialog.qml:50
msgid "Enter or name for the container or leave blank for default name"
msgstr ""
#: ../libertine/qml/HomeView.qml:130
#, fuzzy
msgid "Enter package name or Debian file"
msgstr "Please enter the exact package name of the app to install:"
#: ../libertine/qml/PackageInfoView.qml:66
msgid "Failure reason"
msgstr ""
#: ../libertine/qml/ContainerInfoView.qml:48
msgid "ID"
msgstr ""
#: ../libertine/qml/PackageInfoView.qml:28
msgid "Information for the %1 package"
msgstr "Information for the %1 package"
#: ../libertine/qml/WelcomeView.qml:58
msgid "Install"
msgstr "Install"
#: ../libertine/qml/SearchResults.qml:42
#: ../libertine/qml/DebianPackagePicker.qml:34
msgid "Install Package"
msgstr "Install Package"
#: ../libertine/qml/HomeView.qml:45
#, fuzzy
msgid "Install new package"
msgstr "Install Package"
#: ../libertine/qml/PackageInfoView.qml:58
#, fuzzy
msgid "Install status"
msgstr "Install status: %1"
#: ../libertine/qml/ContainerPasswordDialog.qml:36
msgid "Invalid password entered"
msgstr ""
#: ../libertine/qml/ContainersView.qml:31
msgid "My Containers"
msgstr "My Containers"
#: ../libertine/qml/ContainerInfoView.qml:55
#, fuzzy
msgid "Name"
msgstr "Name: %1"
#: ../libertine/qml/DebianPackagePicker.qml:53
msgid "No Debian packages available"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:49
#, fuzzy
msgid "No Search Results Found"
msgstr "No search results for %1."
#: ../libertine/qml/SearchPackagesDialog.qml:39
#: ../libertine/qml/ContainerPasswordDialog.qml:52
#: ../libertine/qml/HomeView.qml:65 ../libertine/qml/ExtraArchivesView.qml:54
#: ../libertine/qml/ContainerOptionsDialog.qml:64
msgid "OK"
msgstr ""
#: ../libertine/qml/PackageInfoView.qml:33
msgid "Obtaining package version…"
msgstr "Obtaining package version…"
#: ../libertine/qml/HomeView.qml:202
msgid "Package Info"
msgstr "Package Info"
#: ../libertine/qml/SearchResultsView.qml:28
msgid "Package Search Results"
msgstr ""
#: ../libertine/qml/HomeView.qml:56
msgid "Package name or Debian package path"
msgstr ""
#: ../libertine/qml/PackageInfoView.qml:51
#, fuzzy
msgid "Package version"
msgstr "Package version: %1"
#: ../libertine/qml/ContainerPasswordDialog.qml:28
msgid "Password is required to create a Libertine container"
msgstr ""
#: ../libertine/qml/HomeView.qml:188
msgid "Remove Package"
msgstr "Remove Package"
#: ../libertine/qml/ExtraArchivesView.qml:97
msgid "Remove extra archive"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:64
msgid "Return to Apps Page"
msgstr ""
#: ../libertine/qml/PackageExistsDialog.qml:43
#, fuzzy
msgid "Return to search results"
msgstr "No search results for %1."
#: ../libertine/qml/SearchResultsView.qml:38
msgid "Search"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:54
msgid "Search Again"
msgstr ""
#: ../libertine/qml/PackageExistsDialog.qml:33
msgid "Search again"
msgstr ""
#: ../libertine/qml/PackageExistsDialog.qml:29
msgid "Search again or return to search results."
msgstr ""
#: ../libertine/qml/HomeView.qml:143
msgid "Search archives for a package"
msgstr ""
#: ../libertine/qml/SearchPackagesDialog.qml:27
msgid "Search archives for packages"
msgstr ""
#: ../libertine/qml/SearchPackagesDialog.qml:26
#: ../libertine/qml/SearchResultsView.qml:39
msgid "Search for packages"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:90
#, fuzzy
msgid "Searching for packages…"
msgstr "Obtaining package version…"
#: ../libertine/qml/ContainerInfoView.qml:69
#, fuzzy
msgid "Status"
msgstr "Status: %1"
#: ../libertine/qml/HomeView.qml:114
msgid "Switch Container"
msgstr "Switch Container"
#: ../libertine/qml/PackageExistsDialog.qml:28
#, fuzzy
msgid "The %1 package is already installed."
msgstr "Please enter the exact package name of the app to install:"
#: ../libertine/qml/HomeView.qml:76
#, fuzzy
msgid ""
"The %1 package is already installed. Please try a different package name."
msgstr "Package %1 already installed. Please try a different package name."
#: ../libertine/qml/HomeView.qml:108
msgid "Update Container"
msgstr "Update Container"
#: ../libertine/qml/WelcomeView.qml:27
msgid "Welcome"
msgstr "Welcome"
#: ../libertine/qml/WelcomeView.qml:42
msgid "Welcome to the Ubuntu Legacy Application Support Manager."
msgstr "Welcome to the Ubuntu Legacy Application Support Manager."
#: ../libertine/qml/WelcomeView.qml:50
msgid ""
"You do not have Legacy Application Support configured at this time. "
"Downloading and setting up the required environment takes some time and "
"network bandwidth."
msgstr ""
"You do not have Legacy Application Support configured at this time. "
"Downloading and setting up the required environment takes some time and "
"network bandwidth."
#: ../libertine/qml/ExtraArchivesView.qml:33
msgid "add"
msgstr ""
#: ../libertine/qml/ContainerOptionsDialog.qml:56
#, fuzzy
msgid "container name"
msgstr "Container Info"
#: ../libertine/qml/ContainersView.qml:68 ../libertine/qml/HomeView.qml:187
msgid "delete"
msgstr "delete"
#: ../libertine/qml/ContainersView.qml:95
msgid "edit"
msgstr "edit"
#: ../libertine/ContainerConfig.cpp:152 ../libertine/ContainerConfig.cpp:186
#: ../libertine/qml/PackageInfoView.qml:120
msgid "failed"
msgstr "failed"
#: ../libertine/qml/ConfigureContainer.qml:55
#: ../libertine/qml/ContainerOptionsDialog.qml:40
msgid "i386 multiarch support"
msgstr "i386 multiarch support"
#: ../libertine/qml/ContainersView.qml:86 ../libertine/qml/HomeView.qml:201
msgid "info"
msgstr "info"
#: ../libertine/ContainerConfig.cpp:185
msgid "installed"
msgstr "installed"
#: ../libertine/ContainerConfig.cpp:148 ../libertine/ContainerConfig.cpp:184
#: ../libertine/qml/ContainersView.qml:51 ../libertine/qml/HomeView.qml:171
#: ../libertine/qml/ExtraArchivesView.qml:80
msgid "installing"
msgstr "installing"
#: ../libertine/ContainerConfig.cpp:147 ../libertine/ContainerConfig.cpp:183
msgid "new"
msgstr "new"
#: ../libertine/qml/ContainerPasswordDialog.qml:41
#, fuzzy
msgid "password"
msgstr "Password"
#: ../libertine/ContainerConfig.cpp:149
msgid "ready"
msgstr "ready"
#: ../libertine/qml/ExtraArchivesView.qml:96
#, fuzzy
msgid "remove"
msgstr "removed"
#: ../libertine/ContainerConfig.cpp:151 ../libertine/ContainerConfig.cpp:188
#: ../libertine/qml/PackageInfoView.qml:110
#: ../libertine/qml/ContainerInfoView.qml:88
msgid "removed"
msgstr "removed"
#: ../libertine/ContainerConfig.cpp:150 ../libertine/ContainerConfig.cpp:187
#: ../libertine/qml/ContainersView.qml:52 ../libertine/qml/HomeView.qml:172
#: ../libertine/qml/ExtraArchivesView.qml:81
msgid "removing"
msgstr "removing"
#: ../libertine/qml/SearchPackagesDialog.qml:31
msgid "search"
msgstr ""
#~ msgid "ID: %1"
#~ msgstr "ID: %1"
#~ msgid "Install Apps"
#~ msgstr "Install Apps"
#~ msgid "Please enter a package name to search for:"
#~ msgstr "Please enter a package name to search for:"
#~ msgid "Please enter the password for your user: "
#~ msgstr "Please enter the password for your user: "
./po/libertine.pot 0000644 0000156 0000165 00000020342 12702745452 014225 0 ustar jenkins jenkins # SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR Canonical Ltd.
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR , YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-04-08 16:01-0400\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME \n"
"Language-Team: LANGUAGE \n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ../libertine/ContainerConfig.cpp:147 ../libertine/ContainerConfig.cpp:183
msgid "new"
msgstr ""
#: ../libertine/ContainerConfig.cpp:148 ../libertine/ContainerConfig.cpp:184
#: ../libertine/qml/ContainersView.qml:51 ../libertine/qml/HomeView.qml:171
#: ../libertine/qml/ExtraArchivesView.qml:80
msgid "installing"
msgstr ""
#: ../libertine/ContainerConfig.cpp:149
msgid "ready"
msgstr ""
#: ../libertine/ContainerConfig.cpp:150 ../libertine/ContainerConfig.cpp:187
#: ../libertine/qml/ContainersView.qml:52 ../libertine/qml/HomeView.qml:172
#: ../libertine/qml/ExtraArchivesView.qml:81
msgid "removing"
msgstr ""
#: ../libertine/ContainerConfig.cpp:151 ../libertine/ContainerConfig.cpp:188
#: ../libertine/qml/PackageInfoView.qml:110
#: ../libertine/qml/ContainerInfoView.qml:88
msgid "removed"
msgstr ""
#: ../libertine/ContainerConfig.cpp:152 ../libertine/ContainerConfig.cpp:186
#: ../libertine/qml/PackageInfoView.qml:120
msgid "failed"
msgstr ""
#: ../libertine/ContainerConfig.cpp:185
msgid "installed"
msgstr ""
#: ../libertine/qml/PackageExistsDialog.qml:28
msgid "The %1 package is already installed."
msgstr ""
#: ../libertine/qml/PackageExistsDialog.qml:29
msgid "Search again or return to search results."
msgstr ""
#: ../libertine/qml/PackageExistsDialog.qml:33
msgid "Search again"
msgstr ""
#: ../libertine/qml/PackageExistsDialog.qml:43
msgid "Return to search results"
msgstr ""
#: ../libertine/qml/ContainersView.qml:31
msgid "My Containers"
msgstr ""
#: ../libertine/qml/ContainersView.qml:68 ../libertine/qml/HomeView.qml:187
msgid "delete"
msgstr ""
#: ../libertine/qml/ContainersView.qml:69
msgid "Delete Container"
msgstr ""
#: ../libertine/qml/ContainersView.qml:86 ../libertine/qml/HomeView.qml:201
msgid "info"
msgstr ""
#: ../libertine/qml/ContainersView.qml:87
msgid "Container Info"
msgstr ""
#: ../libertine/qml/ContainersView.qml:95
msgid "edit"
msgstr ""
#: ../libertine/qml/ContainersView.qml:96
msgid "Container Apps"
msgstr ""
#: ../libertine/qml/ConfigureContainer.qml:27
msgid "Configure %1"
msgstr ""
#: ../libertine/qml/ConfigureContainer.qml:55
#: ../libertine/qml/ContainerOptionsDialog.qml:40
msgid "i386 multiarch support"
msgstr ""
#: ../libertine/qml/ConfigureContainer.qml:59
msgid "Additional archives and PPAs"
msgstr ""
#: ../libertine/qml/SearchPackagesDialog.qml:26
#: ../libertine/qml/SearchResultsView.qml:39
msgid "Search for packages"
msgstr ""
#: ../libertine/qml/SearchPackagesDialog.qml:27
msgid "Search archives for packages"
msgstr ""
#: ../libertine/qml/SearchPackagesDialog.qml:31
msgid "search"
msgstr ""
#: ../libertine/qml/SearchPackagesDialog.qml:39
#: ../libertine/qml/ContainerPasswordDialog.qml:52
#: ../libertine/qml/HomeView.qml:65 ../libertine/qml/ExtraArchivesView.qml:54
#: ../libertine/qml/ContainerOptionsDialog.qml:64
msgid "OK"
msgstr ""
#: ../libertine/qml/SearchPackagesDialog.qml:57
#: ../libertine/qml/ContainerPasswordDialog.qml:70
#: ../libertine/qml/HomeView.qml:86 ../libertine/qml/ExtraArchivesView.qml:62
#: ../libertine/qml/ContainerOptionsDialog.qml:75
msgid "Cancel"
msgstr ""
#: ../libertine/qml/PackageInfoView.qml:28
msgid "Information for the %1 package"
msgstr ""
#: ../libertine/qml/PackageInfoView.qml:33
msgid "Obtaining package version…"
msgstr ""
#: ../libertine/qml/PackageInfoView.qml:51
msgid "Package version"
msgstr ""
#: ../libertine/qml/PackageInfoView.qml:58
msgid "Install status"
msgstr ""
#: ../libertine/qml/PackageInfoView.qml:66
msgid "Failure reason"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:28
msgid "Package Search Results"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:38
msgid "Search"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:49
msgid "No Search Results Found"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:54
msgid "Search Again"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:64
msgid "Return to Apps Page"
msgstr ""
#: ../libertine/qml/SearchResultsView.qml:90
msgid "Searching for packages…"
msgstr ""
#: ../libertine/qml/SearchResults.qml:42
#: ../libertine/qml/DebianPackagePicker.qml:34
msgid "Install Package"
msgstr ""
#: ../libertine/qml/DebianPackagePicker.qml:7
msgid "Available Debian Packages to Install"
msgstr ""
#: ../libertine/qml/DebianPackagePicker.qml:53
msgid "No Debian packages available"
msgstr ""
#: ../libertine/qml/ContainerPasswordDialog.qml:27
msgid "Authentication required"
msgstr ""
#: ../libertine/qml/ContainerPasswordDialog.qml:28
msgid "Password is required to create a Libertine container"
msgstr ""
#: ../libertine/qml/ContainerPasswordDialog.qml:36
msgid "Invalid password entered"
msgstr ""
#: ../libertine/qml/ContainerPasswordDialog.qml:41
msgid "password"
msgstr ""
#: ../libertine/qml/HomeView.qml:27
msgid "Classic Apps - %1"
msgstr ""
#: ../libertine/qml/HomeView.qml:45
msgid "Install new package"
msgstr ""
#: ../libertine/qml/HomeView.qml:46
msgid "Enter exact package name or full path to a Debian package file"
msgstr ""
#: ../libertine/qml/HomeView.qml:56
msgid "Package name or Debian package path"
msgstr ""
#: ../libertine/qml/HomeView.qml:76
msgid ""
"The %1 package is already installed. Please try a different package name."
msgstr ""
#: ../libertine/qml/HomeView.qml:102
msgid "Configure Container"
msgstr ""
#: ../libertine/qml/HomeView.qml:108
msgid "Update Container"
msgstr ""
#: ../libertine/qml/HomeView.qml:114
msgid "Switch Container"
msgstr ""
#: ../libertine/qml/HomeView.qml:130
msgid "Enter package name or Debian file"
msgstr ""
#: ../libertine/qml/HomeView.qml:136
msgid "Choose Debian package to install"
msgstr ""
#: ../libertine/qml/HomeView.qml:143
msgid "Search archives for a package"
msgstr ""
#: ../libertine/qml/HomeView.qml:188
msgid "Remove Package"
msgstr ""
#: ../libertine/qml/HomeView.qml:202
msgid "Package Info"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:26
msgid "Additional Archives and PPAs"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:33
msgid "add"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:34
msgid "Add a new PPA"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:43
msgid "Add additional PPA"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:44
msgid "Enter name of PPA in the form ppa:user/ppa-name:"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:96
msgid "remove"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:97
msgid "Remove extra archive"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:133
msgid "Adding archive failed"
msgstr ""
#: ../libertine/qml/ExtraArchivesView.qml:137
msgid "Dismiss"
msgstr ""
#: ../libertine/qml/WelcomeView.qml:27
msgid "Welcome"
msgstr ""
#: ../libertine/qml/WelcomeView.qml:42
msgid "Welcome to the Ubuntu Legacy Application Support Manager."
msgstr ""
#: ../libertine/qml/WelcomeView.qml:50
msgid ""
"You do not have Legacy Application Support configured at this time. "
"Downloading and setting up the required environment takes some time and "
"network bandwidth."
msgstr ""
#: ../libertine/qml/WelcomeView.qml:58
msgid "Install"
msgstr ""
#: ../libertine/qml/ContainerInfoView.qml:28
msgid "Container information for %1"
msgstr ""
#: ../libertine/qml/ContainerInfoView.qml:48
msgid "ID"
msgstr ""
#: ../libertine/qml/ContainerInfoView.qml:55
msgid "Name"
msgstr ""
#: ../libertine/qml/ContainerInfoView.qml:62
msgid "Distribution"
msgstr ""
#: ../libertine/qml/ContainerInfoView.qml:69
msgid "Status"
msgstr ""
#: ../libertine/qml/ContainerOptionsDialog.qml:27
msgid "Container Options"
msgstr ""
#: ../libertine/qml/ContainerOptionsDialog.qml:28
msgid "Configure options for container creation."
msgstr ""
#: ../libertine/qml/ContainerOptionsDialog.qml:50
msgid "Enter or name for the container or leave blank for default name"
msgstr ""
#: ../libertine/qml/ContainerOptionsDialog.qml:56
msgid "container name"
msgstr ""
./po/CMakeLists.txt 0000644 0000156 0000165 00000000651 12702745452 014265 0 ustar jenkins jenkins set (GETTEXT_PACKAGE "libertine")
intltool_update_potfile(
ALL
UBUNTU_SDK_DEFAULTS
POTFILES_TEMPLATE POTFILES.in.in
COPYRIGHT_HOLDER "Canonical Ltd."
GETTEXT_PACKAGE ${GETTEXT_PACKAGE}
)
intltool_install_translations(
ALL
GETTEXT_PACKAGE ${GETTEXT_PACKAGE}
)
file(GLOB_RECURSE ALL_POFILES "*.po")
add_custom_target(potfiles
ALL
SOURCES
POTFILES.in.in
${GETTEXT_PACKAGE}.pot
${ALL_POFILES}
)
./tools/ 0000755 0000156 0000165 00000000000 12702745452 012245 5 ustar jenkins jenkins ./tools/libertine-launch.1 0000644 0000156 0000165 00000000707 12702745452 015560 0 ustar jenkins jenkins .TH libertine-launch "1" "April 2016" "libertine-launch 0.99" "User Commands"
.SH NAME
libertine-launch \- launch an application in a Libertine container
.SH DESCRIPTION
usage: libertine\-launch [\-h] container_id ...
.PP
launch an application in a Libertine container
.SS "positional arguments:"
.TP
container_id
Libertine container ID
.TP
app_exec_line
exec line
.SS "optional arguments:"
.TP
\fB\-h\fR, \fB\-\-help\fR
show this help message and exit
./tools/libertine-container-manager.1 0000644 0000156 0000165 00000013713 12702745452 017701 0 ustar jenkins jenkins .TH libertine-container-manager "1" " April 2016" "libertine-container-manager 0.99" "User Commands"
.SH NAME
libertine-container-manager \- Manage Libertine containers for supporting legacy X applications on Unity 8
.SH SYNOPSIS
.B libertine-container-manager
[ -v | -q ]
.I command
[
.I command_options
]
.br
.B libertine-container-manager
-h
.br
.B libertine-container-manager
.I command
-h
.SH DESCRIPTION
libertine-container-manager is a utility for managing Libertine containers used to support legacy X applications on Unity 8.
It is possible to create new containers, delete containers, update containers, install new packages in a container, remove a package from a container, search for possible packages to install, and list all of the current containers.
.SH OPTIONS
.TP
.BR \-q ", " \-\-quiet ""
do not print status updates on stdout
.TP
.BR \-v ", " \-\-verbose ""
extra verbose output
.TP
.BR \-h ", " \-\-help ""
Print a summary of the command line options and exit.
.SH COMMAND OVERVIEW
.TP
.B libertine-container-manager create [options]
Create a new Libertine container.
.TP
.B libertine-container-manager destroy [options]
Destroy (delete) an existing Liberine container.
.TP
.B libertine-container-manager install-package [options]
Install a package inside an existing Libertine container.
.TP
.B libertine-container-manager remove-package [options]
Remove an installed package inside an existing Libertine container.
.TP
.B libertine-container-manager search-cache [options]
Searches the apt cache inside an existing Libertine container for matches based on the given search string.
.TP
.B libertine-container-manager update [options]
Updates the packages inside an existing Libertine container.
.TP
.B libertine-container-manager list [options]
Lists all existing Libertine containers.
.TP
.B libertine-container-manager list-apps [options]
Lists available app launchers in a container.
.TP
.B libertine-container-manager exec [options]
Runs an arbitrary command in the specified Libertine container.
.TP
.B libertine-container-manager configure [options]
Configures various options in the specified Libertine container.
.SH COMMAND REFERENCE
.TP
.B libertine-container-manager create [options]
.TP
.SS Options:
.BR \-h ", " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.IP
.BR \-i " ID, " \-\-id " ID" ""
.RS 14
Container identifier. Required.
.RE
.IP
.BR \-t " TYPE, " \-\-type " TYPE" ""
.RS 14
Type of Libertine container to create. Either 'lxc' or 'chroot'.
.RE
.IP
.BR \-\-password " password" ""
.RS 14
User's password for creating LXC containers. Intended for testing only.
.RE
.IP
.BR \-d " DISTRO, " \-\-distro " DISTRO" ""
.RS 14
Ubuntu distro series to create.
.RE
.IP
.BR \-n " NAME, " \-\-name " NAME" ""
.RS 14
User friendly container name.
.RE
.IP
.BR \-\-force ""
.RS 14
Force installation of unsupported distro.
.RE
.IP
.BR \-m ", " \-\-multiarch ""
.RS 14
Enable i386 support.
.RE
.TP
.B libertine-container-manager destroy [options]
.TP
.SS Options:
.BR \-h " , " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.IP
.BR \-i " ID, " \-\-id " ID" ""
.RS 14
Container identifier. Default container is used if omitted.
.RE
.TP
.B libertine-container-manager install-package [options]
.TP
.SS Options:
.BR \-h ", " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.IP
.BR \-i " ID, " \-\-id " ID" ""
.RS 14
Container identifier. Default container is used if omitted.
.RE
.IP
.BR \-p " PACKAGE, " \-\-package " PACKAGE" ""
.RS 14
Name of package to install. Required.
.RE
.TP
.B libertine-container-manager remove-package [options]
.TP
.SS Options:
.BR \-h ", " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.IP
.BR \-i " ID, " \-\-id " ID" ""
.RS 14
Container identifier. Default container is used if omitted.
.RE
.IP
.BR \-p " PACKAGE, " \-\-package " PACKAGE" ""
.RS 14
Name of package to remove. Required.
.RE
.TP
.B libertine-container-manager search-cache [options]
.TP
.SS Options:
.BR \-h ", " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.IP
.BR \-i " ID, " \-\-id " ID" ""
.RS 14
Container identifier. Default container is used if omitted.
.RE
.IP
.BR \-s " SEARCH_STRING, " \-\-search-string " SEARCH_STRING" ""
.RS 14
String to search for in the package cache. Required.
.RE
.TP
.B libertine-container-manager update [options]
.TP
.SS Options:
.BR \-h ", " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.IP
.BR \-i " ID, " \-\-id " ID" ""
.RS 14
Container identifier. Default container is used if omitted.
.RE
.TP
.B libertine-container-manager list
.TP
.SS Options:
.BR \-h ", " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.TP
.B libertine-container-manager list-apps [options]
.TP
.SS Options:
.BR \-h ", " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.IP
.BR \-i " ID, " \-\-id " ID" ""
.RS 14
Container identifier. Default container is used if omitted.
.RE
.IP
.BR \-j ", " \-\-json ""
.RS 14
Uses JSON output format.
.RE
.TP
.B libertine-container-manager exec [options]
.TP
.SS Options:
.BR \-h ", " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.IP
.BR \-i " ID, " \-\-id " ID" ""
.RS 14
Container identifier. Default container is used if omitted.
.RE
.IP
.BR \-C " COMMAND, " \-\-command " COMMAND" ""
.RS 14
The command to be executed.
.RE
.TP
.B libertine-container-manager configure [options]
.TP
.SS Options:
.BR \-h ", " \-\-help ""
.RS 14
Prints help for this command and exits.
.RE
.IP
.BR \-i " ID, " \-\-id " ID" ""
.RS 14
Container identifier. Default container is used if omitted.
.RE
.IP
.BR \-m ", " \-\-multiarch ""
.RS 14
Enable i386 support.
.RE
.IP
.BR \-a " ARCHIVE_NAME, " \-\-add-archive " ARCHIVE_NAME" ""
.RS 14
Adds an archive to the specified container. Format like "ppa:user/ppa-name".
.RE
.IP
.BR \-d " ARCHIVE_NAME, " \-\-delete-archive " ARCHIVE_NAME" ""
.RS 14
Deletes an archive to the specified container. Format like "ppa:user/ppa-name".
.RE
.TP
.SH SEE ALSO
.UR https://launchpad.net/libertine
.BR https://launchpad.net/libertine
./tools/libertine-lxc-manager.1 0000644 0000156 0000165 00000000411 12702745452 016474 0 ustar jenkins jenkins .TH libertine-lxc-manager "1" "April 2016" "libertine-lxc-manager 0.99" "User Commands"
.SH NAME
libertine-lxc-manager \- monitors LXC activity performed by libertine
.SH DESCRIPTION
usage: libertine\-lxc\-manager
.PP
monitors LXC activity performed by libertine
./tools/libertine-launch 0000755 0000156 0000165 00000005467 12702745452 015434 0 ustar jenkins jenkins #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (C) 2015 Canonical Ltd.
# Author: Christopher Townsend
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import argparse
import os
import libertine.utils
import psutil
import shlex
import time
from libertine import LibertineContainer
def set_dbus_session_socket_path():
unique_id = os.environ['DISPLAY'].strip(':')
if not os.path.exists(libertine.utils.get_libertine_runtime_dir()):
os.makedirs(libertine.utils.get_libertine_runtime_dir())
dbus_session_socket_path = (
os.path.join(libertine.utils.get_libertine_runtime_dir(), 'host_dbus_session' + unique_id))
os.environ['DBUS_SESSION_BUS_ADDRESS'] = "unix:path=" + dbus_session_socket_path
return dbus_session_socket_path
def launch_libertine_session_bridge(session_socket_path):
libertine_session_bridge_cmd = "libertine-session-bridge " + session_socket_path
args = shlex.split(libertine_session_bridge_cmd)
return psutil.Popen(args)
def detect_session_bridge_socket(session_socket_path):
retries = 0
while not os.path.exists(session_socket_path):
if retries >= 10:
raise RuntimeError("Timeout waiting for Libertine Dbus session bridge socket")
print("Libertine Dbus session bridge socket is not ready. Waiting...")
retries += 1
time.sleep(.5)
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(description='launch an application in a Libertine container')
arg_parser.add_argument('container_id',
help='Libertine container ID')
arg_parser.add_argument('app_exec_line', nargs=argparse.REMAINDER,
help='exec line')
args = arg_parser.parse_args()
if not libertine.utils.container_exists(args.container_id):
raise RuntimeError("Container ID %s does not exist." % args.container_id)
session_socket_path = set_dbus_session_socket_path()
session_bridge = launch_libertine_session_bridge(session_socket_path)
detect_session_bridge_socket(session_socket_path)
container = LibertineContainer(args.container_id)
try:
container.launch_application(args.app_exec_line)
except:
raise
finally:
session_bridge.terminate()
./tools/libertine-xmir 0000755 0000156 0000165 00000001373 12702745445 015133 0 ustar jenkins jenkins #!/bin/sh
# Copyright (C) 2016 Canonical Ltd.
# Author: Christopher Townsend
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
# Add and/or remove Xmir options here
exec Xmir -title @ $@
./tools/libertine-session-bridge 0000755 0000156 0000165 00000006343 12702745445 017073 0 ustar jenkins jenkins #!/usr/bin/python3
import libertine.utils
import os
import select
import signal
import sys
from socket import *
def accept_new_connection():
newconn = container_dbus_session_sock.accept()[0]
descriptors.append(newconn)
host_dbus_session_sock = socket(AF_UNIX, SOCK_STREAM)
host_dbus_session_sock.connect(host_dbus_session_addr)
descriptors.append(host_dbus_session_sock)
socket_pairs.append([newconn, host_dbus_session_sock])
def get_socket_pair(socket):
for i in range(len(socket_pairs)):
if socket in socket_pairs[i]:
return socket_pairs[i]
def get_socket_partner(socket):
socket_pair = get_socket_pair(socket)
for i in range(len(socket_pair)):
if socket != socket_pair[i]:
return socket_pair[i]
def close_connections(remove_socket):
partner_socket = get_socket_partner(remove_socket)
socket_pair = get_socket_pair(remove_socket)
socket_pairs.remove(socket_pair)
descriptors.remove(remove_socket)
remove_socket.shutdown(SHUT_RDWR)
remove_socket.close()
descriptors.remove(partner_socket)
partner_socket.shutdown(SHUT_RDWR)
partner_socket.close()
def close_all_connections():
for i, j in socket_pairs:
i.shutdown(SHUT_RDWR)
i.close()
j.shutdown(SHUT_RDWR)
j.close()
def get_host_dbus_socket():
socket_key = "DBUS_SESSION_BUS_ADDRESS=unix:abstract="
with open(os.path.join(libertine.utils.get_user_runtime_dir(), 'dbus-session'), 'r') as fd:
dbus_session_str = fd.read()
fd.close()
host_dbus_socket = dbus_session_str.partition(socket_key)[2]
host_dbus_socket = host_dbus_socket.rstrip('\n')
host_dbus_socket = "\0%s" % host_dbus_socket
return host_dbus_socket
def socket_cleanup(signum, frame):
container_dbus_session_sock.close()
close_all_connections()
os.remove(dbus_session_socket_path)
def main_loop():
signal.signal(signal.SIGTERM, socket_cleanup)
signal.signal(signal.SIGINT, socket_cleanup)
while 1:
try:
rlist, wlist, elist = select.select(descriptors, [], [])
except InterruptedError:
continue
except:
break
for sock in rlist:
if sock.fileno() == -1:
continue
if sock == container_dbus_session_sock:
accept_new_connection()
else:
data = sock.recv(4096)
if len(data) == 0:
close_connections(sock)
continue
send_sock = get_socket_partner(sock)
if send_sock.fileno() < 0:
continue
totalsent = 0
while totalsent < len(data):
sent = send_sock.send(data)
if sent == 0:
close_connections(sock)
break
totalsent = totalsent + sent
dbus_session_socket_path = sys.argv[1]
container_dbus_session_sock = socket(AF_UNIX, SOCK_STREAM)
container_dbus_session_sock.bind(dbus_session_socket_path)
container_dbus_session_sock.listen(5)
host_dbus_session_addr = get_host_dbus_socket()
descriptors = [container_dbus_session_sock]
socket_pairs = []
main_loop()
./tools/libertine-session-bridge.1 0000644 0000156 0000165 00000000547 12702745452 017225 0 ustar jenkins jenkins .TH libertine-session-bridge "1" "April 2016" "libertine-session-bridge 0.99" "User Commands"
.SH NAME
libertine-session-bridge \- listen for data from a DBUS session
.SH DESCRIPTION
usage: libertine\-session-bridge DBUS_SOCKET
.PP
listen for data from a DBUS session on the given socket path
.SS "positional arguments:"
.TP
DBUS_SOCKET
path to DBUS socket
./tools/libertine-xmir.1 0000644 0000156 0000165 00000000336 12702745452 015263 0 ustar jenkins jenkins .TH libertine-xmir "1" "April 2016" "libertine-xmir 0.99" "User Commands"
.SH NAME
libertine-xmir \- runs an xmir session
.SH DESCRIPTION
usage: libertine\-xmir
.PP
runs an xmir session with the given positional options
./tools/libertine-container-manager 0000755 0000156 0000165 00000056510 12702745452 017547 0 ustar jenkins jenkins #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2016 Canonical Ltd.
# Author: Christopher Townsend
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import argparse
import fcntl
import json
import libertine.utils
import lsb_release
import getpass
import os
import platform
import sys
from apt.debfile import DebPackage
from distro_info import UbuntuDistroInfo, DistroDataOutdated
from libertine import LibertineContainer
def read_container_config_file():
container_list = {}
container_config_file = libertine.utils.get_libertine_database_file_path()
if (os.path.exists(container_config_file) and
os.path.getsize(container_config_file) != 0):
with open(container_config_file, 'r') as fd:
container_list = json.load(fd)
return container_list
def write_container_config_file(container_list):
container_config_file = libertine.utils.get_libertine_database_file_path()
with open(container_config_file, 'w') as fd:
fcntl.lockf(fd, fcntl.LOCK_EX)
json.dump(container_list, fd, sort_keys=True, indent=4)
fd.write('\n')
fcntl.lockf(fd, fcntl.LOCK_UN)
def get_default_container_id():
default_container_id = None
container_list = read_container_config_file()
if "defaultContainer" in container_list:
default_container_id = container_list['defaultContainer']
return default_container_id
def select_container_type():
kernel_release = platform.release().split('.')
if int(kernel_release[0]) >= 4:
return "lxc"
elif int(kernel_release[0]) == 3 and int(kernel_release[1]) >= 13:
return "lxc"
else:
return "chroot"
def get_host_distro_release():
distinfo = lsb_release.get_distro_information()
return distinfo.get('CODENAME', 'n/a')
def is_distro_valid(distro, force):
if force:
return UbuntuDistroInfo().valid(distro)
supported_distros = UbuntuDistroInfo().supported()
try:
supported_distros.index(distro)
except ValueError:
return False
return True
def get_distro_codename(distro):
ubuntu_distro_info = UbuntuDistroInfo()
for row in ubuntu_distro_info._rows:
if row['series'] == distro:
return row['codename']
return None
def update_container_install_status(container_id, new_status):
container_list = read_container_config_file()
for container in container_list['containerList']:
if container['id'] == container_id:
container['installStatus'] = new_status
write_container_config_file(container_list)
break
def update_container_multiarch_support(container_id, multiarch):
container_list = read_container_config_file()
if multiarch == 'enabled' and libertine.utils.get_host_architecture() == 'i386':
multiarch = 'disabled'
for container in container_list['containerList']:
if container['id'] == container_id:
container['multiarch'] = multiarch
write_container_config_file(container_list)
break
def get_container_multiarch_support(container_id):
container_list = read_container_config_file()
for container in container_list['containerList']:
if container['id'] == container_id:
if not 'multiarch' in container:
return 'disabled'
else:
return container['multiarch']
def update_archive_install_status(container_id, archive_name, new_status):
container_list = read_container_config_file()
for container in container_list['containerList']:
if container['id'] == container_id:
for archive in container['extraArchives']:
if archive['archiveName'] == archive_name:
archive['archiveStatus'] = new_status
write_container_config_file(container_list)
return
def add_container_archive(container_id, archive_name):
container_list = read_container_config_file()
for container in container_list['containerList']:
if container['id'] == container_id:
archive_obj = {'archiveName': archive_name, 'archiveStatus': 'new'}
if 'extraArchives' not in container:
container['extraArchives'] = [archive_obj]
else:
container['extraArchives'].append(archive_obj)
write_container_config_file(container_list)
break
def delete_container_archive(container_id, archive_name):
container_list = read_container_config_file()
for container in container_list['containerList']:
if container['id'] == container_id:
for archive in container['extraArchives']:
if archive['archiveName'] == archive_name:
container['extraArchives'].remove(archive)
write_container_config_file(container_list)
return
print("%s does not exist." % archive_name)
sys.exit(1)
def archive_exists(container_id, archive_name):
container_list = read_container_config_file()
for container in container_list['containerList']:
if container['id'] == container_id:
if 'extraArchives' not in container:
return False
else:
for archive in container['extraArchives']:
if archive['archiveName'] == archive_name:
return True
return False
def add_new_container(id, name, type, distro):
if not os.path.exists(libertine.utils.get_libertine_database_dir_path()):
os.makedirs(libertine.utils.get_libertine_database_dir_path())
container_list = read_container_config_file()
container_obj = {'id': id, 'installStatus': 'new', 'type': type,
'distro': distro, 'name': name, 'installedApps': []}
if "defaultContainer" not in container_list:
container_list['defaultContainer'] = id
if "containerList" not in container_list:
container_list['containerList'] = [container_obj]
else:
container_list['containerList'].append(container_obj)
write_container_config_file(container_list)
def delete_container(container_id):
container_list = read_container_config_file()
if not container_list:
print("Unable to delete container. No containers defined.")
sys.exit(1)
for container in container_list['containerList']:
if container['id'] == container_id:
container_list['containerList'].remove(container)
# Set a new defaultContainer if the current default is being deleted.
if container_list['defaultContainer'] == container_id and container_list['containerList']:
container_list['defaultContainer'] = container_list['containerList'][0]['id']
# Remove the defaultContainer if there are no more containers left.
elif not container_list['containerList']:
del container_list['defaultContainer']
write_container_config_file(container_list)
break
def package_exists(container_id, package_name):
container_list = read_container_config_file()
if not container_list:
return False
for container in container_list['containerList']:
if container['id'] == container_id:
for package in container['installedApps']:
if package['packageName'] == package_name:
return True
return False
def update_package_install_status(container_id, package_name, new_status):
container_list = read_container_config_file()
for container in container_list['containerList']:
if container['id'] == container_id:
for package in container['installedApps']:
if package['packageName'] == package_name:
package['appStatus'] = new_status
write_container_config_file(container_list)
return
def add_new_package(container_id, package_name):
container_list = read_container_config_file()
if not container_list:
print("No containers defined. Please create a new container before installing a package.")
sys.exit(1)
for container in container_list['containerList']:
if container['id'] == container_id:
package_obj = {'packageName': package_name, 'appStatus': 'new'}
if not container['installedApps']:
container['installedApps'] = [package_obj]
else:
container['installedApps'].append(package_obj)
write_container_config_file(container_list)
break
def delete_package(container_id, package_name):
container_list = read_container_config_file()
if not container_list:
print("No containers defined. Please create a new container before installing a package.")
sys.exit(1)
for container in container_list['containerList']:
if container['id'] == container_id:
for package in container['installedApps']:
if package['packageName'] == package_name:
container['installedApps'].remove(package)
write_container_config_file(container_list)
return
print("Package \'%s\' does not exist." % package_name)
sys.exit(1)
def create(args):
password = None
if args.distro and not is_distro_valid(args.distro, args.force):
print("Invalid distro %s" % args.distro, file=sys.stderr)
sys.exit(1)
if args.id and libertine.utils.container_exists(args.id):
print("Container id \'%s\' is already used." % args.id, file=sys.stderr)
sys.exit(1)
elif not args.id:
args.id = get_unique_container_id(distro)
if not args.distro:
args.distro = get_host_distro_release()
if not args.name:
args.name = "Ubuntu \'" + get_distro_codename(args.distro) + "\'"
if not args.type:
container_type = select_container_type()
else:
container_type = args.type
if container_type == "lxc":
if args.password:
password = args.password
elif sys.stdin.isatty():
print("Your user password is required for creating a Libertine container.")
password = getpass.getpass()
else:
password = sys.stdin.readline().rstrip()
add_new_container(args.id, args.name, container_type, args.distro)
multiarch = 'disabled'
if args.multiarch:
multiarch = 'enabled'
update_container_multiarch_support(args.id, multiarch)
container = LibertineContainer(args.id)
update_container_install_status(args.id, "installing")
if not container.create_libertine_container(password, args.multiarch, args.verbosity):
delete_container(args.id)
sys.exit(1)
update_container_install_status(args.id, "ready")
def destroy(args):
if args.id and not libertine.utils.container_exists(args.id):
print("Container id \'%s\' does not exist." % args.id, file=sys.stderr)
sys.exit(1)
elif not args.id:
args.id = get_default_container_id()
container = LibertineContainer(args.id)
update_container_install_status(args.id, "removing")
container.destroy_libertine_container()
update_container_install_status(args.id, "removed")
delete_container(args.id)
def install_package(args):
if args.id and not libertine.utils.container_exists(args.id):
print("Container id \'%s\' does not exist." % args.id, file=sys.stderr)
sys.exit(1)
elif not args.id:
args.id = get_default_container_id()
is_debian_package = args.package.endswith('.deb')
if is_debian_package:
if os.path.exists(args.package):
package = DebPackage(args.package).pkgname
else:
print("%s does not exist." % args.package)
sys.exit(1)
else:
package = args.package
if package_exists(args.id, package):
if not is_debian_package:
print("Package \'%s\' is already installed." % package)
sys.exit(1)
else:
add_new_package(args.id, package)
container = LibertineContainer(args.id)
update_package_install_status(args.id, package, "installing")
if not container.install_package(args.package, args.verbosity):
delete_package(args.id, package)
sys.exit(1)
update_package_install_status(args.id, package, "installed")
def remove_package(args):
if args.id and not libertine.utils.container_exists(args.id):
print("Container id \'%s\' does not exist." % args.id, file=sys.stderr)
sys.exit(1)
elif not args.id:
args.id = get_default_container_id()
if not package_exists(args.id, args.package):
print("Package \'%s\' is not installed." % args.package)
sys.exit(1)
container = LibertineContainer(args.id)
update_package_install_status(args.id, args.package, "removing")
container.remove_package(args.package, args.verbosity)
update_package_install_status(args.id, args.package, "removed")
delete_package(args.id, args.package)
def search_cache(args):
if args.id and not libertine.utils.container_exists(args.id):
print("Container id \'%s\' does not exist." % args.id, file=sys.stderr)
sys.exit(1)
elif not args.id:
args.id = get_default_container_id()
container = LibertineContainer(args.id)
container.search_package_cache(args.search_string)
def update(args):
if args.id and not libertine.utils.container_exists(args.id):
print("Container id \'%s\' does not exist." % args.id, file=sys.stderr)
sys.exit(1)
elif not args.id:
args.id = get_default_container_id()
container = LibertineContainer(args.id)
container.update_libertine_container(args.verbosity)
def list(args):
containers = libertine.utils.Libertine.list_containers()
for container in containers:
print("%s" % container)
def list_apps(args):
if args.id and not libertine.utils.container_exists(args.id):
print("Container id \'%s\' does not exist." % args.id, file=sys.stderr)
sys.exit(1)
elif not args.id:
args.id = get_default_container_id()
container = LibertineContainer(args.id)
print(container.list_app_launchers(use_json=args.json))
def exec(args):
if args.id and not libertine.utils.container_exists(args.id):
print("Container id \'%s\' does not exist." % args.id, file=sys.stderr)
sys.exit(1)
elif not args.id:
args.id = get_default_container_id()
container = LibertineContainer(args.id)
sys.exit(container.exec_command(args.command))
def configure(args):
if args.id and not libertine.utils.container_exists(args.id):
print("Container id \'%s\' does not exist." % args.id, file=sys.stderr)
sys.exit(1)
elif not args.id:
args.id = get_default_container_id()
container = LibertineContainer(args.id)
if args.multiarch and libertine.utils.get_host_architecture() == 'amd64':
multiarch = 'disabled'
if args.multiarch == 'enable':
multiarch = 'enabled'
current_multiarch = get_container_multiarch_support(args.id)
if current_multiarch == multiarch:
print("i386 multiarch support is already %s" % multiarch)
sys.exit(1)
container.configure_command('multiarch', args.multiarch)
update_container_multiarch_support(args.id, multiarch)
elif args.add_archive:
if archive_exists(args.id, args.add_archive):
print("%s already added in container." % args.add_archive)
sys.exit(1)
add_container_archive(args.id, args.add_archive)
update_archive_install_status(args.id, args.add_archive, 'installing')
if container.configure_command('add-archive', args.add_archive) != 0:
delete_container_archive(args.id, args.add_archive)
sys.exit(1)
update_archive_install_status(args.id, args.add_archive, 'installed')
elif args.delete_archive:
if not archive_exists(args.id, args.delete_archive):
print("%s is not added in container." % args.delete_archive)
sys.exit(1)
update_archive_install_status(args.id, args.delete_archive, 'removing')
if container.configure_command('delete-archive', args.delete_archive) != 0:
sys.exit(1)
delete_container_archive(args.id, args.delete_archive)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Legacy X application support for Unity 8")
parser.add_argument('-q', '--quiet',
action='store_const', dest='verbosity', const=0,
help=('do not print status updates on stdout'))
parser.add_argument('-v', '--verbose',
action='store_const', dest='verbosity', const=2,
help=('extra verbose output'))
subparsers = parser.add_subparsers(dest="subparser_name")
# Handle the create command and its options
parser_create = subparsers.add_parser(
'create',
help=("Create a new Libertine container."))
parser_create.add_argument(
'-i', '--id',
required=True,
help=("Container identifier. Required."))
parser_create.add_argument(
'-t', '--type',
help=("Type of Libertine container to create. Either 'lxc' or 'chroot'."))
parser_create.add_argument(
'-d', '--distro',
help=("Ubuntu distro series to create."))
parser_create.add_argument(
'-n', '--name',
help=("User friendly container name."))
parser_create.add_argument(
'--force', action='store_true',
help=("Force the installation of the given valid Ubuntu distro even if "
"it is no longer supported."))
parser_create.add_argument(
'-m', '--multiarch', action='store_true',
help=("Add i386 support to amd64 Libertine containers. This option has "
"no effect when the Libertine container is i386."))
parser_create.add_argument(
'--password',
help=("Pass in the user's password when creating an LXC container. This "
"is intended for testing only and is very insecure."))
parser_create.set_defaults(func=create)
# Handle the destroy command and its options
parser_destroy = subparsers.add_parser(
'destroy',
help=("Destroy any existing environment entirely."))
parser_destroy.add_argument(
'-i', '--id',
help=("Container identifier. Default container is used if omitted."))
parser_destroy.set_defaults(func=destroy)
# Handle the install-package command and its options
parser_install = subparsers.add_parser(
'install-package',
help=("Install a package in the specified Libertine container."))
parser_install.add_argument(
'-p', '--package',
required=True,
help=("Name of package to install or full path to a Debian package. Required."))
parser_install.add_argument(
'-i', '--id',
help=("Container identifier. Default container is used if omitted."))
parser_install.set_defaults(func=install_package)
# Handle the remove-package command and its options
parser_install = subparsers.add_parser(
'remove-package',
help=("Remove a package in the specified Libertine container."))
parser_install.add_argument(
'-p', '--package',
required=True,
help=("Name of package to remove. Required."))
parser_install.add_argument(
'-i', '--id',
help=("Container identifier. Default container is used if omitted."))
parser_install.set_defaults(func=remove_package)
# Handle the search-cache command and its options
parser_search = subparsers.add_parser(
'search-cache',
help=("Search for packages based on the search string in the specified Libertine container."))
parser_search.add_argument(
'-s', '--search-string',
required=True,
help=("String to search for in the package cache. Required."))
parser_search.add_argument(
'-i', '--id',
help=("Container identifier. Default container is used if omitted."))
parser_search.set_defaults(func=search_cache)
# Handle the update command and its options
parser_update = subparsers.add_parser(
'update',
help=("Update the packages in the Libertine container."))
parser_update.add_argument(
'-i', '--id',
help=("Container identifier. Default container is used if omitted."))
parser_update.set_defaults(func=update)
# Handle the list command
parser_list = subparsers.add_parser(
"list",
help=("List all Libertine containers."))
parser_list.set_defaults(func=list)
# Handle the list-apps command and its options
parser_list_apps = subparsers.add_parser(
'list-apps',
help=("List available app launchers in a container."))
parser_list_apps.add_argument(
'-i', '--id',
help=("Container identifier. Default container is used if omitted."))
parser_list_apps.add_argument(
'-j', '--json',
action='store_true',
help=("use JSON output format."))
parser_list_apps.set_defaults(func=list_apps)
# Handle the execute command and it's options
parser_exec = subparsers.add_parser(
'exec',
help=("Run an arbitrary command in the specified Libertine container."))
parser_exec.add_argument(
'-i', '--id',
help=("Container identifier. Default container is used if omitted."))
parser_exec.add_argument(
'-c', '--command',
help=("The command to run in the specified container."))
parser_exec.set_defaults(func=exec)
# Handle the configure command and it's options
parser_configure = subparsers.add_parser(
'configure',
help=("Configure various options in the specified Libertine container."))
parser_configure.add_argument(
'-i', '--id',
help=("Container identifier. Default container is used if omitted."))
parser_configure.add_argument(
'-m', '--multiarch',
choices=['enable', 'disable'],
help=("Enables or disables i386 multiarch support for amd64 Libertine "
"containers. This option has no effect when the Libertine "
"container is i386."))
parser_configure.add_argument(
'-a', '--add-archive',
metavar='Archive name',
help=("Adds an archive (PPA) in the specified Libertine container. Needs to be "
"in the form of \"ppa:user/ppa-name\"."))
parser_configure.add_argument(
'-d', '--delete-archive',
metavar='Archive name',
help=("Deletes an existing archive (PPA) in the specified Libertine container. "
"Needs to be in the form of \"ppa:user/ppa-name\"."))
parser_configure.set_defaults(func=configure)
# Actually parse the args
args = parser.parse_args()
if args.verbosity is None:
args.verbosity = 1
args.func(args)
./tools/CMakeLists.txt 0000644 0000156 0000165 00000000564 12702745452 015012 0 ustar jenkins jenkins install(PROGRAMS libertine-container-manager libertine-launch libertine-session-bridge libertine-lxc-manager libertine-xmir
DESTINATION ${CMAKE_INSTALL_BINDIR})
install(FILES libertine-launch.1 libertine-container-manager.1 libertine-session-bridge.1 libertine-lxc-manager.1 libertine-xmir.1
DESTINATION ${CMAKE_INSTALL_MANDIR}/man1
COMPONENT doc)
./tools/libertine-lxc-manager 0000755 0000156 0000165 00000007353 12702745445 016356 0 ustar jenkins jenkins #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (C) 2015 Canonical Ltd.
# Author: Christopher Townsend
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import libertine.utils
import lxc
import os
import select
import signal
import shlex
import subprocess
from collections import Counter
from socket import *
def lxc_setup_pulse():
pulse_socket_path = os.path.join(libertine.utils.get_libertine_runtime_dir(), 'pulse_socket')
lsof_cmd = 'lsof -n %s' % pulse_socket_path
args = shlex.split(lsof_cmd)
lsof = subprocess.Popen(args, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
lsof.wait()
if not os.path.exists(pulse_socket_path) or lsof.returncode == 1:
pactl_cmd = (
'pactl load-module module-native-protocol-unix auth-anonymous=1 socket=%s'
% pulse_socket_path)
args = shlex.split(pactl_cmd)
subprocess.Popen(args).wait()
def launch_lxc_container(container_id):
container = lxc.Container(container_id, libertine.utils.get_libertine_containers_dir_path())
lxc_setup_pulse()
if not container.running:
if not container.start():
print("Container failed to start")
return False
return True
def stop_lxc_container(container_id):
container = lxc.Container(container_id, libertine.utils.get_libertine_containers_dir_path())
if container.running:
container.stop()
def socket_cleanup(signum, frame):
libertine_lxc_mgr_socket.close()
def process_data(data):
msg = data.decode().split(' ')
op_code = msg[0]
container_id = msg[1]
if op_code == 'start':
if not launch_lxc_container(container_id):
return 'FAILED'
app_counter[container_id] += 1
elif op_code == 'stop':
app_counter[container_id] -= 1
if app_counter[container_id] == 0:
stop_lxc_container(container_id)
return 'OK'
def main_loop():
while 1:
try:
rlist, wlist, elist = select.select(descriptors, [], [])
except InterruptedError:
continue
except:
break
for sock in rlist:
if sock.fileno() == -1:
continue
if sock == libertine_lxc_mgr_socket:
sock_fd = libertine_lxc_mgr_socket.accept()[0]
descriptors.append(sock_fd)
else:
data = sock.recv(1024)
if len(data) == 0:
descriptors.remove(sock)
sock.shutdown(SHUT_RDWR)
sock.close()
continue
message = process_data(data)
sock.send(message.encode())
if __name__ == '__main__':
signal.signal(signal.SIGTERM, socket_cleanup)
signal.signal(signal.SIGINT, socket_cleanup)
if not os.path.exists(libertine.utils.get_libertine_runtime_dir()):
os.makedirs(libertine.utils.get_libertine_runtime_dir())
app_counter = Counter()
libertine_lxc_mgr_socket = socket(AF_UNIX, SOCK_STREAM)
libertine_lxc_mgr_socket.bind(libertine.utils.get_libertine_lxc_socket())
libertine_lxc_mgr_socket.listen(20)
descriptors = [libertine_lxc_mgr_socket]
main_loop()
./COPYING 0000644 0000156 0000165 00000104513 12702745445 012146 0 ustar jenkins jenkins GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
./python/ 0000755 0000156 0000165 00000000000 12702745445 012430 5 ustar jenkins jenkins ./python/libertine/ 0000755 0000156 0000165 00000000000 12702745452 014403 5 ustar jenkins jenkins ./python/libertine/utils.py 0000644 0000156 0000165 00000007622 12702745452 016124 0 ustar jenkins jenkins #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (C) 2015 Canonical Ltd.
# Author: Christopher Townsend
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
import json
import os
import psutil
import subprocess
import xdg.BaseDirectory as basedir
from gi import require_version
require_version('Libertine', '1')
from gi.repository import Libertine
def container_exists(container_id):
container_config_file_path = get_libertine_database_file_path()
if (os.path.exists(container_config_file_path) and
os.path.getsize(container_config_file_path) != 0):
with open(get_libertine_database_file_path()) as fd:
container_list = json.load(fd)
if container_list:
for container in container_list['containerList']:
if container['id'] == container_id:
return True
return False
def get_libertine_container_rootfs_path(container_id):
path = Libertine.container_path(container_id)
if path is None:
path = os.path.join(get_libertine_containers_dir_path(), container_id, 'rootfs')
return path
def get_libertine_containers_dir_path():
xdg_cache_home = os.getenv('XDG_CACHE_HOME',
os.path.join(os.getenv('HOME'), '.cache'))
return os.path.join(xdg_cache_home, 'libertine-container')
def get_libertine_database_dir_path():
xdg_data_home = os.getenv('XDG_DATA_HOME',
os.path.join(os.getenv('HOME'), '.local', 'share'))
return os.path.join(xdg_data_home, 'libertine')
def get_libertine_database_file_path():
return os.path.join(get_libertine_database_dir_path(), 'ContainersConfig.json')
def get_libertine_container_userdata_dir_path(container_id):
path = Libertine.container_home_path(container_id)
if path is None:
path = os.path.join(basedir.xdg_data_home, 'libertine-container', 'user-data', container_id)
return path
def get_user_runtime_dir():
try:
return basedir.get_runtime_dir()
except KeyError:
import tempfile
return tempfile.mkdtemp()
def get_libertine_runtime_dir():
return os.path.join(get_user_runtime_dir(), 'libertine')
def get_host_architecture():
dpkg = subprocess.Popen(['dpkg', '--print-architecture'],
stdout=subprocess.PIPE,
universal_newlines=True)
if dpkg.wait() != 0:
parser.error("Failed to determine the local architecture.")
return dpkg.stdout.read().strip()
def create_libertine_user_data_dir(container_id):
user_data = get_libertine_container_userdata_dir_path(container_id)
if not os.path.exists(user_data):
os.makedirs(user_data)
def get_libertine_lxc_socket():
return '\0libertine_lxc_socket'
def get_libertine_lxc_pulse_socket_path():
return os.path.join(get_libertine_runtime_dir(), 'pulse_socket')
def setup_window_manager(container_id):
if os.path.exists(os.path.join(get_libertine_container_rootfs_path(container_id),
'usr', 'bin', 'matchbox-window-manager')):
return ['matchbox-window-manager', '-use_titlebar', 'no']
else:
return ['compiz']
def terminate_window_manager(window_manager):
for child in window_manager.children():
child.terminate()
child.wait()
window_manager.terminate()
window_manager.wait()
./python/libertine/__init__.py 0000644 0000156 0000165 00000002033 12702745445 016514 0 ustar jenkins jenkins """
:mod:`libertine` -- bindings for the Libertine application sandbox
==================================================================
.. module:: libertine
:synopsis: A sandbox for running DEB-packaged X11-based applications
"""
# Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
__all__ = [
# from Libertine
'LibertineContainer', 'utils'
]
__docformat__ = "restructuredtext en"
from libertine.Libertine import LibertineContainer
./python/libertine/AppDiscovery.py 0000644 0000156 0000165 00000017742 12702745445 017402 0 ustar jenkins jenkins # Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
from . import utils
from xdg.BaseDirectory import xdg_data_dirs
import configparser
import glob
import io
import json
import os
import re
import sys
class IconCache(object):
"""
Caches the names of all icon files available in the standard places (possibly
in a container) and provides a search function to deliver icon file names
matching a given icon name.
See the `Freedesktop.org icon theme specification
`_
for the detailed specification.
"""
def __init__(self, root_path, file_loader=None):
"""
:param root_path: Where to start the file scan.
:type root_path: A valid filesystem path string.
:param file_loader: A function that builds a cache of filenames.
:type file_loader: Function returning a list of filenames.
"""
if file_loader:
self._icon_cache = file_loader(root_path)
else:
self._icon_cache = self._file_loader(root_path)
def _get_icon_search_paths(self, root_path):
"""
Gets a list of paths on which to search for icons.
:param root_path: Where to start the file scan.
:type root_path: A valid filesystem path string.
:rtype: A list of filesystem patch to serarch for qualifying icon files.
"""
icon_search_paths = []
icon_search_paths.append(os.path.join(root_path, os.environ['HOME'], ".icons"))
for d in reversed(xdg_data_dirs):
icon_search_paths.append(os.path.join(root_path, d.lstrip('/'), "icons"))
icon_search_paths.append(os.path.join(root_path, "usr/share/pixmaps"))
return icon_search_paths
def _file_loader(self, root_path):
"""
Loads a cache of file names by scanning the filesystem rooted at
``root_path``.
:param root_path: Where to start the file scan.
:type root_path: A valid filesystem path.
:rtype: A list of fully-qualified file paths.
"""
file_names = []
pattern = re.compile(r".*\.(png|svg|xpm)")
for path in self._get_icon_search_paths(root_path):
for base, dirs, files in os.walk(path):
for file in files:
if pattern.match(file):
file_names.append(os.path.join(base, file))
return file_names
def _find_icon_files(self, icon_name):
"""
Finds a list of file name strings matching the given icon name.
:param icon_name: An icon name, pobably from a .desktop file.
:rtype: A list of filename strings matching the icon name.
"""
icon_file_names = []
match_string = r"/" + os.path.splitext(icon_name)[0] + r"\....$"
pattern = re.compile(match_string)
for icon_file in self._icon_cache:
if pattern.search(icon_file):
icon_file_names.append(icon_file)
return icon_file_names
def expand_icons(self, desktop_icon_list):
"""
Expands a string containing a list of icon names into a list of matching
file names.
:param desktop_icon_list: A string containing a list of icon names
separated by semicolons.
:rtype: A list of filename stings matching the icon names passed in.
See `the Freedesktop.org desktop file specification
`_
for more information.
"""
if desktop_icon_list:
icon_list = desktop_icon_list.split(';')
if icon_list[0][0] == '/':
return icon_list
icon_files = []
for i in icon_list:
icon_files += self._find_icon_files(i)
return icon_files
return []
def expand_mime_types(desktop_mime_types):
if desktop_mime_types:
return desktop_mime_types.split(';')
return []
class AppInfo(object):
def __init__(self, desktop_file_name, config_entry, icon_cache):
self.desktop_file_name = desktop_file_name
self.name = config_entry.get('Name')
if not self.name:
raise RuntimeError("required Name attribute is missing")
d = config_entry.get('NoDisplay')
self.no_display = (d != None and d == 'true')
self.exec_line = config_entry.get('Exec')
if not self.exec_line:
raise RuntimeError("required Exec attribute is missing")
self.icons = icon_cache.expand_icons(config_entry.get('Icon'))
self.mime_types = expand_mime_types(config_entry.get('MimeType'))
def __str__(self):
with io.StringIO() as ostr:
print(self.name, file=ostr)
print(" desktop_file={}".format(self.desktop_file_name), file=ostr)
print(" no-display={}".format(self.no_display), file=ostr)
print(" exec='{}'".format(self.exec_line), file=ostr)
for icon in self.icons:
print(" icon: {}".format(icon), file=ostr)
for mime in self.mime_types:
print(" mime: {}".format(mime), file=ostr)
return ostr.getvalue()
def to_json(self):
return json.dumps(self.__dict__)
def desktop_file_is_showable(desktop_entry):
"""
Determines if a particular application entry should be reported: the entry
can not be hidden and must be showable in Unity.
"""
t = desktop_entry.get('Type')
if t != 'Application':
return False
n = desktop_entry.get('Hidden')
if n and n == 'true':
return False
n = desktop_entry.get('NoShowIn')
if n:
targets = n.split(';')
if 'Unity' in targets:
return False
n = desktop_entry.get('OnlyShowIn')
if n:
targets = n.split(';')
if 'Unity' not in targets:
return False
return True
def get_app_info(desktop_path, icon_cache):
for desktop_file_name in glob.glob(desktop_path):
desktop_file = configparser.ConfigParser(strict=False, interpolation=None)
try:
desktop_file.read(desktop_file_name)
desktop_entry = desktop_file['Desktop Entry']
if desktop_file_is_showable(desktop_entry):
yield AppInfo(desktop_file_name, desktop_entry, icon_cache)
except Exception as ex:
print("error processing {}: {}".format(desktop_file_name, ex), file=sys.stderr)
class AppLauncherCache(object):
"""
Caches a list of application launcher information (derived from .desktop
files installed in a container.
"""
def __init__(self, name, root_path):
self.name = name
self.app_launchers = []
icon_cache = IconCache(root_path)
for dir in reversed(xdg_data_dirs):
path = os.path.join(root_path, dir.lstrip('/'), "applications")
for app_info in get_app_info(os.path.join(path, "*.desktop"), icon_cache):
self.app_launchers.append(app_info)
def __str__(self):
with io.StringIO() as ostr:
print("{}\n".format(self.name), file=ostr)
for app_info in self.app_launchers:
print(" {}".format(app_info), file=ostr)
return ostr.getvalue()
def to_json(self):
return json.dumps(self,
default=lambda o: o.__dict__,
sort_keys=True,
indent=4)
./python/libertine/LxcContainer.py 0000644 0000156 0000165 00000026077 12702745452 017362 0 ustar jenkins jenkins # Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
import crypt
import lxc
import os
import psutil
import shlex
import subprocess
from .Libertine import BaseContainer
from . import utils
from socket import *
home_path = os.environ['HOME']
def check_lxc_net_entry(entry):
lxc_net_file = open('/etc/lxc/lxc-usernet')
found = False
for line in lxc_net_file:
if entry in line:
found = True
break
return found
def setup_host_environment(username, password):
lxc_net_entry = "%s veth lxcbr0 10" % str(username)
if not check_lxc_net_entry(lxc_net_entry):
passwd = subprocess.Popen(["sudo", "--stdin", "usermod", "--add-subuids", "100000-165536",
"--add-subgids", "100000-165536", str(username)],
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
passwd.communicate((password + '\n').encode('UTF-8'))
add_user_cmd = "echo %s | sudo tee -a /etc/lxc/lxc-usernet > /dev/null" % lxc_net_entry
subprocess.Popen(add_user_cmd, shell=True)
def get_lxc_default_config_path():
return os.path.join(home_path, '.config', 'lxc')
def lxc_container(container_id):
config_path = utils.get_libertine_containers_dir_path()
if not os.path.exists(config_path):
os.makedirs(config_path)
container = lxc.Container(container_id, config_path)
return container
def get_host_timezone():
with open(os.path.join('/', 'etc', 'timezone'), 'r') as fd:
host_timezone = fd.read().strip('\n')
return host_timezone
class LibertineLXC(BaseContainer):
"""
A concrete container type implemented using an LXC container.
"""
def __init__(self, container_id):
super().__init__(container_id)
self.container_type = "lxc"
self.container = lxc_container(container_id)
def is_running(self):
return self.container.running
def timezone_needs_update(self):
host_timezone = get_host_timezone()
with open(os.path.join(self.root_path, 'etc', 'timezone'), 'r') as fd:
container_timezone = fd.read().strip('\n')
if host_timezone == container_timezone:
return False
else:
return True
def start_container(self):
if not self.container.running:
if not self.container.start():
raise RuntimeError("Container failed to start")
if not self.container.wait("RUNNING", 10):
raise RuntimeError("Container failed to enter the RUNNING state")
if not self.container.get_ips(timeout=30):
self.stop_container()
raise RuntimeError("Not able to connect to the network.")
self.run_in_container("umount /tmp/.X11-unix")
self.run_in_container("umount -l /usr/lib/locale")
def stop_container(self):
self.container.stop()
def run_in_container(self, command_string):
cmd_args = shlex.split(command_string)
return self.container.attach_wait(lxc.attach_run_command, cmd_args)
def update_packages(self, verbosity=1):
if self.timezone_needs_update():
self.run_in_container("bash -c \'echo \"{}\" >/etc/timezone\'".format(
get_host_timezone()))
self.run_in_container("rm -f /etc/localtime")
self.run_in_container("dpkg-reconfigure -f noninteractive tzdata")
super().update_packages(verbosity)
def destroy_libertine_container(self):
if self.container.defined:
self.container.stop()
self.container.destroy()
def create_libertine_container(self, password=None, multiarch=False, verbosity=1):
if password is None:
return False
installed_release = self.get_container_distro(self.container_id)
username = os.environ['USER']
user_id = os.getuid()
group_id = os.getgid()
setup_host_environment(username, password)
# Generate the default lxc default config, if it doesn't exist
config_path = get_lxc_default_config_path()
config_file = "%s/default.conf" % config_path
if not os.path.exists(config_path):
os.makedirs(config_path)
if not os.path.exists(config_file):
with open(config_file, "w+") as fd:
fd.write("lxc.network.type = veth\n")
fd.write("lxc.network.link = lxcbr0\n")
fd.write("lxc.network.flags = up\n")
fd.write("lxc.network.hwaddr = 00:16:3e:xx:xx:xx\n")
fd.write("lxc.id_map = u 0 100000 %s\n" % user_id)
fd.write("lxc.id_map = g 0 100000 %s\n" % group_id)
fd.write("lxc.id_map = u %s %s 1\n" % (user_id, user_id))
fd.write("lxc.id_map = g %s %s 1\n" % (group_id, group_id))
fd.write("lxc.id_map = u %s %s %s\n" % (user_id + 1, (user_id + 1) + 100000, 65536 - (user_id + 1)))
fd.write("lxc.id_map = g %s %s %s\n" % (group_id + 1, (group_id + 1) + 100000, 65536 - (user_id + 1)))
utils.create_libertine_user_data_dir(self.container_id)
# Figure out the host architecture
architecture = utils.get_host_architecture()
if not self.container.create("download", 0,
{"dist": "ubuntu",
"release": installed_release,
"arch": architecture}):
print("Failed to create container")
return False
self.create_libertine_config()
if verbosity == 1:
print("starting container ...")
try:
self.start_container()
except RuntimeError as e:
print("Container failed to start: %s" % e)
self.destroy_libertine_container()
return False
self.run_in_container("userdel -r ubuntu")
self.run_in_container("useradd -u {} -p {} -G sudo {}".format(
str(user_id), crypt.crypt(password), str(username)))
if multiarch and architecture == 'amd64':
if verbosity == 1:
print("Adding i386 multiarch support...")
self.run_in_container("dpkg --add-architecture i386")
if verbosity == 1:
print("Updating the contents of the container after creation...")
self.update_packages(verbosity)
if not self.install_package("software-properties-common", verbosity):
print("Failure installing software-properties-common during container creation")
self.destroy_libertine_container()
return False
if verbosity == 1:
print("Installing Matchbox as the Xmir window manager...")
if not self.install_package('matchbox', verbosity=verbosity):
print("Failure installing matchbox during container creation")
self.destroy_libertine_container()
return False
if verbosity == 1:
print("stopping container ...")
self.stop_container()
return True
def create_libertine_config(self):
user_id = os.getuid()
home_entry = (
"%s %s none bind,create=dir"
% (utils.get_libertine_container_userdata_dir_path(self.container_id),
home_path.strip('/'))
)
# Bind mount the user's home directory
self.container.append_config_item("lxc.mount.entry", home_entry)
xdg_user_dirs = ['Documents', 'Music', 'Pictures', 'Videos']
for user_dir in xdg_user_dirs:
xdg_user_dir_entry = (
"%s/%s %s/%s none bind,create=dir,optional"
% (home_path, user_dir, home_path.strip('/'), user_dir)
)
self.container.append_config_item("lxc.mount.entry", xdg_user_dir_entry)
# Bind mount the user's dconf back end
user_dconf_path = os.path.join(home_path, '.config', 'dconf')
user_dconf_entry = (
"%s %s none bind,create=dir,optional"
% (user_dconf_path, user_dconf_path.strip('/'))
)
self.container.append_config_item("lxc.mount.entry", user_dconf_entry)
# Setup the mounts for /run/user/$user_id
run_user_entry = "/run/user/%s run/user/%s none rbind,optional,create=dir" % (user_id, user_id)
self.container.append_config_item("lxc.mount.entry", "tmpfs run tmpfs rw,nodev,noexec,nosuid,size=5242880")
self.container.append_config_item("lxc.mount.entry",
"none run/user tmpfs rw,nodev,noexec,nosuid,size=104857600,mode=0755,create=dir")
self.container.append_config_item("lxc.mount.entry", run_user_entry)
self.container.append_config_item("lxc.include", "/usr/share/libertine/libertine-lxc.conf")
# Dump it all to disk
self.container.save_config()
def launch_application(self, app_exec_line):
libertine_lxc_mgr_sock = socket(AF_UNIX, SOCK_STREAM)
libertine_lxc_mgr_sock.connect(utils.get_libertine_lxc_socket())
# Tell libertine-lxc-manager that we are starting a new app
message = "start " + self.container_id
libertine_lxc_mgr_sock.send(message.encode())
# Receive the reply from libertine-lxc-manager
data = libertine_lxc_mgr_sock.recv(1024)
if data.decode() == 'OK':
if not self.container.wait("RUNNING", 10):
print("Container failed to enter the RUNNING state")
return
if not self.container.get_ips(timeout=30):
print("Not able to connect to the network.")
return
else:
print("Failure detected from libertine-lxc-manager")
return
window_manager = self.container.attach(lxc.attach_run_command,
utils.setup_window_manager(self.container_id))
# Setup pulse to work inside the container
os.environ['PULSE_SERVER'] = utils.get_libertine_lxc_pulse_socket_path()
self.container.attach_wait(lxc.attach_run_command,
['sudo', '-E', '-u', os.environ['USER']] + app_exec_line)
utils.terminate_window_manager(psutil.Process(window_manager))
# Tell libertine-lxc-manager that the app has stopped.
message = "stop " + self.container_id
libertine_lxc_mgr_sock.send(message.encode())
# Receive the reply from libertine-lxc-manager (ignore it for now).
data = libertine_lxc_mgr_sock.recv(1024)
libertine_lxc_mgr_sock.close()
./python/libertine/ChrootContainer.py 0000644 0000156 0000165 00000024567 12702745452 020074 0 ustar jenkins jenkins # Copyright 2015 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
import os
import psutil
import shlex
import shutil
import subprocess
from .Libertine import BaseContainer
from . import utils
def chown_recursive_dirs(path):
uid = 0
gid = 0
if 'SUDO_UID' in os.environ:
uid = int(os.environ['SUDO_UID'])
if 'SUDO_GID' in os.environ:
gid = int(os.environ['SUDO_GID'])
if uid != 0 and gid != 0:
for root, dirs, files in os.walk(path):
for d in dirs:
os.chown(os.path.join(root, d), uid, gid)
for f in files:
os.chown(os.path.join(root, f), uid, gid)
os.chown(path, uid, gid)
class LibertineChroot(BaseContainer):
"""
A concrete container type implemented using a plain old chroot.
"""
def __init__(self, container_id):
super().__init__(container_id)
self.container_type = "chroot"
os.environ['FAKECHROOT_CMD_SUBST'] = '$FAKECHROOT_CMD_SUBST:/usr/bin/chfn=/bin/true'
os.environ['DEBIAN_FRONTEND'] = 'noninteractive'
def run_in_container(self, command_string):
cmd_args = shlex.split(command_string)
if self.get_container_distro(self.container_id) == "trusty":
command_prefix = self._build_privileged_proot_cmd()
else:
command_prefix = "fakechroot fakeroot chroot " + self.root_path
args = shlex.split(command_prefix + ' ' + command_string)
cmd = subprocess.Popen(args)
return cmd.wait()
def destroy_libertine_container(self):
shutil.rmtree(self.root_path)
def create_libertine_container(self, password=None, multiarch=False, verbosity=1):
installed_release = self.get_container_distro(self.container_id)
architecture = utils.get_host_architecture()
# Create the actual chroot
if installed_release == "trusty":
command_line = "debootstrap --verbose " + installed_release + " " + self.root_path
else:
command_line = "fakechroot fakeroot debootstrap --verbose --variant=fakechroot {} {}".format(
installed_release, self.root_path)
args = shlex.split(command_line)
cmd = subprocess.Popen(args)
cmd.wait()
if cmd.returncode != 0:
print("Failed to create container")
self.destroy_libertine_container()
return False
# Remove symlinks as they can ill-behaved recursive behavior in the chroot
if installed_release != "trusty":
print("Fixing chroot symlinks...")
os.remove(os.path.join(self.root_path, 'dev'))
os.remove(os.path.join(self.root_path, 'proc'))
with open(os.path.join(self.root_path, 'usr', 'sbin', 'policy-rc.d'), 'w+') as fd:
fd.write("#!/bin/sh\n\n")
fd.write("while true; do\n")
fd.write("case \"$1\" in\n")
fd.write(" -*) shift ;;\n")
fd.write(" makedev) exit 0;;\n")
fd.write(" *) exit 101;;\n")
fd.write("esac\n")
fd.write("done\n")
os.fchmod(fd.fileno(), 0o755)
# Add universe, multiverse, and -updates to the chroot's sources.list
if (utils.get_host_architecture() == 'armhf'):
archive = "deb http://ports.ubuntu.com/ubuntu-ports "
else:
archive = "deb http://archive.ubuntu.com/ubuntu "
if verbosity == 1:
print("Updating chroot's sources.list entries...")
with open(os.path.join(self.root_path, 'etc', 'apt', 'sources.list'), 'a') as fd:
fd.write(archive + installed_release + "-updates main\n")
fd.write(archive + installed_release + " universe\n")
fd.write(archive + installed_release + "-updates universe\n")
fd.write(archive + installed_release + " multiverse\n")
fd.write(archive + installed_release + "-updates multiverse\n")
utils.create_libertine_user_data_dir(self.container_id)
if installed_release == "trusty":
print("Additional configuration for Trusty chroot...")
cmd_line_prefix = self._build_privileged_proot_cmd()
command_line = cmd_line_prefix + " dpkg-divert --local --rename --add /etc/init.d/systemd-logind"
args = shlex.split(command_line)
cmd = subprocess.Popen(args).wait()
command_line = cmd_line_prefix + " dpkg-divert --local --rename --add /sbin/initctl"
args = shlex.split(command_line)
cmd = subprocess.Popen(args).wait()
command_line = cmd_line_prefix + " dpkg-divert --local --rename --add /sbin/udevd"
args = shlex.split(command_line)
cmd = subprocess.Popen(args).wait()
command_line = cmd_line_prefix + " dpkg-divert --local --rename --add /usr/sbin/rsyslogd"
args = shlex.split(command_line)
cmd = subprocess.Popen(args).wait()
command_line = cmd_line_prefix + " ln -s /bin/true /etc/init.d/systemd-logind"
args = shlex.split(command_line)
cmd = subprocess.Popen(args).wait()
command_line = cmd_line_prefix + " ln -s /bin/true /sbin/initctl"
args = shlex.split(command_line)
cmd = subprocess.Popen(args).wait()
command_line = cmd_line_prefix + " ln -s /bin/true /sbin/udevd"
args = shlex.split(command_line)
cmd = subprocess.Popen(args).wait()
command_line = cmd_line_prefix + " ln -s /bin/true /usr/sbin/rsyslogd"
args = shlex.split(command_line)
cmd = subprocess.Popen(args).wait()
if multiarch and architecture == 'amd64':
if verbosity == 1:
print("Adding i386 multiarch support...")
self.run_in_container("dpkg --add-architecture i386")
if verbosity == 1:
print("Updating the contents of the container after creation...")
self.update_packages(verbosity)
if not self.install_package("libnss-extrausers", verbosity):
print("Failure installing libnss-extrausers during container creation")
self.destroy_libertine_container()
return False
if not self.install_package("software-properties-common", verbosity):
print("Failure installing software-properties-common during container creation")
self.destroy_libertine_container()
return False
if verbosity == 1:
print("Installing Matchbox as the Xmir window manager...")
if not self.install_package('matchbox', verbosity):
print("Failure installing matchbox during container creation")
self.destroy_libertine_container()
return False
# Check if the container was created as root and chown the user directories as necessary
chown_recursive_dirs(utils.get_libertine_container_userdata_dir_path(self.container_id))
return True
def update_packages(self, verbosity=1):
super().update_packages(verbosity)
self._run_ldconfig(verbosity)
def install_package(self, package_name, verbosity=1, extra_apt_args=""):
returncode = super().install_package(package_name, verbosity, extra_apt_args)
if returncode:
self._run_ldconfig(verbosity)
return returncode
def _build_proot_command(self):
proot_cmd = '/usr/bin/proot'
if not os.path.isfile(proot_cmd) or not os.access(proot_cmd, os.X_OK):
raise RuntimeError('executable proot not found')
proot_cmd += " -R " + self.root_path
# Bind-mount the host's locale(s)
proot_cmd += " -b /usr/lib/locale"
# Bind-mount extrausers on the phone
if os.path.exists("/var/lib/extrausers"):
proot_cmd += " -b /var/lib/extrausers"
home_path = os.environ['HOME']
# Bind-mount common XDG direcotries
bind_mounts = (
" -b %s:%s"
% (utils.get_libertine_container_userdata_dir_path(self.container_id), home_path)
)
xdg_user_dirs = ['Documents', 'Music', 'Pictures', 'Videos']
for user_dir in xdg_user_dirs:
user_dir_path = os.path.join(home_path, user_dir)
bind_mounts += " -b %s:%s" % (user_dir_path, user_dir_path)
proot_cmd += bind_mounts
user_dconf_path = os.path.join(home_path, '.config', 'dconf')
if os.path.exists(user_dconf_path):
proot_cmd += " -b %s" % user_dconf_path
return proot_cmd
def _build_privileged_proot_cmd(self):
proot_cmd = '/usr/bin/proot'
if not os.path.isfile(proot_cmd) or not os.access(proot_cmd, os.X_OK):
raise RuntimeError('executable proot not found')
proot_cmd += " -b /usr/lib/locale -S " + self.root_path
return proot_cmd
def launch_application(self, app_exec_line):
# FIXME: Disabling seccomp is a temporary measure until we fully understand why we need
# it or figure out when we need it.
os.environ['PROOT_NO_SECCOMP'] = '1'
# Workaround issue where a custom dconf profile is on the machine
if 'DCONF_PROFILE' in os.environ:
del os.environ['DCONF_PROFILE']
proot_cmd = self._build_proot_command()
args = shlex.split(proot_cmd)
args.extend(utils.setup_window_manager(self.container_id))
window_manager = psutil.Popen(args)
args = shlex.split(proot_cmd)
args.extend(app_exec_line)
psutil.Popen(args).wait()
utils.terminate_window_manager(window_manager)
def _run_ldconfig(self, verbosity=1):
if verbosity == 1:
print("Refreshing the container's dynamic linker run-time bindings...")
command_line = self._build_privileged_proot_cmd() + " ldconfig.REAL"
args = shlex.split(command_line)
subprocess.Popen(args).wait()
./python/libertine/Libertine.py 0000644 0000156 0000165 00000032270 12702745452 016676 0 ustar jenkins jenkins # Copyright 2015-2106 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
from .AppDiscovery import AppLauncherCache
from gi.repository import Libertine
import abc
import contextlib
import json
import libertine.utils
import os
import shutil
def get_container_type(container_id):
"""
Retrieves the type of container for a given container ID.
:param container_id: The Container ID to search for.
"""
try:
with open(libertine.utils.get_libertine_database_file_path()) as fd:
container_list = json.load(fd)
for container in container_list["containerList"]:
if container["id"] == container_id:
return container["type"]
except FileNotFoundError:
pass
# Return lxc as the default container type
return "lxc"
def apt_args_for_verbosity_level(verbosity):
"""
Maps numeric verbosity levels onto APT command-line arguments.
:param verbosity: 0 is quiet, 1 is normal, 2 is incontinent
"""
return {
0: '--quiet=2',
1: '--assume-yes',
2: '--quiet=1 --assume-yes --option APT::Status-Fd=1'
}.get(verbosity, '')
def apt_command_prefix(verbosity):
return '/usr/bin/apt ' + apt_args_for_verbosity_level(verbosity) + ' '
class BaseContainer(metaclass=abc.ABCMeta):
"""
An abstract base container to provide common functionality for all
concrete container types.
:param container_id: The machine-readable container name.
"""
def __init__(self, container_id):
self.container_type = 'unknown'
self.container_id = container_id
self.root_path = libertine.utils.get_libertine_container_rootfs_path(self.container_id)
def create_libertine_container(self, password=None, multiarch=False, verbosity=1):
pass
def destroy_libertine_container(self, verbosity=1):
pass
def copy_package_to_container(self, package_path):
"""
Copies a Debian package from the host to a pre-determined place
in a container.
:param package_path: The full path to the Debian package located
on the host.
"""
if os.path.exists(os.path.join(self.root_path, 'tmp', package_path.split('/')[-1])):
return False
shutil.copy2(package_path, os.path.join(self.root_path, 'tmp'))
return True
def delete_package_in_container(self, package_path):
"""
Deletes a previously copied in Debian package in a container.
:param package_path: The full path to the Debian package located
on the host.
"""
os.remove(os.path.join(self.root_path, 'tmp', package_path.split('/')[-1]))
def is_running(self):
"""
Indicates if the container is 'running'. The definition of 'running'
depends on the type of the container.
"""
return False
def start_container(self):
"""
Starts the container. To start the container means to put it into a
'running' state, the meaning of which depends on the type of the
container.
"""
pass
def stop_container(self):
"""
Stops the container. The opposite of start_container().
"""
pass
@abc.abstractmethod
def run_in_container(self, command_string):
"""
Runs a command inside the container context.
:param command_string: The command line to execute in the container context.
"""
pass
def update_packages(self, verbosity=1):
"""
Updates all packages installed in the container.
:param verbosity: the chattiness of the output on a range from 0 to 2
"""
self.run_in_container(apt_command_prefix(verbosity) + '--force-yes update')
self.run_in_container(apt_command_prefix(verbosity) + '--force-yes upgrade')
def install_package(self, package_name, verbosity=1, extra_apt_args=""):
"""
Installs a named package in the container.
:param package_name: The name of the package as APT understands it or
a full path to a Debian package on the host.
:param verbosity: the chattiness of the output on a range from 0 to 2
"""
if package_name.endswith('.deb'):
delete_package = self.copy_package_to_container(package_name)
self.run_in_container('ls -la ' + os.environ['HOME'])
self.run_in_container('dpkg -i ' +
os.path.join('/', 'tmp', package_name.split('/')[-1]))
ret = self.run_in_container(apt_command_prefix(verbosity) +
extra_apt_args + " install -f") == 0
if delete_package:
self.delete_package_in_container(package_name)
return ret
else:
return self.run_in_container(apt_command_prefix(verbosity) +
extra_apt_args + " install '" + package_name + "'") == 0
def configure_command(self, command, *args, verbosity=1):
"""
Configures the container based on what the command is.
:param command: The configuration command to run.
:param *args: List of arguments used for the given configuration command
"""
if command == 'multiarch':
if args[0] == 'enable':
ret = self.run_in_container("dpkg --add-architecture i386")
if ret or ret == 0:
self.run_in_container(apt_command_prefix(verbosity) + '--force-yes update')
return ret
else:
self.run_in_container(apt_command_prefix(verbosity) + "purge \".*:i386\"")
return self.run_in_container("dpkg --remove-architecture i386")
elif command == 'add-archive':
if not os.path.exists(os.path.join(self.root_path, 'usr', 'bin', 'add-apt-repository')):
self.update_packages(verbosity)
self.install_package("software-properties-common", verbosity)
return self.run_in_container("add-apt-repository -y " + args[0])
elif command == 'delete-archive':
return self.run_in_container("add-apt-repository -y -r " + args[0])
def get_container_distro(self, container_id):
"""
Retrieves the distro code name for a given container ID.
:param container_id: The Container ID to search for.
"""
with open(libertine.utils.get_libertine_database_file_path()) as fd:
container_list = json.load(fd)
for container in container_list["containerList"]:
if container["id"] == container_id:
return container["distro"]
return ""
@property
def name(self):
"""
The human-readable name of the container.
"""
name = Libertine.container_name(self.container_id)
if not name:
name = 'Unknown'
return name
class LibertineMock(BaseContainer):
"""
A concrete mock container type. Used for unit testing.
"""
def __init__(self, container_id):
super().__init__(container_id)
self.container_type = "mock"
def create_libertine_container(self, password=None, multiarch=False, verbosity=1):
return True
def run_in_container(self, command_string):
return 0
def launch_application(self, app_exec_line):
import subprocess
cmd = subprocess.Popen(app_exec_line)
cmd.wait()
class ContainerRunning(contextlib.ExitStack):
"""
Helper object providing a running container context.
Starts the container running if it's not already running, and shuts it down
when the context is destroyed if it was not running at context creation.
"""
def __init__(self, container):
super().__init__()
if not container.is_running():
container.start_container()
self.callback(lambda: container.stop_container())
class LibertineContainer(object):
"""
A sandbox for DEB-packaged X11-based applications.
"""
def __init__(self, container_id):
"""
Initializes the container object.
:param container_id: The machine-readable container name.
"""
super().__init__()
container_type = get_container_type(container_id)
if container_type == "lxc":
from libertine.LxcContainer import LibertineLXC
self.container = LibertineLXC(container_id)
elif container_type == "chroot":
from libertine.ChrootContainer import LibertineChroot
self.container = LibertineChroot(container_id)
elif container_type == "mock":
self.container = LibertineMock(container_id)
else:
raise RuntimeError("Unsupported container type %s" % container_type)
@property
def container_id(self):
return self.container.container_id
@property
def name(self):
return self.container.name
@property
def container_type(self):
return self.container.container_type
@property
def root_path(self):
return self.container.root_path
def destroy_libertine_container(self):
"""
Destroys the container and releases all its system resources.
"""
self.container.destroy_libertine_container()
def create_libertine_container(self, password=None, multiarch=False, verbosity=1):
"""
Creates the container.
"""
return self.container.create_libertine_container(password, multiarch, verbosity)
def update_libertine_container(self, verbosity=1):
"""
Updates the contents of the container.
"""
with ContainerRunning(self.container):
self.container.update_packages(verbosity)
def install_package(self, package_name, verbosity=1):
"""
Installs a package in the container.
"""
with ContainerRunning(self.container):
return self.container.install_package(package_name, verbosity)
def remove_package(self, package_name, verbosity=1):
"""
Removes a package from the container.
:param package_name: The name of the package to be removed.
:param verbosity: The verbosity level of the progress reporting.
"""
with ContainerRunning(self.container):
self.container.run_in_container(apt_command_prefix(verbosity) + "purge '" + package_name + "'") == 0
self.container.run_in_container(apt_command_prefix(verbosity) + "autoremove --purge") == 0
def search_package_cache(self, search_string):
"""
Searches the container's package cache for a named package.
:param search_string: the (regex) to use to search the package cache.
The regex is quoted to sanitize it.
"""
with ContainerRunning(self.container):
self.container.run_in_container("/usr/bin/apt-cache search '" + search_string + "'")
def launch_application(self, app_exec_line):
"""
Launches an application in the container.
:param app_exec_line: the application exec line as passed in by
ubuntu-app-launch
"""
if libertine.utils.container_exists(self.container.container_id):
self.container.launch_application(app_exec_line)
else:
raise RuntimeError("Container with id %s does not exist." % self.container.container_id)
def list_app_launchers(self, use_json=False):
"""
Enumerates all application launchers (based on .desktop files) available
in the container.
:param use_json: Indicates the returned string should be i JSON format.
The default format is some human-readble format.
:rtype: A printable string containing a list of application launchers
available in the container.
"""
if use_json:
return AppLauncherCache(self.container.name,
self.container.root_path).to_json()
else:
return str(AppLauncherCache(self.container.name,
self.container.root_path))
def exec_command(self, exec_line):
"""
Runs an arbitrary application in the container. Mainly used for status
reporting, etc. in the container.
:param exec_line: The exec line to run inside the container. For
example, 'apt-cache policy package-foo'
:rtype: The output of the given command.
"""
with ContainerRunning(self.container):
return self.container.run_in_container(exec_line)
def configure_command(self, command, *args):
with ContainerRunning(self.container):
return self.container.configure_command(command, *args)
./python/CMakeLists.txt 0000644 0000156 0000165 00000000436 12702745445 015173 0 ustar jenkins jenkins execute_process(COMMAND python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
OUTPUT_VARIABLE python_site_packages
OUTPUT_STRIP_TRAILING_WHITESPACE)
install(DIRECTORY libertine
DESTINATION ${python_site_packages})
./data/ 0000755 0000156 0000165 00000000000 12702745452 012016 5 ustar jenkins jenkins ./data/libertine-lxc-manager.conf 0000644 0000156 0000165 00000000461 12702745445 017041 0 ustar jenkins jenkins description "Service to manage Libertine LXC's"
author "Christopher Townsend "
start on started unity8
stop on desktop-end
respawn
pre-start script
dpkg -s python3-libertine-lxc > /dev/null 2>&1 || { stop; exit 0; }
end script
exec /usr/bin/libertine-lxc-manager
./data/libertine_64.png 0000644 0000156 0000165 00000013265 12702745445 015023 0 ustar jenkins jenkins PNG
IHDR @ @ iq bKGD pHYs + tIME
ˮ tEXtComment Created with GIMPW IDATx^{eW]?_{otNtg<@ QBb"fT&B*EQJ@Q,@$(%aftGnwo<^7
(ߪ]{{:?[NjQƊGj|f'Y^~Z+vdhzС)U`)*Ld,$nEBG87n3FQ9#:^Aq=n"RVzСc}a[uH<RoP/]$"vB0eQam
ab)[~j,U*^`]f3(B
Wږez:VcDAp*Cuƌ
ZC1;w~}aPE [ qjQUZwb=[PHiyJ@Cσs+* W(::-XzٯD4^PglrV!B 7Ըc1U:u(^IbP/Ay!BC\3Ԃ:PZ{drF_{rs.ku/PAT"KD4M&&L(} 68g)\VK_veJ)Py>a֧Dckzm{p?VE<^_737={KO l]9e9@a{}#"(!I D@R
E dy|C{1ԇ1>lܸϿIW^
d~po颴[[Bp8p%S^7QPʶ@jhgPdHq|sI0`u.瓛)WGWi6rj7%DJz@%K?}0U@/=j51l\Buʼ1z1DH1ѐ83Ibf^{Cxn0?[䃃%+:{ƃe먗*uC].d~T>Gj
tUWG
ek