Canonical Voices

UbuntuTouch

[原]利用ContentHub API来import图片

由于Ubuntu OS的安全机制,任何第三方的应用无法访问另外一个应用的存储。这样就带来了问题,比如我们想访问Gallery中的图片怎么办?我们可以利用Ubuntu OS提供的ContentHub API来访问另外一个应用所提供的可以访问的内容。前提是另外一个应用必须有相应的功能实现exporter的功能。在这篇文章中,我们来介绍如何使用ContentHub来获取由Gallery所提供的图片。更多关于ContentHub的API介绍,可以参照链接


1)创建一个最基本的QML应用

我们打开SDK来创建一个最基本的QML应用。我们使用"App with Simple UI" 模版。并取一个名字为“contenthub-importer”。在这里,我们必须注意如下项:

applicationName: "com.ubuntu.developer.liu-xiao-guo.contenthub-importer"

这个应用的名称必须和package的名称是一致的。否则在以后我们导入图片到本应用时,由于目录的路径不同从而会导致所创建的目录不能访问。我们将生成的package名称为:

com.ubuntu.developer.liu-xiao-guo.contenthub-importer_0.1_all.click

在手机上导入的路径将为:



当然这是我们在最后运行应用时,在导入图片后才可以创建的路径。

2)设计我们的界面

我们的设计界面如下:



在屏幕的做上方,是一个“ComboButton”。我们的设计如下:

        ListModel {
            id: typemodel
            ListElement { name: "Import single item" }
            ListElement { name: "Import multiple items" }
        }

        ListItem.Empty {
            id: options

            ComboButton {
                id: type
                anchors {
                    left: parent.left
                    margins: units.gu(2)
                }

                dropdownColor: "red"
                width: root.width/2

                expanded: false

                text: "Import single item"
                ListView {
                    anchors.fill: parent
                    model: typemodel
                    delegate: ListItem.Standard {
                        text: modelData

                        onClicked: {
                            console.log("item is clicked!" + index + " " + name);
                            type.expanded = false;
                            type.text = text;

                            console.log("type is: " + type.text);

                            if ( name === "Import single item") {
                                activeTransfer = picSourceSingle.request(appStore);
                            } else if ( name === "Import multiple items" ) {
                                activeTransfer = picSourceMulti.request(appStore);
                            }
                        }
                    }
                }
            }

            Button {
                anchors {
                    right: parent.right
                    margins: units.gu(2)
                }
                text: "Finalize import"
                enabled: activeTransfer.state === ContentTransfer.Collected
                onClicked: activeTransfer.finalize()
            }
        }

我们可以选择import一个或多个图片。我们同时也定义两个ContentPeer。一个ContentPeer是一个已经向ContentHub注册作为一个数据源或一个有ContentType定义的目的地。

        ContentPeer {
            id: picSourceSingle
            contentType: ContentType.Pictures
            handler: ContentHandler.Source
            selectionType: ContentTransfer.Single
        }

        ContentPeer {
            id: picSourceMulti
            contentType: ContentType.Pictures
            handler: ContentHandler.Source
            selectionType: ContentTransfer.Multiple
        }

我们也可以定义一个“ContentPeerModel”来显示所有可以提供图片的应用。

        // Provides a list<ContentPeer> suitable for use as a model
        ContentPeerModel {
            id: picSources
            // Type of handler: Source, Destination, or Share
            handler: ContentHandler.Source
            // well know content type
            contentType: ContentType.Pictures
        }

我们可以用如下的ListView来显示这些应用:

        ListView {
            id: peerList
            anchors {
                left: parent.left
                right: parent.right
                top: options.bottom
            }
            height: childrenRect.height
            model: picSources.peers

            delegate: ListItem.Standard {
                text: modelData.name
                control: Button {
                    text: "Import"
                    onClicked: {
                        // Request the transfer, it needs to be created and dispatched from the hub
                        activeTransfer = modelData.request();
                    }
                }
            }
        }

我们可以用如下的方法来检测在transfer过程中的状态:

        Connections {
            target: activeTransfer
            onStateChanged: {
                //            console.log("StateChanged: " + activeTransfer.state);
                switch (activeTransfer.state) {
                case ContentTransfer.Created:
                    console.log("Created");
                    break
                case ContentTransfer.Initiated:
                    console.log("Initiated");
                    break;
                case ContentTransfer.InProgress:
                    console.log("InProgress");
                    break;
                case ContentTransfer.Downloading:
                    console.log("Downloading");
                    break;
                case ContentTransfer.Downloaded:
                    console.log("Downloaded");
                    break;
                case ContentTransfer.Charged:
                    console.log("Charged");
                    break;
                case ContentTransfer.Collected:
                    console.log("Collected");
                    break;
                case ContentTransfer.Aborted:
                    console.log("Aborted");
                    break;
                case ContentTransfer.Finalized:
                    console.log("Finalized");
                    break;
                default:
                    console.log("not recognized state!")
                    break;
                }

                if (activeTransfer.state === ContentTransfer.Charged) {
                    importItems = activeTransfer.items;

                    for ( var i = 0; i < importItems.length; i ++ ) {
                        console.log(importItems[i].url);
                    }

                    var item;
                    for ( item in importItems ) {
                        console.log( "imported url: " + importItems[item].url);
                    }
                }
            }

在上面的代码中,我们显示了存入本应用中的文件的路径。这里activeTransfer及importItems被定义如下:

    property list<ContentItem> importItems
    property var activeTransfer

我们用另外一个ListView来显示我们所导入的照片:

        ListView {
            id: peerList
            anchors {
                left: parent.left
                right: parent.right
                top: options.bottom
            }
            height: childrenRect.height
            model: picSources.peers

            delegate: ListItem.Standard {
                text: modelData.name
                control: Button {
                    text: "Import"
                    onClicked: {
                        // Request the transfer, it needs to be created and dispatched from the hub
                        activeTransfer = modelData.request();
                    }
                }
            }
        }

最应用显示的效果如下:



整个的代码在如下的地址可以找到:

bzr branch lp:~liu-xiao-guo/debiantrial/contenthub-importer



作者:UbuntuTouch 发表于2014-11-6 18:07:22 原文链接
阅读:85 评论:0 查看评论

Read more
Steph

Last week was a week of firsts for me: my first trip to America, my first Sprint and my first chili-dog.

Introducing myself as the new (only) Editorial and Web Publisher, I dove head first into the world of developers, designers and Community members. It was a very absorbing week, which after felt more like a marathon than a sprint.

After being grilled by Customs, finally we arrived at Tyson’s Corner where 200 or so other developers, designers and Community members gathered for the Devices Sprint. It was a great opportunity for me to see how people from each corner of the world contribute to Ubuntu, and share their passion for open source. I especially found it interesting to see how designers and developers work together, given their different mind sets and how they collaborated together.

The highlight for me was talking to some of the Community guys, it was really interesting to talk to them about why and how they contribute from all corners of the world.

From left to right: Riccardo, Andrew, Filippo and Victor.

(From left to right: Riccardo, Andrew, Filippo and Victor)

The main ballroom.

(The main Ballroom)

Design Team dinner.  From the left: TingTing, Andrew, John, Giorgio, Marcus, Olga, James, Florian, Bejan and Jouni.

(Design Team dinner. From the left: TingTing, Andrew, John, Giorgio, Marcus, Olga, James, Florian, Bejan and Jouni)

I caught up with Olga and Giorgio to share their thoughts and experiences from the Sprint:

So how did the Sprint go for you guys?

Olga: “It was very busy and productive in terms of having face time with development, which was the main reason we went, as we don’t get to see them that often.

For myself personally, I have a better understanding of things in terms of what the issues are and what is needed, and also what can or cannot be done in certain ways. I was very pleased with the whole sprint. There was a lot of running around between meetings, where I tried to use the the time in-between to catch-up with people. On the other hand as well, Development made the approach to the Design Team in terms of guidance, opinions and a general catch-up/chat, which was great!

Steph: “I agree, I found it especially productive in terms of getting the right people in the same room and working face-to-face, as it was a lot more productive than sharing a document or talking on IRC.”

Giorgio: “Working remotely with the engineers works well for certain tasks, but the Design Team sometimes needs to achieve a higher bandwidth through other means of communication, so these sprints every 3 months are incredibly useful.

What a Sprint allows us to do is to put a face to the name and start to understand each other’s needs, expectations and problems, as stuff gets lost in translation.

I agree with Olga, this Sprint was a massive opportunity to shift to much higher level of collaboration with the engineers.

What was your best moment?

Giorgio: “My best moment was when the engineers perception towards the efforts of the Design Team changed. My goal is to better this collaboration process with each Sprint.”

Did anything come up that you didn’t expect?

Giorgio: “Gaming was an underground topic that came up during the Sprint. There was a nice workshop on Wednesday on it, which was really interesting.”

Steph: “Andrew a Community Developer I interviewed actually made two games one evening during the Sprint!”

Olga: “They love what they do, they’re very passionate and care deeply.”

Do you feel as a whole the Design Team gave off a good vibe?

Giorgio: “We got a good vibe but it’s still a working progress, as we need to raise our game and become even better. This has been a long process as the design of the Platform and Apps wasn’t simply done overnight. However, now we are in a mature stage of the process where we can afford to engage with Community more. We are all in this journey together.

Canonical has a very strong engineering nature, as it was founded by engineers and driven by them, and it is has evolved because of this. As a result, over the last few years the design culture is beginning to complement that. Now they expect steer from the Design Team on a number of things, for example: Responsive design and convergence.

The Sprint was good, as we finally got more of a perception on what other parties expect from you. It’s like a relationship, you suddenly have a moment of clarity and enlightenment, where you start to see that you actually need to do that, and that will make the relationship better.”

Olga: The other parties and the Development Team started to understand that initiated communication is not just the responsibility of the Design Team, but it’s an engagement we all need to be involved in.”

In all it was a very productive week, as everyone worked hard to push for the first release of the BQ phone; together with some positive feedback and shout-outs for the Design Team :)

Unicorn hard at work.

(Unicorn hard at work)

There was a bit of time for some sightseeing too…

It would have been rude not to see what the capital had to offer, so on the weekend before the sprint we checked out some of Washington’s iconic sceneries.

The Washington Monument.

(The Washington Monument)

We saw most of the important parliamentary buildings like the White House, Washington Monument and Lincoln’s Statue. Seeing them in the flesh was spectacular, however, I half expected a UFO to appear over the Monument like in ‘Independence Day’, and for Abraham Lincoln to suddenly get up off his chair like in the movie ‘Night at the Museum’ - unfortunately none of that happened.

The White House.

(The White House)

D.C. isn’t as buzzing as London but it definitely has a lot of character, as it embodies an array of thriving ethnic pockets that represented African, Asian and Latin American cultures, and also a lot of Italians. Washington is known for getting its sax on, so me and a few of the Design Team decided to check-out the night scene and hit a local Jazz Club in Georgetown.

...And all the jazz.

(Twins Jazz Club)

On the Sunday, we decided to leave the hustle and bustle of the city and venture to the beautiful Great Falls Park, which was only 10-15 minutes from the hotel. The park was located in the Northern Fairfax County along the banks of the Potomac River, which is an integral part of the George Washington Memorial Parkway. Its creeks and rapids made for some great selfie opportunities…

Great Falls Park.

(Great Falls Park)

Read more
UbuntuTouch

Ubuntu SDK对我们大多数开发者来说非常有效。它甚至可以帮我们来进行在线调试。在这篇文章中,我们来介绍如何使用command line来编译并运行我们的scope。


1)创建一个最基本的Scope

我们可以使用Ubuntu SDK来创建一个最基本的Scope。在创建时,我们可以选择任何一个template。我们可以在SDK中试着在Desktop上进行编译运行以确保没有任何问题。



我们创建一个叫做“scopetest”的scope。

2)运用Command Line进行编译及运行

我们首先打开一个Terminal。我们也可以打开已经创建好的template Scope中的readme.txt文件:

This project contains a simple Unity Scope and all files needed to build
and deploy it. Building it is simple. First you need to install the scopes
development package and CMake. Then you go into the source root and type
the following commands.

mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=debug ..
make

我们首先进入Scope所在的目录,并创建一个“build”子目录。

  


  


我们打入如上所述的命令。等编译好没有错误后,我们再进入当前目录下的“src”子目录,并打入如下的命令:

unity-scope-tool com.ubuntu.developer.liu-xiao-guo.scopetest_scopetest.ini 

这样,我们就可以在desktop上运行我们的scope了。


3)安装到手机中

我们可以创建两个如下的scripts文件:

build.sh


build.sh:
#!/bin/bash
click-buddy --arch armhf --framework ubuntu-sdk-14.10 --dir ..

provision.sh

#!/bin/bash
rm -f ../*click
click-buddy --arch armhf --framework ubuntu-sdk-14.10 --dir .. --provision

并同时把这两个文件存于scope项目的上一个目录。对我来说,我存放于“release”目录中。这样当我们处于“build”目录时,




我们也可以同时使用provision.sh来部署scope到手机中



在我们的手机上就可以看到我们已经部署好的scope。我们如果看不到的话,我们可以通过搜索的方式找到我们的scope。


作者:UbuntuTouch 发表于2014-10-31 10:54:57 原文链接
阅读:176 评论:0 查看评论

Read more
Michael Hall

With all of the new documentation coming to support the development of Unity Scopes, it’s time for us to have another development shodown! Contestants will have five (5) weeks to develop a project, from scratch, and submit it to the Ubuntu Store. But this time all of the entries must be Scopes.

Be sure to update to the latest SDK packages to ensure that you have the correct template and tools. You should also create a new Click chroot to get the latest build and runtime packages.

Prizes

prizesWe’ve got some great prizes lined up for the winners of this competition.

  • 1st place will win a new Dell XPS 13 Laptop, Developer Edition (preloaded with Ubuntu)
  • Runners up will receive one of:
    • Logitech UE Boom Bluetooth speakers
    • Nexus 7 running Ubuntu
    • An Ubuntu bundle, featuring:
      • Ubuntu messenger bag
      • Ubuntu Touch Infographic T-shirt
      • Ubuntu Neoprene Laptop Sleeve
    • An Ubuntu bundle, featuring:
      • Ubuntu backpack
      • Ubuntu Circle of Friends Dot Design T-shirt
      • Ubuntu Neoprene Laptop Sleeve

Judging

Scope entries will be reviewed by a panel of judges from a variety of backgrounds and specialties, all of whom will evaluate the scope based on the following criteria:

  • General Interest – Scopes that are of more interest to general phone users will be scored higher. We recommend identifying what kind of content phone users want to have fast, easy access to and then finding an online source where you can query for it
  • Creativity – Scopes are a unique way of bringing content and information to a user, and we’ve only scratched the surface of what they can do. Thinking outside the box and providing something new and exciting will lead to a higher score for your Scope
  • Features – There’s more to scopes than basic searching, take advantage of the departments, categories and settings APIs to enhance the functionality of your Scope
  • Design – Scopes offer a variety of ways to customize the way content is displayed, from different layouts to visual styling. Take full advantage of what’s possible to provide a beautiful presentation of your results.
  • Awareness / Promotion – we will award extra points to those of you who blog, tweet, facebook, Google+, reddit, and otherwise share updates and information about your scope as it progresses.

The judges for this contest are:

  • Chris Wayne developer behind a number of current pre-installed Scopes
  • Joey-Elijah Sneddon Author and editor of Omg!Ubuntu!
  • Victor Thompson Ubuntu Core Apps developer
  • Jouni Helminen Designer at Canonical
  • Alan Pope from the Ubuntu Community Team at Canonical

Learn how to write Ubuntu Scopes

To get things started we’ve recently introduced a new Unity Scope project template into the Ubuntu SDK, you can use this to get a working foundation for your code right away. Then you can follow along with our new SoundCloud scope tutorial to learn how to tailor your code to a remote data source and give your scope a unique look and feel that highlights both the content and the source. To help you out along the way, we’ll be scheduling a series of online Workshops that will cover how to use the Ubuntu SDK and the Scope APIs. In the last weeks of the contest we will also be hosting a hackathon on our IRC channel (#ubuntu-app-devel on Freenode) to answer any last questions and help you get your c If you cannot join those, you can still find everything you need to know in our scope developer documentation.

How to participate

If you are not a programmer and want to share some ideas for cool scopes, be sure to add and vote for scopes on our reddit page. The contest is free to enter and open to everyone. The five week period starts on the Thursday 30th October and runs until Wednesday 3rd December 2014! Enter the Ubuntu Scope Showdown >

Read more
facundo

A la caza del Octubre


Cuando estuve planificando el segundo semestre de este año no tenía idea que Octubre iba a estar tan complicado.

Lo primero grande que me llevó mucho tiempo fue el cumpleaños de Felipe. Este año hicimos algo en un saloncito (el mismo donde le festejamos el primer cumple) para los amiguitos del jardín y todos nuestros familiares/amigos que tienen niños, el mismo viernes que Felipe cumplía. Y luego un asado en casa para todo el resto de amigos y familiares, el domingo siguiente.

Felu soplando la velita

Salió todo muy bien, pero organizar todo lleva varios, varios días y terminás exhausto :p. Igual, la que más labura en estos casos es Moni, desde muchas semanas antes... haciendo decoraciones, los souvenirs, escenografías, y mil cosas más. Yo me ocupo de muchas cosas que tienen que ser los últimos días, así que lo mío es más corto, pero intensivo.

Felipe 5

Algo que no tenía planeado al armar el segundo semestre era una semana de laburo en Washington. Claro, es una semana hábil más el viaje durante el finde, así que ocupa bastante tiempo.

Yo ya conocía Washington (ver este post y siguientes), así que no me hice mucha malasangre porque no tenía tiempo de pasear por los alrededores y el centro. Igual algo caminamos, especialmente una noche que hicimos la cena de equipo, y nos fuimos a una ciudad costera cercana, a comer "bien local" (estuvo buenísimo). Y siempre es una excusa para volver a reencontrarse con gente, romper la rutina, jugar algunos juegos de mesa, etc... ¡ah! y trabajar en equipo, claro, :p

Salsa

Y para cerrar el mes, justo la semana posterior al viaje, asistí a mi primera Ekoparty (la conferencia seguridad más grande de latinoamérica). Esto lo estoy escribiendo el jueves a la mañana, así que todavía me resta asistir a dos tercios de la misma, y el primer día estuve a full en el stand de PyAr.

Bueno, "estuve", ¡estuvimos! Con Gabriel, Osiris, Nico y Julián, armando todo lo que es la competencia de Python Argentina, que armamos especialmente para Ekoparty. Lo que armamos fue un TypusPocus toqueteado especialmente para el evento; lo hacemos correr en una RasPi en modo "kiosco" para que la gente juegue, y sincronicamos los highscores a otra RasPi donde también corre TypusPocus, en modo "showcase" (mostrando highscores y propagandas de PyAr, la próxima PyConAr, y cosas del mismo juego).

Stand de PyAr en la Ekoparty

El stand va siendo un éxito. Ayer volaron los 100 microtutoriales que llevé, y la gente viene y va todo el tiempo. El jueves (hoy!) voy medio día, y mañana ya voy desde temprano y me quedo hasta bien el final. Y como ya tenemos 98% de todo listo, seguro que voy a ir a varias charlas de la conferencia misma, que hay algunas muy copadas.

Y ni hablemos de que todavía no liberé la nueva versión de Encuentro, o que tengo a medio armar varias cosas de CDPedia, las clases atrasadas de tenis, y muchas cosas para hacer en casa. Esperemos que Noviembre venga más tranquilo...

Read more
Jussi Pakkanen

Bug finding tools

In Canonical’s recent devices sprint I held a presentation on automatic bug detection tools. The slides are now available here and contain info on tools such as:

Enjoy.

 

Read more
Daniel Holbach

In the Community Q&A with Alan and Michael yesterday, I talked a bit about the sprint in Washington already, but I thought I’d write up a bit more about it again.

First of all: it was great to see a lot of old friends and new faces at the sprint. Especially with the two events (14.10 release and upcoming phone release) coming together, it was good to lock people up in various rooms and let them figure it out when nobody could run away easily. For me it was a great time to chat with lots of people and figure out if we’re still on track and if our old assumptions still made sense.  :-)

We were all locked up in a room as well...We were all locked up in a room as well…

What was pretty fantastic was the general vibe there. Everyone was crazy busy, but everybody seemed happy to see that their work of the last months and years is slowly coming together. There are still bugs to be fixed but we are close to getting the first Ubuntu phone ever out the door. Who would have thought that a couple of years ago?

It was great to catch up with people about our App Development story. There were a number of things we looked at during the sprint:

  • Up until now we had a Virtualbox image with Ubuntu and the SDK installed for people at training (or App Dev School) events, who didn’t have Ubuntu installed. This was a clunky solution, my beta testing at xda:devcon confirmed that. I sat down with Michael Vogt who encouraged me to look into providing something more akin to an “official ISO” and showed me the ropes in terms of creating seeds and how livecd-rootfs is used.
  • I had a number of conversations with XiaoGuo Liu, who works for Canonical as well, and has been testing our developer site and our tools for the last few months. He also wrote lots and lots of great articles about Ubuntu development in Chinese. We talked about providing our developer site in Chinese as well, how we could integrate code snippets more easily and many other things.
  • I had a many chats at the breakfast buffet with Zoltan and Zsombor of the SDK team (it always looked like we were there at the same time).  We talked about making fat packages easier to generate, my experiences with kits and many other things.
  • It was also great to catch up with David Callé who is working on scopes documentation. He’s just great!

What also liked a lot was being able to debug issues with the phone on the spot. I changed to the proposed channel, set it to read-write and installed debug symbols and voilà, grabbing the developer was never easier. My personal recommendation: make sure the problem happens around 12:00, stand in the hallway with your laptop attached to the phone and wait for the developer in charge to grab lunch. This way I could find out more about a couple of issues which are being fixed now.

It was also great to meet the non-Canonical folks at the sprint who worked on the Core Apps like crazy.

What I liked as well was our Berlin meet-up: we basically invited Berliners, ex-Berliners and honorary Berliners and went to a Mexican place. Wished I met those guys more often.

I also got my Ubuntu Pioneers T-Shirt. Thanks a lot! I’ll make sure to post a selfie (as everyone else :-)) soon.

Thanks a lot for a great sprint, now I’m looking forward to the upcoming Ubuntu Online Summit (12-14 Nov)! Make sure you register and add your sessions to the schedule!

Read more
UbuntuTouch

[原]使用Ubuntu SDK开发Flickr应用教程

在这篇文章中我们将一步一步地教大家怎么在Ubuntu手机平台来开发一个QML的应用。我们知道QML开发对很多初学者来说并不难。我们需要有一些简单的javascript的基础就可以开始我们的开发了。QML应用的调试也是很方便的。我们通过这个教程的学习,掌握基本的开发流程及界面设计。最终的应用显示的图片如下:

     

1)创建一个最基本的QML应用

我们首先打开Ubuntu SDK,并选择“App with Simple UI”模版。

  

这样我们就产生了一个最基本的QML应用。我们可以在desktop上运行它(通过按下Ctrl+R)键或点击SDK左下方的绿色的运行键。我们同时修改main.qml中的尺寸为:

    width: units.gu(80)
    height: units.gu(100)

这样我们的应用更像手机的长宽比。修改应用的title为:

        title: i18n.tr("Flickr")


应用中有一个按钮,大家可以点击并看看有什么变化。

2)实现一个最基本的列表

回头看看我们的设计,我们需要有一个列表来列出我们的图片。我们这里来使用一个列表的控件来实现它。在Ubuntu SDK的toolkit中,有一个conrtol叫做UbuntuListView。我们可以使用它来设计我们的列表。当然我们也可以使用QML中的ListView。UbuntuListView有一些更多的功能比如PullToRefresh。我们可以在下面用到。我们首先通过如下的方式添加一个文件“PictureListView.qml”到项目中。



    



这样我们就基本上创建了一个叫做“PictureListView.qml”的文件。在这里,它实际上创建一个叫做“PictureListView”的Component。一个Component的名称通常是以大写字母为开始的。通常它是以“Item”为基础的元素。Item在QML中是所有可视元素的最基础的元素。相当于在我们C++或JAVA编程中最基础的一个类。PictureListView.qml的设计如下:

import QtQuick 2.0

Item {
    anchors.fill: parent

}

为了能够在main.qml中调用它,我们修改我们的main.qml如下:

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

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

    /*
     This property enables the application to change orientation
     when the device is rotated. The default is false.
    */
    //automaticOrientation: true

    // Removes the old toolbar and enables new features of the new header.
    useDeprecatedToolbar: false

    width: units.gu(80)
    height: units.gu(100)

    Page {
        id:mainPage
        title: i18n.tr("Flickr")
        clip:true

        PictureListView {
            anchors.fill: parent
        }
    }
}

注意这里的“applicationName”。对于一些应用来说它必须是和应用的包的名称是一样的。因为应用安全的考虑,在使用ContentHub或使用API时创建自己的设置文件,都存在于和这个名称相关的目录里。重新运行运行程序,显示如下。目前我们的应用应该没有做上面东西。代码可以在如下的地址找到:

bzr branch lp:~liu-xiao-guo/debiantrial/flick1

2)完成UbuntuListView

我们再次回顾一下我们最上面的设计。里面是一个ListView。这里我们来使用UbuntuListView来完成该View。我们重新设计我们的PictureListView.qml文件。为了能够显示我们的ListView,我们对PictureListView做了一个简单的展示:

import QtQuick 2.0
import Ubuntu.Components 1.1
import Ubuntu.Components.ListItems 1.0

Item {
    id: mainScreen

    UbuntuListView {
        id: listView
        width: mainScreen.width
        height:mainScreen.height

        model: 10

        delegate:
            Text {
                text: "Hi"
            }

        Scrollbar {
            flickableItem: listView
        }
    }
}

重新运行程序,我们可以看到显示为10个“Hi”,证明ListView已经是在工作,虽然不是我们所需要的设计。在我们的设计中,我们的ListView的左边是一个图片,右边是一些文字。为了快速设计的方便,我们们将先只显示一行字。同时我们可以在网上的任何一个位置下载一个我们自己喜欢的图片并存放到项目根目录下的一个叫做“images”的目录中,并重新命令为sample.jpg。在这里,我选择网上的一个图片。我们也需要下载另外一个图片list.png来完成我们的这个步骤(存放于images目录中)。我们可以同时参阅Qt网页里的ListView介绍。我们修改我们的程序如下:

import QtQuick 2.0
import Ubuntu.Components 1.1
import Ubuntu.Components.ListItems 1.0

Item {
    id: mainScreen

    ListModel {
        id: sampleListModel

        ListElement {
            imagePath: "images/sample.jpg"
            title: "First picture"
        }
        ListElement {
            imagePath: "images/sample.jpg"
            title: "Second picture"
        }
        ListElement {
            imagePath: "images/sample.jpg"
            title: "Third picture"
        }
    }

    Component {
        id: listDelegate
        BorderImage {
            source: "images/list.png"
            border { top:4; left:4; right:100; bottom: 4 }
            anchors.right: parent.right
            // width: mainScreen.width
            width: ListView.view.width

            property int fontSize: 25

            Rectangle {
                id: imageId
                x: 6; y: 4; width: parent.height - 10; height:width; color: "white"; smooth: true
                anchors.verticalCenter: parent.verticalCenter

                BorderImage {
                    source: imagePath; x: 0; y: 0
                    height:parent.height
                    width:parent.width
                    anchors.verticalCenter: parent.verticalCenter
                }

            }

            Text {
                x: imageId.width + 20
                y: 15
                width: ListView.view.width*2/3
                text: title; color: "white"
                font { pixelSize: fontSize; bold: true }
                elide: Text.ElideRight; style: Text.Raised; styleColor: "black"
            }
        }
    }

    UbuntuListView {
        id: listView
        width: mainScreen.width
        height:mainScreen.height

        model: sampleListModel

        delegate: listDelegate
    }

    Scrollbar {
        flickableItem: listView
    }
}

特别值得注意的是,我们这里使用了一个叫做listDelegate的Component来显示每一个list中的项。这个listDelegate相当于是每个ListView中的每一项显示的模版。对于Android开发比较熟悉的开发者来说,这个并不陌生。Android里是采用adapter来实现相同功能的。同时我们也使用了一个人工假想的sampleListModel来填充我们的数据。重新运行我们的应用。我们可以看到如下的显示:



到这里,我们基本上已经完成了整个ListView的显示。整个的源代码在如下的网址可以下载:

bzr branch lp:~liu-xiao-guo/debiantrial/flick2


3)创建toolbar

在这个章节里,我们来完成我们的toolbar的设计。再回到我们最上面图显示的最初的设计,我们需要有一个输入的框来输入我们的关键词以来搜索。

    BorderImage {
        id:toolbar

        anchors.bottom:parent.bottom
        anchors.horizontalCenter: parent.horizontalCenter

        width: parent.width
        height: units.gu(6)

        source: "images/toolbar.png"
        border.left: 4; border.top: 4
        border.right: 4; border.bottom: 4

        Row {
            id:inputcontainer
            anchors.centerIn:toolbar
            anchors.verticalCenterOffset:6
            spacing:12
            Text {
                id:label
                font.pixelSize:30
                anchors.verticalCenter:parent.verticalCenter;
                text: i18n.tr("Search:")
                font.bold:true
                style:Text.Raised
                styleColor:"#fff"
                color:"#444"
            }

            TextField {
                id:input
                placeholderText: "Please input a text to search:"
                width:220
                text:"Beijing"
            }
        }

        Image {
            id: backbutton
            opacity:0
            source: "images/back.png"
            anchors.verticalCenter:parent.verticalCenter
            anchors.verticalCenterOffset:0
            anchors.left:parent.left
            anchors.leftMargin:8

            MouseArea{
                anchors.fill:parent
                onClicked: mainScreen.state=""
                scale:4
            }
        }
    }

整个的设计也是非常直接的。我们使用了一个toolbar.png作为背景。使用一个Row来管理我们的“Search”及TextField输入框。同时我们还有一个在默认情况下opacity为零的back.png的Image。当opacity为零时,就是不可见。许多的control还有visible。虽然在某种程度上,visible和opacity有相同的功能,但是由于opacity可以从“0”到“1”进行变化,从而达到动画的效果。它用来显示在detail屏中来返回到ListView.默认情况下是不可见的。我们需要下载toolbar.pngback.png来完成该步骤。为了能够得到整屏的显示,我们也对ListView的高度进行调整如下:

    UbuntuListView {
        id: listView
        width: mainScreen.width
        height:mainScreen.height - toolbar.height
        model: sampleListModel
        delegate: listDelegate
    }

这样整个屏幕的上方是一个ListView,下面的部分是toolbar。重新运行我们的应用,我们可以看到如下的画面:



虽然现在还不能做什么,但是我们应用的基本框架已经搭好了。在接下来的章节中,我们来更进一步把真实的数据填进来。这个步骤的代码在如下的地址可以找到:

bzr branch lp:~liu-xiao-guo/debiantrial/flick3

3)对ListView添加真实的数据


虽然上面我们已经有一个显示,但是毕竟是虚假的数据。在这个章节中,我们将使用XmlListModel来对Flickr网站进行请求并得到真实的数据。首先,我们在PictureListView.qml的开始部分加入

import QtQuick.XmlListModel 2.0

这里我们包含上面的XmlListModel的库,就可以使用它里面的API了。在sampleListModel的上面加入如下的代码:

XmlListModel {
    id: feedModel

//     source: "http://api.flickr.com/services/feeds/photos_public.gne?format=rss2"
    source: "http://api.flickr.com/services/feeds/photos_public.gne?format=rss2&tags=" + escape(input.text)
    query: "/rss/channel/item"  // flickr
    namespaceDeclarations:  "declare namespace media=\"http://search.yahoo.com/mrss/\";"

    // Flickr
    XmlRole { name: "title"; query: "title/string()" }
    XmlRole { name: "imagePath"; query: "media:thumbnail/@url/string()" }
    XmlRole { name: "photoAuthor"; query: "author/string()" }
    XmlRole { name: "photoDate"; query: "pubDate/string()" }

    XmlRole { name: "url"; query: "media:content/@url/string()" }
    XmlRole { name: "description"; query: "description/string()" }
    XmlRole { name: "tags"; query: "media:category/string()" }
    XmlRole { name: "photoWidth"; query: "media:content/@width/string()" }
    XmlRole { name: "photoHeight"; query: "media:content/@height/string()" }
    XmlRole { name: "photoType"; query: "media:content/@type/string()" }
}

同时修改listView的model为feedModel:

    UbuntuListView {
        id: listView
        width: mainScreen.width
        height:mainScreen.height - toolbar.height
        model: feedModel
        delegate: listDelegate
    }

这里我们使用了XmlListModel来查询我们的数据。我们可以在浏览器中输入地址http://api.flickr.com/services/feeds/photos_public.gne?format=rss2&tags=beijing。我们可以看到如下的显示



我们通过XmlListModel进行查询,并同时转换为我们所需要的数据进行显示。比如我们用到的“title”及“imagePath”。在查询时我们也同时使用了input输入框中的text。我们运行我们刚生成的应用,并同时修改在输入框中的内容,比如“shanghai”或“tianjing”等。我们会看到内容的改变。


  


为了使得图片的大小更加适合于在手机上显示,我们也同时修改listDelegate中BorderImage的高度为180.

所有的源码可以在如下的地址找到:


bzr branch lp:~liu-xiao-guo/debiantrial/flick4

4)显示照片的详细信息


我们虽然已经显示了照片的详细信息,我们希望在点击每个ListView中的每个项目的时候,能够更加清楚地看得到更加详细的照片信息。为了能够达到这个目的,我们可以在ListView的右边放置一个同样大小的屏幕。当我们点击ListView中的每一项时,我们就把屏幕向右移动。这样就可以看到照片的详细信息。当我们看完照片时,我们也可以把屏幕向左移动这样又回到ListView的页面。为了达到这样的设计,我们在我们的项目中加入一个新的叫做“SpinnerImage.qml”的Component。它的创建方法和上面介绍的“PictureListView.qml”是一样的。它的设计如下:

import QtQuick 2.0

Image {
    id:image

    property bool loading:status != Image.Ready

    Image {
        id: container
        property bool on: false
        source: "images/spinner.png";
        visible: loading
        anchors.centerIn:parent
        NumberAnimation on rotation {
            running: loading ; from: 0; to: 360;
            loops: Animation.Infinite; duration: 2000
        }
    }
}

我们可以看到,这是一个Image中含有一个Image的Component。当id为image中的Image还在下载时,里面的container中的spinner.png将不断地旋转。我们需要下载spinner.png文件。

我们需要修改ListView的设计如下:

    Row {
        id:viewcontainer

        UbuntuListView {
            id: listView
            width: mainScreen.width
            height:mainScreen.height - toolbar.height

            model: feedModel
            delegate: listDelegate

            Scrollbar {
                flickableItem: listView
            }
        }

        SpinnerImage {
            id:viewscreen
            clip:true
            width:mainScreen.width
            height:mainScreen.height - toolbar.height
            smooth:true
            fillMode:Image.PreserveAspectFit
        }
    }

在这里我们使用了一个Row布局,从而产生了一个和mainScreen宽度两倍的显示。在起始显示的时候,只有最左边的显示可以在屏幕中展示。为了能够响应对屏幕的触控,我们在我们的listDeleage中最外层的BorderImage中加入MouseArea中如下的代码:

    Component {
        id: listDelegate
        BorderImage {
            source: "images/list.png"
            border { top:4; left:4; right:100; bottom: 4 }
            anchors.right: parent.right
            // width: mainScreen.width
            width: ListView.view.width
            height: 180

            property int fontSize: 25

            Rectangle {
                id: imageId
                x: 6; y: 4; width: parent.height - 10; height:width; color: "white"; smooth: true
                anchors.verticalCenter: parent.verticalCenter

                SpinnerImage {
                    source: imagePath; x: 0; y: 0
                    height:parent.height
                    width:parent.width
                    anchors.verticalCenter: parent.verticalCenter
                }
            }

            Text {
                x: imageId.width + 20
                y: 15
                width: mainScreen.width - x - 40
                text: title; color: "white"
                font { pixelSize: fontSize; bold: true }
                elide: Text.ElideRight; style: Text.Raised; styleColor: "black"
            }

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    viewcontainer.x -= mainScreen.width
                }
            }
        }
    }

重新运行应用。我们发现,当我们点击listview中的每一项时,就会很快地切换到另外一个页面,并展示该图片。在实际体验中,这个可能并不是最好的,有时我们希望能看到一个平滑过度的中间状态,就像我们在其它平台中看到的那样。我们在这里可以使用QML中的状态来实现这个功能。在PictureListView.qml中,加入如下的代码(放在mainScreen):
    states: [
        State {
            name: "view"
            PropertyChanges {
                target: viewcontainer
                x:-mainScreen.width
            }
            PropertyChanges {
                target: backbutton
                opacity:1
            }
            PropertyChanges {
                target: inputcontainer
                opacity:0
            }
        }
    ]

    transitions: [
        Transition {
            NumberAnimation { target: viewcontainer; property: "x"; duration: 500
                easing.type:Easing.OutSine}
            NumberAnimation { target: inputcontainer; property: "opacity"; duration: 200}
            NumberAnimation { target: backbutton; property: "opacity"; duration: 200}
        }
    ]

在这里我们定义了一个新的状态“view”。默认的状态为"",即一个空字符串。在状态放生切换时我们可以使用transitions来实现动画的展示。在上面,我们使得在x发生改变时,需要500毫秒来完成。同样我们也使得backbutton及inputcontainer的opacity也发生改变。有兴趣的开发者可以调整一下时间的参数来看看这个变化的过程。这样我们就可以看到状态的变化。加入了状态后,我们重新改写listDelegate中MouseArea中的代码:

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    viewscreen.source = imagePath.replace("_s", "_m")
                    mainScreen.state = "view"
                }
            }

在这里,我们同时也修改了imagePath中的内容,从而使得我们能够在展示详细图片时,使用的是“中”(m)等大小的图片而不是“小”(s)的图片。重新运行我们的应用:


   

当我们点击在ListView中的每个项时,就会展示它的详细的图片的情况。我们可以点击详细图片下方的箭头回到ListView中去。这个代码在toolbar的如下代码中可以到:

        Image {
            id: backbutton
            opacity:0
            source: "images/back.png"
            anchors.verticalCenter:parent.verticalCenter
            anchors.verticalCenterOffset:0
            anchors.left:parent.left
            anchors.leftMargin:8

            MouseArea{
                anchors.fill:parent
                onClicked: mainScreen.state=""
                scale:4
            }
        }

在这里我们可以看到,当我们点击的时候,mainScreen的状态state有设为"",也就是应用最起始的状态。在x坐标发生变化时,我们可以通过transitions来实现动画的效果。

这个应用在手机的图片为:

  


整个应用的源码在如下地址可以找到:

bzr branch lp:~liu-xiao-guo/debiantrial/flick5


5)更进一步完善应用


细心的开发者如果在手机上运行并输入字符串时,可能会发现跳出的键盘挡住了我们的输入框。我们可以通过打开在main.qml中的MainView中的如下的项:

anchorToKeyboard: true

更多的阅读可以参照文章来详细了解。

另外,在ListView中,当照片还在下载时,我们也希望能够看到不断选择的spinner。我们可以把listDelegate中的imageId修改为:

            Rectangle {
                id: imageId
                x: 6; y: 4; width: parent.height - 10; height:width; color: "white"; smooth: true
                anchors.verticalCenter: parent.verticalCenter

                SpinnerImage {
                    source: imagePath; x: 0; y: 0
                    height:parent.height
                    width:parent.width
                    anchors.verticalCenter: parent.verticalCenter
                }
            }

我们可以在UbuntuListView中加入“PullToRefresh”如下的代码:

        UbuntuListView {
            id: listView
            width: mainScreen.width
            height:mainScreen.height - toolbar.height

            model: feedModel
            delegate: listDelegate

            // let refresh control know when the refresh gets completed
            PullToRefresh {
                refreshing: listView.model.status === XmlListModel.Loading
                onRefresh: listView.model.reload()
            }

            Scrollbar {
                flickableItem: listView
            }
        }

这样,当我们往下拉ListView时,会自动更新我们的ListView中的内容。

我们也可以通过修改Flickr.png来实现我们自己的定制的icon。整个应用的最终版本在如下的地址可以找到:

bzr branch lp:~liu-xiao-guo/debiantrial/flick6

6)加入Swipe功能


目前我们的应用应该还是比较地完善。我们还希望加入一个功能。当我们显示大的图片时,我们希望能够通过从左向右的滑动来回到以前的列表的画面。这样我们就不必使用点击屏幕左下方的箭头了。为了实现这个功能,我们复制我们的“SpinnerImage.qml”文件到当前的目录,并同时重新命名为“DetailedImage.qml”文件。我们回到SDK的Flickr的项目中来。我们发现项目已经自己找到这个文件了。这个功能是和CMake项目不太相同的地方。为了捕获Swipe的动作,我们在这个文件中加入对MouseArea的处理。整个源码如下:

import QtQuick 2.0

Image {
    id:image

    property bool loading:status != Image.Ready

    Image {
        id: container
        property bool on: false
        source: "images/spinner.png";
        visible: loading
        anchors.centerIn:parent
        NumberAnimation on rotation {
            running: loading ; from: 0; to: 360;
            loops: Animation.Infinite; duration: 2000
        }
    }

    // Create the detection of swipe
    signal swipeRight;
    signal swipeLeft;
    signal swipeUp;
    signal swipeDown;

    MouseArea {
        anchors.fill: parent
        property int startX;
        property int startY;

        onPressed: {
            startX = mouse.x;
            startY = mouse.y;
        }

        onReleased: {
            var deltax = mouse.x - startX;
            var deltay = mouse.y - startY;

            if (Math.abs(deltax) > 50 || Math.abs(deltay) > 50) {
                if (deltax > 30 && Math.abs(deltay) < 30) {
                    // swipe right
                    swipeRight();
                } else if (deltax < -30 && Math.abs(deltay) < 30) {
                    // swipe left
                    swipeLeft();
                } else if (Math.abs(deltax) < 30 && deltay > 30) {
                    // swipe down
                    swipeDown();
                } else if (Math.abs(deltax) < 30 && deltay < 30) {
                    // swipe up
                    swipeUp();
                }
            }
        }
    }
}

我们通过对MouseArea中的“onPressed”及“onReleased”处理,从而产生相应的信号swipeRight, swipeLeft, swipeUp, swipeDown。为了对这个信号的响应,我们对PictureListView.qml 中的如下部分做一下的修改:

    Row {
        id:viewcontainer

        UbuntuListView {
            id: listView
            width: mainScreen.width
            height:mainScreen.height - toolbar.height

            model: feedModel
            delegate: listDelegate

            // let refresh control know when the refresh gets completed
            PullToRefresh {
                refreshing: listView.model.status === XmlListModel.Loading
                onRefresh: listView.model.reload()
            }

            Scrollbar {
                flickableItem: listView
            }
        }

        DetailedImage {
            id:viewscreen
            clip:true
            width:mainScreen.width
            height:mainScreen.height - toolbar.height
            smooth:true
            fillMode:Image.PreserveAspectFit

            onSwipeRight: {
                onClicked: mainScreen.state=""
            }
        }
    }

我们把原来的“SpinnerImage”改为我们刚生产的“DetailedImage”,并同时对“swipeRight”信号进行响应。注意这里的“onSwipeRight”里的“S”是大写的。当我们得到这个信号时,我们把应用的状态设为最初始的状态""。重新运行我们的应用,并在手机上运行:





如果开发者不知道怎么部署应用到手机上,可以参考文章“ 怎么安装Ubuntu应用到Device中”。在手机上面显示的图片如下:

  

整个应用的源码在如下的地址可以找到:

bzr branch lp:~liu-xiao-guo/debiantrial/flickr7


另外一个更加复杂的版本在如下地址可以下载:

bzr branch lp:~liu-xiao-guo/debiantrial/flickrfinal



作者:UbuntuTouch 发表于2014-10-29 15:44:42 原文链接
阅读:105 评论:0 查看评论

Read more
David Callé

A scope can provide persistent settings for simple customizations, such as allowing the user to configure an email address or select a distance unit as metric or imperial.

In this tutorial, you well learn how to add settings to your scope and allow users to customize their experience.

Read…

scope-settings_coffeenearby2 scope-settings_visitparis2 scope-settings_indieconcerts1

Read more
Joseph Salisbury

Meeting Minutes

IRC Log of the meeting.

Meeting minutes.

Agenda

20141028 Meeting Agenda


Release Metrics and Incoming Bugs

Release metrics and incoming bug data can be reviewed at the following link:

  • http://people.canonical.com/~kernel/reports/kt-meeting.txt


Status: Vivid Development Kernel

The Vivid kernel has been opened and master-next rebased to the lastest
v3.18-rc2 upstream kernel. We have witheld uploading to the archive
until we’ve progressed to a later -rc candidate.
—–
Important upcoming dates:
The Vivid ReleaseSchedule has not yet been posted.


Status: CVE’s

The current CVE status can be reviewed at the following link:

http://people.canonical.com/~kernel/cve/pkg/ALL-linux.html


Status: Stable, Security, and Bugfix Kernel Updates – Utopic/Trusty/Precise/Lucid

Status for the main kernels, until today (Sept. 30):

  • Lucid -
  • Precise -
  • Trusty – Testing

    Current opened tracking bugs details:

  • http://kernel.ubuntu.com/sru/kernel-sru-workflow.html

    For SRUs, SRU report is a good source of information:

  • http://kernel.ubuntu.com/sru/sru-report.html

    Schedule:

    cycle: 10-Oct through 31-Oct
    ====================================================================
    8-Oct Last day for kernel commits for this cycle
    09-Oct – 10-Oct Kernel prep
    12-Oct – 18-Oct Bug verification & Regression testing.
    19-Oct – 25-Oct Bug verification & Regression testing.
    26-Oct – 01-Nov Regression testing & Release to -updates.


Open Discussion or Questions? Raise your hand to be recognized

No open discussions.

Read more
UbuntuTouch

[原]使用URL dispatcher的范例

在上面的一篇文章中,我们介绍了如何使用URL disptacher。在这篇文章中,我们来通过一个范例更进一步来了解如何实现它。


1)创建一个具有URL dispatcher的应用

我们首先打开我们的SDK,然后创建一个最基本的QML template应用。我们把该应用叫做“MyApp”。我们首先在“MyApp”的根目录添加一个文件叫做“MyApp.url-dispatcher”文件,这里面的内容如下:

[
	{
		"protocol": "launchmyapp"
	}
]

这样的定义使得任何在Qt.openUrlExternally()中具有以“launchmyapp:///”开头的调用,就可以打开该应用。比如:

Qt.openUrlExternally("launchmyapp:///123");

同时,我们修改我们的manifest.json文件如下:

{
    "architecture": "all",
    "description": "description of MyApp",
    "framework": "ubuntu-sdk-14.10-dev2",
    "hooks": {
        "MyApp": {
            "apparmor": "MyApp.apparmor",
            "desktop": "MyApp.desktop",
	    "urls": "MyApp.url-dispatcher"
        }
    },
    "maintainer": "XiaoGuo, Liu <xiaoguo.liu@canonical.com>",
    "name": "com.ubuntu.developer.unknown.myapp",
    "title": "MyApp",
    "version": "0.1"
}

注意这里的“urls”项。到这里,我们基本上就可以让我们的应用能够被其它的应用调用了。为了能够得到调用应用传来的参数,我们也同时修改我们的desktop文件如下:

[Desktop Entry]
Name=MyApp
Exec=qmlscene $@ main.qml -- %u
Icon=MyApp.png
Terminal=false
Type=Application
X-Ubuntu-Touch=true

注意这里的"-- %u",这是加入的部分。为了能够在程序中显示得到的URL信息,我们对程序做了如下的修改:


import QtQuick 2.0
import Ubuntu.Components 1.1

/*!
    \brief MainView with a Label and Button elements.
*/

MainView {
    id:root

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

    // Note! applicationName needs to match the "name" field of the click manifest
    applicationName: "com.ubuntu.developer.unknown.myapp"

    Component.onCompleted: {
        mylabel.text = "aaaa";
        console.log( "arg length: " + myarg.arguments.length );

        if ( myarg.defaultArgument === undefined) {
            mylabel.text = "undefined";
        } else {
            mylabel.text = "args: " + myarg.defaultArgument.at(0);
        }

        console.log("argument: " + myarg.defaultArgument.at(0));
        console.log("")
    }

    Arguments {
        id: myarg
        defaultArgument.help: "Expects URL of the media to play."
        defaultArgument.valueNames: ["URL"]
    }

    /*
     This property enables the application to change orientation
     when the device is rotated. The default is false.
    */
    //automaticOrientation: true

    // Removes the old toolbar and enables new features of the new header.
    useDeprecatedToolbar: false

    width: units.gu(50)
    height: units.gu(75)

    Page {
        title: i18n.tr("MyApp")

        Column {
            spacing: units.gu(1)
            anchors {
                margins: units.gu(2)
                fill: parent
            }

            Row {
                spacing: units.gu(2)

                Label {
                    id: mylabel
                    objectName: "label"

                    text: i18n.tr("Received parameters: ")
                }

                Label {
                    id: label
                    objectName: "label"

                    text: i18n.tr("")
                }

                Connections {
                    target: UriHandler
                    onOpened: {
                        // root.applicationName = "good"
                        mylabel.text = "dddddd";

                        var para = "";
                        for (var i = 0; i < uris.length; ++i) {
                            // application.parseArgument(uris[i])
                            console.log( uris[i] );
                            para +=  uris[i];
                        }

                        label.text = para;
                    }
                }
            }
        }
    }

}

注意这里的“UriHandler”部分,当应用在运行时,url dispatcher被调用时,该部分代码会被执行。当应用没有运行时,我们通过传人的参数从而得到输入的参数值:

    Arguments {
        id: myarg
        defaultArgument.help: "Expects URL of the media to play."
        defaultArgument.valueNames: ["URL"]
    }

整个的代码在如下的地址可以找到:

https://code.launchpad.net/~liu-xiao-guo/debiantrial/myapp


2)创建调用应用


这个应用其实很简单。我们直接创建一个基本的QML template应用,同时修改我们的main.qml如下:

import QtQuick 2.0
import Ubuntu.Components 1.1

/*!
    \brief MainView with a Label and Button elements.
*/

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

    // Note! applicationName needs to match the "name" field of the click manifest
    applicationName: "com.ubuntu.developer.unknown.launchmyapp"

    /*
     This property enables the application to change orientation
     when the device is rotated. The default is false.
    */
    //automaticOrientation: true

    // Removes the old toolbar and enables new features of the new header.
    useDeprecatedToolbar: false

    width: units.gu(100)
    height: units.gu(75)

    Page {
        title: i18n.tr("LaunchMyApp")

        Column {
            spacing: units.gu(1)
            anchors {
                margins: units.gu(2)
                fill: parent
            }

            Button {
                objectName: "button"
                width: parent.width

                text: i18n.tr("Launch MyApp")

                onClicked: {
                    Qt.openUrlExternally("launchmyapp:///123");
                }
            }

            Button {
                objectName: "button"
                width: parent.width

                text: i18n.tr("Open MyApp")

                onClicked: {
                    Qt.openUrlExternally("appid://com.ubuntu.developer.unknown.myapp/MyApp/current-user-version");
                }
            }
        }
    }
}

这里我们使用了两种方法来调用我们的“MyApp”。第一种是通过:

 Qt.openUrlExternally("launchmyapp:///123");

这种方法的好处是可以传人我们需要的参数,并解析,从而对于不同的参数可以得到不同的响应。

另外一种方式是通过:

Qt.openUrlExternally("appid://com.ubuntu.developer.unknown.myapp/MyApp/current-user-version");

这种方法不能解析任何的参数,它可以把应用启动起来。我们可以通过如下的方法得到应用的一些信息:


运行我们的应用:



我们按下第一个按钮,如果“MyApp”没有运行时,会显示如下的在左边的画面。如果“MyApp”在已经运行的情况下,可以看到如下的右边的画面:

   

如果,我们点击应用下面的按钮的话,可以看到如下的画面:



整个项目的源码在如下的地址可以找到:


bzr branch lp:~liu-xiao-guo/debiantrial/launchmyapp




作者:UbuntuTouch 发表于2014-10-28 12:49:37 原文链接
阅读:258 评论:0 查看评论

Read more
David Owen

This last Saturday, I gave a presentation on classification, starting with a basic linear classifier and building it up to k-class, n-dimensional classification. I've been asked for the material I used, so here are the links:
Continue reading "Material from my presentation on Classification"

Read more
Nicholas Skaggs

Sprinting in DC: Friday

This week, my team and I are sprinting with many of the core app developers and other folks inside of Ubuntu Engineering. Each day I'm attempting to give you a glimpse of what's happening.

Friday brings an end to an exciting week, and the faces of myself and those around me reflect the discussions, excitement, fun and lack of sleep this week has entailed.

Bubbles!
The first session of the day involved hanging out with the QA team while they heard feedback from various teams on issues with quality and process within there project. Always fun to hear about what causes different teams the most issues when it comes to testing.

Next I spent some time interviewing a couple folks for publishing later. In my case I interviewed Thomi from the QA team and Zoltan from the SDK team about the work going on within there teams and how the last cycle went. The team as a whole has been conducting interviews all week. Look for these interviews to appear on youtube in the coming weeks.

Thursday night while having a look through a book store, I came across an ad for ubuntu in Linux Voice magazine. It made me smile. The dream of running ubuntu on all my devices is becoming closer every day.


I'd like to thank all the community core app developers who joined us this week. Thanks for hanging out with us, providing feedback, and most of all for the creating the wonderful apps we have for the ubuntu phone. Your work has helped shaped the device and turn it into what it is today.

Looking back over the schedule there were sessions I wish I had been able to attend, and it was wonderful catching up with everyone. Sadly my flight home prevented me from attending the closing session and presumably getting a summary of some of these sessions. I can say I was delighted to talk and interact with the unity8 team on the next steps for unity8 on the desktop. I trust next cycle we as a community can do more around testing there work.

As I head to the airport for home, it's time to celebrate the release of utopic unicorn!

Read more
Colin Ian King

even more stress in stress-ng

Over the past few weeks in spare moments I've been adding more stress methods to stress-ng  ready for Ubuntu 15.04 Vivid Vervet.   My intention is to produce a rich set of stress methods that can stress and exercise many facets of a system to force out bugs, catch thermal over-runs and generally torture a kernel in a controlled repeatable manner.

I've also re-structured the tool in several ways to enhance the features and make it easier to maintain.  The cpu stress method has been re-worked to include nearly 40 different ways to stress a processor, covering:

  • Bit manipulation: bitops, crc16, hamming
  • Integer operations: int8, int16, int32, int64, rand
  • Floating point:  long double, double,  float, ln2, hyperbolic, trig
  • Recursion: ackermann, hanoi
  • Computation: correlate, euler, explog, fibonacci, gcd, gray, idct, matrixprod, nsqrt, omega, phi, prime, psi, rgb, sieve, sqrt, zeta
  • Hashing: jenkin, pjw
  • Control flow: jmp, loop
..the intention was to have a wide enough eclectic mix of CPU exercising tests that cover a wide range of typical operations found in computationally intense software.   Use the new --cpu-method option to select the specific CPU stressor, or --cpu-method all to exercise all of them sequentially.

I've also added more generic system stress methods too:
  • bigheap - re-allocs to force OOM killing
  • rename - rename files rapidly
  • utime - update file modification times to create lots of dirty file metadata
  • fstat - rapid fstat'ing of large quantities of files
  • qsort - sorting of large quantities of random data
  • msg - System V message sending/receiving
  • nice - rapid re-nicing processes
  • sigfpe - catch rapid division by zero errors using SIGFPE
  • rdrand - rapid reading of Intel random number generator using the rdrand instruction (Ivybridge and later CPUs only)
Other new options:
  • metrics-brief - this dumps out only the bogo-op metrics that are relevant for just the tests that were run.
  • verify - this will sanity check the stress results per iteration to ensure memory operations and CPU computations are working as expected. Hopefully this will catch any errors on a hot machine that has errors in the hardware. 
  • sequential - this will run all the stress methods one by one (for a default of 60 seconds each) rather than all in parallel.   Use this with the --timeout option to run all the stress methods sequentially each for a specified amount of time. 
  • Specifying 0 instances of any stress method will run an instance of the stress method on all online CPUs. 
The tool also builds and runs on Debian kFreeBSD and GNU HURD kernels although some stress methods or stress options are not included due to lack of support on these other kernels.
The stress-ng man page gives far more explanation of each stress method and more detailed examples of how to use the tool.

For more details, visit here or read the manual.

Read more
ssweeny

Ubuntu 14.10

I’m at a sprint in Washington, DC with my fellow Canonicalers gearing up for the commercial release of our phone OS (more on that later) but that doesn’t mean we’ve forgotten about the desktop and cloud.

Yesterday was another Ubuntu release day! We released Ubuntu 14.10, codenamed the Utopic Unicorn. Look for lots of subtle improvements to the desktop as we prepare some big things to come soon.

As usual, you can take a tour or go straight to the download page.

And while we’re at it, here’s to another 10 years of Ubuntu!

Read more
Nicholas Skaggs

Sprinting in DC: Thursday

This week, my team and I are sprinting with many of the core app developers and other folks inside of Ubuntu Engineering. Each day I'm attempting to give you a glimpse of what's happening.

Today started with some UOS planning which is happening in a couple short weeks. If you haven't yet put it on your calendar, please do so! And plan to not only attend, but consider submitting a session as well. The users track might be just the place for your session. Session topics can be about anything ubuntu related you might want to share or discuss with others.

As the week has progressed I've enjoyed getting to know the core apps developers better. Today we met with all of them to hear feedback on how the projects have been going. Lots of good discussion was had discussing how things like meetings and reviews work, individual project needs and actions that could be taken to improve all of the projects. It's wonderful to have everyone in the same place and able to talk.


After lunch the QA team discussed manual testing and proposed utilizing moztrap for some of the manual testing they are undertaking as part of the CI process for ubuntu touch images. While it is too early to say what implications this will have on manual testing from a community perspective, I'm happy to see the conversation has begun around the current issues facing manual tests. I'm also happy someone else is willing to be a guinea pig for changes like this! For image testing, the qatracker has served us well and will continue to do so, but I hope in the future we can improve the experience. In fact, we have done work in this area recently, and would love to hear from anyone who wants to help improve the qatracker experience. So, whether or not a migration to moztrap occurs at some point, the future looks bright.

The core app developers also got a chance to both get and receive feedback from the SDK and design teams. The deep dives into applications like calendar were very much appreciated and I expect those suggestions will filter into the applications in the near future. As usual the core apps developers came prepared with suggestions and grievances for the SDK team, as well as praises for things done well.

Finally to end the day, we discussed developer mode on the device. Rather than talk about the history of how it was implemented, let me share with you the future. Rather than locking adb access via a password, we'll utilize certificates. The password based solution already will ensure your locked device isn't vulnerable to nefarious humans who might want to connect and steal your data or reflash your phone. However, things like passwordless sudo will be possible with using certificates. In addition if security is the bane of your existence, you will be able to enable developer mode without setting a password at all.

Whew, today was very full!

Read more
Jane Silber

Today marks 10 years of Ubuntu and the release of the 21st version. That is an incredible milestone and one which is worthy of reflection and celebration. I am fortunate enough to be spending the day at our devices sprint with 200+ of the folks that have helped make this possible. There are of course hundreds of others in Canonical and thousands in the community who have helped as well. The atmosphere here includes a lot of reminiscing about the early days and re-telling of the funny stories, and there is a palpable excitement in the air about the future. That same excitement was present at a Canonical Cloud Summit in Brussels last week.

The team here is closing in on shipping our first phone, marking a new era in Ubuntu’s history. There has been excellent work recently to close bugs and improve quality, and our partner BQ is as pleased with the results as we are. We are on the home stretch to this milestone, and are still on track to have Ubuntu phones in the market this year. Further, there is an impressive array of further announcements and phones lined up for 2015.

But of course that’s not all we do – the Ubuntu team and community continue to put out rock solid, high quality Ubuntu desktop releases like clockwork – the 21st of which will be released today. And with the same precision, our PC OEM team continues to make that great work available on a pre-installed basis on millions of PCs across hundreds of machine configurations. That’s an unparalleled achievement, and we really have changed the landscape of Linux and open source over the last decade. The impact of Ubuntu can be seen in countless ways – from the individuals, schools, and enterprises who now use Ubuntu; to proliferation of Codes of Conduct in open source communities; to the acceptance of faster (and near continuous) release cycles for operating systems; to the unique company/community collaboration that makes Ubuntu possible; to the vast number of developers who have now grown up with Ubuntu and in an open source world; to the many, many, many technical innovations to come out of Ubuntu, from single-CD installation in years past to the more recent work on image-based updates.

Ubuntu Server also sprang from our early desktop roots, and has now grown into the leading solution for scale out computing. Ubuntu and our suite of cloud products and services is the premier choice for any customer or partner looking to operate at scale, and it is indeed a “scale-out” world. From easy to consume Ubuntu images on public clouds; to managed cloud infrastructure via BootStack; to standard on-premise, self-managed clouds via Ubuntu OpenStack; to instant solutions delivered on any substrate via Juju, we are the leaders in a highly competitive, dynamic space. The agility, reliability and superior execution that have brought us to today’s milestone remains a critical competency for our cloud team. And as we release Ubuntu 14.10 today, which includes the latest OpenStack, new versions of our tooling such as MaaS and Juju, and initial versions of scale-out solutions for big data and Cloud Foundry, we build on a ten year history of “firsts”.

All Ubuntu releases seem to have their own personality, and Utopic is a fitting way to commemorate the realisation of a decade of vision, hard work and collaboration. We are poised on the edge of a very different decade in Canonical’s history, one in which we’ll carry forward the applicable successes and patterns, but will also forge a new path in the twin worlds of converged devices and scale-out computing. Thanks to everyone who has contributed to the journey thus far. Now, on to Vivid and the next ten years!

Read more
UbuntuTouch

URL dispatcher 是在Ubuntu OS上的一个服务。它可以让我们的应用(confined,i.e, click package应用)来启动其它的应用。这些应用通常是一个特别的URL来 识别的。可能最常见的例子就是向网页浏览器发送http:// URL来启动网页浏览器,但是像music或其它的应用也可以支持。对于大多数的应用来说,这是一个最有用的方式来退出现有的应用来启动另外一个应用。


对于Qt应用来说,它访问URL dispatcher的方法是通过Qt的desktop plugin。C++应用可以通过使用QDesktopServices.openURL()方法。QML应用可以使
用 Qt.openUrlExternally(string)方法。对于其它的应用来说,它们可以利用根据自己的需求使用Platform API或直接使用liburl-dispatcher。

URL dispatcher项目可以在Launchpad的链接找到。

支持的URL格式

基本URL格式


在URL dispatcher中有几种被支持的格式:



application:///$(app_id).desktop
The application URL can be used to start an application with a known Application ID. For applications that install their desktop file in /usr/share/applications the application ID should just be the name of the desktop file.
appid://$(pkg)/$(app)/$(version) Allows for launching an application using an application ID. Also provides for wild cards. The $(app) can be first-listedlast-listed-app or only-listed-app to select the appropriate applicaiton using the click manifest. Also the $(version) can be current-user-version to select the version in the manifest

这里的第二种方法是推荐的方法。比如对于Clock应用来说,我们可以看到如下的应用URL:


appid://com.ubuntu.clock/clock/current-user-version

我们可以通过如下的方法得到在手机中应用click package的信息:


     


应用URL

对于一些应用来说,我们可以在启动应用的时候同时传人一些参数来启动该应用。我们可以通过在应用的Click manifest文件中加入URL的定义来注册该应用可以被一个或多个URL来启动。为了达到这个目的,我们可以在该文件中的“hooks”部分加入一个和“desktop”并列的小的json文件的申明。一个简单的manifest就像下面定义的。


{
        "name": "My App",
        "version": "1.2.3",
        "hooks": {
                "foo": {
                        "desktop": "foo.desktop",
                        "urls": "foo.url-dispatcher"
                }
        }
}

这里它指向另外一个在click包中的JSON文件。它定义了什么URL将被接受。一个简单的文件就像如下的格式:

[
        {
                "protocol": "foo",
                "domain-suffix": "bar.com"
        }
]

通过上面的定义,每当有任何一个像“foo://*.bar.com”格式URL请求,由foo.desktop代表的应用将被自动被调用。在这里,如果“domain-suffix”项被省去的话,该应用将接受所有以“foo”代表的protocol格式的请求。URL dispatcher的定义是一个数组,这样有很多的这样的格式可以在应用中被定义。

一个例程显示如何调用Music及Clock可以在如下的地址找到:

bzr branch lp:~liu-xiao-guo/debiantrial/launchapps

作者:UbuntuTouch 发表于2014-10-23 23:06:03 原文链接
阅读:181 评论:0 查看评论

Read more
Nicholas Skaggs

Sprinting in DC: Wednesday

This week, my team and I are sprinting with many of the core app developers and other folks inside of Ubuntu Engineering. Each day I'm attempting to give you a glimpse of what's happening.

To kick off the day, I led a session on something that has been wreaking havoc for application test writers within the core apps -- environment setup. In theory, setting up the environment to run your test should be easy. In practice, I've found it increasingly difficult. The music, calendar, clock, reminders, file manager and other teams have all been quite affected by this and the canonical QA team and myself have all pitched in to help, but struggled as well. In short, a test should be easy to launch, be well behaved and not delete any user data, and be easy to setup and feed test data into for the test process. I'm happy to report that the idea of a permanent solution has been reached. Now we must implement it of course, but the result should be drastically easier and more reliable test setup for you the test author.

I also had the chance to list some grievances for application developers with the QA team. We spoke about wanting to expand the documentation on testing and specifically targeted the need to create better templates in the ubuntu sdk for new projects. When you start a new project you should have well functioning tests, and we should teach you about how to run them too!



Just before lunch the community core app developers were able to discuss post-RTM plans and features. A review of the apps was undertaken and some desire for new designs or features were discussed. Terminal is being rebuilt to be more aligned with upstream. Music is currently undergoing a re-design which is coming along great. Calculator is anxious to get some design love. Reminders potential for offline notetaking as well as potential name changes were all discussed. Overall, an amazing accomplishment by all the developers!

After lunch, I spent time confirming the fix for a longstanding bug within autopilot. The merge proposal for fixing this bug has been simmering all summer and it's time to get it fixed. The current test suites for calendar and clock have been impacted by this and have already had regressions occur that could have been caught had tests been able to be written for this area. Having myself, the autopilot team, and the calendar developers in one place made fixing this possible.

To end the day, I spent some time attending sessions for changes to CI and learning more about the coming changes to CI within ubuntu. In summary the news is wonderful. CI will test using autopkgtest, and all of ubuntu will come under this umbrella -- phone, desktop, everything. If it's a package and it has tests, we will do all of the autopkgtest goodness currently being done for the distro.

The evening closed with a bit of fun provided by a game making hackathon using bacon2d and the hilariously horrible "Turkish Star Wars". We could always use more games in the ubuntu app store, and I hear there might even still be a pioneers t-shirt or two left if you get it in early!

Read more
facundo


¿Qué es un satélite? Hay varias definiciones... para el propósito de este artículo, podemos decir que es un objeto que orbita alrededor de otro. Nuestro planeta tiene un satélite natural (la Luna) y muchos, muchísimos satélites artificiales.

Crear un nuevo satélite artificial, es decir poner un aparato creado por los humanos a girar alrededor de la tierra es bastante fácil. Es cuestión de subir el aparato lo suficientemente alto, es decir, ponerlo en órbita. Claro, crear un satélite artificial útil tampoco es moco de pavo, hay que ponerlo en una órbita más o menos controlada, y poder comunicarse con el aparato.

Hay un detalle importante en la frase anterior. Estoy hablando de órbitas... una órbita terrestre es el camino que recorre el satélite cuando está girando por alredor de la Tierra. Y claro, hay muchas, ¡infinidades! Agarren una pelota, por ejemplo, y van a ver que pueden trazar con una lapicera muchísimos recorridos distintos alrededor de ella, y a eso hay que sumarle que las órbitas pueden estar a distintas alturas (la altura del satélite afecta la velocidad a la que se desplaza, cuanto más abajo está más rápido tiene que ir para no "caerse", mientras que cuanto más alto está más lento tiene que ir para no "salir disparado" de la órbita terrestre).

Órbitas hay un montón, pero no todas son útiles. Un ejemplo de una órbita útil es la llamada "órbita sincrónica al sol", que se logra combinando altitud e inclinación para lograr que el satélite pase sobre una determinada latitud terrestre a la misma hora del día. Esto es piola para aquellos satélites que tienen que sacar imágenes del suelo terrestre, porque quizás es suficiente con que pasen un par de veces al día por arriba del lugar que tienen que fotografiar. Es el caso de los nanosatélites que estuvimos mandando estos años.

Hay, sin embargo, una órbita que es muy especial. Si al satélite lo ponemos justo sobre la linea del ecuador, y lo hacemos girar a una velocidad específica, en lugar de verlo pasar cada tanto, lo vamos a estar viendo siempre en el mismo punto en el cielo.

Esta órbita se llama geostacionaria. Para ponerlo en términos precisos, la órbita geoestacionaria es una órbita geosíncrona en el plano ecuatorial terrestre, con una excentricidad nula (órbita circular) y un movimiento de oeste a este.

Órbita síncrona

Arthur C. Clarke popularizó la idea de utilizar la órbita geoestacionaria para poner allí satélites de comunicaciones (lo hizo en un paper en 1945, "Extra-Terrestrial Relays", por el cual ganó el premio Marconi en 1982).

Un satélite en órbita geoestacionaria es muy importante para las comunicaciones, porque como siempre se lo ve en el mismo lugar, se puede apuntar una antena y dejarla fija en esa dirección, y tener un enlace permanente con el satélite. O sea que dos puntos en la tierra, apuntando al mismo satélite, pueden estar comunicados todo el tiempo. Este concepto es la base de las comunicaciones modernas en nuestra sociedad, afectando profundamente la forma en que vivimos.

Las órbitas geoestacionarias sólo se pueden conseguir muy cerca de un anillo de 35.786 km sobre el ecuador. En la práctica, esto significa que todos los satélites geoestacionarios deben estar en este anillo, y sólo en ese anillo, por lo cual la cantidad de satélites que se puede poner ahí es limitada.

Estarán de acuerdo conmigo que las comunicaciones son un factor clave en nuestra sociedad: es por eso muy importante quien tiene el poder sobre los satélites en esa órbita, quien los controla. La organización que está coordinando la asignación de estos espacios es la Unión Internacional de Telecomunicaciones.

Con el ARSAT-1 (lanzado el pasado 16 de Octubre) Argentina vuelve a ocupar una posición orbital que tenía asignada (que estuvo ocupada hasta el 2010 por el Nahuel 1A), y que corría el riesgo de perder luego de cuatro años de no utilizarla.

ARSAT 1

Es por eso que este satélite era tan importante. No sólo porque fue desarrollado, financiado y ensamblado acá (Argentina es ahora una de las pocas naciones que hacen sus propios satélites) sino porque es un factor clave en la soberanía del país, ya que permite tener control propio sobre un elemento clave para las comunicaciones.

Read more