Subversion Repositories basico

Rev

Rev 16 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
4 t00mlabs 1
#!/usr/bin/python3
2
# -*- coding: utf-8 -*-
3
# File: basico.py
4
# Author: Tomás Vírseda
5
# License: GPL v3
6
# Description: Main entry point por Basico app
7
import os
74 t00mlabs 8
# -*- coding: utf-8 -*-
4 t00mlabs 9
import sys
74 t00mlabs 10
import codecs
11
sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
4 t00mlabs 12
import traceback as tb
13
import imp
14
import signal
74 t00mlabs 15
from pprint import pprint
4 t00mlabs 16
from os.path import abspath, sep as SEP
17
from configparser import SafeConfigParser, ExtendedInterpolation
74 t00mlabs 18
# import urllib.request
4 t00mlabs 19
 
74 t00mlabs 20
import selenium
21
 
16 t00mlabs 22
import gi
23
gi.require_version('Gtk', '3.0')
24
from gi.repository import Gtk
4 t00mlabs 25
 
74 t00mlabs 26
from .utils import Utils
4 t00mlabs 27
from .log import get_logger
28
from .gui import GUI
29
from .iconmanager import IconManager
30
from .sap import SAP
31
from .settings import Settings
32
from .uifuncs import UIFuncs
33
from .menus import Menus
34
from .projects import Projects
35
from .tasks import Tasks
36
from .plugins import Plugins
37
from .callbacks import Callback
38
from .notify import Notification
74 t00mlabs 39
#from .stats import Stats
40
from .database import Database
41
from .driver import SeleniumDriver
4 t00mlabs 42
from .env import ROOT, APP, LPATH, GPATH, FILE
43
 
44
 
45
class Basico:
46
    def __init__(self):
47
        """Main class: the entry point for Basico.
48
        It stands for Controller.
49
        """
74 t00mlabs 50
 
51
        # Create local paths if they do not exist
52
        for entry in LPATH:
53
            if not os.path.exists(LPATH[entry]):
54
                os.makedirs(LPATH[entry])
55
 
56
 
4 t00mlabs 57
        self.log = get_logger(self.__class__.__name__, FILE['LOG'])
74 t00mlabs 58
        #~ self.log.info("Starting Basico")
59
 
4 t00mlabs 60
        self.services = {}
61
        try:
62
            services = {
63
                'GUI'       :   GUI(),
74 t00mlabs 64
                'Utils'     :   Utils(),
4 t00mlabs 65
                'UIF'       :   UIFuncs(),
66
                'Menus'     :   Menus(),
67
                'SAP'       :   SAP(),
68
                'Settings'  :   Settings(),
69
                'Notify'    :   Notification(),
70
                'Tasks'     :   Tasks(),
71
                'IM'        :   IconManager(),
72
                'Plugins'   :   Plugins(),
73
                'Callbacks' :   Callback(),
74 t00mlabs 74
                #'Stats'     :   Stats(),
75
                'DB'        :   Database(),
76
                'Driver'    :   SeleniumDriver()
4 t00mlabs 77
            }
78
            self.register_services(services)
79
        except Exception as error:
80
            self.log.error(error)
81
            raise
82
 
83
 
74 t00mlabs 84
    def setup(self):
85
        """
86
        Setup Basico Envrionment
87
        Info about ConfigParser options:
88
        https://docs.python.org/3/library/configparser.html#interpolation-of-values
89
        https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.optionxform
90
        """
91
        self.log.debug("Setting up Basico environment")
92
        self.log.debug("Global path: %s" % GPATH['ROOT'])
93
        self.log.debug("Local path: %s" % LPATH['ROOT'])
4 t00mlabs 94
 
95
        # Set up config
96
        CONFIG_FILE = self.get_file('CNF')
97
        self.config = SafeConfigParser(interpolation=ExtendedInterpolation())
98
        self.config.optionxform = str
99
 
100
        # Save config
101
        if not os.path.exists(CONFIG_FILE):
102
            self.log.debug('Configuration file not found. Creating a new one')
103
            with open(CONFIG_FILE, 'w') as configfile:
104
                self.config.write(configfile)
105
            self.log.info('Config file initialited')
106
 
107
 
108
    def get_config(self):
109
        CONFIG_FILE = self.get_file('CNF')
110
        self.config.read(CONFIG_FILE)
111
 
112
        return self.config
113
 
114
 
115
    def get_file(self, name):
116
        try:
117
            return FILE[name]
118
        except:
119
            self.log.error(self.get_traceback())
120
 
121
 
122
    def get_app_info(self, var):
123
        try:
124
            return APP[var]
125
        except:
126
            return None
127
 
128
 
129
    def get_var(self, name, scope='global'):
130
        if scope == 'global':
131
            return GPATH[name]
132
        else:
133
            return LPATH[name]
134
 
135
 
136
    def list_services(self):
137
        """Return a dictionary of services"""
138
        return self.services
139
 
140
 
141
    def get_service(self, name):
142
        """Get/Start a registered service
143
        @type name: name of the service
144
        @param name: given a service name it returns the associated
145
        class. If service was not running it is started.
146
        """
147
        try:
148
            service = self.services[name]
149
            if service.is_started():
150
                return service
151
            else:
152
                service.start(self, name)
153
                return service
154
        except KeyError as service:
155
            self.log.error("Service %s not registered or not found" % service)
156
            raise
157
 
74 t00mlabs 158
 
4 t00mlabs 159
    def register_services(self, services):
160
        """Register a list of services
161
        @type services: dict
162
        @param services: a dictionary of name:class for each service
163
        """
164
        for name in services:
165
            self.register_service(name, services[name])
166
 
167
 
168
    def register_service(self, name, service):
169
        """Register a new service
170
        @type name: string
171
        @param name: name of the service
172
        @type service: class
173
        @param service: class which contains the code
174
        """
175
        try:
176
            self.services[name] = service
177
        except Exception as error:
178
            self.log.error(error)
179
 
180
 
181
    def deregister_service(self, name):
182
        """Deregister a running service
183
        @type name: string
184
        @param name: name of the service
185
        """
186
        self.services[name].end()
187
        self.services[name] = None
74 t00mlabs 188
        self.log.debug("Service %s stopped" % name)
4 t00mlabs 189
 
190
 
16 t00mlabs 191
    def check_gtk_version(self):
192
        vmajor = Gtk.get_major_version()
193
        vminor = Gtk.get_minor_version()
194
        vmicro = Gtk.get_micro_version()
195
        self.log.info("Found GTK+ Version: %d.%d.%d" % (vmajor, vminor, vmicro))
196
 
197
        if vmajor == 3 and vminor >= 18:
198
            return True
199
        else:
200
            return False
201
 
4 t00mlabs 202
    def check(self):
74 t00mlabs 203
        '''
204
        Check Basico environment
205
        '''
206
        utils = self.get_service("Utils")
207
        uif = self.get_service('UIF')
208
        driver = self.get_service('Driver')
4 t00mlabs 209
 
74 t00mlabs 210
        # Show Selenium version
211
        self.log.debug("Selenium version: %s" % selenium.__version__)
212
 
213
        # Check proper GTK version
214
        GTK_VERSION = uif.check_gtk_version()
215
 
216
        # Check Gecko webdrver
217
        GECKO_DRIVER = driver.check()
218
 
219
        run = GTK_VERSION and GECKO_DRIVER
220
 
221
        if run:
222
            self.log.info("Basico environment ready!")
223
            return True
16 t00mlabs 224
        else:
74 t00mlabs 225
            self.log.error("Error(s) found checking Basico environment")
226
            return False
4 t00mlabs 227
 
16 t00mlabs 228
 
229
 
74 t00mlabs 230
 
4 t00mlabs 231
    def stop(self):
232
        """For each service registered, it executes the 'end' method
233
        (if any) to finalize them properly.
234
        """
235
 
236
        # Deregister all services loaded
237
        self.deregister_service('GUI')
238
        for name in self.services:
239
            try:
74 t00mlabs 240
                if name != 'GUI':
241
                    self.deregister_service(name)
242
            except Exception as error:
243
                self.log.error(self.get_traceback())
244
                raise
245
 
4 t00mlabs 246
        self.log.info("Basico finished")
247
 
248
 
249
    def get_traceback(self):
250
        return tb.format_exc()
251
 
252
 
253
    def run(self):
254
        try:
255
            self.gui = self.get_service('GUI')
256
            self.gui.run()
257
        except:
258
            self.log.error(self.get_traceback())
259
 
260
 
261
def main():
262
    #DOC: http://stackoverflow.com/questions/16410852/keyboard-interrupt-with-with-python-gtk
263
    signal.signal(signal.SIGINT, signal.SIG_DFL)
264
    basico = Basico()
74 t00mlabs 265
    basico.setup()
266
    ok = basico.check()
267
    if ok:
4 t00mlabs 268
        basico.run()
269
    sys.exit(0)