Commit 2c3da582 authored by PacMiam's avatar PacMiam

FPM - A new start

* Allow to load a specific binding from binding folder (for the moment, only
* pacmang2).
* Modify Interpreter class to use MainWindow functions
parent bd69fd25
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Modules
# ----------------------------------------------------------------------------
from enum import Enum
# ----------------------------------------------------------------------------
# Enum
# ----------------------------------------------------------------------------
class Fpmd(Enum):
BusName = "org.frugalware.fpmd"
BusPath = "/org/frugalware/fpmd/object"
Stable = "frugalware"
Current = "frugalware-current"
class Groups(Enum):
Applications = ("applications-office", "(^[x]?apps.*)")
Chroot = ("security-high", "(^fw32.*)")
Development = ("applications-development", "(^devel.*)")
Documentation = ("system-help", "(^docs.*)")
Enlightenment = ("package-x-generic", "(^e17.*)")
Fonts = ("preferences-desktop-font", "(^.*fonts.*)")
Games = ("applications-games", "(^games.*)")
Gnome = ("package-x-generic", "(^gnome.*)")
Kde = ("package-x-generic", "(^kde.*)")
Library = ("applications-utilities", "(^compat-.*|^[x]?lib.*|^qt.*-libs)")
Locales = ("preferences-desktop-locale", "(^locale.*)")
Lxde = ("package-x-generic", "(^lxde.*)")
Mate = ("package-x-generic", "(^mate.*)")
Multimedia = ("applications-multimedia", "(^[x]?multimedia.*)")
Network = ("applications-internet", "(^network.*)")
System = ("utilities-system-monitor", "(^base.*|^core.*|^chroot.*)")
Xfce = ("package-x-generic", "(^xfce4.*)")
Xorg = ("video-display", "(^x11.*|^xorg-(?!fonts).*)")
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------
#
# config.py
#
# Configuration parser
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# ------------------------------------------------------------------
# ------------------------------------------------------------------
# Modules
# ------------------------------------------------------------------
# System
from sys import version_info
# Log
from logging import getLogger
from logging.config import fileConfig
# Fpmd
from fpmd.tools.utils import getType
from fpmd.tools.utils import getTranslation
# ------------------------------------------------------------------
# Fix
# ------------------------------------------------------------------
if(version_info[0] >= 3):
from configparser import SafeConfigParser
from configparser import Error as ConfigError
from configparser import MissingSectionHeaderError
else:
from ConfigParser import SafeConfigParser
from ConfigParser import Error as ConfigError
from ConfigParser import MissingSectionHeaderError
# ------------------------------------------------------------------
# Global variables
# ------------------------------------------------------------------
_ = getTranslation("fpmd")
# ------------------------------------------------------------------
# Class
# ------------------------------------------------------------------
class Config (object):
def __init__ (self, path):
"""
Constructor
"""
# ------------------------------------
# Private variables
# ------------------------------------
self.__data = dict()
self.__path = path
# ------------------------------------
# Log
# ------------------------------------
self.__log = getLogger()
# ------------------------------------
# Read configuration
# ------------------------------------
self.__read_config()
# ------------------------------------
# Getter/Setter
# ------------------------------------
def get (self, key, option=None):
if key in self.__data.keys():
if option is None:
return self.__data[key]
elif option in self.__data[key]:
return getType(self.__data[key][option])
return None
def set (self, key, option, value):
if key in self.__data.keys():
self.__data[key][option] = str(value)
else:
raise (KeyError, key)
@property
def data (self):
return self.__data
@property
def sections (self):
return self.__data.keys()
# ------------------------------------
# Methods
# ------------------------------------
def __read_config (self):
"""
Read configuration file and store data into a dictionnary
"""
try:
parser = SafeConfigParser()
parser.read(self.__path)
for section in parser.sections():
self.__data[section] = dict(parser.items(section))
except MissingSectionHeaderError:
self.__log.error(_("Missing section into configuration file"))
except Exception as error:
self.__log.error(
_("Cannot parse configuration file: %s" % str(error)))
def write_configuration (self):
"""
Write data into configuration file
"""
if len(self.__data) > 0:
parser = SafeConfigParser()
# Set sections
for section in self.__data.keys():
parser.add_section(section)
# Set options for current section
for option in self.__data[section]:
parser.set(section, option, self.__data[section][option])
with open(self.__path, 'w') as pipe:
parser.write(pipe)
def update_configuration (self, data):
"""
Update configuration file with default values
:param dict data: Default values
"""
for section in data.keys():
# Add new sections
self.add_section(section, data[section])
# Add new options
for option in data[section].keys():
if not option in self.__data[section]:
self.__data[section][option] = str(data[section][option])
def add_section (self, key, value=dict()):
"""
Add a new section into configuration file
:param str key: New section to add
:param str value: Section value (Default: dict())
"""
if not key in self.__data.keys():
self.__data[key] = value
This diff is collapsed.
......@@ -22,21 +22,118 @@
# Modules
# ----------------------------------------------------------------------------
# Dbus
from dbus import Interface
from dbus import SystemBus
from dbus import DBusException
from dbus.mainloop.glib import DBusGMainLoop
# Interpreter
from binding.pacmang2 import *
from binding.pacmang2.package import Database
# Regex
from re import match
# Thread
from gi.repository.GObject import idle_add
from gi.repository.GObject import source_remove
# ----------------------------------------------------------------------------
# Class
# ----------------------------------------------------------------------------
class Database(object):
class Interpreter(object):
def __init__ (self):
def __init__ (self, interface):
"""
Constructor
"""
DBusGMainLoop(set_as_default=True)
self.database = Database()
# ------------------------------------
# Variables
# ------------------------------------
self.interface = interface("Pacman-G2 binding")
self.groups_data = dict()
# ------------------------------------
# Interface
# ------------------------------------
self.__start_interface()
def __generate_groups_data(self):
"""
Generate data for generic groups
"""
for group in Groups:
icon, regex = group.value
self.groups_data[group.name] = dict(
icon=icon, regex=regex, groups=list())
self.interface.append_group(icon, group.name)
for group in self.database.groups(Fpmd.Current.value):
for key in self.groups_data.keys():
if match(self.groups_data[key]["regex"], str(group)):
self.groups_data[key]["groups"].append(str(group))
break
def load_packages(self, repository, group):
"""
Load packages from a specific group into treeview
"""
yield True
packages = self.database.packages(repository, group)
for package in packages:
yield False
# Check package status
status = False
if self.database.package_installed(package)[0]:
status = True
# Get package informations
data = self.database.package(repository, package)
# Add package into treeview
self.interface.append_package(status, u"<b>%s</b> - %s\n%s" % (
data.name, data.version, data.description))
if ((packages.index(package) + 1) % 5 == 0):
yield True
yield False
def start_thread(self, loader, thread=None):
"""
Start a gobject thread
"""
if thread is not None and not thread == 0:
source_remove(thread)
thread = idle_add(loader)
def __start_interface(self):
"""
Start interface with current binding
"""
self.__generate_groups_data()
self.database.packages_installed()
self.start_thread(
self.load_packages(Fpmd.Current.value, "xapps-extra"))
self.interface.start_interface()
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------
#
# network.py
#
# Network manager
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# ------------------------------------------------------------------
# ------------------------------------------------------------------
# Modules
# ------------------------------------------------------------------
# System
from sys import version_info
if(version_info[0] < 3):
from urllib2 import Request
from urllib2 import urlopen
from urllib2 import URLError
else:
from urllib.request import Request
from urllib.request import urlopen
from urllib.request import urlretrieve
from urllib.error import URLError
# ------------------------------------------------------------------
# Class
# ------------------------------------------------------------------
class Network (object):
def __init__ (self, url):
"""
Constructor
:return: Object Network
:rtype: Network
"""
self.url = url
def checkUrl (self, timeout=10):
"""
Try to open an url and get his status
:return: Url status
:rtype: bool
"""
try:
handle = urlopen(Request(self.url), timeout=timeout)
return True
except:
return False
def downloadContent (self, target=".", timeout=10):
"""
Download content from url
:param str target: Element to download (default ".")
:return: None
"""
if(version_info[0] < 3):
try:
webFile = urlopen(self.url, timeout=timeout)
localFile = open(target, 'w')
localFile.write(webFile.read())
webFile.close()
localFile.close()
return True
except URLError as err:
return False
else:
try:
webFile = urlretrieve(self.url, target)
return True
except URLError as err:
return False
This diff is collapsed.
This diff is collapsed.
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------
#
# utils.py
#
# Miscellaneous functions
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# ------------------------------------------------------------------
# ------------------------------------------------------------------
# Modules
# ------------------------------------------------------------------
# Files
from os import remove
from os import listdir
from os import environ
from os.path import join
from os.path import isdir
from os.path import isfile
from os.path import exists
from os.path import getsize
from os.path import basename
from sys import version_info
from glob import glob
from struct import unpack
from codecs import open as codecOpen
# Logging
from logging import INFO
from logging import DEBUG
from logging import ERROR
from logging import Formatter
from logging import FileHandler
from logging import StreamHandler
# Package
from pkg_resources import require
from pkg_resources import _manager
# Regex
from re import split
from re import search
# System
from subprocess import Popen
from subprocess import PIPE
from sys import version_info
# Translation
from gettext import gettext
from gettext import textdomain
from gettext import bindtextdomain
# ------------------------------------------------------------------
# Fix
# ------------------------------------------------------------------
if(version_info[0] >= 3):
long = int
# ------------------------------------------------------------------
# Methods
# ------------------------------------------------------------------
def file_handler (logger, path):
"""
Set log file for a specific Logger
:param Logger logger: Logger
:param str path: Log file path
"""
handler = FileHandler(path)
handler.setFormatter(
Formatter("%(levelname)s » %(asctime)s - %(funcName)s » %(message)s",
datefmt="%D %H:%M"))
handler.setLevel(ERROR)
return handler
def console_handler (logger, debug=False):
"""
Set log file for a specific Logger
:param Logger logger: Logger
:param str path: Log file path
"""
handler = StreamHandler()
handler.setFormatter(Formatter("%(levelname)s » %(message)s"))
if debug:
handler.setLevel(DEBUG)
else:
handler.setLevel(INFO)
return handler
def getTranslation (eggName):
"""
Return the translation
:param str apps: Application name
:return: Object Gettext
:rtype: Gettext
"""
try:
bindtextdomain(eggName, "/usr/share/locale")
textdomain(eggName)
return gettext
except:
return gettext
def color (text, value="white", bold=False):
"""
Return the right escape sequence color
:param str text: Text to show with selected color
:param str value: Color name (default white)
:param bool bold: Get bold color (default False)
:return: Escape sequence
:rtype: str
"""
colors = dict(black="30", red="31", green="32", yellow="33", blue="34",
purple="35", cyan="36", grey="37", white="38")
boldValue = "0"
if bold:
boldValue = "1"
return ("\033[%s;%sm%s\033[0;38m" % (boldValue, colors.get(value), text))
def splitRegex (pattern, value):
"""
Split the following string : [repo] name
:param str value: Specific string to split
:return: Split string
:rtype: list (str repositoryName, str packageName)
"""
result = split(pattern, value)
if len(result) > 1:
return result[1:-1]
return result
def check_xorg ():
"""
Check if Xorg server is running
:return: X server status
:rtype: bool
"""
try:
if not environ["DISPLAY"] == None:
return True
else:
return False
except:
return False
def getPixmap (eggName, path):
"""
Provides easy access to data in a python egg
Thanks Deluge :)
"""
return require(eggName)[0].get_resource_filename(
_manager, join(*(eggName.split('.') + [path])))
def getType (value):
"""
Return correct type for value
"""
if not value == None:
# int
if not search("^\d+$", str(value)) == None:
return int(value)
# float
elif not search("^\d+\.\d*$", str(value)) == None:
return float(value)
# boolean
elif value in ["True", "true"]:
return True
elif value in ["False", "false"]:
return False
return value
def checkString (value):
"""
Replace specific characters by html codes
"""