Easy Way to Create Unity Lens for Ubuntu (Translation)

This article focuses on the new feature of the Unity environment in Ubuntu - lenses. What is a lens in Unity? Simply put, a lens is an area of ​​the main menu where a user can search for local and network content. How to simply create it is discussed in this article. The original text is from here .

Requirements



So, to create a lens, we need:

* Ubuntu 12.04 LTS - get Ubuntu
* Quickly - install free quickly
* Quickly Lens template - install Quickly Lens template

Lens making



To start, let's write a lens that searches among Wikipedia articles. Creating a lens begins with a simple step - creating a project. To do this, press Ctrl + Alt + T and in the terminal window that appears, enter the following commands:

quickly create unity-lens wikipedia
cd wikipedia

image
Let's get started!

quickly edit


This command will open three files in your default text editor, we are only interested in __init__.py

The first thing we need is the Meta class. It contains a description of our lens. See:
    class Meta:
    	name = 'Wikipedia'
    	description = 'Wikipedia Lens'
    	search_hint = 'Search Wikipedia'
    	icon = 'wikipedia.svg'
    	search_on_blank=True

To begin with, since we make a simple lens, everything can be left unchanged here.

Lens needs categories to visually separate different types of results. For Wikipedia, we need only one category, which we will call “Articles”
After the Meta class, we see the following lines of code:
    	example_category = ListViewCategory("Examples", 'help')

We will modify it for our needs.
* First, we will change the category name to articles_category
* Then, we have a choice between ListView and IconView for different presentation of results within the category. We select: ListView
* We also need to give a display name for our category. It's simple: Articles
* Finally, we need to select an icon for our category and we will take it from the system workspace, namely: dialog-information-symbolic
As a result, we get the line:
    	articles_category = ListViewCategory("Articles", "dialog-information-symbolic")


The internal architecture of the lens is ready, now we are starting to design the search.
The standard template code demonstrates how the result falls into the lens:
    def search(self, search, results):
        # TODO: Add your search results
        results.append('https://wiki.ubuntu.com/Unity/Lenses/Singlet',
                    'ubuntu-logo',
                    self.example_category,
                    "text/html",
                    'Learn More',
                    'Find out how to write your Unity Lens',
                    'https://wiki.ubuntu.com/Unity/Lenses/Singlet')
        pass


... but we want to ask Wikipedia ...

Wikipedia Search



Let's make a new function that is designed to search. We will do it as follows.

We will call our function wikipedia_query. It will take the search string from the user as an argument. We will also take two more Python modules for our needs: urllib2 for sending an HTTP request to the network and simplejson for processing data from Wikipedia.

At the very beginning of our file, we connect the necessary modules using the import command
    	import urllib2
    	import simplejson


Then, in the WikipediaLens (SingleScopeLens) class, our main class, we add the wiki variable, which will simplify our code:
    	wiki = "http://en.wikipedia.org"

And create a function
    	def wikipedia_query(self, search):

where search is the string that the user enters into the search box. We need to adjust it a bit before sending Wikipedia, replace the spaces with “|”, otherwise Vika will not understand our request.
    	search = search.replace(" ", "|")

We create our request using the open Wikipedia API.
    	url = ("%s/w/api.php?action=opensearch&limit=25&format=json&search=%s" % (self.wiki, search))

And we output the result to the results variable, which is located in json, for this we use the simplejson module
    	results = simplejson.loads(urllib2.urlopen(url).read())

We add debug output to understand what we are doing:
    	print "Searching Wikipedia for %s" % (search)

And we finish our work on the function by outputting the results accordingly
    	return results[1]


Our wikipedia_query function looks almost as it should, we also need to add try and except to prevent errors (network errors, results, etc.). To do this, we create an informational message and an empty output.
    	def wikipedia_query(self,search):
    	    try:
    	        search = search.replace(" ", "|")
    	        url = ("%s/w/api.php?action=opensearch&limit=25&format=json&search=%s" % (self.wiki, search))
    	        results = simplejson.loads(urllib2.urlopen(url).read())
    	        print "Searching Wikipedia"
    	        return results[1]
    	    except (IOError, KeyError, urllib2.URLError, urllib2.HTTPError, simplejson.JSONDecodeError):
    	        print "Error : Unable to search Wikipedia"
    	        return []


Now we need to connect the newly written function to the long-existing search
    	def search(self, search, results):
    	    for article in self.wikipedia_query(search):
    	        results.append("%s/wiki/%s" % (self.wiki, article),
    	                    "http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png",
    	                    self.articles_category,
    	                    "text/html",
    	                    article,
    	                    "Wikipedia Article",
    	                    "%s/wiki/%s" % (self.wiki, article))
    	    pass


It works something like this: the search query falls into wikipedia_query , is sent to Wikipedia, the response in JSON is returned to wikipedia_query , passed to search and displayed in the lens. To understand what is happening in results.append, it is very important to look at the output in the lens. It is passed to Unity by template:
    	results.append (url,
    	            icon,
    	            category,
    	            mime-type,
    	            text,
    	            comment,
    	            drag and drop url)


That's all done!

Lens use



Now the most long-awaited moment has come - we are starting to use the lens!
We enter commands in the terminal:

sudo quickly install
quickly run


Lens installation



After successfully testing and debugging the lens, it can be permanently installed in the system. To do this, I will briefly talk about its internal structure. A lens requires at least three files for its operation: a .lens file containing basic information about the lens; an executable file (daemon) that does all the work and a .service file containing the lens name and the path to the executable file. To install them into the system, the setup.py file was created in the project folder.
I used the following commands for installation:

chmod 777 setup.py
./setup.py build
sudo ./setup.py install


image

References


* Read the full article on the structure of the lenses and their creation (Rus.)
* Learn more about Unity and related technologies (in English).
* Learn more about Unity lenses (in English).
* Unity the API
* the Wikipedia opensearch the API
* Lens sdelannay on this guide
* A selection of lenses for Dash    

Also popular now: