~ubuntu-branches/ubuntu/trusty/screenlets/trusty

« back to all changes in this revision

Viewing changes to src/lib/utils.py

  • Committer: Bazaar Package Importer
  • Author(s): Julien Lavergne
  • Date: 2011-02-24 00:51:35 UTC
  • mfrom: (1.1.3 upstream)
  • Revision ID: james.westby@ubuntu.com-20110224005135-p65cxwmpfwwy3woi
Tags: 0.1.2+bzr616-0ubuntu1
* New upstream snapshot.
 - Move individual screenlets into another source package.
 - Many bug fixes since 0.1.2.
* Convert to source format 3.0 (quilt).
* debian/patches
 - Removed all patches, merged upstream.
* debian/rules:
 - Convert to dh7.
 - Don't remove copies of feedparser, not in this package.
 - Don't remove empty directory for the individual screenlets.
* debian/screenlets.install:
 - Update installed files.
* debian/compat
 - Bump to level 7.
* debian/control:
 - Rewrite Depends and build-depends.
* README.Debian :
 - Mention mutter as a composite manager.
* debian/README.source:
 - Remove the README.source.
* debian/screenlets.manpages:
 - Add the manpages.
* debian/copyright:
 - Rewrite with dep5 style.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
gettext.textdomain('screenlets')
24
24
gettext.bindtextdomain('screenlets', screenlets.INSTALL_PREFIX +  '/share/locale')
25
25
import gobject
 
26
from distutils.version import LooseVersion
 
27
from subprocess import *
26
28
try:
27
29
        import gnomevfs
28
30
except:
98
100
                if screenlets.show_question(None, 
99
101
                        _("There is no existing autostart directory for your user account yet. Do you want me to automatically create it for you?"), 
100
102
                        _('Error')):
101
 
                        print _("Auto-create autostart dir ...")
 
103
                        print "Auto-create autostart dir ..."
102
104
                        os.system('mkdir %s' % DIR_AUTOSTART)
103
105
                        if not os.path.isdir(DIR_AUTOSTART):
104
106
                                screenlets.show_error(None, _("Automatic creation failed. Please manually create the directory:\n%s") % DIR_AUTOSTART, _('Error'))
115
117
                if a != -1:
116
118
                        print str(f) + ' duplicate entry'
117
119
                        os.system('rm %s%s' % (chr(34)+DIR_AUTOSTART,f+chr(34)))
118
 
                        print _('Removed duplicate entry')
 
120
                        print 'Removed duplicate entry'
119
121
        if not os.path.isfile(starter) and not os.path.exists(os.environ['HOME'] + '/.config/autostart/CalendarScreenlet'):
120
122
                path = find_first_screenlet_path(name)
121
123
                if path:
122
 
                        print _("Create autostarter for: %s/%sScreenlet.py") % (path, name)
 
124
                        print "Create autostarter for: %s/%sScreenlet.py" % (path, name)
123
125
                        code = ['[Desktop Entry]']
124
126
                        code.append('Name=%sScreenlet' % name)
125
127
                        code.append('Encoding=UTF-8')
134
136
                                        f.write(l + '\n')
135
137
                                f.close()
136
138
                                return True
137
 
                        print _('Failed to create autostarter for %s.') % name
 
139
                        print 'Failed to create autostarter for %s.' % name
138
140
                        return False
139
141
        else:
140
 
                print _("Starter already exists.")
 
142
                print "Starter already exists."
141
143
                return True
142
144
 
143
145
def delete_autostarter ( name):
144
146
        """Delete the autostart for the given screenlet."""
145
147
        if name.endswith('Screenlet'):
146
148
                name = name[:-9]
147
 
        print _('Delete autostarter for %s.') % name
 
149
        print 'Delete autostarter for %s.' % name
148
150
        os.system('rm %s%sScreenlet.desktop' % (DIR_AUTOSTART, name))
149
151
        for f in os.listdir(DIR_AUTOSTART):
150
152
                a = f.find(name + 'Screenlet')
151
153
                if a != -1:
152
154
                        print str(f) + ' duplicate entry'
153
155
                        os.system('rm %s%s' % (chr(34)+DIR_AUTOSTART,f+chr(34)))
154
 
                        print _('Removed duplicate entry')
 
156
                        print 'Removed duplicate entry'
 
157
 
 
158
def get_screenlet_linux_name_by_class_path(path):
 
159
        """Returns screenlet name on form 'foobar-screenlet' by main screenlet class file path."""
 
160
        return path.lower().replace(".py", "").split("/")[path.count("/")].replace("screenlet", "-screenlet")
 
161
 
 
162
def get_screenlet_linux_name_by_class_name(name):
 
163
        """Returns screenlet name on form 'foobar-screenlet' by screenlet class name."""
 
164
        return name.lower().replace("screenlet", "-screenlet")
 
165
 
 
166
def get_screenlet_linux_name_by_short_class_name(name):
 
167
        """Returns screenlet name on form 'foobar-screenlet' by shortened screenlet class name."""
 
168
        return name.lower() + "-screenlet"
 
169
 
 
170
def is_screenlets_ppa_enabled():
 
171
        """Detect if Screenlets default PPA is enabled on system."""
 
172
        import commands
 
173
        result = commands.getstatusoutput("ls /etc/apt/sources.list.d/screenlets-dev-ppa-*.list | xargs grep '^deb.*'")[0]
 
174
        return result == 0
 
175
 
 
176
def get_translator(path):
 
177
        """Returns translator by screenlet class path from __file__."""
 
178
        mo_domain = get_screenlet_linux_name_by_class_path(path)
 
179
 
 
180
        t = gettext.translation(mo_domain, screenlets.INSTALL_PREFIX +  '/share/locale', fallback = True)
 
181
 
 
182
        if not isinstance(t, gettext.GNUTranslations):
 
183
                cut_path_here = path.rfind('/')
 
184
                if cut_path_here > 0:
 
185
                        screenlet_dir = path[0:cut_path_here]
 
186
                else:
 
187
                        screenlet_dir = os.getcwd()
 
188
                mo_dir = screenlet_dir + "/mo"
 
189
                t = gettext.translation(mo_domain, mo_dir, fallback = True)
 
190
        return t.lgettext
155
191
 
156
192
def _contains_path (string):
157
193
        """Internal function: Returns true if the given string contains one of the
158
 
        SCREENLETS_PATH entries."""
159
 
        for p in screenlets.SCREENLETS_PATH:
160
 
                if string.find(p) > -1:
 
194
        Screenlets paths."""
 
195
        # use saved paths for performance reasons
 
196
        for path in screenlets.SCREENLETS_PATH:
 
197
                if string.find(path) > -1:
161
198
                        return True
162
199
        return False
163
200
 
171
208
 
172
209
 
173
210
def find_first_screenlet_path (screenlet_name):
174
 
        """Scan the SCREENLETS_PATH for the first occurence of screenlet "name" and 
175
 
        return the full path to it. This function is used to get the theme/data 
176
 
        directories for a Screenlet."""
 
211
        """Scan the Screenlets paths for the occurence of screenlet "name" with the
 
212
        highest version and return the full path to it. This function is used to get
 
213
        the theme/data directories for a Screenlet and run the Screenlet."""
 
214
        available_versions_paths = []
 
215
        # use saved paths for performance reasons
177
216
        for dir in screenlets.SCREENLETS_PATH:
178
217
                try:
179
218
                        for name in os.listdir(dir):
184
223
                                # if path exists
185
224
                                if os.access(path + '/' + name_py, os.F_OK):
186
225
                                        if name == screenlet_name:
187
 
                                                return path
 
226
                                                available_versions_paths.append(path)
188
227
                                else:
189
228
                                        #print "utils.find_first_screenlet_path: "+\
190
229
                                        #       "LISTED PATH NOT EXISTS: " + path
191
230
                                        pass
192
231
                except OSError: # Raised by os.listdir: the directory doesn't exist
193
232
                        pass
 
233
        if len(available_versions_paths) == 1:
 
234
                return available_versions_paths[0]
 
235
        elif len(available_versions_paths) > 1:
 
236
                path_and_version = []
 
237
                for version_path in available_versions_paths:
 
238
                        path_and_version.append({'version': get_screenlet_metadata_by_path(version_path)['version'], 'path': version_path})
 
239
 
 
240
                sorted_versions = sorted(path_and_version, key=lambda x: LooseVersion(x["version"]), reverse=True)
 
241
                return sorted_versions[0]['path']
 
242
 
194
243
        # nothing found
195
244
        return None
196
245
 
197
246
def get_screenlet_icon (screenlet_name,width,height):
198
247
        img = gtk.gdk.pixbuf_new_from_file_at_size(\
199
248
                        screenlets.INSTALL_PREFIX + '/share/screenlets-manager/noimage.svg',width,height)
 
249
        # use saved paths for performance reasons
200
250
        for path in screenlets.SCREENLETS_PATH:
201
251
                for ext in ['svg', 'png']:
202
252
                        img_path = "%s/%s/icon.%s" % (path, screenlet_name, ext)
213
263
        end = data.find(last, begin)
214
264
        return data[begin:end]
215
265
 
216
 
def get_screenlet_metadata (screenlet_name):
 
266
def get_screenlet_metadata_by_path (path):
217
267
        """Returns a dict with name, info, author and version of the given
218
 
        screenlet. Use with care because it always imports the screenlet 
 
268
        screenlet. Use with care because it may import the screenlet 
219
269
        module and shouldn't be used too often due to performance issues."""
220
 
        # find path to file
221
 
        path = find_first_screenlet_path(screenlet_name)
222
 
        classname = screenlet_name + 'Screenlet'
 
270
 
 
271
        chunks = path.split('/')
 
272
        classname = chunks[len(chunks)-1] + 'Screenlet'
223
273
 
224
274
        try:
225
275
                slfile = open(path + '/'+ classname + '.py','r')
240
290
                version = getBetween(sldata,'__version__','\n')
241
291
                version1 = getBetween(version ,"'","'")
242
292
                if version1.find(' = ') != -1: version1 = getBetween(version ,chr(34),chr(34))
 
293
                requires1=[]
 
294
                if sldata.find('__requires__') > 0:
 
295
                        requires = getBetween(sldata,'__requires__',']')
 
296
                        if len(requires) > 0:
 
297
                                cleaned = requires.split('[')[1].replace("'", "").replace('"', '').replace('\n', '').replace('\t', '')
 
298
                                requires1 = "".join(cleaned.split()).split(",")
 
299
 
243
300
                return {'name'  : name1, 
244
 
                        'info'          : info1, 
 
301
                        'info'          : gettext.dgettext(get_screenlet_linux_name_by_class_name(name1), info1), 
245
302
                        'author'        : author1, 
246
 
                        'version'       : version1
 
303
                        'version'       : version1,
 
304
                        'requires'      : requires1
247
305
                        }               
248
306
        except:
249
307
                try:
254
312
                        cls = getattr(slmod, classname)
255
313
                        sys.path.remove(path)
256
314
                        return {'name'  : cls.__name__, 
257
 
                                'info'          : cls.__desc__, 
 
315
                                'info'          : gettext.dgettext(get_screenlet_linux_name_by_class_name(cls.__name__), cls.__desc__), 
258
316
                                'author'        : cls.__author__, 
259
 
                                'version'       : cls.__version__
 
317
                                'version'       : cls.__version__,
 
318
                                'requires'      : cls.__requires__
260
319
                                }
261
320
                except Exception, ex:
262
 
                        print _("Unable to load '%s' from %s: %s ") % (screenlet_name, path, ex)
 
321
                        print "Unable to load '%s' from %s: %s " % (screenlet_name, path, ex)
263
322
                        return None
264
323
 
 
324
def get_screenlet_metadata (screenlet_name):
 
325
        """Returns a dict with name, info, author and version of the given
 
326
        screenlet. Use with care because it always imports the screenlet 
 
327
        module and shouldn't be used too often due to performance issues."""
 
328
        # find path to file
 
329
        path = find_first_screenlet_path(screenlet_name)
 
330
 
 
331
        return get_screenlet_metadata_by_path(path)
 
332
 
 
333
def refresh_available_screenlet_paths ():
 
334
        """Checks the system Screenlets directory for screenlet packs
 
335
        and updates screenlets.SCREENLETS_PATH. Doesn't remove outdated paths
 
336
        (this doesn't hurt anyone)."""
 
337
        paths = screenlets.SCREENLETS_PATH
 
338
        for name in os.listdir(screenlets.DIR_USER_ROOT):
 
339
                path = screenlets.DIR_USER_ROOT + '/' + name
 
340
                # check if entry is a dir
 
341
                if name.startswith(screenlets.SCREENLETS_PACK_PREFIX):
 
342
                        if path not in paths:
 
343
                                if stat.S_ISDIR(os.stat(path).st_mode):
 
344
                                        paths.append(path)
 
345
 
265
346
def list_available_screenlets ():
266
 
        """Scan the SCREENLETS_PATHs for all existing screenlets and return their
 
347
        """Scan the Screenlets paths for all existing screenlets and return their
267
348
        names (without trailing "Screenlet") as a list of strings."""
268
349
        sls = []
 
350
        # first refresh
 
351
        refresh_available_screenlet_paths()
 
352
        # use saved paths for performance reasons
269
353
        for dir in screenlets.SCREENLETS_PATH:
270
354
                try:
271
355
                        for name in os.listdir(dir):
281
365
                                        pass
282
366
                except OSError: # Raised by os.listdir: the directory doesn't exist
283
367
                        pass
 
368
        sls.sort()
284
369
        return sls
285
370
 
286
371
import session
366
451
                                return dbus.Interface(proxy_obj, screenlets.DAEMON_IFACE)
367
452
 
368
453
                except Exception, ex:
369
 
                        print _("Error in ScreenletsManager.connect_daemon: %s") % ex
 
454
                        print "Error in ScreenletsManager.connect_daemon: %s" % ex
370
455
        return None
371
456
 
372
457
def get_desktop_dir():
497
582
        if not os.path.isdir(DIR_AUTOSTART):
498
583
        # create autostart directory, if not existent
499
584
                if screenlets.show_question(None, _("There is no existing autostart directory for your user account yet. Do you want me to automatically create it for you?"), _('Error')):
500
 
                        print _("Auto-create autostart dir ...")
 
585
                        print "Auto-create autostart dir ..."
501
586
                        os.system('mkdir %s' % DIR_AUTOSTART)
502
587
                        if not os.path.isdir(DIR_AUTOSTART):
503
588
                                screenlets.show_error(None, _("Automatic creation failed. Please manually create the directory:\n%s") % DIR_AUTOSTART, _('Error'))
508
593
        starter = '%sScreenlets Daemon.desktop' % (DIR_AUTOSTART)
509
594
 
510
595
        if not os.path.isfile(starter) and os.path.isfile('%sscreenlets-daemon.desktop' % (DIR_AUTOSTART)) == False:
511
 
                print _("Create autostarter for: Screenlets Daemon")
 
596
                print "Create autostarter for: Screenlets Daemon"
512
597
                code = ['[Desktop Entry]']
513
598
                code.append('Encoding=UTF-8')
514
599
                code.append('Version=1.0')
522
607
                                f.write(l + '\n')
523
608
                        f.close()
524
609
                        return True
525
 
                print _('Failed to create autostarter for %s.') % name
 
610
                print 'Failed to create autostarter for %s.' % name
526
611
                return False
527
612
        else:
528
 
                print _("Starter already exists.")
 
613
                print "Starter already exists."
529
614
                return True
530
615
 
531
616
def launch_screenlet(screenlet):
544
629
# CLASSES
545
630
# ------------------------------------------------------------------------------
546
631
 
547
 
class ScreenletInfo:
 
632
class ScreenletInfo(object):
548
633
        """A container with info about a screenlet."""
549
634
 
550
635
        def __init__ (self, name, lname, info, author, version, icon):
632
717
                return False
633
718
 
634
719
 
635
 
class IniReader:
 
720
class IniReader(object):
636
721
        """A simple config/ini-reader class. This is only used for reading the 
637
722
        theme.conf files yet, thus it only uses string-values.
638
723
        TODO: add writing-functions and let backend use this, too"""
670
755
                try:
671
756
                        f = open (filename, "r")
672
757
                except:
673
 
                        print _("File %s not found") % str(filename)
 
758
                        print "File %s not found" % str(filename)
674
759
                if f:
675
760
                        section_name = ''
676
761
                        for line in f.readlines():
701
786
                                                                try:
702
787
                                                                        self.sections[section_name].append(o)
703
788
                                                                except:
704
 
                                                                        print _("Section %s not found!") % section_name
 
789
                                                                        print "Section %s not found!" % section_name
705
790
                        f.close()
706
791
                        return True
707
792
                else:
709
794
 
710
795
 
711
796
 
712
 
class Notifier:
 
797
class Notifier(object):
713
798
        """A simple and conveniet wrapper for the notification-service. Allows
714
799
        screenlets to easily pop up notes with their own icon (if any)."""
715
800
        
737
822
                                [], {}, timeout)
738
823
                        return True
739
824
                else:
740
 
                        print _("Notify: No DBus running or notifications-daemon unavailable.")
 
825
                        print "Notify: No DBus running or notifications-daemon unavailable."
741
826
                return False
742
827
 
743
828