In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to write Linux desktop scripts, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Getting started with Screenlet
You need to install some programs to start developing screenlet. First, install the screenlets package using Ubuntu Software Center or the command line. In the Ubuntu Software Center, type screenlets in the Search box. You should see two options for the main package and the separate installation package for the documentation.
Python and Ubuntu you can use Python to program screenlet. The basic installation of Ubuntu 10.04 already includes Python 2.6, because many utilities rely on it. You may need additional libraries, depending on your application requirements. For this article, I installed and tested everything on Ubuntu 10.04. Next, download the test screenlet source code from the screenlets.org site. The test screenlet is located in the src/share/screenlets/Test folder and uses Cairo and GTK, which you also need to install. The entire source code of the test program is located in the TestScreenlet.py file. Open this file in your favorite editor to view the infrastructure of screenlet.
Python is highly object-oriented, so the class keyword is used to define objects. In this example, the class is named TestScreenlet and has some defined methods. In TestScreenlet.py, notice line 42 in the following code:
Def _ init__ (self, * * keyword_args):
Python uses the double underscore (_ _) symbol before and after to identify system functions through predefined behavior. In this case, the _ _ init__ function addresses all the intentions and purposes of the constructor of the class and contains any number of initialization steps that will be performed when a new instance of the object is created. By convention, the first parameter of each class method is a reference to the current instance of the class and is named self. With this behavior, you can easily use self to reference the methods and properties of the instance in which it resides:
Self.theme_name = "default"
The Screenlet framework defines some naming conventions and standards, which are outlined on the developer page in screenlets.org. There is also a link to the source code of the screenlet package and the application programming interface (Application Programming Interface,API) documentation. Looking at the code also gives you insight into what each function can do and return by calling parameters.
Write a simple screenlet
The basic components of Screenlet include icon files, source code files, and theme folders. The theme folder contains additional folders for different themes. You will find sample templates and files and folders to help you get started on screenlets.org.
For the first example, use the provided template to create a basic "Hello World" application. The code for this basic application is shown in listing 1.
Listing 1. Python code for Hello World screenlet
#! / usr/bin/env pythonimport screenletsclass HelloWorldScreenlet (screenlets.Screenlet): _ _ name__ = 'HelloWorld'__version__ =' 0.1 licensed authoritative authors _ = 'John Doe'__desc__ =' Simple HelloWorldScreenlet 'def _ _ init__ (self, * * kwargs): # Customize the width and height.screenlets.Screenlet.__init__ (self, width=180, height=50, * * kwargs) def on_draw (self Ctx): # Change the color to white and fill the screenlet.ctx.set_source_rgb (255,255,255) self.draw_rectangle (ctx, 0,0,0, self.width, self.height) # Change the color to black and write the message.ctx.set_source_rgb (0,0,0) text = 'Hello Worldwaters written self.drawbacks text (ctx, text, 10,10, "Sans 9", 20) Self.width) if _ _ name__ = "_ _ main__": import screenlets.sessionscreenlets.session.create_session (HelloWorldScreenlet)
Each application must import the screenlet framework and create a new session. There are other minimum requirements, including any initialization steps and basic drawing functions to render the widget on the screen. The TestScreenlet.py sample has a _ _ init__ method to initialize the object. In this example, you will see a line containing a call to the _ _ init__ method of screenlet, which sets the initial width and height of the window to be created for this application.
The only other function required by this application is the on_draw method. This routine sets the background color of the box to white and draws a rectangle using the previously defined dimensions. It sets the text color to black, the source text to "Hello World!", and then draws the text. Figure 1 shows what you should see when running this screenlet. This basic structure persists when you create more useful applications on these simple blocks later in the text.
Figure 1. Basic screenlet structure
Reuse code in a more complex screenlet
One benefit of writing screenlet is the ability to reuse code from other applications. Code reuse opens up unlimited possibilities through a wide range of open source projects based on the Python language. Although each screenlet has the same basic structure, more methods are defined to deal with different behaviors. Listing 2 shows a sample application named TimeTrackerScreenlet.
Listing 2. Python code for Time Tracker screenlet
#! / usr/bin/env pythonimport screenletsimport cairoimport datetimeclass TimeTrackerScreenlet (screenlets.Screenlet): _ _ name__ = 'TimeTrackerScreenlet'__version__ =' 0.1 licensed authoritative authors _ = 'John Doe'__desc__ =' A basic time tracker screenlet.'theme_dir = 'themes/default'image =' start.png'def _ _ init__ (self, * * keyword_args): screenlets.Screenlet.__init__ (self, width=250, height=50) * * keyword_args) self.add_default_menuitems () self.y = 25self.theme_name = 'default'self.on = Falseself.started = Nonedef on_draw (self, ctx): self.draw_scaled_image (ctx, 0,0, self.theme_dir +' /'+ self.image, self.width, self.height) def on_mouse_down (self Event): if self.on:self.started = datetime.datetime.now () self.image = 'stop.png'self.on = Falseelse:if self.started:length = datetime.datetime.now ()-self.startedscreenlets.show_message (None,'% s seconds'% length.seconds, 'Time') self.started = Noneself.image =' start.png'self.on = Truedef on_draw_shape (self, ctx): self.on_draw (ctx) ctx.rectangle (0,0, self.width) Self.height) ctx.fill () if _ _ name__ = "_ _ main__": import screenlets.sessionscreenlets.session.create_session (TimeTrackerScreenlet)
This example introduces several concepts that you need to know before you start building any useful programs. All screenlet applications have the ability to respond to specific user actions or events, such as mouse clicks or drag-and-drop operations. In this example, the mouse down event is used as a trigger to change the status of the icon. While screenlet is running, the start.png image is displayed. Click the image to change it to a stop.png image and record the start time in self.started. Click the stop image to change the image back to start.png and display the amount of time that has elapsed since you clicked the first image.
Responding to events is another key feature that makes it possible to build any number of different applications. Although this example uses only mouse_down events, you can use the same method for other events generated by the screenlet framework or system events, such as timers. The second concept introduced here is persistent state. Because your application is running continuously, waiting for the event to trigger some actions, you can keep track of the project in memory, such as the time you click to start the image. If necessary, you can also save the information to disk for later retrieval.
Automate tasks through screenlet
Now that you understand the concepts behind developing screenlet, let's put it all together. Most users now use Really Simple Syndication (RSS) readers to read blogs and news feeds. For this final example, you will build a configurable screenlet that monitors specific feeds to find keywords and displays any significant news in a text box. The result will be a clickable link to open the article in your default Web browser. Listing 3 shows the source code for RSS Search screenlet.
Listing 3. Python code for RSS Search screenlet
#! / usr/bin/env pythonfrom screenlets.options import StringOption, IntOption, ListOptionimport xml.dom.minidomimport webbrowserimport screenletsimport urllib2import gobjectimport pangoimport cairoclass RSSSearchScreenlet (screenlets.Screenlet): _ _ name__ = 'RSSSearch'__version__ =' 0.1 written written authorizations _ = 'John Doe'__desc__ =' An RSS search screenlet.'topic = 'Windows Phone 7'feeds = [' http://www.engadget.com/rss.xml', 'http://feeds.gawker.com/gizmodo/full']interval = 10__items = [] _ mousesel = 0__selected = Nonedef _ init__ (self, * * kwargs): # Customize the width and height.screenlets.Screenlet.__init__ (self, width=250, height=300, * * kwargs) self.y = 25def on_init (self): # Add options.self.add_options_group (' Search Options','RSS feeds to search and topic to search for.') self.add_option (StringOption ('Search Options') 'topic',self.topic,'Topic','Topic to search feeds for.')) self.add_option (ListOption (' Search Options','feeds',self.feeds,'RSS Feeds','A list of feeds to search for a topic.')) self.add_option (IntOption ('Search Options','interval',self.interval,'Update Interval') 'How frequently to update (in seconds)') self.update () def update (self): "Search selected feeds and update results." self.__items = [] # Go through each feed.for feed_url in self.feeds:# Load the raw feed and find all item elements.raw = urllib2.urlopen (feed_url). Read () dom = xml.dom.minidom.parseString (raw) items = dom.getElementsByTagName ('item') for item in items:# Find the title and make sure it matches The topic.title = item.getElementsByTagName ('title') [0] .firstChild.dataif self.topic.lower () not in title.lower (): continue# Shorten the title to 30 characters.if len (title) > 30: title = title [: 27] +'... # Find the link and save the item.link = item.getElementsByTagName ('link') [0] .firstChild.dataself. _ _ items.append ((title) Link) self.redraw_canvas () # Set to update again after self.interval.self.__timeout = gobject.timeout_add (self.interval * 1000, self.update) def on_draw (self, ctx): "" Called every time the screenlet is drawn to the screen. "# Draw the background (a gradient). Gradient = cairo.LinearGradient (0, self.height * 2,0,0) gradient.add_color_stop_rgba (1,1,1,1,1) gradient.add_color_stop_rgba (0.7,1) 1,1,0.75) ctx.set_source (gradient) self.draw_rectangle_advanced (ctx, 0,0, self.width-20 recordself.heights-20recollections = (5,5,5,5), fill=True, border_size=1,border_color= (0,0,0,0.25), shadow_size=10,shadow_color= (0,0,0) ) # Make sure we have a pango layout initialized and updated.if self.p_layout = = None: self.p_layout = ctx.create_layout () else:ctx.update_layout (self.p_layout) # Configure fonts.p_fdesc = pango.FontDescription () p_fdesc.set_family ("Free Sans") p_fdesc.set_size (10 * pango.SCALE) self.p_layout.set_font_description (p_fdesc) # Display our text.pos = [20,20] ctx.set_source_rgb (0 0,0) x = 0self.__selected = Nonefor item in self.__items:ctx.save () ctx.translate (* pos) # Find if the current item is under the mouse.if self.__mousesel = x and self.mouse_is_over:ctx.set_source_rgb (0,0,0.5) self.__selected = item [1] else:ctx.set_source_rgb (0,0 0) self.p_layout.set_markup ('% s'% item [0]) ctx.show_layout (self.p_layout) pos [1] + = 20ctx.restore () x + = 1def on_draw_shape (self, ctx): ctx.rectangle (0,0, self.width, self.height) ctx.fill () def on_mouse_move (self Event): "" Called whenever the mouse moves over the screenlet. "" x = event.x / self.scaley = event.y / self.scaleself.__mousesel = int ((y-10) / (20))-1self.redraw_canvas () def on_mouse_down (self Event): "Called when the mouse is clicked." if self.__selected and self.mouse_is_over:webbrowser.open_new (self.__selected) if _ _ name__ = "_ _ main__": import screenlets.sessionscreenlets.session.create_session (RSSSearchScreenlet)
Based on the concepts of the first two examples, this screenlet uses some new concepts, including config pages. In the on_init routine, add three options for the user to specify: a list of RSS feeds for tracking, topics of interest for search, and update intervals. The update routine then uses all of this at run time.
Python is a good language for this type of task. The standard library includes everything you need to load Extensible markup language (Extensible Markup Language,XML) from RSS feeds to searchable lists. In Python, this task requires only three lines of code:
Raw = urllib2.urlopen (feed_url). Read () dom = xml.dom.minidom.parseString (raw) items = dom.getElementsByTagName ('item')
The libraries used in these three lines include urllib2 and xml. In the first line, the complete content found on the feed_url address is read into the character serial. Next, because you know that the string contains XML, use the Python XML library dom.minidom.parseString method to create a document object made up of node objects.
Finally, create a list of element objects that correspond to a single XML element named item. You can then iterate through this list to search for your target topic. Using the for keyword, Python has a good way to iterate over the project list, as shown in the following code snippet:
For item in items:# Find the title and make sure it matches the topic.title = item.getElementsByTagName ('title') [0] .firstChild.dataif self.topic.lower () not in title.lower (): continue
Add each item that matches your criteria to the currently displayed list, which is associated with an instance of screenlet. Using this method, you can run multiple instances of the same screenlet, each configured to search for a different topic. The last part of the update function redraws the text with the updated list and triggers a new update timer based on the interval on the config page. By default, the timer fires every 10 seconds, but you can change it to any value you want. This timer mechanism comes from the gobject library and is part of the GTK framework.
This application greatly expands the on_draw method to accommodate your new functionality. Both the Cairo and Pango libraries allow you to create some effects for text windows. Use progressive to make the background of the widget beautiful and rounded and translucent. Use Pango to add functions to the layout to easily save and store the current context. It also provides a way to generate scalable fonts based on the current size of screenlet.
The trickiest part of the on_draw method is when the user hovers over an item in the list. By using the "for" keyword, you can iterate over the project in screenlet to see if the user hovers over a particular project. If you hover over a specific item, set the selected properties and change the color to provide visual feedback. You can also use a little tag to set the link property to bold-it may not be the most elaborate or effective way to deal with the problem, but it is useful. When the user clicks one of the links in the box, the Web browser with the target URL launches. You can see this feature in the on_mouse_down function. Python and its library allow you to launch the default browser to display the desired page with a single line of code.
These are all the contents of the article "how to write Linux Desktop Scripts". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.