Browse Source

Fixed debug log

sisyphus
JezerM 4 years ago
parent
commit
175c927e6b
  1. 21
      web-greeter/bridge/Greeter.py
  2. 66
      web-greeter/bridge/__init__.py
  3. 20
      web-greeter/globals.py
  4. 6
      web-greeter/greeter.py
  5. 21
      web-greeter/utils/errorPrompt.py
  6. 43
      web-greeter/utils/keyboard.py

21
web-greeter/bridge/Greeter.py

@ -43,12 +43,13 @@ from PyQt5.QtCore import QTimer
# This Application # This Application
from . import ( from . import (
Battery,
language_to_dict, language_to_dict,
layout_to_dict, layout_to_dict,
session_to_dict, session_to_dict,
user_to_dict, user_to_dict,
battery_to_dict, battery_to_dict,
debugLog logger
) )
LightDMGreeter = LightDM.Greeter() LightDMGreeter = LightDM.Greeter()
@ -63,7 +64,7 @@ def changeBrightness(self, method: str, quantity: int):
if child.returncode == 1: if child.returncode == 1:
raise ChildProcessError("xbacklight returned 1") raise ChildProcessError("xbacklight returned 1")
except Exception as err: except Exception as err:
debugLog("Brightness: {}".format(err), 4) logger.error("Brightness: {}".format(err))
else: else:
self.brightness_update.emit() self.brightness_update.emit()
pass pass
@ -75,7 +76,7 @@ def getBrightness(self):
level = subprocess.run(["xbacklight", "-get"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) level = subprocess.run(["xbacklight", "-get"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
return int(level.stdout) return int(level.stdout)
except Exception as err: except Exception as err:
debugLog("Battery: {}".format(err), 4) logger.error("Brightness: {}".format(err))
return -1 return -1
def updateBattery(self): def updateBattery(self):
@ -84,14 +85,9 @@ def updateBattery(self):
try: try:
acpi = subprocess.run(["acpi", "-b"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) acpi = subprocess.run(["acpi", "-b"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
battery = acpi.stdout.split(": ") self._battery.update(acpi.stdout)
data = re.sub("%|,", "", battery[1])
level = data.split(" ")[1]
self._battery = int(level)
self._acpi = acpi.stdout
except Exception as err: except Exception as err:
debugLog("Battery: {}".format(err), 4) logger.error("Battery: {}".format(err))
else: else:
self.property_changed.emit() self.property_changed.emit()
@ -110,8 +106,7 @@ class Greeter(BridgeObject):
noop_signal = bridge.signal() noop_signal = bridge.signal()
property_changed = bridge.signal() property_changed = bridge.signal()
_battery = -1 _battery = Battery()
_acpi = ""
def __init__(self, config, *args, **kwargs): def __init__(self, config, *args, **kwargs):
super().__init__(name='LightDMGreeter', *args, **kwargs) super().__init__(name='LightDMGreeter', *args, **kwargs)
@ -175,7 +170,7 @@ class Greeter(BridgeObject):
@bridge.prop(Variant, notify=property_changed) @bridge.prop(Variant, notify=property_changed)
def batteryData(self): def batteryData(self):
return battery_to_dict(self._acpi) return battery_to_dict(self._battery)
@bridge.prop(int, notify=brightness_update) @bridge.prop(int, notify=brightness_update)
def brightness(self): def brightness(self):

66
web-greeter/bridge/__init__.py

@ -27,6 +27,8 @@
# along with Web Greeter; If not, see <http://www.gnu.org/licenses/>. # along with Web Greeter; If not, see <http://www.gnu.org/licenses/>.
import re import re
import threading, time
from logging import ( from logging import (
getLogger, getLogger,
DEBUG, DEBUG,
@ -37,7 +39,7 @@ from logging import (
log_format = ''.join([ log_format = ''.join([
'%(asctime)s [ %(levelname)s ] %(filename)s %(', '%(asctime)s [ %(levelname)s ] %(filename)s %(',
'lineno)d: %(message)s' 'lineno)d : %(funcName)s | %(message)s'
]) ])
formatter = Formatter(fmt=log_format, datefmt="%Y-%m-%d %H:%M:%S") formatter = Formatter(fmt=log_format, datefmt="%Y-%m-%d %H:%M:%S")
logger = getLogger("greeter") logger = getLogger("greeter")
@ -48,18 +50,45 @@ stream_handler.setFormatter(formatter)
logger.setLevel(DEBUG) logger.setLevel(DEBUG)
logger.addHandler(stream_handler) logger.addHandler(stream_handler)
def debugLog(txt: str, level: int = 1): class setInterval:
if (level == 1): def __init__(self, interval, action):
logger.debug(txt) self.interval = interval
elif (level == 2): self.action = action
logger.info(txt) self.stopEvent = threading.Event()
elif (level == 3): thread = threading.Thread(target=self.__setInterval)
logger.warn(txt) thread.start()
elif (level == 4):
logger.error(txt) def __setInterval(self):
else: nextTime = time.time() + self.interval
logger.debug(txt) while not self.stopEvent.wait(nextTime - time.time()):
nextTime += self.interval
self.action()
class Battery:
_name = ""
_level = -1
_state = ""
def __init__(self):
pass
def update(self, acpi: str):
formatted = re.sub("%|,|\n", "", acpi)
colon = formatted.split(": ")
splitted = colon[1].split(" ")
self._name = colon[0]
self._level = int(splitted[1])
self._state = splitted[0]
def get_name(self):
return self._name
def get_level(self):
return self._level
def get_state(self):
return self._state
def language_to_dict(lang): def language_to_dict(lang):
return dict(code=lang.get_code(), name=lang.get_name(), territory=lang.get_territory()) return dict(code=lang.get_code(), name=lang.get_name(), territory=lang.get_territory())
@ -94,16 +123,11 @@ def user_to_dict(user):
username=user.get_name(), username=user.get_name(),
) )
def battery_to_dict(batt): def battery_to_dict(battery):
if batt == "":
return dict()
formatted = re.sub("%|,|\n", "", batt)
colon = formatted.split(": ")
splitted = colon[1].split(" ")
return dict( return dict(
name = colon[0], name = battery.get_name(),
level = int(splitted[1]), level = battery.get_level(),
state = splitted[0] state = battery.get_state()
) )

20
web-greeter/globals.py

@ -78,18 +78,6 @@ logger.propagate = False
logger.setLevel(DEBUG) logger.setLevel(DEBUG)
logger.addHandler(stream_handler) logger.addHandler(stream_handler)
def debugLog(txt: str, level: int = 1):
if (level == 1):
logger.debug(txt)
elif (level == 2):
logger.info(txt)
elif (level == 3):
logger.warn(txt)
elif (level == 4):
logger.error(txt)
else:
logger.debug(txt)
initial_timeout = 0 initial_timeout = 0
def setScreenSaver(timeout: int): def setScreenSaver(timeout: int):
@ -104,17 +92,17 @@ def setScreenSaver(timeout: int):
subprocess.run(["xset", "s", str(timeout)], check=True) subprocess.run(["xset", "s", str(timeout)], check=True)
except Exception as err: except Exception as err:
debugLog("Screensaver timeout couldn't be set", 4) logger.error("Screensaver timeout couldn't be set")
else: else:
debugLog("Screensaver timeout set") logger.debug("Screensaver timeout set")
def resetScreenSaver(): def resetScreenSaver():
try: try:
subprocess.run(["xset", "s", str(initial_timeout)]) subprocess.run(["xset", "s", str(initial_timeout)])
except Exception as err: except Exception as err:
debugLog("Screensaver reset failed", 4) logger.error("Screensaver reset failed")
else: else:
debugLog("Screensaver reset") logger.debug("Screensaver reset")
BASE_DIR = os.path.dirname(os.path.realpath(__file__)) BASE_DIR = os.path.dirname(os.path.realpath(__file__))

6
web-greeter/greeter.py

@ -41,10 +41,10 @@ from typing import (
# 3rd-Party Libs # 3rd-Party Libs
# This Application # This Application
from utils import config from utils import errorPrompt, keyboard
import globals import globals
from globals import WebGreeter from globals import WebGreeter, logger
def loadWhitherConf(): def loadWhitherConf():
global whither_yaml global whither_yaml
@ -101,7 +101,7 @@ def changeTheme(theme: str):
if theme in dirlist: if theme in dirlist:
custom_config["theme"] = theme custom_config["theme"] = theme
else: else:
globals.debugLog("Theme not found. Going with config theme", 4) logger.error("Theme not found. Going with config theme")
return return
def listThemes(quiet = False): def listThemes(quiet = False):

21
web-greeter/utils/config.py → web-greeter/utils/errorPrompt.py

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
# config.py # errorPrompt.py
# #
# Copyright © 2021 JezerM # Copyright © 2021 JezerM
# #
@ -25,11 +25,9 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Web Greeter; If not, see <http://www.gnu.org/licenses/>. # along with Web Greeter; If not, see <http://www.gnu.org/licenses/>.
from whither.toolkits.bootstrap import WebPage, MainWindow from whither.toolkits.bootstrap import WebPage
from PyQt5.QtCore import QUrl, pyqtSignal, Qt from PyQt5.QtWidgets import QDialogButtonBox, QDialog, QVBoxLayout, QLabel, QPushButton
from PyQt5.QtWidgets import QDialogButtonBox, QDialog, QVBoxLayout, QLabel, QPushButton, QAbstractButton
from PyQt5.QtGui import QKeyEvent
from logging import ( from logging import (
getLogger, getLogger,
@ -138,15 +136,4 @@ def errorPrompt(err):
return return
def keyPressEvent(self, keyEvent: QKeyEvent): WebPage.javaScriptConsoleMessage = javaScriptConsoleMessage
super(MainWindow, self).keyPressEvent(keyEvent)
if (keyEvent.key() == Qt.Key.Key_MonBrightnessUp):
globals.greeter.greeter.brightnessIncrease(globals.greeter.config.features.backlight["value"])
if (keyEvent.key() == Qt.Key.Key_MonBrightnessDown):
globals.greeter.greeter.brightnessDecrease(globals.greeter.config.features.backlight["value"])
MainWindow.keyPressEvent = keyPressEvent
WebPage.javaScriptConsoleMessage = javaScriptConsoleMessage # Yep, you can override functions like this!!!

43
web-greeter/utils/keyboard.py

@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
#
# keyboard.py
#
# Copyright © 2021 JezerM
#
# This file is part of Web Greeter.
#
# Web Greeter 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.
#
# Web Greeter 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.
#
# The following additional terms are in effect as per Section 7 of the license:
#
# The preservation of all legal notices and author attributions in
# the material or in the Appropriate Legal Notices displayed
# by works containing it is required.
#
# You should have received a copy of the GNU General Public License
# along with Web Greeter; If not, see <http://www.gnu.org/licenses/>.
from whither.toolkits.bootstrap import WebPage, MainWindow
from PyQt5.QtCore import QUrl, pyqtSignal, Qt
from PyQt5.QtGui import QKeyEvent
def keyPressEvent(self, keyEvent: QKeyEvent):
super(MainWindow, self).keyPressEvent(keyEvent)
if (keyEvent.key() == Qt.Key.Key_MonBrightnessUp):
globals.greeter.greeter.brightnessIncrease(globals.greeter.config.features.backlight["value"])
if (keyEvent.key() == Qt.Key.Key_MonBrightnessDown):
globals.greeter.greeter.brightnessDecrease(globals.greeter.config.features.backlight["value"])
MainWindow.keyPressEvent = keyPressEvent
Loading…
Cancel
Save