Skip to content

Commit

Permalink
Merge pull request #7 from persianpros/master
Browse files Browse the repository at this point in the history
Safe PEP8
  • Loading branch information
jbleyel authored Apr 13, 2021
2 parents 669bf09 + b22b81e commit 7a5243a
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 59 deletions.
4 changes: 3 additions & 1 deletion plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@
from os import environ as os_environ
import gettext


def localeInit():
lang = language.getLanguage()[:2] # getLanguage returns e.g. "fi_FI" for "language_country"
os_environ["LANGUAGE"] = lang # Enigma doesn't set this (or LC_ALL, LC_MESSAGES, LANG). gettext needs it!
gettext.bindtextdomain("CacheFlush", resolveFilename(SCOPE_PLUGINS, "Extensions/CacheFlush/locale"))


def _(txt):
t = gettext.dgettext("CacheFlush", txt)
if t == txt:
print "[CacheFlush] fallback to default translation for", txt
t = gettext.gettext(txt)
return t


localeInit()
language.addCallback(localeInit)

27 changes: 15 additions & 12 deletions plugin/plugin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# for localized messages
# for localized messages
from . import _
#################################################################################
#
Expand All @@ -7,7 +7,7 @@
VERSION = "1.17"
# Coded by shamann & ims (c)2012 as ClearMem on basic idea by moulikpeta
# latest modyfication by ims:
# - ngettext, getMemory, freeMemory, WHERE_PLUGINMENU, Info, translate
# - ngettext, getMemory, freeMemory, WHERE_PLUGINMENU, Info, translate
# - rebuild timers, less code, renamed to CacheFlush
# - min_free_kbyte, type drop cache, clean dirty cache
#
Expand All @@ -20,40 +20,43 @@
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
#
#################################################################################

from Plugins.Plugin import PluginDescriptor
from Components.config import ConfigSubsection, config, ConfigSelection

config.plugins.CacheFlush = ConfigSubsection()
config.plugins.CacheFlush.where = ConfigSelection(default = "0", choices = [("0",_("plugins")),("1",_("menu-system")),("2",_("extensions")),("3",_("event info"))])
config.plugins.CacheFlush.where = ConfigSelection(default="0", choices=[("0", _("plugins")), ("1", _("menu-system")), ("2", _("extensions")), ("3", _("event info"))])


def startSetup(menuid, **kwargs):
if menuid != "system":
return [ ]
return []
return [(_("Setup CacheFlush"), main, "CacheFlush", None)]


def sessionAutostart(reason, **kwargs):
if reason == 0:
import ui
ui.CacheFlushAuto.startCacheFlush(kwargs["session"])

def main(session,**kwargs):

def main(session, **kwargs):
import ui
session.open(ui.CacheFlushSetupMenu)


def Plugins(path, **kwargs):
name = "CacheFlush"
descr = _("Automatic cache flushing")
list = [PluginDescriptor(where=[PluginDescriptor.WHERE_SESSIONSTART], fnc=sessionAutostart),]
list = [PluginDescriptor(where=[PluginDescriptor.WHERE_SESSIONSTART], fnc=sessionAutostart), ]
if config.plugins.CacheFlush.where.value == "0":
list.append(PluginDescriptor(name=name, description=descr, where=PluginDescriptor.WHERE_PLUGINMENU, needsRestart = True, icon = 'plugin.png', fnc=main))
list.append(PluginDescriptor(name=name, description=descr, where=PluginDescriptor.WHERE_PLUGINMENU, needsRestart=True, icon='plugin.png', fnc=main))
elif config.plugins.CacheFlush.where.value == "1":
list.append(PluginDescriptor(name=name, description=descr, where=PluginDescriptor.WHERE_MENU, needsRestart = True, fnc=startSetup))
list.append(PluginDescriptor(name=name, description=descr, where=PluginDescriptor.WHERE_MENU, needsRestart=True, fnc=startSetup))
elif config.plugins.CacheFlush.where.value == "2":
list.append(PluginDescriptor(name=name, description=descr, where=PluginDescriptor.WHERE_EXTENSIONSMENU, needsRestart = True, fnc=main))
list.append(PluginDescriptor(name=name, description=descr, where=PluginDescriptor.WHERE_EXTENSIONSMENU, needsRestart=True, fnc=main))
elif config.plugins.CacheFlush.where.value == "3":
list.append(PluginDescriptor(name=name, description=descr, where=PluginDescriptor.WHERE_EVENTINFO, needsRestart = True, fnc=main))
list.append(PluginDescriptor(name=name, description=descr, where=PluginDescriptor.WHERE_EVENTINFO, needsRestart=True, fnc=main))
return list

86 changes: 47 additions & 39 deletions plugin/ui.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# for localized messages
# for localized messages
from . import _

from Screens.Screen import Screen
Expand All @@ -16,9 +16,9 @@
if getDesktop(0).size().width() >= 1280:
HD = True

config.plugins.CacheFlush.enable = ConfigYesNo(default = False)
config.plugins.CacheFlush.type = ConfigSelection(default = "3", choices = [("1",_("pagecache")),("2",_("dentries and inodes")),("3",_("pagecache, dentries and inodes"))])
config.plugins.CacheFlush.sync = ConfigYesNo(default = False)
config.plugins.CacheFlush.enable = ConfigYesNo(default=False)
config.plugins.CacheFlush.type = ConfigSelection(default="3", choices=[("1", _("pagecache")), ("2", _("dentries and inodes")), ("3", _("pagecache, dentries and inodes"))])
config.plugins.CacheFlush.sync = ConfigYesNo(default=False)

NGETTEXT = False
try: # can be used ngettext ?
Expand All @@ -32,25 +32,26 @@
choicelist.append(("%d" % i, ngettext("%d minute", "%d minutes", i) % i))
else:
choicelist.append(("%d" % i))
config.plugins.CacheFlush.timeout = ConfigSelection(default = "30", choices = choicelist)
config.plugins.CacheFlush.scrinfo = ConfigYesNo(default = True)
config.plugins.CacheFlush.timeout = ConfigSelection(default="30", choices=choicelist)
config.plugins.CacheFlush.scrinfo = ConfigYesNo(default=True)
choicelist = []
for i in range(1, 11):
if NGETTEXT:
choicelist.append(("%d" % i, ngettext("%d second", "%d seconds", i) % i))
else:
choicelist.append(("%d" % i))
config.plugins.CacheFlush.timescrinfo = ConfigSelection(default = "10", choices = choicelist)
choicelist = [("0",_("Default")),]
config.plugins.CacheFlush.timescrinfo = ConfigSelection(default="10", choices=choicelist)
choicelist = [("0", _("Default")), ]
for i in range(1, 21):
choicelist.append(("%d" % i, "%d kB" % (1024*i)))
config.plugins.CacheFlush.uncached = ConfigSelection(default = "1", choices = choicelist)
config.plugins.CacheFlush.free_default = ConfigInteger(default = 0, limits=(0,9999999999))
choicelist.append(("%d" % i, "%d kB" % (1024 * i)))
config.plugins.CacheFlush.uncached = ConfigSelection(default="1", choices=choicelist)
config.plugins.CacheFlush.free_default = ConfigInteger(default=0, limits=(0, 9999999999))
cfg = config.plugins.CacheFlush

# display mem, used, free and progressbar
ALL = 0x17


def dropCache():
if cfg.sync.value:
system("sync")
Expand All @@ -65,16 +66,19 @@ def dropCache():
system("echo 3 > /proc/sys/vm/drop_caches")
print "[CacheFlush] free pagecache, dentries and inodes"


def getMinFreeKbytes():
for line in open('/proc/sys/vm/min_free_kbytes','r'):
for line in open('/proc/sys/vm/min_free_kbytes', 'r'):
line = line.strip()
print "[CacheFlush] min_free_kbytes is %s kB" % line
return line


def setMinFreeKbytes(size):
system("echo %d > /proc/sys/vm/min_free_kbytes" % (size))
print "[CacheFlush] set min_free_kbytes to %d kB" % size


class CacheFlushSetupMenu(Screen, ConfigListScreen):

skin = """
Expand All @@ -90,13 +94,13 @@ class CacheFlushSetupMenu(Screen, ConfigListScreen):
<widget name="key_yellow" position="240,287" zPosition="2" size="120,30" valign="center" halign="center" font="Regular;22" transparent="1" foregroundColor="yellow" />
<widget name="key_blue" position="360,287" zPosition="2" size="120,30" valign="center" halign="center" font="Regular;22" transparent="1" foregroundColor="blue" />
</screen>"""

def __init__(self, session):
Screen.__init__(self, session)

self.onChangedEntry = [ ]
self.list = [ ]
ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)
self.onChangedEntry = []
self.list = []
ConfigListScreen.__init__(self, self.list, session=session, on_change=self.changedEntry)
self.setup_title = _("Setup CacheFlush")
self["actions"] = ActionMap(["SetupActions", "ColorActions"],
{
Expand All @@ -117,7 +121,7 @@ def __init__(self, session):
self["slide"].setValue(100)
self["slide"].hide()
self["memory"] = Label()
self["min_free_kb"] = Label(_("Uncached memory: %s kB, ( default: %s kB )") % ( getMinFreeKbytes(), str(cfg.free_default.value)))
self["min_free_kb"] = Label(_("Uncached memory: %s kB, ( default: %s kB )") % (getMinFreeKbytes(), str(cfg.free_default.value)))

self.runSetup()
self.onLayoutFinish.append(self.layoutFinished)
Expand All @@ -127,7 +131,7 @@ def layoutFinished(self):
self["memory"].setText(self.getMemory(ALL))

def runSetup(self):
self.list = [ getConfigListEntry(_("Enable CacheFlush"), cfg.enable) ]
self.list = [getConfigListEntry(_("Enable CacheFlush"), cfg.enable)]
if cfg.enable.value:
autotext = _("Auto timeout")
timetext = _("Time of info message")
Expand Down Expand Up @@ -180,7 +184,7 @@ def freeMemory(self):
def getMemory(self, par=0x01):
try:
mm = mu = mf = 0
for line in open('/proc/meminfo','r'):
for line in open('/proc/meminfo', 'r'):
line = line.strip()
if "MemTotal:" in line:
line = line.split()
Expand All @@ -193,14 +197,14 @@ def getMemory(self, par=0x01):
self["memory"].setText("")
self["slide"].hide()
memory = ""
if par&0x01:
memory += "".join((_("Memory:")," %d " % (mm/1024),_("MB")," "))
if par&0x02:
memory += "".join((_("Used:")," %.2f%s" % (100.*mu/mm,'%')," "))
if par&0x04:
memory += "".join((_("Free:")," %.2f%s" % (100.*mf/mm,'%')))
if par&0x10:
self["slide"].setValue(int(100.0*mu/mm+0.25))
if par & 0x01:
memory += "".join((_("Memory:"), " %d " % (mm / 1024), _("MB"), " "))
if par & 0x02:
memory += "".join((_("Used:"), " %.2f%s" % (100. * mu / mm, '%'), " "))
if par & 0x04:
memory += "".join((_("Free:"), " %.2f%s" % (100. * mf / mm, '%')))
if par & 0x10:
self["slide"].setValue(int(100.0 * mu / mm + 0.25))
self["slide"].show()
return memory
except Exception, e:
Expand All @@ -217,7 +221,8 @@ def setUncachedMemory(self):
if cfg.uncached.value == "0":
setMinFreeKbytes(cfg.free_default.value)
else:
setMinFreeKbytes(int(cfg.uncached.value)*1024)
setMinFreeKbytes(int(cfg.uncached.value) * 1024)


class CacheFlushAutoMain():
def __init__(self):
Expand All @@ -236,8 +241,10 @@ def makeShow(self):
else:
self.dialog.hide()


CacheFlushAuto = CacheFlushAutoMain()


class CacheFlushAutoScreen(Screen):
if HD:
skin = """<screen name="CacheFlushAutoScreen" position="830,130" zPosition="10" size="250,30" title="CacheFlush Status" backgroundColor="#31000000" >
Expand Down Expand Up @@ -274,7 +281,7 @@ def __chckState(self):
self.state = cfg.enable.value
if cfg.scrinfo.value and CacheFlushAuto.dialog is not None:
CacheFlushAuto.dialog.show()
self.CacheFlushTimer.start(int(cfg.timeout.value)*60000)
self.CacheFlushTimer.start(int(cfg.timeout.value) * 60000)

def __makeWhatYouNeed(self):
self.__chckState()
Expand All @@ -290,7 +297,8 @@ def __endShow(self):

def __setUncachedMemory(self):
if cfg.uncached.value != "0":
setMinFreeKbytes(int(cfg.uncached.value)*1024)
setMinFreeKbytes(int(cfg.uncached.value) * 1024)


class CacheFlushInfoScreen(Screen):
if HD:
Expand Down Expand Up @@ -356,27 +364,27 @@ def getMemInfo(self):
mem = 0
free = 0
i = 0
for line in open('/proc/meminfo','r'):
( name, size, units ) = line.strip().split()
for line in open('/proc/meminfo', 'r'):
(name, size, units) = line.strip().split()
if name.find("MemTotal") != -1:
mem = int(size)
if name.find("MemFree") != -1:
free = int(size)
if i < 28:
ltext += "".join((name,"\n"))
lvalue += "".join((size," ",units,"\n"))
ltext += "".join((name, "\n"))
lvalue += "".join((size, " ", units, "\n"))
else:
rtext += "".join((name,"\n"))
rvalue += "".join((size," ",units,"\n"))
rtext += "".join((name, "\n"))
rvalue += "".join((size, " ", units, "\n"))
i += 1
self['lmemtext'].setText(ltext)
self['lmemvalue'].setText(lvalue)
self['rmemtext'].setText(rtext)
self['rmemvalue'].setText(rvalue)

self["slide"].setValue(int(100.0*(mem-free)/mem+0.25))
self['pfree'].setText("%.1f %s" % (100.*free/mem,'%'))
self['pused'].setText("%.1f %s" % (100.*(mem-free)/mem,'%'))
self["slide"].setValue(int(100.0 * (mem - free) / mem + 0.25))
self['pfree'].setText("%.1f %s" % (100. * free / mem, '%'))
self['pused'].setText("%.1f %s" % (100. * (mem - free) / mem, '%'))

except Exception, e:
print "[CacheFlush] getMemory FAIL:", e
Expand Down
14 changes: 7 additions & 7 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import setup_translate

pkg = 'Extensions.CacheFlush'
setup (name = 'enigma2-plugin-extensions-cacheflush',
version = '1.17',
description = 'periodicaly flush box cache',
packages = [pkg],
package_dir = {pkg: 'plugin'},
package_data = {pkg: ['*.png', 'locale/*/LC_MESSAGES/*.mo']},
cmdclass = setup_translate.cmdclass, # for translation
setup(name='enigma2-plugin-extensions-cacheflush',
version='1.17',
description='periodicaly flush box cache',
packages=[pkg],
package_dir={pkg: 'plugin'},
package_data={pkg: ['*.png', 'locale/*/LC_MESSAGES/*.mo']},
cmdclass=setup_translate.cmdclass, # for translation
)
5 changes: 5 additions & 0 deletions setup_translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
from distutils.command.build import build as _build
import os


class build_trans(cmd.Command):
description = 'Compile .po files into .mo files'

def initialize_options(self):
pass

Expand All @@ -25,11 +27,14 @@ def run(self):
if os.system("msgfmt '%s' -o '%s'" % (src, dest)) != 0:
raise Exception, "Failed to compile: " + src


class build(_build):
sub_commands = _build.sub_commands + [('build_trans', None)]

def run(self):
_build.run(self)


cmdclass = {
'build': build,
'build_trans': build_trans,
Expand Down

0 comments on commit 7a5243a

Please sign in to comment.