Canonical Voices

UbuntuTouch

在我们的Ubuntu SDK中,它提供了一个"Web App"的模版,它很方便地让我们把一个Web-based网页转换成一个Ubuntu的应用.大家可以参考我的文章"如何使用在线Webapp生成器生成安装包"来创建Web App.在今天的文章中,我们来介绍如实现一个全屏的Web App.


下面我们以百度地图为例.当我们利用我们的Ubuntu SDK创建一个应用时:

baidumap.desktop

[Desktop Entry]
Name=百度地图
Comment=webapp for baidumap
Type=Application
Icon=baidumap.png
Exec=webapp-container --enable-back-forward --store-session-cookies --webappUrlPatterns=https?://map.baidu.com/* http://map.baidu.com %u
Terminal=false
X-Ubuntu-Touch=true

细心的开发者可以看到在上面的"--enable-back-forward"选项.它让我们的Web App在最上面有一个title/header的地方,就像下面的图展示的那样:



在上面的图中,我们可以看到有一个"百度地图"的标题栏.它可以让我们返回以前的页面.

如果我们把上面的"--enable-back-forward"选项去掉,也就是:

Exec=webapp-container --store-session-cookies --webappUrlPatterns=https?://map.baidu.com/* http://map.baidu.com %u

那么我们的运行结果将是:



我们可以看出来,我们的header/title区域不见了.这样的好处是我们可以得到更多的显示区域.当然我们还是可以看到我们的indicator区域.

对于一些游戏的页面来说,能有一个全屏的用户界面是一个至高无上的需求,那么,我们可以更进一步来做如下的修改.我们添加一个"--fullscreen"的选项.

[Desktop Entry]
Name=百度地图
Comment=webapp for baidumap
Type=Application
Icon=baidumap.png
Exec=webapp-container --fullscreen -cookies --webappUrlPatterns=https?://map.baidu.com/* http://map.baidu.com %u
Terminal=false
X-Ubuntu-Touch=true

重新运行我们的项目:



我们可以看到一个全屏的应用,甚至连indicator的影子都没有.

更多关于Web App开发的信息可以在网站找到.



作者:UbuntuTouch 发表于2016/6/23 9:30:22 原文链接
阅读:166 评论:0 查看评论

Read more
UbuntuTouch

在Ubuntu SDK中,它提供了一个PlaceSearchModel接口.通过这个接口,我们可以在规定的区域里搜寻我们需要的地点,比如,KFC, Pizzar,或银行.在今天的教程中,我们来利用这个API来展示如何搜寻我们的兴趣点.

   


PlaceSearchModel的基本用法:

    PlaceSearchModel {
        id: searchModel
        plugin: myPlugin

        searchTerm: "KFC"
        searchArea: QtPositioning.circle(curLocation)

        Component.onCompleted: update()
    }


这里的searchTerm就是我们需要搜索的关键词.searchArea标示的是我们以什么为中心进行搜索.每当有一个新的关键词要进行搜索时,我们可以通过如下的方式来做:

                    searchModel.searchTerm = text
                    searchModel.update();

这里的plugin是已经存在于我们的系统的plugin.我们实际上是可以通过如下的方式来得到系统所有的plugin的:

    Plugin {
        id: plugin

        // Set the default one
        Component.onCompleted: {
            name = availableServiceProviders[0]
        }
    }

具体的使用方法可以参阅文章"在Ubuntu手机上利用Map API来显示地图并动态显示标记".

当一个地点被成功搜寻后,它返回的数据如下:


我们可以通过这些数据来显示我们得到位置的信息.

基于这些理解,我们做出了我们的例程:

Main.qml

import QtQuick 2.4
import Ubuntu.Components 1.3
import Ubuntu.Components.Popups 1.3
import QtLocation 5.3
import QtPositioning 5.2

MainView {
    // objectName for functional testing purposes (autopilot-qt5)
    objectName: "mainView"

    // Note! applicationName needs to match the "name" field of the click manifest
    applicationName: "placesearchmodel.liu-xiao-guo"

    width: units.gu(60)
    height: units.gu(85)

    property bool centerCurrent: true

    Plugin {
        id: myPlugin
        name: "osm"
    }

    PositionSource {
        id: positionSource
        property variant lastSearchPosition: curLocation
        active: true
        updateInterval: 5000
        onPositionChanged:  {
            var currentPosition = positionSource.position.coordinate

            if ( centerCurrent ) {
                map.center = currentPosition
            }

            var distance = currentPosition.distanceTo(lastSearchPosition)
            //            if (distance > 500) {
            // 500m from last performed pizza search
            lastSearchPosition = currentPosition
            searchModel.searchArea = QtPositioning.circle(currentPosition)
            searchModel.update()
            //            }
        }
    }

    property variant curLocation: QtPositioning.coordinate( 59.93, 10.76, 0)

    PlaceSearchModel {
        id: searchModel
        plugin: myPlugin

        searchTerm: "KFC"
        searchArea: QtPositioning.circle(curLocation)

        Component.onCompleted: update()
    }

    Connections {
        target: searchModel
        onStatusChanged: {
            if (searchModel.status == PlaceSearchModel.Error)
                console.log(searchModel.errorString());
        }
    }

    Component {
        id: pop
        Popover {
            id: popover
            width: units.gu(20)
            property var model
            Column {
                anchors {
                    left: parent.left
                    right: parent.right
                }

                Label {
                    anchors.horizontalCenter: parent.horizontalCenter
                    text: {
                        switch (model.type) {
                        case PlaceSearchModel.UnknownSearchResult:
                            return "type: UnknownSearchResult"
                        case PlaceSearchModel.PlaceResult:
                            return "type: PlaceResult"
                        case PlaceSearchModel.ProposedSearchResult:
                            return "type: ProposedSearchResult"
                        }
                    }
                    fontSize: "medium"
                }

                Label {
                    anchors.horizontalCenter: parent.horizontalCenter
                    text: "title: " + model.title
                    fontSize: "medium"
                }

                Label {
                    anchors.horizontalCenter: parent.horizontalCenter
                    text: "distance: " + (model.distance).toFixed(2) + "m"
                    fontSize: "medium"
                }

                Label {
                    anchors.horizontalCenter: parent.horizontalCenter
                    text: "sponsored: " + model.sponsored
                    fontSize: "medium"
                }
            }
        }
    }

    Page {
        id: page
        header: standardHeader

        PageHeader {
            id: standardHeader
            visible: page.header === standardHeader
            title: "PlaceSearchModel"
            trailingActionBar.actions: [
                Action {
                    iconName: "edit"
                    text: "Edit"
                    onTriggered: page.header = editHeader
                }
            ]
        }

        PageHeader {
            id: editHeader
            visible: page.header === editHeader
            leadingActionBar.actions: [
                Action {
                    iconName: "back"
                    text: "Back"
                    onTriggered: {
                        page.header = standardHeader
                    }
                }
            ]
            contents: TextField {
                id: input
                anchors {
                    left: parent.left
                    right: parent.right
                    verticalCenter: parent.verticalCenter
                }
                placeholderText: "input words .."
                text: "KFC"

                onAccepted: {
                    // clear all of the markers
                    mapItemView.model.reset()

                    searchModel.searchTerm = text
                    searchModel.update();
                }
            }
        }

        Item  {
            anchors {
                left: parent.left
                right: parent.right
                bottom: parent.bottom
                top: page.header.bottom
            }

            Map {
                id: map
                anchors.fill: parent
                plugin: Plugin {
                    name: "osm"
                }
                center: curLocation
                zoomLevel: 13

                gesture {
                    onPanFinished: {
                        centerCurrent = false
                    }
                }

                MapCircle {
                    id: mylocation
                    center: positionSource.position.coordinate
                    radius: units.gu(4)
                    color: "yellow"
                }

                MapItemView {
                    id: mapItemView
                    model: searchModel
                    delegate: MapQuickItem {
                        id: mapitem
                        coordinate: place.location.coordinate

                        anchorPoint.x: image.width * 0.5
                        anchorPoint.y: image.height

                        sourceItem: Column {
                            Image {
                                width: units.gu(3)
                                height: width
                                id: image
                                source: "marker.png"
                            }
                            Text { text: title; font.bold: true }
                        }

                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                onClicked: PopupUtils.open(pop, mapitem, { 'model': model })
                            }
                        }
                    }
                }

                Component.onCompleted: {
                    zoomLevel = 15
                }
            }
        }

    }
}


整个项目的源码在:https://github.com/liu-xiao-guo/PlaceSearchModel



            
作者:UbuntuTouch 发表于2016/6/21 8:40:59 原文链接
阅读:109 评论:0 查看评论

Read more
UbuntuTouch

在今天的例程中,我们将重点介绍如何使用Ubuntu手机SDK所提供的SDK来创建一个可以聊天的应用.通过这个例程,我们来展示如何利用Bluetooth API接口在两个Ubuntu手机或Ubuntu电脑上进行聊天.


    


1)创建一个Bluetooth Chat server


chatserver.cpp

#include "chatserver.h"

#include <qbluetoothserver.h>
#include <qbluetoothsocket.h>
#include <qbluetoothlocaldevice.h>

static const QLatin1String serviceUuid("e8e10f95-1a70-4b27-9ccf-02010264e9c8");

ChatServer::ChatServer(QObject *parent)
:   QObject(parent), rfcommServer(0)
{
}

ChatServer::~ChatServer()
{
    stopServer();
}

void ChatServer::startServer(const QBluetoothAddress& localAdapter)
{
    if (rfcommServer)
        return;

    rfcommServer = new QBluetoothServer(QBluetoothServiceInfo::RfcommProtocol, this);
    connect(rfcommServer, SIGNAL(newConnection()), this, SLOT(clientConnected()));
    bool result = rfcommServer->listen(localAdapter);
    if (!result) {
        qWarning() << "Cannot bind chat server to" << localAdapter.toString();
        return;
    }

    //serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceRecordHandle, (uint)0x00010010);

    QBluetoothServiceInfo::Sequence classId;

    classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::SerialPort));
    serviceInfo.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList,
                             classId);

    classId.prepend(QVariant::fromValue(QBluetoothUuid(serviceUuid)));

    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceClassIds, classId);
    serviceInfo.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList,classId);

    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceName, tr("Bt Chat Server"));
    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceDescription,
                             tr("Example bluetooth chat server"));
    serviceInfo.setAttribute(QBluetoothServiceInfo::ServiceProvider, tr("qt-project.org"));

    serviceInfo.setServiceUuid(QBluetoothUuid(serviceUuid));

    QBluetoothServiceInfo::Sequence publicBrowse;
    publicBrowse << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::PublicBrowseGroup));
    serviceInfo.setAttribute(QBluetoothServiceInfo::BrowseGroupList,
                             publicBrowse);

    QBluetoothServiceInfo::Sequence protocolDescriptorList;
    QBluetoothServiceInfo::Sequence protocol;
    protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap));
    protocolDescriptorList.append(QVariant::fromValue(protocol));
    protocol.clear();
    protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::Rfcomm))
             << QVariant::fromValue(quint8(rfcommServer->serverPort()));
    protocolDescriptorList.append(QVariant::fromValue(protocol));
    serviceInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList,
                             protocolDescriptorList);

    serviceInfo.registerService(localAdapter);
}

void ChatServer::stopServer()
{
    // Unregister service
    serviceInfo.unregisterService();

    // Close sockets
    qDeleteAll(clientSockets);

    // Close server
    delete rfcommServer;
    rfcommServer = 0;
}

void ChatServer::disconnect()
{
    qDebug() << "Going to disconnect in server";

    foreach (QBluetoothSocket *socket, clientSockets) {
        qDebug() << "sending data in server!";
        socket->close();
    }
}

void ChatServer::sendMessage(const QString &message)
{
    qDebug() << "Going to send message in server: " << message;
    QByteArray text = message.toUtf8() + '\n';

    foreach (QBluetoothSocket *socket, clientSockets) {
        qDebug() << "sending data in server!";
        socket->write(text);
    }
    qDebug() << "server sending done!";
}

void ChatServer::clientConnected()
{
    qDebug() << "clientConnected";

    QBluetoothSocket *socket = rfcommServer->nextPendingConnection();
    if (!socket)
        return;

    connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
    clientSockets.append(socket);
    emit clientConnected(socket->peerName());
}

void ChatServer::clientDisconnected()
{
    QBluetoothSocket *socket = qobject_cast<QBluetoothSocket *>(sender());
    if (!socket)
        return;

    emit clientDisconnected(socket->peerName());

    clientSockets.removeOne(socket);

    socket->deleteLater();
}

void ChatServer::readSocket()
{
    QBluetoothSocket *socket = qobject_cast<QBluetoothSocket *>(sender());
    if (!socket)
        return;

    while (socket->canReadLine()) {
        QByteArray line = socket->readLine().trimmed();
        emit messageReceived(socket->peerName(),
                             QString::fromUtf8(line.constData(), line.length()));
    }
}


在这里我们通过QBluetoothServer来创建一个Bluetooth基于RFCOMM协议的server.我们发布一个基于这个协议的server.其它想连接这个服务器的client,必须寻找我们在这里所定义的ServiceUuid:

 classId << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::SerialPort));
    serviceInfo.setAttribute(QBluetoothServiceInfo::BluetoothProfileDescriptorList,
                             classId);

    classId.prepend(QVariant::fromValue(QBluetoothUuid(serviceUuid)));

这里所定义的serviceUuid:

static const QLatin1String serviceUuid("e8e10f95-1a70-4b27-9ccf-02010264e9c8");

2)创建一个Bluetooth client


我们可以创建一个Bluetooth的client用来发起一个向Bluetooth server的连接请求.

chatclient.cpp


#include "chatclient.h"

#include <qbluetoothsocket.h>

ChatClient::ChatClient(QObject *parent)
:   QObject(parent), socket(0)
{
}

ChatClient::~ChatClient()
{
    stopClient();
}

void ChatClient::startClient(const QBluetoothServiceInfo &remoteService)
{
    if (socket)
        return;

    // Connect to service
    socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
    qDebug() << "Create socket";
    socket->connectToService(remoteService);
    qDebug() << "ConnectToService done";

    connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
    connect(socket, SIGNAL(connected()), this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
}

void ChatClient::stopClient()
{
    delete socket;
    socket = 0;
}

void ChatClient::readSocket()
{
    if (!socket)
        return;

    while (socket->canReadLine()) {
        QByteArray line = socket->readLine();
        emit messageReceived(socket->peerName(),
                             QString::fromUtf8(line.constData(), line.length()));
    }
}

void ChatClient::sendMessage(const QString &message)
{
    qDebug() << "Sending data in client: " + message;

    QByteArray text = message.toUtf8() + '\n';
    socket->write(text);
}

void ChatClient::connected()
{
    emit connected(socket->peerName());
}

void ChatClient::disconnect() {
    qDebug() << "Going to disconnect in client";
    if ( socket ) {
        qDebug() << "diconnecting...";
        socket->close();
    }
}

当我们发生一个请求的时候,我们可以通过如下的方式来连接:

chat.cpp

void Chat::connectToDevice(QString name)
{
    qDebug() << "Connecting to " << name;

    // Trying to get the service
    QBluetoothServiceInfo service;
    QMapIterator<QString, QBluetoothServiceInfo> i(remoteSelector->m_discoveredServices);
    bool found = false;
    while (i.hasNext()){
        i.next();
        QString key = i.key();
        if ( key == name ) {
            qDebug() << "The device is found";
            service = i.value();
            qDebug() << "value: " << i.value().device().address();
            found = true;
            break;
        }
    }

    if ( found ) {
        qDebug() << "Going to create client";
        ChatClient *client = new ChatClient(this);
        qDebug() << "Connecting...";

        connect(client, SIGNAL(messageReceived(QString,QString)),
                this, SIGNAL(showMessage(QString,QString)));
        connect(client, SIGNAL(disconnected()), this, SIGNAL(clientDisconnected()));
        connect(client, SIGNAL(disconnected()), this, SLOT(clientIsDisconnected()));
        connect(client, SIGNAL(connected(QString)), this, SIGNAL(connected(QString)));
        connect(this, SIGNAL(sendMessage(QString)), client, SLOT(sendMessage(QString)));
        connect(this, SIGNAL(disconnect()), client, SLOT(disconnect()));

        qDebug() << "Start client";
        client->startClient(service);

        clients.append(client);
    }
}



3)扫描Bluetooth device


我们可以通过如下的方法来扫描附件的Bluetooth设备:

remoteselector.cpp


#include <qbluetoothdeviceinfo.h>
#include <qbluetoothaddress.h>
#include <qbluetoothlocaldevice.h>

#include "remoteselector.h"

QT_USE_NAMESPACE

RemoteSelector::RemoteSelector(QBluetoothAddress &localAdapter, QObject *parent)
: QObject(parent)
{
    m_discoveryAgent = new QBluetoothServiceDiscoveryAgent(localAdapter);

    connect(m_discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)),
            this, SLOT(serviceDiscovered(QBluetoothServiceInfo)));
    connect(m_discoveryAgent, SIGNAL(finished()), this, SLOT(discoveryFinished()));
    connect(m_discoveryAgent, SIGNAL(canceled()), this, SLOT(discoveryFinished()));
}

RemoteSelector::~RemoteSelector()
{
    delete m_discoveryAgent;
}

void RemoteSelector::startDiscovery(const QBluetoothUuid &uuid)
{
    qDebug() << "startDiscovery";
    if (m_discoveryAgent->isActive()) {
        qDebug() << "stop the searching first";
        m_discoveryAgent->stop();
    }

    m_discoveryAgent->setUuidFilter(uuid);
    m_discoveryAgent->start(QBluetoothServiceDiscoveryAgent::FullDiscovery);

}

void RemoteSelector::stopDiscovery()
{
    qDebug() << "stopDiscovery";
    if (m_discoveryAgent){
        m_discoveryAgent->stop();
    }
}

QBluetoothServiceInfo RemoteSelector::service() const
{
    return m_service;
}

void RemoteSelector::serviceDiscovered(const QBluetoothServiceInfo &serviceInfo)
{
#if 0
    qDebug() << "Discovered service on"
             << serviceInfo.device().name() << serviceInfo.device().address().toString();
    qDebug() << "\tService name:" << serviceInfo.serviceName();
    qDebug() << "\tDescription:"
             << serviceInfo.attribute(QBluetoothServiceInfo::ServiceDescription).toString();
    qDebug() << "\tProvider:"
             << serviceInfo.attribute(QBluetoothServiceInfo::ServiceProvider).toString();
    qDebug() << "\tL2CAP protocol service multiplexer:"
             << serviceInfo.protocolServiceMultiplexer();
    qDebug() << "\tRFCOMM server channel:" << serviceInfo.serverChannel();
#endif

    QString remoteName;
    if (serviceInfo.device().name().isEmpty())
        remoteName = serviceInfo.device().address().toString();
    else
        remoteName = serviceInfo.device().name();

    qDebug() << "adding to the list....";
    qDebug() << "remoteName: "  << remoteName;
    m_discoveredServices.insert(remoteName, serviceInfo);
    emit newServiceFound();
}

void RemoteSelector::discoveryFinished()
{
    qDebug() << "discoveryFinished";
    emit finished();
}

我们可以通过调用startDiscovery()来扫描附近的设备.在调用时,我们可以设置我们想要的serviceUuid:

chat.cpp


void Chat::searchForDevices()
{      
    qDebug() << "search for devices!";
    if ( remoteSelector ) {
        delete remoteSelector;
        remoteSelector = NULL;
    }

    QBluetoothAddress adapter = QBluetoothAddress();
    remoteSelector = new RemoteSelector(adapter, this);

    connect(remoteSelector, SIGNAL(newServiceFound()), this, SLOT(newServiceFound()));

    remoteSelector->m_discoveredServices.clear();
    remoteSelector->startDiscovery(QBluetoothUuid(serviceUuid));
    connect(remoteSelector, SIGNAL(finished()), this, SIGNAL(discoveryFinished()));
}

这样就可以扫描到具有我们所需要的serviceUuid的设备来提供连接.在扫描时,Bluetooth server必须是在运行的状态.


4)应用UI设计


我们的应用UI设计比较简单.就想上面显示的图一样,我们最上面的显示当前正在运行该应用的Bluetooth server的设备.当我们点击该设备时,就开始向该设备发送连接请求.在我们的下面的对话框中,会显示连接的状态及对话:

Main.qml


import QtQuick 2.4
import Ubuntu.Components 1.3
import QtBluetooth 5.3

MainView {
    // objectName for functional testing purposes (autopilot-qt5)
    objectName: "mainView"

    // Note! applicationName needs to match the "name" field of the click manifest
    applicationName: "btchat.xiaoguo"

    width: units.gu(60)
    height: units.gu(85)

    function getBluetoothState(state) {
        switch (state ) {
        case BluetoothSocket.Unconnected:
            return "Unconnected";
        case BluetoothSocket.ServiceLookup:
            return "ServiceLookup";
        case BluetoothSocket.Connecting:
            return "Connecting";
        case BluetoothSocket.Connected:
            return "Connected";
        case BluetoothSocket.Bound:
            return "Bound";
        case BluetoothSocket.Closing:
            return "Closing";
        case BluetoothSocket.Listening:
            return "Listening";
        case BluetoothSocket.ServiceLookup:
            return "ServiceLookup";
        case BluetoothSocket.NoServiceSet:
            return "NoServiceSet";
        default:
            return "Unknow state"
        }
    }

    function appendMessage(msg, alignright) {
        mymodel.append({ "msg": msg, "alignright": alignright} )
        listview.positionViewAtIndex(mymodel.count - 1, ListView.Beginning)
    }

    Connections {
        target: chat
        onConnected: {
            console.log("Connected: " + name)
            appendMessage( "connected to " + name, false )
        }

        onDisconnected: {
            console.log("Disconnected: " + name )
            appendMessage( "disconnected " + name, false )
        }

        onClientDisconnected: {
            console.log("Client Disconnected")
            appendMessage("Client Disconnected", false)
        }

        onShowMessage: {
            console.log("sender: " + sender )
            console.log("message: " + message )
            message = message.replace(/(\r\n|\n|\r)/gm,"");
            var msg = '<font color = "green">' + message + '</font>';
            console.log("msg: " + msg)
            appendMessage(msg, false)
        }

        onNewServicesFound: {
            console.log("new services found!")
            devlist.model = list;
        }

        onDiscoveryFinished: {
            console.log("discovery finished");
            indicator.running = false;
        }
    }

    ListModel {
        id: mymodel
    }

    ListModel {
        id: services
    }

    BluetoothDiscoveryModel {
        id: btModel
        running: false
        discoveryMode: BluetoothDiscoveryModel.FullServiceDiscovery
        onRunningChanged : {
        }

        onErrorChanged: {
        }

        onServiceDiscovered: {
            console.log("service has been found!")
            services.append( {"service": service })
        }
        uuidFilter: "e8e10f95-1a70-4b27-9ccf-02010264e9c8"
    }

    BluetoothSocket {
        id: socket
        connected: true

        onSocketStateChanged: {
            console.log("socketState: " + socketState);
            console.log("Connected to server! ")
            appendMessage( "State: " + getBluetoothState(socketState) )
        }

        onStringDataChanged: {
            console.log("Received data: " )
            var data = "Going to send: " + socket.stringData;
            data = data.substring(0, data.indexOf('\n'))
            console.log(data);
            appendMessage("Received: " + data)
        }
    }

    Component {
        id: highlight
        Rectangle {
            width: devlist.width
            height: devlist.delegate.height
            color: "lightsteelblue"; radius: 5
            Behavior on y {
                SpringAnimation {
                    spring: 3
                    damping: 0.2
                }
            }
        }
    }

    Page {
        id: page
        header: standardHeader

        PageHeader {
            id: standardHeader
            visible: page.header === standardHeader
            title: "Bluetooth chat"
            trailingActionBar.actions: [
                Action {
                    iconName: "edit"
                    text: "Edit"
                    onTriggered: page.header = editHeader
                }
            ]
        }

        PageHeader {
            id: editHeader
            visible: page.header === editHeader
            leadingActionBar.actions: [
                Action {
                    iconName: "back"
                    text: "Back"
                    onTriggered: {
                        page.header = standardHeader
                    }
                }
            ]
            contents: Row {
                id: layout
                anchors {
                    left: parent.left
                    right: parent.right
                    verticalCenter: parent.verticalCenter
                }
                spacing: units.gu(2)

                TextField {
                    id: input
                    width: parent.width*2/3
                    placeholderText: "input words .."
                    text: "I love you!"

                    onAccepted: {
                        console.log("going to send: " + text)
                    }
                }

                Button {
                    text: "Send"
                    width: parent.width - input.width - layout.spacing;
                    onClicked: {
                        console.log("send is clicked")
                        console.log("chat length: " + input.text.length)
                        chat.sendMessage(input.text);
                        appendMessage(input.text, true)
                    }
                }
            }
        }

        Item {
            anchors {
                left: parent.left
                right: parent.right
                bottom: parent.bottom
                top: page.header.bottom
            }

            ActivityIndicator {
                id: indicator
                anchors.centerIn: parent
            }

            Column {
                anchors.fill: parent

                Label {
                    text: "Devices are:"
                    fontSize: "x-large"
                }

                ListView {
                    id: devlist
                    width: parent.width
                    height: parent.height/4
                    model: services
                    highlight: highlight
                    delegate: Label {
                        width: parent.width
                        text: modelData
                        fontSize: "x-large"
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                console.log("it is selected")
                                chat.connectToDevice(modelData)
                            }
                        }
                    }
                }

                Rectangle {
                    width: parent.width
                    height: units.gu(0.4)
                    color: "green"
                }

                ListView {
                    id: listview
                    width: parent.width
                    height: parent.height - devlist.height
                    model: mymodel
                    delegate: Item {
                        width: page.width
                        height: txt.height * 1.2 /*+ div.height*/

                        Rectangle {
                            width: txt.contentWidth
                            height: parent.height
                            color: alignright? "green" : "white"
                            radius: units.gu(0.5)
                            anchors.right: alignright ? parent.right : undefined
                            anchors.verticalCenter: parent.verticalCenter
                        }

                        Label {
                            id: txt
                            width: parent.width*0.7
                            text: msg
                            anchors.right: alignright ? parent.right : undefined
                            horizontalAlignment: alignright ? Text.AlignRight :
                                                              Text.AlignLeft
                            fontSize: "large"
                            anchors.verticalCenter: parent.verticalCenter
                            wrapMode: Text.WordWrap
                        }

//                        Rectangle {
//                            id: div
//                            width: parent.width
//                            height: units.gu(0.2)
//                            color: "blue"
//                        }
                    }
                }
            }


            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                anchors.bottom: parent.bottom
                anchors.bottomMargin: units.gu(1)
                spacing: units.gu(2)

                Button {
                    text: "Search"
                    onClicked: {
                        console.log("btModel.running: " + btModel.running )
                        var list = []
                        devlist.model = list;
                        chat.searchForDevices()
                        indicator.running = true
                    }
                }

                Button {
                    text: "Stop search"
                    onClicked: {
                        console.log("Stop is clicked!")
                        chat.stopSearch();
                        indicator.running = false
                    }
                }

                Button {
                    text: "Disconnect"
                    onClicked: {
                        console.log("Disconnect is clicked!")
                        chat.disconnect();
                    }
                }
            }
        }
    }
}

整个应用的代码在:https://github.com/liu-xiao-guo/btchat


作者:UbuntuTouch 发表于2016/7/5 14:19:11 原文链接
阅读:98 评论:0 查看评论

Read more
UbuntuTouch

对于一些Ubuntu Geek来说,他们有时更喜欢使用命令行的方式来启动在手机中的应用,并通过这样的方式来调试我们的应用.我们可以通过如下的方式进入到手机的shell中:




我们可以在手机中寻找如下的预先安装好的应用:



对于这里面的应用来说,我们可以通如下的命令来启动我们的应用:


phablet@ubuntu-phablet:~$ ubuntu-app-launch messaging-app

这样我们就可以启动messaging应用了.

当然,我们也可以启动我们已经安装过得应用:


我们可以通过click list命令来查看所有已经安装的应用.我们可以通过如下的方式来启动该应用

$ ubuntu-app-launch `ubuntu-app-triplet com.ubuntu.camera`



在上面的例子中,我们可以启动camera应用.


作者:UbuntuTouch 发表于2016/7/6 17:33:21 原文链接
阅读:86 评论:0 查看评论

Read more
UbuntuTouch

Canonical公司于最近2016年4月发布了一个新的16.04系统,并且这个系统是长期支持版(Long Term Support - LTS).它一如既往地支持debian安装包,但同时它也支持最新的snap安装包.snap安装包是Canonical公司最新发布的一种安装包的格式.更多的信息可以在我们的官方开发者网站:https://developer.ubuntu.com/en/desktop/http://snapcraft.io/查看.


1)16.04桌面支持


如果大家还没自己的16.04的桌面系统,大家可以在地址下载最新的16.04的系统.



从上面的图中,我们可以看出来在16.04的桌面中支持两种格式的安装包:snapdebian.另外我们可以看出,snap包每个安装的应用都是自成一体:包含应用运行所需要的任何依赖(dependencies);同时我们可以看出每个应用都是互相隔离的.和debian包相比较,我们可以看出来每个debian应用的安装依赖于其它包的安装;debian应用之间可以不受限制地互相访问而造成安全问题;删除其中的一个debian应用或包可能导致其它的应用不可以正常运行.相比较而言,不同的snap应用可以安装同样一个软件的不同版本(比如一个安装python 2.7,另外一个应用安装python 3.3)而不造成任何的干扰.从理论上讲,一个snap应用可以安装到任何一个Linux的发行版上,因为它不依赖于操作系统及其发布版本.这对于应用的维护来说是非常好的.

Canonical公司目前正在号召全社区把应用移植成为snap包,并最终把操作系统变为ubuntu core系统,从而打造最安全的操作系统及良好的应用维护.

对于一个All-snap Ubuntu core系统来说(如上面的右图所示),它可以分为两个逻辑部分:

  • 只读的最基本的系统
    • 这部分包括配置文件,标准目录,库,工具及核心的服务.系统的这部分是只读的,里面的每个元素不可以被分别更新.这个被称之为"system-image".在一个系统中,这种image可以达到两个及以上.这些最基本的系统是一种root filesystem的形式出现的.在启动后它们之间可以互相roll back,也即如果一个系统启动有问题,可以自动切换到先前的或指定的系统image去.这个部分也是通过snap打包来实现的.
  • 可写的snap应用及在其之上的架构(framework).它们利用上面的系统所提供的服务达成.

2)安装


为了能够使得在16.04的系统上运行snap应用,我们必须做一些安装.在我们的terminal中打入:

$ sudo apt update
$ sudo apt install snapd
$ sudo apt install snapcraft

在我们的16.04系统中,我们必须打开universe,这样我们可以在以后的开发中安装snapcraft工具了.snapcraft是为了我们能够编译一个snap项目而必须的一个工具,尽管在运行时并不需要.它位于下图所示的universe channel中.



然后,你就可以在我们的terminal中安装及运用一个我们所需要的应用:

$ sudo snap install ubuntu-calculator-app
$ ubuntu-calculator-app.calculator

我们可以在我们的电脑的dash中直接运行我们所安装的应用:





如果大家想安装更多的应用的话,可以直接到我们桌面系统的应用商店进行安装:



从上面我们可以看出来,calculator应用也是在里面的.如果大家想知道这个应用是如何实现的,请参考源码:

https://code.launchpad.net/~dpm/ubuntu-calendar-app/snap-all-things

细心的开发者也许会发现,这个应用实际上是使用了同样一个和Ubuntu手机一样的代码.没有做任何的改变.从某种意义上讲,Ubuntu实现了真正意义上的融合(Convergence)应用设计.从另外一个角度上讲,这个snap应用时间上可以部署到任何一个Linux的发行版上,只要有它支持snap包,并且它将不依赖于操作系统的版本发布.维护性应该是非常好的.

我们怎么通过命令行来查找我们所需要的snap应用呢?

liuxg@liuxg:~$ snap find calculator
Name                   Version    Developer      Notes  Summary
ubuntu-calculator-app  2.1+snap3  ubuntucoredev  -      Ubuntu Calculator application for the Unity 7 desktop

我们可以通过上面的命令来查找在商店里应用名字含有calculator的应用.我们可以通过如下的命令来寻找所有在商店里发布的snap应用:

liuxg@liuxg:~$ snap find 
Name                       Version                    Developer             Notes    Summary
ab                         1.0                        snappy-test           -        Test snap with shortest name
ag-mcphail                 1.0.1                      njmcphail             -        The Silver Searcher - mcphail's build and upstream git version
alsa-utils                 1.1.0-1                    woodrow               -        Utilities for configuring and using ALSA
apktool                    2.1.1                      ligboy                -        A tool for reverse engineering 3rd party, closed, binary Android apps.
...

当然,我们也可以通过如下的方法找寻到我们所需要的应用:
liuxg@liuxg:~$ snap find | grep hello
hello                      2.10                       canonical             -        GNU Hello, the "hello world" snap
hello-bluet                0.1                        bluet                 -        Qt Hello World example
hello-huge                 1.0                        noise                 -        a really big snap
hello-snap                 0.01                       muhammad              -        GNU hello-snap, the "Hello, Snap!" snap

3)删除一个snap应用


刚才我们已经成功安装了一个snap应用到我们的桌面系统中.我们现在可以通过如下的命令来删除该应用.我们首先在命令行中显示已经被安装的应用:

liuxg@liuxg:~$ snap list
Name                   Version               Rev  Developer      Notes
hello-world            6.1                   26   canonical      -
rssreader              1.0                   x1                  devmode
rssreader-app          1.0                   x2                  -
snaptest               1                     x1                  devmode
snaptest-app           1                     x3                  devmode
ubuntu-calculator-app  2.1+snap3             5    ubuntucoredev  -
ubuntu-core            16.04+20160531.11-56  122  canonical      -
webcam-webui           1                     x1                  -

在上面,我们看到已经安装了ubuntu-calculator-app应用.我们可以通过如下的方法来删除它.
liuxg@liuxg:~$ sudo snap remove ubuntu-calculator-app
[sudo] password for liuxg: 

Done

重新显示我们已经安装的snap应用列表:

liuxg@liuxg:~$ snap list
Name           Version               Rev  Developer  Notes
hello-world    6.1                   26   canonical  -
rssreader      1.0                   x1              devmode
rssreader-app  1.0                   x2              -
snaptest       1                     x1              devmode
snaptest-app   1                     x3              devmode
ubuntu-core    16.04+20160531.11-56  122  canonical  -
webcam-webui   1                     x1 
显然我们再也找不到ubuntu-calculator-app应用了.


4)在哪里找到安装的文件


当我们把一个应用到我们的系统中后,我们可以通过如下的命令来查看在我们的系统中所安装的所有的snap应用:

liuxg@liuxg:~$ snap list
Name                   Version               Rev  Developer      Notes
hello-world            6.1                   26   canonical      -
rssreader              1.0                   x1                  devmode
rssreader-app          1.0                   x2                  -
snaptest               1                     x1                  devmode
snaptest-app           1                     x3                  devmode
ubuntu-calculator-app  2.1+snap3             5    ubuntucoredev  -
ubuntu-core            16.04+20160531.11-56  122  canonical      -
webcam-webui           1                     x1                  -

对于一些开发者来说,snap的一些命令可能比较陌生.我们可以通过如下的方法来得到帮助:

$ snap --help      # Or use 'snap <command> --help' for help on a specific command

安装好我们的应用后,我们可以在如下的路径找到我们的snap安装文件:

liuxg@liuxg:/var/lib/snapd/snaps$ ls
hello-world_26.snap    rssreader_x1.snap     snaptest-app_x3.snap          ubuntu-core_122.snap
rssreader-app_x1.snap  snaptest-app_x1.snap  snaptest_x1.snap              webcam-webui_x1.snap
rssreader-app_x2.snap  snaptest-app_x2.snap  ubuntu-calculator-app_5.snap

我们可以通过如下的方法查看系统中的mount的情况:

liuxg@liuxg:~$ mount | grep calculator
/var/lib/snapd/snaps/ubuntu-calculator-app_5.snap on /snap/ubuntu-calculator-app/5 type squashfs (ro,relatime)

从上面我们可以看出来,实际上我们是把/var/lib/snapd/snaps/ubuntu-calculator-app_5.snap文件通过mount的方法使之可以在/snap/ubuntu-calculator-app/5目录中可以看见.一般来说,一个snap应用在被成功安装后,它位于/snap/$name/$version/目录中.

liuxg@liuxg:/snap/ubuntu-calculator-app/5$ tree -L 2
.
├── bin
│   └── calculator
├── build
│   └── ubuntu-calculator-app
├── command-calculator.wrapper
├── etc
│   ├── apparmor.d
│   ├── dbus-1
│   ├── default
│   ├── drirc
│   ├── fonts
│   ├── gps.conf
│   ├── gss
│   ├── init
│   ├── init.d
│   ├── ldap
│   ├── pki
│   ├── pulse
│   ├── ucf.conf
│   ├── X11
│   └── xdg
├── lib
│   ├── systemd
│   └── x86_64-linux-gnu
├── meta
│   ├── gui
│   └── snap.yaml
├── usr
│   ├── bin
│   ├── lib
│   └── share
└── var
    └── lib

细心的读者也许已经发现,在被mount的目录中的文件就像另外一个Linux的安装文件结构.它实际上是把这个calculator所需要的所有需要的文件安装到同样的一个根目录中,从而摆脱对系统文件的任何需求.理论上讲,我们的应用不会因为系统的升级或版本的变化而造成不能运行的情况.这对于一些软件开发商来说无疑是一个天大的利好!我们今天设计好的软件,在Ubuntu升级为20.4时,我们不需要做任何的修改.当然,我们也可以把我们的应用部署到其它的任何一个Linux发行版上,它也可以运行得非常好.我们不需要考虑它到底运行的是什么版本的Linux系统及什么版本的发行.

当然对于一个snap应用来说,它的snap文件包的大小也是非常大的.
-rw-r--r--  1 liuxg liuxg 122M 7月  12 12:00 ubuntu-calculator-app_2.1+snap3_amd64.snap

从上面可以看出来,我们的snap包的大小达到122M.如果我们想查看我们所在包里面的内容,我们可以通过如下的命令来实现:

 $ unsquashfs -l ubuntu-calculator-app_2.1+snap3_amd64.snap | less
squashfs-root
squashfs-root/bin
squashfs-root/bin/calculator
squashfs-root/command-calculator.wrapper
squashfs-root/etc
squashfs-root/etc/X11
squashfs-root/etc/X11/Xreset
squashfs-root/etc/X11/Xreset.d
squashfs-root/etc/X11/Xreset.d/README
squashfs-root/etc/X11/Xresources
squashfs-root/etc/X11/Xresources/x11-common
squashfs-root/etc/X11/Xsession
squashfs-root/etc/X11/Xsession.d
squashfs-root/etc/X11/Xsession.d/20x11-common_process-args
squashfs-root/etc/X11/Xsession.d/30x11-common_xresources
squashfs-root/etc/X11/Xsession.d/35x11-common_xhost-local
squashfs-root/etc/X11/Xsession.d/40x11-common_xsessionrc
squashfs-root/etc/X11/Xsession.d/50x11-common_determine-startup
squashfs-root/etc/X11/Xsession.d/60x11-common_localhost
squashfs-root/etc/X11/Xsession.d/60x11-common_xdg_path
...

我们也可以直接通过如下的命令来得到在snap包中所有的文件:

$ unsquashfs ubuntu-calculator-app_2.1+snap3_amd64.snap
$ cd cd squashfs-root
# Hack hack hack
$ snapcraft snap

我们可以通过最后的命名snapcraft snap来重新打包我们的应用.

我们来看一看我们安装后的应用所占的空间大小:

375M	./ubuntu-calculator-app/

也就是说一个应用安装后的空间大小是350M大小.当然这也依赖于我们所安装的应用类型.针对我们的ubuntu-calculator-app来说,我们在包里把我们所需要的Qt库及其它需要的任何东西都打入到包里面了.对于其它的任何python应用来说,也是同样的,我们可以把python版本所需要的任何库都打入到我们的包里面.我们根本不需要担心它会不会对其它的应用造成任何的影响.


5)发布我们的应用到商店


我们可以很方便地把我们已经开发好的应用通过"My Apps"发布到我们的应用商店.在上传我们的应用时,我们一定要记得选择"Ubuntu Core"作为商店来上传.




为了上传一个新的snap应用到商店,我们只需要填入我们所需要的metadata信息及上传我们开发的snap文件即可:





6)受限的snap应用



当一个snap应用被安装后,在运行时,它被置于一个受限的安全的沙箱之中,并且每个应用都是互相隔离的.在默认的情况下,每个snap包中的每个应用都可以互相访问对方,并协同工作.但是,如果它访问其它的不在自己包里的应用或其它资源,它将是受限的.

实现这个安全沙箱的技术叫做AppArmorseccomp及device cgroups.每个应用都有自己的/tmp目录,devpts等.这个受限的设置是由一个叫做snapcraft.yaml的项目文件所定义的.在这个文件中,snap申明它想要访问的资源,系统将会为它生产相应的限制.关于snapcraft.yaml的详细介绍,我们会在以后的文章中逐步介绍.

由于在snap系统中,每个应用的运行是受限的.每个snap应用想访问沙箱以外的资源,它必须要使用interface.interface让我们可以分享一个snap的资源,和其它的snap进行交互及访问我们想得到的硬件资源.一个interface定义了两端之间的交互规则.在两端被称之为plug及slot.我们也可以理解slot为提供放(provider),而plug为消费方(consumer).我们可以通过自动或手动的方式来把plug和slot一起联系起来.当然,我们也可以删除这种连接.

作为一个例子,当我们使用snapcraft来生产我们想要的snap文件时,我们想要我们的snap应用最终能够访问我们用户的$HOME文件目录.在snap系统中,我们是通过一个叫做plug及slot的概念来实现的.我们可以通过如下的命令来查看我们已经存在的plug及slot.

liuxg@liuxg:~$ snap interfaces
Slot                 Plug
:camera              -
:cups-control        -
:firewall-control    -
:gsettings           -
:home                rssreader-app,snaptest-app
:locale-control      -
:log-observe         -
:modem-manager       -
:mount-observe       -
:network             -
:network-bind        webcam-webui
:network-control     -
:network-manager     -
:network-observe     -
:opengl              rssreader-app,snaptest-app,ubuntu-calculator-app
:optical-drive       -
:ppp                 -
:pulseaudio          -
:snapd-control       -
:system-observe      -
:timeserver-control  -
:timezone-control    -
:unity7              rssreader-app,snaptest-app,ubuntu-calculator-app
:x11                 -

上面显示了在我的电脑系统中每个snap应用所定义的plug.关于interfaces的更详细的介绍可以参阅我们的文档"Interfaces".在文章里,它详细地介绍每个plugs.当我们的应用需要访问到我们所需要的资源时,在我们的snapcraft.yaml项目文件中,我们必须申明这个权限,这样我们的应用就可以访问到我们所需要的资源.比如,针对我们的snap,如果我们想要访问$HOME目录时,我们可以在snapcraft.yaml中这样定义:

name: foo
apps:
  bar:
    command: bin/bar
    plugs: [ home, unity7 ] 

这样我们的snap应用就可以访问到$HOME目录了.否则我们就可能在/var/log/syslog文件中发现denied错误信息.更多关于安全的介绍可以参阅文章"Snap security policy and sandboxing".

另外我们值得指出的是:如果我们想我们的应用还是像我们以前在ubuntu的桌面上运行而不受snap安全机制的限制,我们可以使用如下的命令来安装我们的应用:

$ sudo snap install <package.snap> --devmode

就像上面指出的那样,这是一种在developer mode下的开发.它可以让开发者在起始开发应用时放开安全问题(不受限制)大胆开发.在发布应用时,我们再进行安全的调试.更多这方面的介绍,我们可以参阅文章"Learn to make a snap"或文章"helloworld Snap例程".

我们必须注意的是:

Snaps can be uploaded to the edge and beta channels only

关于snapcraft.yaml的知识,我们会在以后的章节中详细介绍,所以大家先不要着急!


7)如何得到snap帮助


就想我们上面所写的那样,我们可以通过如下命令来得到snap的帮助:

liuxg@liuxg:~$ snap --help
Usage:
  snap [OPTIONS] <command>

The snap tool interacts with the snapd daemon to control the snappy software platform.


Application Options:
      --version  print the version and exit

Help Options:
  -h, --help     Show this help message

Available commands:
  abort        Abort a pending change
  ack          Adds an assertion to the system
  change       List a change's tasks
  changes      List system changes
  connect      Connects a plug to a slot
  create-user  Creates a local system user
  disconnect   Disconnects a plug from a slot
  find         Finds packages to install
  help         Help
  install      Install a snap to the system
  interfaces   Lists interfaces in the system
  known        Shows known assertions of the provided type
  list         List installed snaps
  login        Authenticates on snapd and the store
  logout       Log out of the store
  refresh      Refresh a snap in the system
  remove       Remove a snap from the system
  run          Run the given snap command
  try          Try an unpacked snap in the system

针对每个snap下面的命令,我们可以通过如下的方式来得它的帮助信息:

liuxg@liuxg:~$ snap install -h
Usage:
  snap [OPTIONS] install [install-OPTIONS] <snap>

The install command installs the named snap in the system.

Application Options:
      --version        print the version and exit

Help Options:
  -h, --help           Show this help message

[install command options]
          --channel=   Use this channel instead of stable
          --edge       Install from the edge channel
          --beta       Install from the beta channel
          --candidate  Install from the candidate channel
          --stable     Install from the stable channel
          --devmode    Install the snap with non-enforcing security

通过上面的方法,我们可以对snap命令有更深的理解.

7)如编译一个snap应用


如果大家已经有一个snap的项目,你只需要:
  • 安装snapcraft.请参阅文章的开始部分
  • 在项目的根目录下,直接键入"snapcraft"即可.在项目的根目录下通常含有snapcraft.yaml文件或.snapcraft.yaml文件.
Canonical公司已经号召很多的全球开发者开发snap应用.我们已经把已经开发好的应用放在如下的仓库里了.如果大家对这个感兴趣,请安装如下的指令来下载这些应用作为参考:

$ git clone https://github.com/ubuntu/snappy-playpen.git
$ cd snappy-playpen

目前已经有如下的项目可以供我们参考:

atom/               idea/                openttd/         tinyproxy/
cloudfoundry-cli/   imagemagick-edge/    plank/           tyrant-unleashed-optimizer/
consul/             imagemagick-stable/  qcomicbook/      ubuntu-clock-app/
dcos-cli/           keepassx/            qdriverstation/  ubuntukylin-icon-theme/
deis-workflow-cli/  kpcli/               ristretto/       vault/
dosbox/             leafpad/             scummvm/         vlc/
ffmpeg/             minetest/            shotwell/        wallpaperdownloader/
galculator/         moon-buggy/          smplayer/        youtube-dl/
gitter-im/          mpv/                 snap-template/
heroku/             openjdk-demo/        snaptest/

我们可以直接进入到项目的根目录下,键入如下的命令即可:
$ snapcraft
当项目被成功编译完后,我们可以直接在项目的根目录下找到一个扩展名为.snap的文件.这就是我们所需要的snap安装文件.我们可以参照我们上面讲述的方法来安装这个文件.

如果想清除一个snap应用在编译过程中的文件,我们可以打入如下的命令:

$ snapcraft clean

更多关于snapcraft的知识可以参阅它的帮助:

liuxg@liuxg:~$ snapcraft --help
snapcraft

Usage:
 ...

The available commands are:
  help         Obtain help for a certain plugin or topic
  init         Initialize a snapcraft project.
  list-plugins List the available plugins that handle different types of part.
  login        Authenticate session against Ubuntu One SSO.
  logout       Clear session credentials.
  register     Register the package name in the store.
  tour         Setup the snapcraft examples tour in the specified directory,
               or ./snapcraft-tour/.
  upload       Upload a snap to the Ubuntu Store.

The available lifecycle commands are:
  clean        Remove content - cleans downloads, builds or install artifacts.
  cleanbuild   Create a snap using a clean environment managed by lxd.
  pull         Download or retrieve artifacts defined for a part.
  build        Build artifacts defined for a part. Build systems capable of
               running parallel build jobs will do so unless
               "--no-parallel-build" is specified.
  stage        Stage the part's built artifacts into the common staging area.
  prime        Final copy and preparation for the snap.
  snap         Create a snap.

Parts ecosystem commands
  update       Updates the parts listing from the cloud.
  define       Shows the definition for the cloud part.
  search       Searches the remotes part cache for matching parts.

Calling snapcraft without a COMMAND will default to 'snap'

在snapcraft打包的过程中,它经历如下的几个阶段:

  pull         Download or retrieve artifacts defined for a part.
  build        Build artifacts defined for a part. Build systems capable of
               running parallel build jobs will do so unless
               "--no-parallel-build" is specified.
  stage        Stage the part's built artifacts into the common staging area.
  prime        Final copy and preparation for the snap.
  snap         Create a snap.

我们可以通过snapcraft来对每个阶段分别处理来查看每一步到底做什么.比如"snapcraft pull"等.打包的顺序是按照上面所列举的顺序执行的.更多关于如何打包的过程请参阅连接http://snapcraft.io/create/

如果大家对如何开发一个Ubuntu桌面的应用感兴趣的话,可以参阅我的文章"如何把一个qmake的Ubuntu手机应用打包为一个snap应用"或"helloworld Snap例程".

8)如何运行一个snap应用


我们可以在Dash中运行我们的应用,同时,我们也可以在terminal中通过命令行的方式来启动我们的应用.在我们设计我们的snap应用时,通常我们使用一个叫做snapcraft.yaml的项目文件.我们现在来用一个例子来说明:

snapcraft.yaml


name: snaptest-app
version: 1
summary: This is a summary
description: This is the description
confinement: devmode

apps:
  test:
    command: desktop-launch $SNAP/lib/x86_64-linux-gnu/bin/snaptest
    plugs: [home,unity7,opengl]

parts:
  application:
    source: ./src
    plugin: qmake
    qt-version: qt5
    build-packages:
      - cmake
      - gettext
      - intltool
      - ubuntu-touch-sounds
      - suru-icon-theme
      - qml-module-qttest
      - qml-module-qtsysteminfo
      - qml-module-qt-labs-settings
      - qtdeclarative5-u1db1.0
      - qtdeclarative5-qtmultimedia-plugin
      - qtdeclarative5-qtpositioning-plugin
      - qtdeclarative5-ubuntu-content1
      - qt5-default
      - qtbase5-dev
      - qtdeclarative5-dev
      - qtdeclarative5-dev-tools
      - qtdeclarative5-folderlistmodel-plugin
      - qtdeclarative5-ubuntu-ui-toolkit-plugin
      - xvfb
    stage-packages:
      - ubuntu-sdk-libs
      - qtubuntu-desktop
      - qml-module-qtsysteminfo
    snap:
      - -usr/share/doc
      - -usr/include
    after: [desktop/qt5]

在上面的snapcraft.yaml文件中,我们的包的名字叫做"snaptest-app".在apps下定义了一个应用叫做"test".那么在命令行中,我们可以通过如下的方式来运行我们的最终的应用:

$ snaptest-app.test

也就是说,我们可以通过<<package-name>>.<<application-name>>来启动我们的应用.如果大家想对snapcraft有更多的了解,请参阅我们录制的视频"Snapcraft操作演示--教你如何snap一个应用


9)如何让我们的系统恢复到没有snap安装的起始状态


我们在开发snap的过程中,我们发现经常可能的情况是一个snap占用太多的空间.加之如果有多个版本被安装的话(每次安装都会生产一个新的版本),那么我们硬盘的空间占用将会变得很大.如果我们去手动去除这些版本的话,非常麻烦.我们可能需要用到umount,并且容易造成如下目录中的文件:

/var/lib/snapd/state.json

的破损,以至于我们在正常使用snap list命令不能产生我们想要的结果.那么我们如何处理这个问题呢?
我们可以在如下的地址获取我们想要的脚本:

git clone https://github.com/zyga/devtools/

让后运行如下下载的命令:

$ sudo ./reset-state

我们按照命令所指出的提示进行操作.这样我们就可以把我之前所有已经安装过的snap应用及环境都删除.我们的系统恢复到原来没有安装过任何snap的状态!


10)更多的学习资源


我们可以通过如下的方法得到我们需要的例程:

$ sudo apt update
$ sudo apt install snapd snapcraft snapcraft-examples

我们也可以通过如下的方式得到我们已经开发好的应用的源码:

$ git clone https://github.com/ubuntu/snappy-playpen

我们可以利用这些资源来参考学习所有已经有的应用.



作者:UbuntuTouch 发表于2016/7/12 11:06:39 原文链接
阅读:771 评论:0 查看评论

Read more
UbuntuTouch

我们知道Ubuntu平台提供了良好的融合(convergence)设计.通过融合设计,使得我们的同样一个应用在不需要修改任何代码的情况下,重新打包就可以运行到不同的屏幕尺寸的设备上.当然,Canonical公司最终的目的是实现snap应用运行到所有设备上,而不需要进行任何的重新打包的动作.目前Ubuntu手机上支持的应用打包格式是click包.在为了的Ubuntu SDK中,最终我们会把snap的支持加入到我们的SDK之中去.那么目前我们怎么把我们已经开发好的应用打包成为一个snap应用包,并可以成功部署到我们的电脑桌面(16.04)上呢?

如果大家对如何安装一个snap应用到16.04的桌面系统上的话,请参阅文章"安装snap应用到Ubuntu 16.4桌面系统".


1)通过Ubuntu SDK开发一个我们需要的手机应用


我们可以通过Ubuntu SDK来创建一个我们想要的项目.关于如何创建一个Ubuntu手机应用,这个不在我们的这个教程范围.如果你对如何利用Ubuntu SDK开发一个手机应用感兴趣的话,请参考我们的文章"Ubuntu 手机开发培训准备".这里将不再累述!

值得指出的是:在今天的教程中,我们将教大家如何把一个qmake的Ubuntu手机应用打包为一个snap的应用.这里,我们将利用之前我已经开发的一个项目作为例程来开始.我们在terminal下打入如下的命令:

$ git clone https://github.com/liu-xiao-guo/rssreader_snap

下载后的源码结构如下:

liuxg@liuxg:~/snappy/desktop/rssreader$ tree -L 2
.
├── snapcraft.yaml
└── src
    ├── manifest.json.in
    ├── po
    ├── rssreader
    └── rssreader.pro

从上面的结构上,我们可以看到:在src目录下的整个项目是有我们的Ubuntu SDK所创建的一个qmake项目,它有一个项目文件.pro文件.在手机上的运行情况如下:

  

同时,在我们项目的根目录下,我们发现了另外一个文件snapcraft.yaml.这个文件就是为了能够让我们把我们的qmake项目最终打包为snap应用的snap项目文件.


2)为我们的qmake项目打包


在上节中,我们已经提到了我们项目的snapcraft.yaml文件.现在我们把这个文件展示如下:

snapcraft.yaml


name: rssreader-app
version: 1.0
summary: A snap app from Ubuntu phone app
description: This is an exmaple showing how to convert a Ubuntu phone app to a desktop snap app
confinement: strict

apps:
  rssreader:
    command: desktop-launch $SNAP/lib/x86_64-linux-gnu/bin/rssreader
    plugs: [home,unity7,opengl]

parts:
  rssreader:
    source: src/
    plugin: qmake
    qt-version: qt5
    build-packages:
      - cmake
      - gettext
      - intltool
      - ubuntu-touch-sounds
      - suru-icon-theme
      - qml-module-qttest
      - qml-module-qtsysteminfo
      - qml-module-qt-labs-settings
      - qtdeclarative5-u1db1.0
      - qtdeclarative5-qtmultimedia-plugin
      - qtdeclarative5-qtpositioning-plugin
      - qtdeclarative5-ubuntu-content1
      - qt5-default
      - qtbase5-dev
      - qtdeclarative5-dev
      - qtdeclarative5-dev-tools
      - qtdeclarative5-folderlistmodel-plugin
      - qtdeclarative5-ubuntu-ui-toolkit-plugin
      - xvfb
    stage-packages:
      - ubuntu-sdk-libs
      - qtubuntu-desktop
      - qml-module-qtsysteminfo
      - ubuntu-defaults-zh-cn
    snap:
      - -usr/share/doc
      - -usr/include
    after: [desktop/qt5]

初以乍看,这个文件和我们以往所看到的文件都不同.似乎很复杂!关于snapcraft.yaml的具体解释,我们可以参考我们的官方文档"snapcraft.yaml syntax".

在这里,我们做一个简单的解释:
  • name: 这是最终的包的名称.针对我们的情况,我们最终的snap包的名字为rssreader-app_1.0_amd64.snap
  • version: 这是我们包的版本信息.就像我们包的名称rssreader-app_1.0_amd64.snap所展示的那样.1.0是我们的版本信息
  • summary: 这是一个描述我们包信息的字符串.根据我们的设计,他只能最多长达79个字符
  • description:这是一个描述我们包的字符串.它可以比summary来得更长一些
  • confinement: 受限的种类:strict 或 devmode.当我们设置为devmode时,在安装时加上--devmode选项时,可以使得我们的应用不接受任何的安全的限制.就像我们以前在Ubuntu电脑上开发一样.我们可以随意地访问任何一个我们想要访问的目录等等
  • apps: 在这里定义我们的应用及其运行时所需要的命令.针对我们的情况,我们定义rssreader为我们的应用.当我们执行我们的应用时,我们需要使用<<包名>>.<<应用名>>来运行我们的应用.针对我们的情况,我们使用rssreader-app.rssreader来通过命令行来运行我们的应用
    • command:这是用来启动我们应用所需要的命令行.针对我们的情况:desktop-launch $SNAP/lib/x86_64-linux-gnu/bin/rssreader.这里的desktop-launch来自我们下面的已经预先编译好的包 desktop/qt5
    • plugs:这一项定义了我们的snap应用所访问的权限.通过我们的设定,我们可以访问系统的$HOME目录及使用opengl等.更多细节请擦参阅Interfaces
  • parts: 每个part定义了我们软件所需要的部分.每个part就像一个mini的小项目.在我们编译时可以在parts的目录中分别找到对应的部分
    • rssreader: 我们定义的part的名称.它的名字可以是任何你所喜欢的名称
      • source: 定义part的源码.它可以在网站上的任何一个软件(bzr, git, tar)
      • plugin: 定义编译part所需要用到的plugin.开发者也可以拓展snapcraft的plugin.请参阅文章"Write your own plugins
      • qt-version:这个是针对Qt plugin来说的.定义Qt的版本
      • build-packages:定义在这里的每个包都是为了用来编译我们的项目的.需要安装的.它们将不会出现在最终的snap文件中
      • stage-packages:这些定义的包都要最终被打入到snap包中,并形成运行该应用所需要的文件.特别值得指出的是:我们加入了中文包ubuntu-defaults-zh-cn,从而使得我们的应用可以看见中文的显示.当然,我们包的大小也从100多兆增加到300多兆.注意这里的包都对应在我们通常ubuntu下的debian包
      • snap:定义了我们需要的或不需要的文件.在这里我们通过"-"来把一些不想要的文件剔除从而不打入到我们的包中
      • after:表明我们的这个part的编译必须是在desktop/qt5下载之后.对于有些项目,我们必须先得到一个part,并使用这个part来编译我们其它的part.在这种情况下,我们可以使用after来表明我们的先后顺序.在这里,我们也利用了其它人所开发的part desktop/qt5.我们可以在网址https://wiki.ubuntu.com/snapcraft/parts找到别人已经发布的parts.这些parts的描述也可以在地址https://wiki.ubuntu.com/Snappy/Parts找到.我们可以重复利用它们.在命令行中,我们也可以公共如下的命令来查找已经有的parts:
        • snapcraft update
        • snapcraft search
当然我们只做了一个简单的描述.更详细的关于snapcraft.yaml的描述,请参阅我们的文档"snapcraft.yaml syntax"或文档

3)编译我们的snap应用


为了编译我们的snap应用,其实非常简单.我们直接进入到我们的项目的根目录下,并打入如下的命令:

$ snapcraft

这样,我们就可以编译我们的应用,并最终生产我们所需要的.snap文件:

312M 7月  13 12:25 rssreader-app_1.0_amd64.snap

就像我们上节中介绍的那样,由于我们加入了中文字体,所以我们的应用变得非常庞大.没有字体的snap包大约为141M.
如果我们想要清楚我们的打包过程中的中间文件,我们可以打入如下的命令:

$ snapcraft clean

它将清除在parts, stage及prime目录下的所有的文件.更多关于snapcraft的介绍,可以参阅我的文章"安装snap应用到Ubuntu 16.4桌面系统".我们也可以通过如下的方式来得到它的帮助:

$ snapcraft --help


4)安装及运行我们的应用


我们可以通过如下的命令来安装我们的.snap文件:

$ sudo snap install rssreader-app_1.0_amd64.snap

我们可以通过如下的命令来运行我们的应用:

$ rssreader-app.rssreader

运行时的画面如下:



从上面可以看出来.我们没有经过任何的修改,但是我们的手机应用也可以在16.04的桌面上运行得非常好.在本应用中,它也使用了融合(Convergence)技术,从而使得我们的应用在不同的屏幕尺寸上自动适配.大家可以参阅我的文章"运用AdaptivePageLayout来做融合(convergence)设计以实现动态布局


5)安全调试


我们可以在我们的桌面系统中安装如下的软件:

$ snap install snappy-debug

如果在安装的过程中提示还需要安装其它的应用软件,我们按照提示安装即可.
接下来我们在一个terminal中打入如下的命令:

$ snappy-debug.security scanlog

根据Interfaces文档介绍,log-observe是不能自动连接的,我们需要使用如下的命令来手动建立这种连接:

$ sudo snap connect snappy-debug:log-observe ubuntu-core:log-observe

这种方法也适用于我们建立其它需要手动链接的的情况.然后在另外一个terminal中打入如下的命令:

$ rssreader-app.rssreader

那么我们可以在这个窗口看到如下的信息:



显然在我们的应用运行时产生了一些安全的问题,并提示一些上面的输出信息.我们切换到另外一个运行命令"snappy-debug.security scanlog"的窗口:



显然在这个输出窗口也显示了一些"DENIED"安全错误信息.那么这些问题是怎么来的呢?显然,这可能是我们的应用没有设置相应的plug所致.我们可以参阅我们的官方文档interfaces,并结合我们的应用.我们可以初步判断,我们可能需要network及network-bind plug.这是因为我们的应用是一个网路的应用,需要从网上抓数据.另外,在我们代码的main.cpp中,我们使用了如下的代码:

QNetworkAccessManager *MyNetworkAccessManagerFactory::create(QObject *parent)
{
    QNetworkAccessManager *nam = new QNetworkAccessManager(parent);

    QString path = getCachePath();
    QNetworkDiskCache* cache = new QNetworkDiskCache(parent);
    cache->setCacheDirectory(path);
    nam->setCache(cache);

    return nam;
}

这段代码是为了设置一个cache,从而使得我们抓过来的照片能够得到cache,进而我们不需要浪费网路资源重复获取同样的一个照片.根据我们目前所有的plugs:

liuxg@liuxg:~$ snap interfaces
Slot                 Plug
:camera              -
:cups-control        -
:firewall-control    -
:gsettings           -
:home                rssreader-app
:locale-control      -
:log-observe         snappy-debug
:modem-manager       -
:mount-observe       -
:network             -
:network-bind        -
:network-control     -
:network-manager     -
:network-observe     -
:opengl              rssreader-app
:optical-drive       -
:ppp                 -
:pulseaudio          -
:snapd-control       -
:system-observe      -
:timeserver-control  -
:timezone-control    -
:unity7              rssreader-app
:x11                 -

显然,netwrok-manager是我们所需要的plug.我们可以在我们的snapcraft.yaml加入上面所述的两个plug.修改过后的snapcraft.yaml文件如下:

snapcraft.yaml

name: rssreader-app
version: 1.0
summary: A snap app from Ubuntu phone app
description: This is an exmaple showing how to convert a Ubuntu phone app to a desktop snap app
confinement: strict

apps:
  rssreader:
    command: desktop-launch $SNAP/lib/x86_64-linux-gnu/bin/rssreader
    plugs: [network,network-bind,network-manager,home,unity7,opengl]

parts:
  rssreader:
    source: src/
    plugin: qmake
    qt-version: qt5
    build-packages:
      - cmake
      - gettext
      - intltool
      - ubuntu-touch-sounds
      - suru-icon-theme
      - qml-module-qttest
      - qml-module-qtsysteminfo
      - qml-module-qt-labs-settings
      - qtdeclarative5-u1db1.0
      - qtdeclarative5-qtmultimedia-plugin
      - qtdeclarative5-qtpositioning-plugin
      - qtdeclarative5-ubuntu-content1
      - qt5-default
      - qtbase5-dev
      - qtdeclarative5-dev
      - qtdeclarative5-dev-tools
      - qtdeclarative5-folderlistmodel-plugin
      - qtdeclarative5-ubuntu-ui-toolkit-plugin
      - xvfb
    stage-packages:
      - ubuntu-sdk-libs
      - qtubuntu-desktop
      - qml-module-qtsysteminfo
      - ubuntu-defaults-zh-cn
    snap:
      - -usr/share/doc
      - -usr/include
    after: [desktop/qt5]
 

重新打包我们的应用并安装.我们可以利用:
$ snap interfaces
来显示我们应用所有的plug:

liuxg@liuxg:~/snappy/desktop/rssreader$ snap interfaces
Slot                 Plug
:camera              -
:cups-control        -
:firewall-control    -
:gsettings           -
:home                rssreader-app
:locale-control      -
:log-observe         snappy-debug
:modem-manager       -
:mount-observe       -
:network             rssreader-app
:network-bind        rssreader-app
:network-control     -
:network-manager     -
:network-observe     -
:opengl              rssreader-app
:optical-drive       -
:ppp                 -
:pulseaudio          -
:snapd-control       -
:system-observe      -
:timeserver-control  -
:timezone-control    -
:unity7              rssreader-app
:x11                 -
-                    rssreader-app:network-manager

在上面的最后一行,我们可以看到:
-                    rssreader-app:network-manager
这是什么意思呢?我们来重新查看连接interfaces,在那个页面里虽然目前还没有network-manager的介绍,但是我们可以看到诸如:

network-control

Can configure networking. This is restricted because it gives wide, privileged access to networking and should only be used with trusted apps.

Usage: reserved Auto-Connect: no

我们需要注意的是最下面的一句话:Auto-Connect: no.也就是说自动连接不存在.对于我们的networrk-manager的情况也是一样的.我们需要手动来连接.那么我们该如何来手动连接呢?

liuxg@liuxg:~$ snap --help
Usage:
  snap [OPTIONS] <command>

The snap tool interacts with the snapd daemon to control the snappy software platform.


Application Options:
      --version  print the version and exit

Help Options:
  -h, --help     Show this help message

Available commands:
  abort        Abort a pending change
  ack          Adds an assertion to the system
  change       List a change's tasks
  changes      List system changes
  connect      Connects a plug to a slot
  create-user  Creates a local system user
  disconnect   Disconnects a plug from a slot
  find         Finds packages to install
  help         Help
  install      Install a snap to the system
  interfaces   Lists interfaces in the system
  known        Shows known assertions of the provided type
  list         List installed snaps
  login        Authenticates on snapd and the store
  logout       Log out of the store
  refresh      Refresh a snap in the system
  remove       Remove a snap from the system
  run          Run the given snap command
  try          Try an unpacked snap in the system

我们通过上面的命令,我们可以知道snap有一个叫做connect的命令.进一步:

liuxg@liuxg:~$ snap connect -h
Usage:
  snap [OPTIONS] connect <snap>:<plug> <snap>:<slot>

The connect command connects a plug to a slot.
It may be called in the following ways:

$ snap connect <snap>:<plug> <snap>:<slot>

Connects the specific plug to the specific slot.

$ snap connect <snap>:<plug> <snap>

Connects the specific plug to the only slot in the provided snap that matches
the connected interface. If more than one potential slot exists, the command
fails.

$ snap connect <plug> <snap>[:<slot>]

Without a name for the snap offering the plug, the plug name is looked at in
the gadget snap, the kernel snap, and then the os snap, in that order. The
first of these snaps that has a matching plug name is used and the command
proceeds as above.

Application Options:
      --version            print the version and exit

Help Options:
  -h, --help               Show this help message

显然我们需要使用如下的命令来完成我们的connect工作:

$ snap connect <plug> <snap>[:<slot>]

针对我们的情况,我们使用如下的命令:

$ sudo snap connect rssreader-app:network-manager ubuntu-core:network-manager

当我们打入上面的命令后,我们重新来看我们的snap interfaces:
liuxg@liuxg:~$ snap interfaces
Slot                 Plug
:camera              -
:cups-control        -
:firewall-control    -
:gsettings           -
:home                rssreader-app
:locale-control      -
:log-observe         snappy-debug
:modem-manager       -
:mount-observe       -
:network             rssreader-app
:network-bind        rssreader-app
:network-control     -
:network-manager     rssreader-app
:network-observe     -
:opengl              rssreader-app
:optical-drive       -
:ppp                 -
:pulseaudio          -
:snapd-control       -
:system-observe      -
:timeserver-control  -
:timezone-control    -
:unity7              rssreader-app
:x11                 -

显然这一次,我们已经成功地把network-manager加入到我们的应用中.我们可以重新运行我们的应用:

liuxg@liuxg:~/snappy/desktop/rssreader$ rssreader-app.rssreader 

(process:9770): Gtk-WARNING **: Locale not supported by C library.
	Using the fallback 'C' locale.
Gtk-Message: Failed to load module "overlay-scrollbar"
Gtk-Message: Failed to load module "gail"
Gtk-Message: Failed to load module "atk-bridge"
Gtk-Message: Failed to load module "unity-gtk-module"
Gtk-Message: Failed to load module "canberra-gtk-module"
qml: columns: 1
qml: columns: 2
qml: currentIndex: 0
qml: index: 0
qml: adding page...
qml: sourcePage must be added to the view to add new page.
qml: going to add the page
qml: it is added: 958
XmbTextListToTextProperty result code -2
XmbTextListToTextProperty result code -2

显然我们的应用再也没有相应的错误提示了.



6)为我们的应用加上应用图标



到目前我们的应用虽然接近完美,但是我们还是不能够在我们的dash中启动我们的应用.为此,我们在我们的应用的根目录下创建了一个setup/gui目录.在该目录下,我们创建如下的两个文件:

liuxg@liuxg:~/snappy/desktop/rssreader/setup/gui$ ls -l
total 100
-rw-rw-r-- 1 liuxg liuxg   325 7月  14 13:18 rssreader.desktop
-rw-rw-r-- 1 liuxg liuxg 91353 7月  14 11:50 rssreader.png

加入这两个文件后的项目结构为:

liuxg@liuxg:~/snappy/desktop/rssreader$ tree -L 3
.
├── setup
│   └── gui
│       ├── rssreader.desktop
│       └── rssreader.png
├── snapcraft.yaml
└── src
    ├── manifest.json.in
    ├── po
    │   └── rssreader.liu-xiao-guo.pot
    ├── rssreader
    │   ├── components
    │   ├── main.cpp
    │   ├── Main.qml
    │   ├── rssreader.apparmor
    │   ├── rssreader.desktop
    │   ├── rssreader.png
    │   ├── rssreader.pro
    │   ├── rssreader.qrc
    │   └── tests
    └── rssreader.pro

有了上面的两个文件,我们再次重新打包并安装我们的snap应用.安装完后,在我们的dash里:


我们可以找到我们的RSS Reader应用了.


7)在不需要安装的情况下运行我们的应用



我们知道在开发的过程中,我们每次安装的时候都会产生一个新的版本.这个新的安装不仅花费很多的时间,而且占用系统的空间(每个版本占用的空间比较大).在开发时,我们能否不用安装而直接使用已经在打包过程中生产的文件呢?答案是肯定的.我们可以通过:

liuxg@liuxg:~$ snap --help
Usage:
  snap [OPTIONS] <command>

The snap tool interacts with the snapd daemon to control the snappy software platform.


Application Options:
      --version  print the version and exit

Help Options:
  -h, --help     Show this help message

Available commands:
  abort        Abort a pending change
  ack          Adds an assertion to the system
  change       List a change's tasks
  changes      List system changes
  connect      Connects a plug to a slot
  create-user  Creates a local system user
  disconnect   Disconnects a plug from a slot
  find         Finds packages to install
  help         Help
  install      Install a snap to the system
  interfaces   Lists interfaces in the system
  known        Shows known assertions of the provided type
  list         List installed snaps
  login        Authenticates on snapd and the store
  logout       Log out of the store
  refresh      Refresh a snap in the system
  remove       Remove a snap from the system
  run          Run the given snap command
  try          Try an unpacked snap in the system

我们在上面的命令中,发现一个叫做try的命令.在我们运行完snapcraft命令后,snapcraft会帮我们生产相应的.snap文件.同时它也帮我们生产如下的目录:

liuxg@liuxg:~/snappy/desktop/rssreader$ ls -d */
parts/  prime/  setup/  src/  stage/

这其中有一个叫做prime的目录,其实它的里面就是我们安装snap后的文件.我们可以使用如下的方法:

$ sudo snap try prime/

通过上面的命令我们就可以把我们的snap安装到系统中.重新展示我们的snap安装目录:

liuxg@liuxg:/var/lib/snapd/snaps$ ls -al
total 287200
drwxr-xr-x 2 root root      4096 7月  15 11:13 .
drwxr-xr-x 7 root root      4096 7月  15 11:13 ..
-rw------- 1 root root  98439168 7月  14 13:10 mpv_x1.snap
-rw------- 1 root root 127705088 7月  14 17:30 photos-app_x1.snap
lrwxrwxrwx 1 root root        42 7月  15 11:13 rssreader-app_x1.snap -> /home/liuxg/snappy/desktop/rssreader/prime
-rw------- 1 root root     16384 7月  13 15:53 snappy-debug_22.snap
-rw------- 1 root root  67899392 7月  13 12:26 ubuntu-core_122.snap

我们看见其实就是一个软链接.通过这样的方法,我们很快地部署了我们的snap应用.同时避免每次安装时各个不同版本之间带来的不同安装.snap包实际上是一个使用squashfs打包而生产的.通过snap try,我们不需要创建一个squashfs文件.他的另外一个好处是我们可以随时修改这个snap的应用的内容,这是因为它本身是read-write的.我们可以甚至加上--devmode选项来取消应用对安全的限制.


8)利用devmode免除在开发时的安全考虑



我们知道在开发的过程中,我们有时不知道需要使用哪写plug来保证我们的软件正常运行.这个时候,我们可以在我们的snapcraft中定义修改我们的confinement使之成为devmode:

snapcraft.yaml


name: rssreader-app
version: 1.0
summary: A snap app from Ubuntu phone app
description: This is an exmaple showing how to convert a Ubuntu phone app to a desktop snap app
confinement: devmode

apps:
  rssreader:
    command: desktop-launch $SNAP/lib/x86_64-linux-gnu/bin/rssreader
    plugs: [network,network-bind,network-manager,home,unity7,opengl]

parts:
  rssreader:
    source: src/
    plugin: qmake
    qt-version: qt5
    build-packages:
      - cmake
      - gettext
      - intltool
      - ubuntu-touch-sounds
      - suru-icon-theme
      - qml-module-qttest
      - qml-module-qtsysteminfo
      - qml-module-qt-labs-settings
      - qtdeclarative5-u1db1.0
      - qtdeclarative5-qtmultimedia-plugin
      - qtdeclarative5-qtpositioning-plugin
      - qtdeclarative5-ubuntu-content1
      - qt5-default
      - qtbase5-dev
      - qtdeclarative5-dev
      - qtdeclarative5-dev-tools
      - qtdeclarative5-folderlistmodel-plugin
      - qtdeclarative5-ubuntu-ui-toolkit-plugin
      - xvfb
    stage-packages:
      - ubuntu-sdk-libs
      - qtubuntu-desktop
      - qml-module-qtsysteminfo
      - ubuntu-defaults-zh-cn
    snap:
      - -usr/share/doc
      - -usr/include
    after: [desktop/qt5]
 

请注意上面的这一行:

confinement: devmode

当我们这样设计后,plugs里定义的所有的plug将不起任何的作用(我们甚至可以把它们全部删除).在我们安装我们的snap时,我们使用如下的命令:

$ sudo snap install rssreader-app_1.0_amd64.snap --devmode

注意我们上面加入--devmode选项.它表明,我们的应用将不受任何的安全沙箱的限制.它可以做它任何喜欢做的事情.在运行的过程中将不再生产任何的安全错误的提示.这样的设计对于我们开发者来说,我们可以很快地开发出我们所需要的应用,而不用先考虑我们的安全问题.












作者:UbuntuTouch 发表于2016/7/13 14:37:48 原文链接
阅读:569 评论:0 查看评论

Read more
UbuntuTouch

今天我把我们global同事的一个视频传到我们的youku网站上了.请大家观看如何从零开始来打包一个snap应用.大家如果有什么问题,请在文章的下面进行评论.我会尽我所能来回到所有的问题.


Ubuntu Snapcraft演示

作者:UbuntuTouch 发表于2016/7/20 17:09:04 原文链接
阅读:44 评论:0 查看评论

Read more
UbuntuTouch

在先前的文章"如何把一个qmake的Ubuntu手机应用打包为一个snap应用"中,我们介绍了如何把一个qmake的一个Ubuntu手机应用打包为一个snap的桌面应用.在今天的教程中,我们将展示如何把一个cmake的Ubuntu手机项目转换为一个snap的桌面应用.



1)通过Ubuntu SDK开发一个我们需要的手机应用



我们可以通过Ubuntu SDK来创建一个我们想要的项目.关于如何创建一个Ubuntu手机应用,这个不在我们的这个教程范围.如果你对如何利用Ubuntu SDK开发一个手机应用感兴趣的话,请参考我们的文章"Ubuntu 手机开发培训准备".这里将不再累述!


值得指出的是:在今天的教程中,我们将教大家如何把一个cmake的Ubuntu手机应用打包为一个snap的应用.这里,我们将利用之前我已经开发的一个项目作为例程来开始.我们在terminal下打入如下的命令:

$ git clone https://github.com/liu-xiao-guo/photos

下载后的源码结构如下:

liuxg@liuxg:~/snappy/desktop/photos$ tree -L 2
.
├── photos.wrapper
├── setup
│   └── gui
├── snapcraft.yaml
├── snappy-qt5.conf
└── src
    ├── app
    ├── CMakeLists.txt
    ├── manifest.json.in
    ├── photos.apparmor
    └── po

就像我们上面展示的那样,在src的目录中有一个完整的可以执行的cmake手机应用.它的项目管理文件是CMakeLists.txt.在它的根目录下有一个文件叫做snapcraft.yaml文件.这个是用来打包我们的CMake手机应用,并使之成为一个可以在我们的16.04桌面上运行的snap应用.



2)为我们的CMake项目打包


在上节中,我们已经提到了我们项目的snapcraft.yaml文件.现在我们把这个文件展示如下:


snapcraft.yaml


name: photos-app
version: 1.0
summary: Ubuntu photos app
description: |
   This is a demo app showing how to convert a cmake ubuntu phone app to a snap app

apps:
  photos:
    command: photos
    plugs: [network,home,unity7,opengl]

parts:
  photos:
    plugin: cmake
    configflags: [-DCMAKE_INSTALL_PREFIX=/usr, -DCLICK_MODE=off]
    source: src/
    build-packages:
      - cmake
      - gettext
      - intltool
      - ubuntu-touch-sounds
      - suru-icon-theme
      - qml-module-qttest
      - qml-module-qtsysteminfo
      - qml-module-qt-labs-settings
      - qtdeclarative5-u1db1.0
      - qtdeclarative5-qtmultimedia-plugin
      - qtdeclarative5-qtpositioning-plugin
      - qtdeclarative5-ubuntu-content1
      - qt5-default
      - qtbase5-dev
      - qtdeclarative5-dev
      - qtdeclarative5-dev-tools
      - qtdeclarative5-folderlistmodel-plugin
      - qtdeclarative5-ubuntu-ui-toolkit-plugin
      - xvfb
    stage-packages:
      - ubuntu-sdk-libs
      - qtubuntu-desktop
      - qml-module-qtsysteminfo
      - ubuntu-defaults-zh-cn
    snap:
      - -usr/share/doc
      - -usr/include
  environment:
    plugin: copy
    files:
      photos.wrapper: bin/photos
      snappy-qt5.conf: etc/xdg/qtchooser/snappy-qt5.conf

在这里,我不想再累述这里的每一个字段的意思.大家可以参阅我的文章"如何把一个qmake的Ubuntu手机应用打包为一个snap应用".特别值得指出的是,在我们的这个snapcraft.yaml文件中,我们定义了一个新的environment的part(它可以是我们喜欢的任何名称).在它里面,它使用了copy plugin.它把当前目录下的photos.wrapper拷入到bin/photos下.我们的command中的执行文件是photos.在我们打包时,我们必须记住需要把我们的script变为可以执行的脚本:

$ chmod a+x photos.wrapper

在我们的项目中,因为CMake项目不含有任何的C++代码,所以我们必须使用qmlscene来启动.这个在我们的photos.wrapper中可以看到:

photos.wrapper

#!/bin/sh

ARCH='x86_64-linux-gnu'

export LD_LIBRARY_PATH=$SNAP/usr/lib/$ARCH:$LD_LIBRARY_PATH

# XKB config
export XKB_CONFIG_ROOT=$SNAP/usr/share/X11/xkb

# Qt Platform to Mir
#export QT_QPA_PLATFORM=ubuntumirclient
export QTCHOOSER_NO_GLOBAL_DIR=1
export QT_SELECT=snappy-qt5

# Qt Libs
export LD_LIBRARY_PATH=$SNAP/usr/lib/$ARCH/qt5/libs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$SNAP/usr/lib/$ARCH/pulseaudio:$LD_LIBRARY_PATH

# Qt Modules
export QT_PLUGIN_PATH=$SNAP/usr/lib/$ARCH/qt5/plugins
export QML2_IMPORT_PATH=$SNAP/usr/lib/$ARCH/qt5/qml/photos
export QML2_IMPORT_PATH=$QML2_IMPORT_PATH:$SNAP/usr/lib/$ARCH/qt5/qml
export QML2_IMPORT_PATH=$QML2_IMPORT_PATH:$SNAP/lib/$ARCH

# Mesa Libs
export LD_LIBRARY_PATH=$SNAP/usr/lib/$ARCH/mesa:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$SNAP/usr/lib/$ARCH/mesa-egl:$LD_LIBRARY_PATH

# XDG Config
export XDG_CONFIG_DIRS=$SNAP/etc/xdg:$XDG_CONFIG_DIRS
export XDG_CONFIG_DIRS=$SNAP/usr/xdg:$XDG_CONFIG_DIRS
# Note: this doesn't seem to work, QML's LocalStorage either ignores
# or fails to use $SNAP_USER_DATA if defined here
export XDG_DATA_DIRS=$SNAP_USER_DATA:$XDG_DATA_DIRS
export XDG_DATA_DIRS=$SNAP/usr/share:$XDG_DATA_DIRS

# Not good, needed for fontconfig
export XDG_DATA_HOME=$SNAP/usr/share

# Font Config
export FONTCONFIG_PATH=$SNAP/etc/fonts/config.d
export FONTCONFIG_FILE=$SNAP/etc/fonts/fonts.conf

# Tell libGL where to find the drivers
export LIBGL_DRIVERS_PATH=$SNAP/usr/lib/$ARCH/dri

# Necessary for the SDK to find the translations directory
export APP_DIR=$SNAP

# ensure the snappy gl libs win
export LD_LIBRARY_PATH="$SNAP_LIBRARY_PATH:$LD_LIBRARY_PATH"

cd $SNAP
exec $SNAP/usr/bin/qmlscene $SNAP/share/qml/photos/Main.qml

在上面的最后一句,它显示了我们如何启动我们的应用:

exec $SNAP/usr/bin/qmlscene $SNAP/share/qml/photos/Main.qml

我们可以直接在我们的项目根目录下打入如下的命令:

$ snapcraft

它即可把我们的应用打包为我们想要的snap应用包.

关于如何安装和运行我们的应用.这里我就不再累述.请大家参阅我文章"如何把一个qmake的Ubuntu手机应用打包为一个snap应用".

下面,我们把运行的结果的截图显示如下:

 


作者:UbuntuTouch 发表于2016/7/15 14:20:31 原文链接
阅读:56 评论:0 查看评论

Read more
UbuntuTouch

[原]helloworld Snap例程

我们在很多的语言开发中都少不了使用"Hello, the world!"来展示一个开发环境的成功与否,在今天的教程中,我们也毫不例外地利用这个例子来展示snap应用是如何构建的.虽然这个例子很简单,但是在我们进入例程的过程中,我们会慢慢地发现有关snap系统的一些特性,这样可以更好地帮助我们来了解这个系统.如果大家想了解16.04的桌面对snap的支持,请参阅文章"安装snap应用到Ubuntu 16.4桌面系统".


1)环境安装


我们仿照在文章"安装snap应用到Ubuntu 16.4桌面系统"中的"安装"一节进行安装.记得一定要选上"universe"才可以安装成功.



2)从Snap商店中安装hello-world应用


我们可以通过如下的命令在Snap商店中找到这个应用:

$ sudo snap install hello-world

在安装完这个应用后,我们可以在如下的目录中找到关于这个应用的snap.yaml文件.这个文件很类似于一个项目的snapcraft.yaml文件.只是它里面没有什么parts的部分.

liuxg@liuxg:/snap/hello-world/current/meta$ ls 
gui  snap.yaml

其中snap.yaml的内容如下:

snap.yaml

name: hello-world
version: 6.3
architectures: [ all ]
summary: The 'hello-world' of snaps
description: |
    This is a simple snap example that includes a few interesting binaries
    to demonstrate snaps and their confinement.
    * hello-world.env  - dump the env of commands run inside app sandbox
    * hello-world.evil - show how snappy sandboxes binaries
    * hello-world.sh   - enter interactive shell that runs in app sandbox
    * hello-world      - simply output text
apps:
 env:
   command: bin/env
 evil:
   command: bin/evil
 sh:
   command: bin/sh
 hello-world:
   command: bin/echo

可以看出来它的格式非常接近我们的snapcraft.yaml项目文件.这里文件中指出的env,evil,sh及echo命令,我们可以在如下的目录中找到:

liuxg@liuxg:/snap/hello-world/current/bin$ ls
echo  env  evil  sh

当然,我们可以使用我们的vi编辑器来查看里面的具体的内容.整个的文件架构如下:

liuxg@liuxg:/snap/hello-world/current$ tree -L 3
.
├── bin
│   ├── echo
│   ├── env
│   ├── evil
│   └── sh
└── meta
    ├── gui
    │   └── icon.png
    └── snap.yaml


3)创建我们自己的hello-world项目


由于一些原因,我们在网上已经找不到这个项目的源码了.由于这个项目非常简单,我们可以通过我们自己的方法来重建这个项目:我们把上面的snap.yaml进行修改为我们所需要的snapcraft.yaml,并把我们所需要的文件考入到我们需哟啊的目录.这样我们就可以很容易地重构这个项目.这样做的目的是我们想通过修改这个项目来展示一些我们想看到的特性.

对于开发者来说,如果你没有一个现成的snapcraft.yaml文件供你参考的话,你可以直接使用如下的命令来生产一个模版来进行编辑:

$ snapcraft init

这样在我们的项目的根目录下就会生产一个snapcraft.yaml的样板件.我们可以利用这个文件来作为开始进行编辑:

snapcraft.yaml

name: my-snap  # the name of the snap
version: 0  # the version of the snap
summary: This is my-snap's summary  # 79 char long summary
description: This is my-snap's description  # a longer description for the snap
confinement: devmode  # use "strict" to enforce system access only via declared interfaces

parts:
    my-part:  # Replace with a part name of your liking
        # Get more information about plugins by running
        # snapcraft help plugins
        # and more information about the available plugins
        # by running
        # snapcraft list-plugins
        plugin: nil

经过我们的重构,我们终于完成了我们的第一个snap应用.目录架构如下:

liuxg@liuxg:~/snappy/desktop/helloworld$ tree -L 3
.
├── bin
│   ├── echo
│   ├── env
│   ├── evil
│   └── sh
├── setup
│   └── gui
│       └── icon.png
└── snapcraft.yaml

在这里snapcraft是我们的项目文件,它被用于来打包我们的应用.它的内容如下:

snapcraft.yaml


name: hello-xiaoguo
version: 1.0
architectures: [ all ]
summary: The 'hello-world' of snaps
description: |
    This is a simple snap example that includes a few interesting binaries
    to demonstrate snaps and their confinement.
    * hello-world.env  - dump the env of commands run inside app sandbox
    * hello-world.evil - show how snappy sandboxes binaries
    * hello-world.sh   - enter interactive shell that runs in app sandbox
    * hello-world      - simply output text
confinement: strict

apps:
 env:
   command: bin/env
 evil:
   command: bin/evil
 sh:
   command: bin/sh
 hello-world:
   command: bin/echo

parts:
 hello:
  plugin: copy
  files:
    ./bin: bin

从内容上看,它和我们之前看到的snap几乎是一样的.这里我们使用了copy plugin.我们可以通过如下的命令来查询目前已经支持的所有的plugins:

liuxg@liuxg:~/snappy/desktop/helloworld$ snapcraft list-plugins
ant        catkin  copy  gulp  kbuild  make   nil     python2  qmake  tar-content
autotools  cmake   go    jdk   kernel  maven  nodejs  python3  scons

事实上,在snapcraft下的plugin架构也是开发的,开发者可以开发自己所需要的plugin.
在我们打包我们的应用之前,我们必须确保在bin目录下的所有文件都是可以执行的:

liuxg@liuxg:~/snappy/desktop/helloworld/bin$ ls -al
total 24
drwxrwxr-x 2 liuxg liuxg 4096 7月  13 00:31 .
drwxrwxr-x 4 liuxg liuxg 4096 7月  18 10:31 ..
-rwxrwxr-x 1 liuxg liuxg   31 7月  12 05:20 echo
-rwxrwxr-x 1 liuxg liuxg   27 7月  12 05:20 env
-rwxrwxr-x 1 liuxg liuxg  274 7月  12 05:20 evil
-rwxrwxr-x 1 liuxg liuxg  209 7月  12 05:20 sh

否则的话,我们需要使用如下的命令来完成:

$ chmod a+x echo

至此,我们已经完成了一个最基本的hello-world项目.


4)编译并执行我们的应用


在我们的项目的根目录下,我们直接打入如下的命令:

$ snapcraft

如果一切顺利的话,我们可以在项目的根目录下看到如下的文件及目录:

liuxg@liuxg:~/snappy/desktop/helloworld$ tree -L 2
.
├── bin
│   ├── echo
│   ├── env
│   ├── evil
│   └── sh
├── hello-xiaoguo_1.0_all.snap
├── parts
│   └── hello
├── prime
│   ├── bin
│   ├── command-env.wrapper
│   ├── command-evil.wrapper
│   ├── command-hello-world.wrapper
│   ├── command-sh.wrapper
│   └── meta
├── setup
│   └── gui
├── snapcraft.yaml
└── stage
    └── bin

我们可以看见一个生产的snap文件.当然,我们也看到了一下其它的文件目录:parts, stage及prime.这些目录是在打包过程中自动生成的.有关更多关于snapcraft的帮助信息,我们可以通过如下的命令来获得:

liuxg@liuxg:~/snappy/desktop/helloworld$ snapcraft --help
...

The available lifecycle commands are:
  clean        Remove content - cleans downloads, builds or install artifacts.
  cleanbuild   Create a snap using a clean environment managed by lxd.
  pull         Download or retrieve artifacts defined for a part.
  build        Build artifacts defined for a part. Build systems capable of
               running parallel build jobs will do so unless
               "--no-parallel-build" is specified.
  stage        Stage the part's built artifacts into the common staging area.
  prime        Final copy and preparation for the snap.
  snap         Create a snap.

Parts ecosystem commands
  update       Updates the parts listing from the cloud.
  define       Shows the definition for the cloud part.
  search       Searches the remotes part cache for matching parts.

Calling snapcraft without a COMMAND will default to 'snap'

...

在上面我们可以看出,打包一个snap应用所必须的生命周期:pullbuildstageprimesnap.对于一个snap的项目来说,它的每个part的文件可以存在于一下网站上,比如git,bzr或tar.在打包的过程中,snapcraft可以将它们自动从网上下载下来,并存于parts目录下.通过build,把每个part的安装的文件至于每个part下的一个叫做install的子目录中.在stage过程中,它分别把每个part的文件集中起来,并存于一个统一的文件架构中.prime是最终把stage中可以用打包的文件放在一起,这样我们可以在最后的过程中来通过snap过程来打包为snap包.更多关于这些生命周期的描述,大家可以参阅文章"Snapcraft Overview".我们也可以参阅视频"Snapcraft操作演示--教你如何snap一个应用".

如果大家想清除这些在打包过程中的中间文件,我们可以在命令行中打入如下的命令:

$ snapcraft clean

我们可以通过如下的命令来安装我们的应用:

$ sudo snap install hello-xiaoguo_1.0_all.snap

如果我们通过上面的方法进行安装的话,每次安装都会生产一个新的版本,并且占用系统的硬盘资源.我们也可以通过如下的方式来进行安装:

$ sudo snap try prime/

这种方法的好处是,它不必要每次都生产一个新的版本.在安装时,它直接使用一个软链接的方式,把我们编译的prime目录直接进行mount.

这样我们就可以把我们的应用安装到我们的16.04的桌面系统中了.我们可以通过如下的命令来查看:

liuxg@liuxg:~/snappy/desktop/helloworld$ snap list
Name           Version               Rev  Developer  Notes
hello-world    6.3                   27   canonical  -
hello-xiaoguo  1.0                   x2              -
ubuntu-core    16.04+20160531.11-56  122  canonical  -

显然我们的hello-xiaoguo应用已经被成功安装到系统中了.那么我们怎么来运行我们的应用呢?

从我们的snapcraft.yaml文件中,我们可以看出来,我们的包名叫做hello-xiaoguo.在我们的这个包中,我们定义了四个应用:env, evil,sh及hello-world.那么我们运行它们时,我们分别需要使用如下的命令来运行:

$ hello-xiaoguo.env
$ hello-xiaoguo.evil
$ hello-xiaoguo.sh
$ hello-xiaoguo.hello-world

也即,我们使用<<包名>>.<<应用名>>格式来运行我们的应用.比如:

liuxg@liuxg:~/snappy/desktop/helloworld$ hello-xiaoguo.hello-world 
Hello World!


我们可以使用如下的命令来查看我们的snap文件包里的内容:

$ unsquashfs -l hello-xiaoguo_1.0_all.snap

一个snap文件包其实就是一个压缩的squashfs文件.我们也可以通过如下的方式来得到包里所有的内容:
$ unsquashfs hello-xiaoguo_1.0_all.snap  
$ cd cd squashfs-root  
# Hack hack hack  
$ snapcraft snap  
这里我们就留给开发者们自己做练习.



5)Snap的运行环境


每个应用在被安装到系统的时候,系统将会为这个包里的每个应用生产一个相应的启动脚本.它们可以在如下的路径中找到:

liuxg@liuxg:/snap/bin$ ls -l
total 52
-rwxr-xr-x 1 root root 708 7月  20 15:37 hello-world
-rwxr-xr-x 1 root root 783 7月  21 15:13 hello-world-cli
-rwxr-xr-x 1 root root 683 7月  20 15:37 hello-world.env
-rwxr-xr-x 1 root root 687 7月  20 15:37 hello-world.evil
-rwxr-xr-x 1 root root 679 7月  20 15:37 hello-world.sh
-rwxr-xr-x 1 root root 743 7月  22 15:30 hello-xiaoguo.createfile
-rwxr-xr-x 1 root root 767 7月  22 15:30 hello-xiaoguo.createfiletohome
-rwxr-xr-x 1 root root 715 7月  22 15:30 hello-xiaoguo.env
-rwxr-xr-x 1 root root 719 7月  22 15:30 hello-xiaoguo.evil
-rwxr-xr-x 1 root root 747 7月  22 15:30 hello-xiaoguo.hello-world
-rwxr-xr-x 1 root root 711 7月  22 15:30 hello-xiaoguo.sh
-rwxr-xr-x 1 root root 726 7月  22 11:32 snappy-debug.security
-rwxr-xr-x 1 root root 798 7月  20 10:44 telegram-sergiusens.telegram

我们可以通过cat命令来查看这些脚本的具体的内容.
我们可以执行如下的命令:

$ hello-xiaoguo.env | grep SNAP

通过上面的指令,我们可以得到关于一个snap运行时的所有环境变量:

liuxg@liuxg:~$ hello-xiaoguo.env | grep SNAP
SNAP_USER_COMMON=/home/liuxg/snap/hello-xiaoguo/common
SNAP_LIBRARY_PATH=/var/lib/snapd/lib/gl:
SNAP_COMMON=/var/snap/hello-xiaoguo/common
SNAP_USER_DATA=/home/liuxg/snap/hello-xiaoguo/x2
SNAP_DATA=/var/snap/hello-xiaoguo/x2
SNAP_REVISION=x2
SNAP_NAME=hello-xiaoguo
SNAP_ARCH=amd64
SNAP_VERSION=1.0
SNAP=/snap/hello-xiaoguo/x2

这些和snap相关的环境变量可以在我们的应用中进行引用.这些变量的介绍如下:



在我们编程的过程中,我们不必要hard-code我们的变量.比如我们可以在我们的snapcraft中引用$SNAP,它表示我们当前的snap的安装的路径.同时,我们可以看到一个很重要的目录:

SNAP_DATA=/var/snap/hello-xiaoguo/x2

这个目录是我们的snap的私有的目录.我们的snap只能向这个目录或SNAP_USER_DATA进行读写的操作.否则,将会产生安全的错误信息.比如在我们的evil脚本中:

evil

#!/bin/sh

set -e
echo "Hello Evil World!"

echo "This example demonstrates the app confinement"
echo "You should see a permission denied error next"

echo "Haha" > /var/tmp/myevil.txt

echo "If you see this line the confinement is not working correctly, please file a bug"

我们通过这个脚本向/var/tmp/中的myevil.txt写入"Haha",它会造成安全的DENIED错误信息:

liuxg@liuxg:~$ hello-xiaoguo.evil
Hello Evil World!
This example demonstrates the app confinement
You should see a permission denied error next
/snap/hello-xiaoguo/x2/bin/evil: 9: /snap/hello-xiaoguo/x2/bin/evil: cannot create /var/tmp/myevil.txt: Permission denied

另外一种查找错误的方方法是打开我们的系统的log信息(/var/log/syslog

8307 comm="fswebcam" requested_mask="r" denied_mask="r" fsuid=0 ouid=0
Jul 19 13:27:18 liuxg kernel: [19665.330053] audit: type=1400 audit(1468906038.378:4309): apparmor="DENIED" operation="open" profile="snap.webcam-webui.webcam-webui" name="/etc/fonts/fonts.conf" pid=18307 comm="fswebcam" requested_mask="r" denied_mask="r" fsuid=0 ouid=0
Jul 19 13:27:25 liuxg gnome-session[2151]: (nm-applet:2584): nm-applet-WARNING **: ModemManager is not available for modem at /hfp/org/bluez/hci0/dev_F4_B7_E2_CC_F0_56
Jul 19 13:27:26 liuxg kernel: [19673.182647] audit: type=1400 audit(1468906046.230:4310): apparmor="DENIED" operation="mknod" profile="snap.hello-xiaoguo.evil" name="/var/tmp/myevil.txt" pid=18314 comm="evil" requested_mask="c" denied_mask="c" fsuid=1000 ouid=1000

或直接使用如下的命令:

liuxg@liuxg:~/snappy/desktop/helloworld$ cat /var/log/syslog | grep DENIED | grep hello-xiaoguo
Jul 19 13:25:25 liuxg kernel: [19552.926619] audit: type=1400 audit(1468905925.975:4276): apparmor="DENIED" operation="mknod" profile="snap.hello-xiaoguo.evil" name="/var/tmp/myevil.txt" pid=18273 comm="evil" requested_mask="c" denied_mask="c" fsuid=1000 ouid=1000
Jul 19 13:27:26 liuxg kernel: [19673.182647] audit: type=1400 audit(1468906046.230:4310): apparmor="DENIED" operation="mknod" profile="snap.hello-xiaoguo.evil" name="/var/tmp/myevil.txt" pid=18314 comm="evil" requested_mask="c" denied_mask="c" fsuid=1000 ouid=1000

这其中最根本的原因是因为我们的snap应用不能访问不属于他自己的目录.这是snap应用最根本的安全机制.我们可以看到上面的operation项.他指出了我们具体的错误操作.
对于snap应用的另外一个安全方面的问题是seccomp violation.对于一个叫做audit的应用来说,我们可以通过如下的方式来得到它的错误信息:

$ sudo grep audit /var/log/syslog

一个seccomp violation的例子可能如下:

audit: type=1326 audit(1430766107.122:16): auid=1000 uid=1000 gid=1000 ses=15 pid=1491 comm="env" exe="/bin/bash" sig=31 arch=40000028 syscall=983045 compat=0 ip=0xb6fb0bd6 code=0x0

那么这个violation的具体的意思是什么呢?我们可以通过如下的命令来查看这个错我的信息:

$ scmp_sys_resolver 983045
set_tls

请注意上面的983045来自于我们的错误信息中的"syscall=983045".这样,我们就可以定位我们的哪些系统调用有问题.

为了说明问题,我们创建一个createfile的脚本:

createfile

#!/bin/sh

set -e
echo "Hello a nice World!"

echo "This example demonstrates the app confinement"
echo "This app tries to write to its own user directory"

echo "Haha" > $HOME/test.txt

echo "Succeeded! Please find a file created at $HOME/test.txt"
echo "If do not see this, please file a bug"

在我们的snapcraft.yaml中加入:

 createfile:
   command: bin/createfile

重新打包我们的应用:

liuxg@liuxg:~/snappy/desktop/helloworld$ hello-xiaoguo.createfile 
Hello a nice World!
This example demonstrates the app confinement
This app tries to write to its own user directory
Succeeded! Please find a file created at /home/liuxg/snap/hello-xiaoguo/x3/test.txt
If do not see this, please file a bug

在这里,我们可以看见我们已经成功地在位置/home/liuxg/snap/hello-xiaoguo/x3/生产一个文件.$HOME的定义可以通过如下的方式获得:

liuxg@liuxg:~/snappy/desktop/helloworld$ hello-xiaoguo.env | grep home
GPG_AGENT_INFO=/home/liuxg/.gnupg/S.gpg-agent:0:1
SNAP_USER_COMMON=/home/liuxg/snap/hello-xiaoguo/common
ANDROID_NDK_ROOT=/home/liuxg/android-ndk-r10e
SNAP_USER_DATA=/home/liuxg/snap/hello-xiaoguo/x3
PWD=/home/liuxg/snappy/desktop/helloworld
HOME=/home/liuxg/snap/hello-xiaoguo/x3
XAUTHORITY=/home/liuxg/.Xauthority

细心的开发者也许会发现它的定义其实和变量SNAP_USER_DATA是一样的:

liuxg@liuxg:~/snappy/desktop/helloworld$ hello-xiaoguo.env | grep SNAP
SNAP_USER_COMMON=/home/liuxg/snap/hello-xiaoguo/common
SNAP_LIBRARY_PATH=/var/lib/snapd/lib/gl:
SNAP_COMMON=/var/snap/hello-xiaoguo/common
SNAP_USER_DATA=/home/liuxg/snap/hello-xiaoguo/x3
SNAP_DATA=/var/snap/hello-xiaoguo/x3
SNAP_REVISION=x3
SNAP_NAME=hello-xiaoguo
SNAP_ARCH=amd64
SNAP_VERSION=1.0
SNAP=/snap/hello-xiaoguo/x3

对于一个daemon应用来说,这个$HOME变量的值,是指向$SNAP_DATA而不是$SNAP_USER_DATA.这一点大家要记住.具体的描述可以参阅文章"Snap security policy and sandboxing".

关于security的调试是一件非常麻烦的是.庆幸的是,我们可以利用snappy-debug来帮我们调试.它可以帮我们解析我们到底是哪些地方有错误,并且帮我们解析系统调用的名称等.

$ sudo snap install snappy-debug
$ sudo /snap/bin/snappy-debug.security scanlog foo

具体的使用方法,我们可以参阅文章"Snap security policy and sandboxing".




6)创建一个可以向桌面home写入的app


在上一节的内容中,我们基本上已经看到了snap应用的安全性的一些方面.在我们的snap应用中,假如我们想向我们的桌面电脑中的home里写内容,那应该是怎么办呢?首先,我们创建一个如下的createfiletohome脚本:

createfiletohome:


#!/bin/sh

set -e
echo "Hello a nice World!"

echo "This example demonstrates the app confinement"
echo "This app tries to write to its own user directory"

echo "Haha" > /home/$USER/test.txt

echo "Succeeded! Please find a file created at $HOME/test.txt"
echo "If do not see this, please file a bug"

在上面我们向我们的用户的home目录写入我们需要的内容.如果我们重新编译并运行我们的应用,我们会发现:

liuxg@liuxg:~/snappy/desktop/helloworld$ hello-xiaoguo.createfiletohome 
Hello a nice World!
This example demonstrates the app confinement
This app tries to write to its own user directory
/snap/hello-xiaoguo/x1/bin/createfiletohome: 9: /snap/hello-xiaoguo/x1/bin/createfiletohome: cannot create /home/liuxg/test.txt: Permission denied

显然,它产生了一个错误的信息.我们不可以向我们的用户的home写入任何的内容.那么我们怎么才可以呢?

方法一: 我们使用如下的方法来安装我们的应用:

$ sudo snap install hello-xiaoguo_1.0_all.snap --devmode

注意上面的--devmode,它表明在开发的过程中,我们的snap应用忽略任何的安全问题,也就是我们的snap将和以前开发的任何应用一样,不接受snap系统所带来的任何的安全的限制.这种方式一般适合在早期开发一个snap应用时使用.等到我们把功能完善后,我们再来完善我们的安全的部分.

针对使用--devmode打包的snap来说(我们也可以在snapcraft.yaml中的confinement设为devmode),我们必须注意的是: 

Snaps can be uploaded to the edge and beta channels only



方法二:我们重新把我们的snapcraft.yaml改写如下:

snapcraft.yaml

name: hello-xiaoguo
version: 1.0
architectures: [ all ]
summary: The 'hello-world' of snaps
description: |
    This is a simple snap example that includes a few interesting binaries
    to demonstrate snaps and their confinement.
    * hello-world.env  - dump the env of commands run inside app sandbox
    * hello-world.evil - show how snappy sandboxes binaries
    * hello-world.sh   - enter interactive shell that runs in app sandbox
    * hello-world      - simply output text
confinement: strict

apps:
 env:
   command: bin/env
 evil:
   command: bin/evil
 sh:
   command: bin/sh
 hello-world:
   command: bin/echo
 createfile:
   command: bin/createfile
 createfiletohome:
   command: bin/createfiletohome
   plugs: [home]

parts:
 hello:
  plugin: copy
  files:
    ./bin: bin

在上面,我们在createfiletohome应用下加入了home plug.它表明我们的应用可以访问用户的home目录.在snap系统,如果一个应用想访问另外一个受限的资源或访问一个被其它应用所拥有的资源时,我们可以通过interface来实现.更多的关于snap的interface方面的知识,大家可以参阅Interfaces链接.我们可以通过如下的命令来查看所有的interface:

liuxg@liuxg:~$ snap interfaces
Slot                 Plug
:camera              -
:cups-control        -
:firewall-control    -
:gsettings           -
:home                -
:locale-control      -
:log-observe         -
:modem-manager       -
:mount-observe       -
:network             -
:network-bind        -
:network-control     -
:network-manager     -
:network-observe     -
:opengl              -
:optical-drive       -
:ppp                 -
:pulseaudio          -
:snapd-control       -
:system-observe      -
:timeserver-control  -
:timezone-control    -
:unity7              -
:x11                 -

重新打包我们的应用:

liuxg@liuxg:~/snappy/desktop/helloworld$ hello-xiaoguo.createfiletohome 
Hello a nice World!
This example demonstrates the app confinement
This app tries to write to its own user directory
Succeeded! Please find a file created at /home/liuxg/snap/hello-xiaoguo/x1/test.txt
If do not see this, please file a bug

现在,我们再也没有上面显示的那个错误信息了.


7)应用的shell


虽然我们的hello应用非常简单,但是它确实展示了我们很多希望看到的snap应用的一面.在我们的应用中,我们还有一个应用叫做sh.它事件上是一个shell.我们可以通过如下的方式来启动它:

$ hello-xiaoguo.sh

当这个应用被启动后:

liuxg@liuxg:~$ hello-xiaoguo.sh
Launching a shell inside the default app confinement. Navigate to your
app-specific directories with:

  $ cd $SNAP
  $ cd $SNAP_DATA
  $ cd $SNAP_USER_DATA

bash-4.3$ env | grep snap
SNAP_USER_COMMON=/home/liuxg/snap/hello-xiaoguo/common
SNAP_LIBRARY_PATH=/var/lib/snapd/lib/gl:
SNAP_COMMON=/var/snap/hello-xiaoguo/common
SNAP_USER_DATA=/home/liuxg/snap/hello-xiaoguo/x4
SNAP_DATA=/var/snap/hello-xiaoguo/x4
PATH=/snap/hello-xiaoguo/x4/bin:/snap/hello-xiaoguo/x4/usr/bin:/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
HOME=/home/liuxg/snap/hello-xiaoguo/x4
XDG_DATA_DIRS=/usr/share/ubuntu:/usr/share/gnome:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop
SNAP=/snap/hello-xiaoguo/x4
bash-4.3$ 
我们可以通过这个shell来完成我们想要的任务.比如:

bash-4.3$ cd /home/liuxg
bash-4.3$ pwd
/home/liuxg
bash-4.3$ touch hello.text
touch: cannot touch 'hello.text': Permission denied

我们发现,由于snap安全的限制,我们不能向以前的系统那样,可以自由地在任何地方创建一个我们想要的文件了.还有更多的例子,我们留给你们自己来慢慢地体会.






作者:UbuntuTouch 发表于2016/7/18 11:12:59 原文链接
阅读:710 评论:0 查看评论

Read more
UbuntuTouch

[原]WebCam snap应用实例

相信大家好多人都已经使用过webcam.对webcam的使用并不陌生.在今天的实例中,我们来介绍webcam的snap设计.如果大家先前看过我的ubuntu core的IoT设计,可能对这个项目并不陌生.大家可以参阅我的文章"snapcraft动手实践 --- Web Camera".只可惜,在那篇文章中的webcam在当时的情况下,没法在kvm中的环境中在桌面上测试,除非我们安装一个snappy的电脑系统.今天的snap实战中,我们的主要设计和以前的几乎是一样的,只是有一些细微的变化(这是由于我们的snap设计在不断演进中造成的).

webcam设计的源码我们可以在如下的地址找到:

https://github.com/snapcore/snapcraft/tree/master/demos/webcam-webui

我们可以它通过如下的方法把源代码下下来:

$ git clone https://github.com/ubuntu-core/snapcraft
$ cd snapcraft/demos

关于webcam应用的介绍,大家可以在如下的地址找到:

https://developer.ubuntu.com/en/snappy/build-apps/your-first-snap/

我们首先来看一下这个应用的snapcraft.yaml:

snapcraft.yaml

name: webcam-webui
version: 1
summary: Webcam web UI
description: Exposes your webcam over a web UI
confinement: strict

apps:
  webcam-webui:
    command: bin/webcam-webui
    daemon: simple
    plugs: [network-bind]

parts:
  cam:
    plugin: go
    go-packages:
      - github.com/mikix/golang-static-http
    stage-packages:
      - fswebcam
    filesets:
      fswebcam:
        - usr/bin/fswebcam
        - lib
        - usr/lib
      go-server:
        - bin/golang-*
    stage:
      - $fswebcam
      - $go-server
    snap:
      - $fswebcam
      - $go-server
      - -usr/share/doc
  glue:
    plugin: copy
    files:
      webcam-webui: bin/webcam-webui

注意:这是到目前为止的snapcraft.yaml文件,其中并没有camera plug.我们已经报告一个bug了.如果大家直接打包这个应用:

$ snapcraft

并安装这个应用:

$ sudo snap install webcam-webui_1_amd64.snap

由于这个应用是一个daemon类型的应用.我们视为一个service,也即我们并不需要手动来启动该应用.在安装的时候,它就自动被运行.我可以在我们的浏览器中打开如下的地址:



很显然,我们的webserver已经在正常运行,但是我们看不见任何的camera输出.这是为什么呢?
我们使用如下的命令来查看我们的service运行的日志:

$ journalctl -u snap.webcam-webui.webcam-webui

我们得到了如下的结果:


我们可以看出来,其中的一些信息(记住要翻到最后的信息).显然它显示了:

7月 19 10:33:13 liuxg ubuntu-core-launcher[13442]: Trying source module v4l2...
7月 19 10:33:13 liuxg ubuntu-core-launcher[13442]: Error opening device: /dev/video0
7月 19 10:33:13 liuxg ubuntu-core-launcher[13442]: open: Permission denied

这说明什么问题呢?它表明我们遇到了安全的问题.我们的应用不能打开设备/dev/video0.那么我们怎么来更正我们的问题呢?我们来在terminal中打入如下的命令:

liuxg@liuxg:~$ snap interfaces
Slot                 Plug
:camera              -
:cups-control        -
:firewall-control    -
:gsettings           -
:home                -
:locale-control      -
:log-observe         -
:modem-manager       -
:mount-observe       -
:network             -
:network-bind        webcam-webui
:network-control     -
:network-manager     -
:network-observe     -
:opengl              -
:optical-drive       -
:ppp                 -
:pulseaudio          -
:snapd-control       -
:system-observe      -
:timeserver-control  -
:timezone-control    -
:unity7              -
:x11                 -

请注意我们最前面的一个Slot: camera.我们在想我们的这个应用不就是一个camera应用吗?如果我们希望访问camera我们必须设置camera plug,这样我们才可以真正地访问我们的这个设备.有了这样的想法,我们在我们的snapcraft.yaml中加入camera.更后的snapcraft.yaml的文件如下:

snapcraft.yaml


name: webcam-webui
version: 1
summary: Webcam web UI
description: Exposes your webcam over a web UI
confinement: strict

apps:
  webcam-webui:
    command: bin/webcam-webui
    daemon: simple
    plugs: [camera,network-bind]

parts:
  cam:
    plugin: go
    go-packages:
      - github.com/mikix/golang-static-http
    stage-packages:
      - fswebcam
    filesets:
      fswebcam:
        - usr/bin/fswebcam
        - lib
        - usr/lib
      go-server:
        - bin/golang-*
    stage:
      - $fswebcam
      - $go-server
    snap:
      - $fswebcam
      - $go-server
      - -usr/share/doc
  glue:
    plugin: copy
    files:
      webcam-webui: bin/webcam-webui

请注意,我们在plug里加入了camera.重新打包并安装我们的应用.我们再次运行:

liuxg@liuxg:~$ snap interfaces
Slot                 Plug
:camera              -
:cups-control        -
:firewall-control    -
:gsettings           -
:home                -
:locale-control      -
:log-observe         -
:modem-manager       -
:mount-observe       -
:network             -
:network-bind        webcam-webui
:network-control     -
:network-manager     -
:network-observe     -
:opengl              -
:optical-drive       -
:ppp                 -
:pulseaudio          -
:snapd-control       -
:system-observe      -
:timeserver-control  -
:timezone-control    -
:unity7              -
:x11                 -
liuxg@liuxg:~$ snap interfaces
Slot                 Plug
:camera              -
:cups-control        -
:firewall-control    -
:gsettings           -
:home                -
:locale-control      -
:log-observe         -
:modem-manager       -
:mount-observe       -
:network             -
:network-bind        webcam-webui
:network-control     -
:network-manager     -
:network-observe     -
:opengl              -
:optical-drive       -
:ppp                 -
:pulseaudio          -
:snapd-control       -
:system-observe      -
:timeserver-control  -
:timezone-control    -
:unity7              -
:x11                 -
-                    webcam-webui:camera

显然,这次,我们看见了:

-                    webcam-webui:camera

这里虽然显示了camera的plug,但是它并没有真正地连接起来.我们查看文档Interfaces.在这篇文章中:

camera

Can access the first video camera. Suitable for programs wanting to use the webcams.

Usage: common Auto-Connect: no

它显示了:Auto-Connect: no.我们需要手动连接.

$ sudo snap connect webcam-webui:camera ubuntu-core:camera

通过上面的命令,我们可以使得一个plug和一个slot进行手动连接.重新运行如下的命令:

liuxg@liuxg:~$ snap interfaces
Slot                 Plug
:camera              webcam-webui
:cups-control        -
:firewall-control    -
:gsettings           -
:home                -
:locale-control      -
:log-observe         -
:modem-manager       -
:mount-observe       -
:network             -
:network-bind        webcam-webui
:network-control     -
:network-manager     -
:network-observe     -
:opengl              -
:optical-drive       -
:ppp                 -
:pulseaudio          -
:snapd-control       -
:system-observe      -
:timeserver-control  -
:timezone-control    -
:unity7              -
:x11                 -

这次,我们看见了我们的应用webcam-webui已经和network-bin及camera建立起来连接了.我们再次打开我们的浏览器:






我们整个项目的源码在:https://github.com/liu-xiao-guo/webcam-snap

我们可以通过如下的方式来查询我们的service的运行情况:

$ systemctl status snap.webcam-webui.webcam-webui

liuxg@liuxg:~$ systemctl status snap.webcam-webui.webcam-webui
● snap.webcam-webui.webcam-webui.service - Service for snap application webcam-webui.webcam-webui
   Loaded: loaded (/etc/systemd/system/snap.webcam-webui.webcam-webui.service; enabled; vendor prese
   Active: active (running) since 二 2016-07-19 12:38:02 CST; 36min ago
 Main PID: 16325 (webcam-webui)
   CGroup: /system.slice/snap.webcam-webui.webcam-webui.service
           ├─16325 /bin/sh /snap/webcam-webui/x1/bin/webcam-webui
           ├─16327 golang-static-http
           └─17488 sleep 10

7月 19 13:14:31 liuxg ubuntu-core-launcher[16325]: Adjusting resolution from 384x288 to 960x540.
7月 19 13:14:31 liuxg ubuntu-core-launcher[16325]: --- Capturing frame...
7月 19 13:14:31 liuxg ubuntu-core-launcher[16325]: Captured frame in 0.00 seconds.
7月 19 13:14:32 liuxg ubuntu-core-launcher[16325]: --- Processing captured image...
7月 19 13:14:32 liuxg ubuntu-core-launcher[16325]: Fontconfig error: Cannot load default config file
7月 19 13:14:32 liuxg ubuntu-core-launcher[16325]: Fontconfig error: Cannot load default config file
7月 19 13:14:32 liuxg ubuntu-core-launcher[16325]: Fontconfig error: Cannot load default config file
7月 19 13:14:32 liuxg ubuntu-core-launcher[16325]: Unable to load font 'sans': fontconfig: Couldn't f
7月 19 13:14:32 liuxg ubuntu-core-launcher[16325]: Disabling the the banner.
7月 19 13:14:32 liuxg ubuntu-core-launcher[16325]: Writing JPEG image to 'shot.jpeg'.

我们可以通过如下的方式来停止一个service:
$ sudo systemctl stop snap.webcam-webui.webcam-webui

我们可以通过如下的方式来启动一个service:

$ sudo systemctl start snap.webcam-webui.webcam-webui





作者:UbuntuTouch 发表于2016/7/19 10:55:55 原文链接
阅读:98 评论:0 查看评论

Read more
niemeyer

One of my “official side projects” is the Go language driver for MongoDB, started a few years back while looking for a way to store data conveniently from the Go language while leaving aside some of the problems we have mapping code into table-based approaches.

Nowadays this is used in projects at Canonical, in the MongoDB tooling itself, and also in some of my own personal projects. For the personal server-side projects I’ve been using docker containers to conveniently deploy the database tooling, but this week when I went to update some of my older images pulled from the docker hub I found that the docker installed on that server was a bit too old, so it was time to update the servers.

But that got me wondering: what if I replaced all those containers by snaps? This would allow me to keep the convenience and safety of the isolation, while making a lot of things simpler. Unlike docker, snaps make the installed tooling more easily accessible to the host system (bins in the search path, processes as actual children from shell and systemd, etc), and can even use system resources directly assuming interfaces allow it (e.g. home files).

So I got into that, and perhaps ended up overdoing it a little bit. Based on my experience testing the driver, I really appreciate having all versions available for playing with, rather than just the latest one. This is how my local development system looks like right now:

$ snap list | grep 'Name\|mongo'
Name                  Version               Rev     Developer   Notes
mongo22               2.2.7                 1       niemeyer    -
mongo24               2.4.14                1       niemeyer    -
mongo26               2.6.12                1       niemeyer    -
mongo30               3.0.12                1       niemeyer    -
mongo32               3.2.7                 1       niemeyer    -
mongo33               3.3.9                 1       niemeyer    -

These are backed by upstream tarballs (snapcraft downloaded them pre-built from mongodb.com), and are all installed, running, and with tooling available for playing with. They are also published to the snap store which means you can easily make use of them locally as well. If you want to do that, here is a crash course on snaps and on how I packaged the database together specifically.

If you’re using Ubuntu, update to release 16.04 which has snaps working out of the box. For other distributions have a look at snapcraft.io to see what command must be run for ensuring it is available.

Then, pick your version and install it. For example, if you want to play with the features just announced at MongoDB World this week, you want the unstable version 3.3.9:

$ snap install mongo33
93.59 MB / 93.59 MB [============================] 100.00 % 1.33 MB/s 

Name     Version  Rev  Developer  Notes
mongo33  3.3.9    1    niemeyer   -

After that you already have the tooling available in your path (assuming you have /snap/bin there), and the daemon started. So go ahead and fire the client to talk to the database:

$ mongo33
MongoDB shell version: 3.3.9
connecting to: 127.0.0.1:3317/test
MongoDB server version: 3.3.9
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
Server has startup warnings: 
(...) 
(...) ** NOTE: This is a development version (3.3.9) of MongoDB.
(...) **       Not recommended for production.
> 

Note that the server started on the non-standard port 33017 to allow multiple versions to be running together. The pattern is that the snap mongoNN will run on port NN017.

The tools installed also follow a similar pattern. Where upstream uses mongo, mongod, mongodump, etc, the snaps will have them under /snap/bin as mongo33, mongo33.d, mongo33.dump, and so on.

The systemd unit, if you want to interact with it for restarting, improving, debugging, etc, is named snap.mongo33.mongod.service, as usual for any snap that contains a daemon (snap.<snap name>.<app name>.service).

The data for the process that runs under systemd lives in the the standard writable area that the confinement system opens up for snaps in general – in this specific case /var/snap/mongo33/common/. The common directory is reused untouched on updates across snap revisions, which implies snapd won’t copy the data over when doing such updates. This compromises slightly the update safety, but is worth it for bulk data that we don’t want to copy on every snap refresh.

So this ended up quite nicely. Next up is the Go server code itself, which will be packed as a snap too, for deploying it into the servers in a similar way. The exact details for how these snaps are being built are publicly available too.

If you want a hand doing something similar, we have some helpful people at #snappy on FreeNode and also snapcraft@lists.snapcraft.io.

@gniemeyer

Read more
Grazina Borosko

Every year since 2001, creatives from different design disciplines meet and share their ideas and innovations about digital, interaction and print design in the design festival called OFFF.

This festival was previously held in different countries, but has now found its home in Barcelona at the Design Museum. For three days the festival was jam-packed full of inspirational ideas and speakers such as Paula Scher, Tony Brook, Joshua Davis and many more.

 

IMG_4973

OFFF  space in the Design Musem

OFFF

OFFF 2016 book and program

What is the festival about?

The festival gives a great overview of design trends, work processes and implementation practices, as well as generating ideas and inspiration from around the world. A festival organizer claimed that: “it is more than just a Festival hosting innovative and international speakers, it is more than a meeting point for all talents around the world to collaborate, it is more than feeding the future. OFFF is a community inviting all those who are eager to learn to participate and get inspired by a three-day journey of conferences, workshops, activities, and performances.”

 

Ustwo

Ustwo

Hey studio

Hey studio

A word of advice…

Before coming to the festival make sure you have a list of speakers you would like to hear, because there are 50 different talks taking place covering a wide scope of topics. It was interesting to hear designers sharing their experiences in design, such as self-initiated projects, dealing with clients, social life versus private, time management and working in a team and solo difficulties.

 

Nonformat

Non-Format

Joshua Davis deisgn

Joshua Davis design

Why you should go to the festival

Being surrounded by creative people for a three days helps you look at your work from the different perspectives. It is always healthy to leave your comfort zone and talk to other creators to see what kind of issues other people have, and how they are solving them. There’s no wrong or right way in the creative process. There are different ways which might work for you, and some that don’t. Inspiring talks give you energy and make you believe that anything is possible to achieve; you just need to do it!

 

Mark Adamson

Danny Sangra

 

 

Read more
Paty Davila

Last week I was invited to Beijing to take part in the China Launch Sprint. The focus of the sprint was to identify action items in our product roadmap for the next devices that will ship Ubuntu Touch in the Chinese market later this year.

photo_2016-06-17_15-25-12

I am a lead UX designer in the product strategy team currently doing many exciting things, such as designing the convergence experience across the Ubuntu platform. I was invited to offer design support and participate in the planning of the work we will be doing with our industry partner, China Mobile, after reviewing the CTA test results.

What is CTA?

CTA stands for China type approval which is a certificate granted to a product that meets a set of regulatory, technical and safety requirements. Generally, type approval is required before a product is allowed to be sold in a particular country.

Topics covered:

  • CTA Level 1-4 test cases and developed a new testing tool for pre-install applications.
    We reviewed the content and proposed design for all five of Migu scopes with design team’s input.
  • Also, we discussed the new RCS (Rich Communication Suite) integration with our Messaging app and prepared demos [link] for MWC Shanghai, Asia’s biggest mobile event happening at the end of this month.
  • And explored ideas around the design of mCloud service integration with our storage framework.

Achievements

The sprint was very productive and a great experience to sync up with old and new faces. We were all excited to explore ideas and work together on the next steps for China Mobile and Ubuntu.

Downtown in Beijing

I had some downtime to explore the city and have a taste of Beijing’s most interesting local dishes and potions with people I met from the sprint…

photo_2016-06-17_15-23-56

Michi has creatively named this one as snake juice.

Team dinner :)

A large team dinner.

photo_2016-06-28_15-40-59

The famous Great Wall of China.

The city lights of Beijing :)

The city lights of Beijing :)

Read more
Daniel Holbach

Next week on Tuesday, 5th July, we want to have our next Snappy Playpen event. As always we are going to work together on snapping software for our repository on github. Whatever app, service or piece of software you bring is welcome.

The focus of last week was ironing out issues and documenting what we currently have. Some outcomes of this were:

We want to continue this work, but add a new side to this: upstreaming our work. It is great that we get snaps working, but it is much better if the upstream project in question can take over the ownership of snaps themselves. Having snapcraft.yaml in their source tree will make this a lot easier. To kick off this work, we started some documentation on how to best do that and track this effort.

You are all welcome to the event and we look forward to work together with you. Coordination is happening on #snappy on Freenode and Gitter. We will make sure all our experts are around to help you if you have questions.

Looking forward to seeing you there!

Read more
Victor Palau

First of all, I wanted to recommend the following recipe from Digital Ocean on how to rollout your own Docker Registry in Ubuntu 14.04. As with most of their stuff, it is super easy to follow.

I also wanted to share a small improvement on the recipe to include a UI front-end to the registry.

Once you have completed the recipe and have a repository secured and running, you extend your docker-compose file to look like this:

nginx:
 image: "nginx:1.9"
 ports:
 - 443:443
 - 8080:8080
 links:
 - registry:registry
 - web:web
 volumes:
 - ./nginx/:/etc/nginx/conf.d:ro

web:
 image: hyper/docker-registry-web
 ports:
 - 8000:8080
 links:
 - registry
 environment:
 REGISTRY_HOST: registry

registry:
 image: registry:2
 ports:
 - 127.0.0.1:5000:5000
 environment:
 REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY: /data
 volumes:
 - ./data:/data

You will also need to include a configuration file for web in the nginx folder.

file: ~/docker-registry/nginx/web.conf

upstream docker-registry-web {
 server web:8080;
 }

server {
 listen 8080;
 server_name [YOUR DOMAIN];

# SSL
 ssl on;
 ssl_certificate /etc/nginx/conf.d/domain.crt;
 ssl_certificate_key /etc/nginx/conf.d/domain.key;

location / {

# To add basic authentication to v2 use auth_basic setting plus add_header
 auth_basic "registry.localhost";
 auth_basic_user_file /etc/nginx/conf.d/registry.password;

proxy_pass http://docker-registry-web;
 proxy_set_header Host $http_host; # required for docker client's sake
 proxy_set_header X-Real-IP $remote_addr; # pass on real client's IP
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto $scheme;
 proxy_read_timeout 900;
 }
 }

docker-compose up and you should be able to have a ssl secured UI frontend in port 8080 (https://yourdomain:8080/)
If you have any improvement tips I am all ears!


Read more
Colin Ian King

What's new in stress-ng 0.06.07?

Since my last blog post about stress-ng, I've pushed out several more small releases that incorporate new features and (as ever) a bunch more bug fixes.  I've been eyeballing gcov kernel coverage stats to find more regions in the kernel where stress-ng needs to exercise.   Also, testing on a range of hardware (arm64, s390x, etc) and a range of kernels has eeked out some bugs and helped me to improve stress-ng.  So what's new?

New stressors:

  • ioprio  - exercises ioprio_get(2) and ioprio_set(2) (I/O scheduling classes and priorities)
  • opcode - generates random object code and executes this, generating and catching illegal instructions, bus errors,  segmentation  faults,  traps and floating  point errors.
  • stackmmap - allocates a 2MB stack that is memory mapped onto a temporary file. A recursive function works down the stack and flushes dirty stack pages back to the memory mapped file using msync(2) until the end of the stack is reached (stack overflow). This exercises dirty page and stack exception handling.
  • madvise - applies random madvise(2) advise settings on pages of a 4MB file backed shared memory mapping.
  • pty - exercise pseudo terminal operations.
  • chown - trivial chown(2) file ownership exerciser.
  • seal - fcntl(2) file SEALing exerciser.
  • locka - POSIX advisory locking exerciser.
  • lockofd - fcntl(2) F_OFD_SETLK/GETLK open file description lock exerciser.
Improved stressors:
  • msg: add in IPC_INFO, MSG_INFO, MSG_STAT msgctl calls
  • vecmath: add more ops to make vecmath more demanding
  • socket: add --sock-type socket type option, e.g. stream or seqpacket
  • shm and shm-sysv: add msync'ing on the shm regions
  • memfd: add hole punching
  • mremap: add MAP_FIXED remappings
  • shm: sync, expand, shrink shm regions
  • dup: use dup2(2)
  • seek: add SEEK_CUR, SEEK_END seek options
  • utime: exercise UTIME_NOW and UTIME_OMIT settings
  • userfaultfd: add zero page handling
  • cache:  use cacheflush() on systems that provide this syscall
  • key:  add request_key system call
  • nice: add some randomness to the delay to unsync nicenesses changes
If any new features land in Linux 4.8 I may add stressors for them, but for now I suspect that's about it for the big changes for stress-ng for the Ubuntu Yakkey 16.10 release.

Read more
David Callé

Snapcraft 2.12 is here and is making its way to your 16.04 machines today.

This release takes Snapcraft to a whole new level. For example, instead of defining your own project parts, you can now use and share them from a common, open, repository. This feature was already available in previous versions, but is now much more visible, making this repo searchable and locally cached.

Without further ado, here is a tour of what’s new in this release.

Commands

2.12 introduces ‘snapcraft update’, ‘search’ and ‘define’, which bring more visibility to the Snapcraft parts ecosystem. Parts are pieces of code for your app, that can also help you bundle libraries, set up environment variables and other tedious tasks app developers are familiar with.

They are literally parts you aggregate and assemble to create a functional app. The benefits of using a common tool is that these parts can be shared amongst developers. Here is how you can access this repository.

  • snapcraft update : refresh the list of remote parts
  • snapcraft search : list and search remote parts
  • snapcraft define : display information and content about a remote part

5273725bbff337eaf4eb07a81af97cd82051866b.png

To get a sense of how these commands are used, have a look at the above example, then you can dive into details and what we mean by “ecosystem of parts”.

Snap name registration

Another command you will find useful is the new ‘register’ one. Registering a snap name is reserving the name on the store.

  • snapcraft register

6875784c98c671707e1de1b27bb0cdba4690d68e.png

As a vendor or upstream, you can secure snap names when you are the publisher of what most users expect to see under this name.

Of course, this process can be reverted and disputed. Here is what the store workflow looks like when I try to register an already registered name:

snap-name-register.png

On the name registration page of the store, I’m going to try to register ‘my-cool-app’, which already exists.

snap-name-register-failed.png

I’m informed that the name has already been registered, but I can dispute this or use another name.

snap-name-register-dispute.png

I can now start a dispute process to retrieve ownership of the snap name.

Plugins and sources

Two new plugins have been added for parts building: qmake and gulp.

qmake

The qmake plugin has been requested since the advent of the project, and we have seen many custom versions to fill this gap. Here is what the default qmake plugin allows you to do:

  • Pass a list of options to qmake
  • Specify a Qt version
  • Declare list of .pro files to pass to the qmake invocation

gulp

The hugely popular nodejs builder is now a first class citizen in Snapcraft. It inherits from the existing nodejs plugin and allows you to:

  • Declare a list of gulp tasks
  • Request a specific nodejs version

Subversion

SVN is still a major version control system and thanks to Simon Quigley from the Lubuntu project, you can now use svn: URIs in the source field of your plugins.

Highlights

Many other fixes made their way into the release, with two highlights:

  • You can now use hidden .snapcraft.yaml files
  • snapcraft cleanbuild’ now creates ephemeral LXC containers and won’t clutter your drive anymore

The full changelog for this milestone is available here and the list of bugs in sight for 2.13 can be found here. Note that this list will probably change until the next release, but if you have a Snapcraft itch to scratch, it’s a good list to pick your first contribution from.

Install Snapcraft

On Ubuntu

Simply open up a terminal with Ctrl+Alt+t and run these commands to install Snapcraft from the Ubuntu archives on Ubuntu 16.04 LTS

sudo apt update
sudo apt install snapcraft

On other platforms

Get the Snapcraft source code ›

Get snapping!

There is a thriving community of developers who can give you a hand getting started or unblock you when creating your snap. You can participate and get help in multiple ways:

Read more
David Barth

Cordova Ubuntu Update

A few weeks ago we participated to Phonegap Day EU 2016

A few weeks ago we participated to Phonegap Day EU 2016. It was a great opportunity to meet with the Cordova development team and app developers gathered for this occasion.

We demo'ed the latest Ubuntu 16.04 LTS release, running on a brand new BQ M10 tablet in convergence mode. It was really interesting to discuss with app developers. Creating responsive user interfaces is already a common topic for web developers, and Cordova developers by extension. 

On the second day, we hosted a workshop on developing Ubuntu applications with Cordova and popular frameworks like Ionic. Alexandre Abreu also showed his new cordova-plugin-ble-central for Ubuntu. This one lets you connect to an IoT device, like one of those new RPI boards, directly to an Ubuntu app using the Bluetooth Low Energy stack. Snappy, Ubuntu and Cordova all working together !

Last but not least, we started the release process for cordova-ubuntu 4.3.4. This is the latest stable update to the Ubuntu platform support code for Cordova apps. It's coming along with a set of documentation updates available here and on the upstream cordova doc site

We've made a quick video to summarize this and walk you through the first steps of creating your own Ubuntu app using Cordova. You can now watch it at: https://www.youtube.com/watch?v=ydnG7wVrsW4

Let us know about your ideas : we're eager to see what you can do with the new release and plugins.

Read more
Luca Paulina

Juju GUI 2.0

Juju is a cloud orchestration tool which enables users to build models to run applications. You can just as easily use it to deploy a simple WordPress blog or a complex big data platform. Juju is a command line tool but also has a graphical user interface (GUI) where users can choose services from a store, assemble them visually in the GUI, build relations and configure them with the service inspector.

Juju GUI allows users to

  • Add charms and bundles from the charm store
  • Configure services
  • Deploy applications to a cloud of their choice
  • Manage charm settings
  • Monitor model health

Over the last year we’ve been working on a redesign of the Juju GUI. This redesign project focused on improving four key areas, which also acted as our guiding design principles.

1. Improve the functionality of the core features of the GUI

  • Organised similar areas of the core navigation to create a better UI model.
  • Reduced the visual noise of the canvas and the inspector to help users navigate complex models.
  • Introduced a better flow between the store and the canvas to aid adding services without losing context.
Hero before
Hero after

‹ ›

Empty state of the canvas

 

Hero before
Hero after

‹ ›

Integrated store

 

Hero before
Hero after

‹ ›

Apache charm details

 

2. Reduce cognitive load and pace the user

  • Reduced the amount of interaction patterns to minimise the amount of visual translation.
  • Added animation to core features to inform users of the navigation model in an effort to build a stronger concept of home.
  • Created a symbiotic relationship between the canvas and the inspector to help navigation of complex models.
Hero before
Hero after

‹ ›

Mediawiki deployment

 

3. Provide an at-a-glance understanding of model health

  • Prioritised the hierarchy of status so users are always aware of the most pressing issues and can discern which part of the application is effected.
  • Easier navigation to units with a negative status to aid the user in triaging issues.
  • Used the same visual patterns throughout the web app so users can spot problematic issues.
Hero before
Hero after

‹ ›

Mediawiki deployment with errors

 

4. Surface functions and facilitate task-driven navigation

  • Established a new hierarchy based on key tasks to create a more familiar navigation model.
  • Redesigned the inspector from the ground up to increase discoverability of inspector led functions.
  • Simplified the visual language and interaction patterns to help users navigate at-a-glance and with speed to triage errors, configure or scale out.
  • Surfaced relevant actions at the right time to avoid cluttering the UI.
Hero before
Hero after

‹ ›

Inspector home view

 

Hero before
Hero after

‹ ›

Inspector errors view

 

Hero before
Hero after

‹ ›

Inspector config view

 

The project has been amazing, we’re really happy to see that it’s launched and are already planning the next updates.



<>

Read more
Luca Paulina

Design in the open

As the Juju design team grew it was important to review our working process and to see if we could improve it to create a more agile working environment. The majority of employees at Canonical work distributed around the globe, for instance the Juju UI engineering team has employees from Tasmania to San Francisco. We also work on a product which is extremely technical and feedback is crucial to our velocity.

We identified the following aspects of our process which we wanted to improve:

  • We used different digital locations for storing their design outcomes and assets (Google Drive, Google Sites and Dropbox).
  • The entire company used Google Drive so it was ideal for access, but its lacklustre performance, complex sharing options and poor image viewer meant it wasn’t good for designs.
  • We used Dropbox to store iterations and final designs but it was hard to maintain developer access for sharing and reference.
  • Conversations and feedback on designs in the design team and with developers happened in email or over IRC, which often didn’t include all interested parties.
  • We would often get feedback from teams after sign-off, which would cause delays.
  • Decisions weren’t documented so it was difficult to remember why a change had been made.

Finding the right tool

I’ve always been interested in the concept of designing in the open. Benefits of the practice include being more transparent, faster and more efficient. They also give the design team more presence and visibility across the organisation. Kasia (Juju’s project manager) and I went back and forth on which products to use and eventually settled on GitHub (GH).

The Juju design team works in two week iterations and at the beginning of a new iteration we decided to set up a GH repo and trial the new process. We outlined the following rules to help us start:

  • Issues should be created for each project.
  • All designs/ideas/wireframes should be added inline to the issues.
  • All conversations should be held within GH, no more email or IRC conversations, and notes from any meetings should be added to relevant issues to create a paper trail.

Reaction

As the iteration went on, feedback started rolling in from the engineering team without us requesting it. A few developers mentioned how cool it was to see how the design process unfolded. We also saw a lot of improvement in the Juju design team: it allowed us to collaborate more easily and it was much easier to keep track of what was happening.

At the end of the trial iteration, during our clinic day, we closed completed issues and uploaded the final assets to the “code” section of the repo, creating a single place for our files.

After the first successful iteration we decided to carry this on as a permanent part of our process. The full range of benefits of moving to GH are:

  • Most employees of Canonical have a GH account and can see our work and provide feedback without needing to adopt a new tool.
  • Project management and key stakeholders are able to see what we’re doing, how we collaborate, why a decision has been made and the history of a project.
  • Provides us with a single source for all conversations which can happen around the latest iteration of a project.
  • One place where anyone can view and download the latest designs.
  • A single place for people to request work.

Conclusion

As a result of this change our designs are more accessible which allows developers and stakeholders to comment and collaborate with the design team aiding in our agile process. Below is an example thread where you can see how GH is used in the process. I shows how we designed the new contextual service block actions.

GH_conversation_new_navigation

Read more