ya2 · news · projects · code · about

more cleaning
[pmachines.git] / ya2 / engine / log.py
CommitLineData
8ee66edd
FC
1from logging import basicConfig, info, INFO, DEBUG, getLogger
2from configparser import ConfigParser
3from sys import platform, argv
8ce16d6c
FC
4from platform import system
5from pathlib import Path
6from glob import glob
8ee66edd
FC
7from json import load, dumps
8#from datetime import datetime
9from pprint import pprint
10from os import getcwd, environ
8ce16d6c 11from os.path import exists, dirname
8ee66edd
FC
12from traceback import print_stack
13from sys import version_info
14# from platform import system, release, architecture, platform, processor, \
15# version, machine
16# from multiprocessing import cpu_count
8ce16d6c
FC
17from panda3d.core import Filename, GraphicsWindow, PandaSystem
18from panda3d.bullet import get_bullet_version
53ddf3c3 19from ya2.gameobject import Colleague
b3bd2e45 20from ya2.lib.p3d.p3d import LibP3d
8ce16d6c 21import sys
8ee66edd
FC
22
23
24lev = INFO
25opt_path = ''
26if platform in ['win32', 'linux'] and not exists('main.py'):
27 # it is the deployed version for windows
8ce16d6c 28 opt_path = str(Filename.get_user_appdata_directory()) + '/pmachines'
8ee66edd
FC
29opath = LibP3d.fixpath(opt_path + '/options.ini') if opt_path else \
30 'options.ini'
31if exists(opath):
32 with open(opath) as json_file:
33 #optfile = load(json_file)
34 optfile = ConfigParser()
35 optfile.read(opath)
36 # optfile['development']['verbose'] and int(optfile['development']['verbose']) or \
37 if optfile['development']['verbose_log'] and int(optfile['development']['verbose_log']):
38 lev = DEBUG
39
40basicConfig(level=lev, format='%(asctime)s %(message)s', datefmt='%H:%M:%S')
41getLogger().setLevel(lev) # it doesn't work otherwise
42
43
44class LogMgrBase(Colleague): # headless log manager
45
46 @staticmethod
47 def init_cls():
48 return LogMgr if base.win else LogMgrBase
49
50 def __init__(self, mediator):
51 Colleague.__init__(self, mediator)
52 self.log_cfg()
53
54 def log(self, msg, verbose=False):
55 if verbose and not self.eng.cfg.dev_cfg.verbose_log: return
56 info(msg)
57
8ce16d6c
FC
58 @property
59 def is_appimage(self):
60 par_path = str(Path(__file__).parent.absolute())
61 is_appimage = par_path.startswith('/tmp/.mount_Pmachi')
62 return is_appimage and par_path.endswith('/usr/bin')
63
dd32d640
FC
64 # @property
65 # def curr_path(self):
66 # # this is different from the music's one since it does not work
67 # # with the version in windows
68 # if sys.platform == 'darwin':
69 # return dirname(__file__) + '/../Resources/'
70 # # return dirname(__file__)
71 # par_path = str(Path(__file__).parent.absolute())
72 # if self.is_appimage:
73 # return str(Path(par_path).absolute())
74 # is_snap = par_path.startswith('/snap/')
75 # is_snap = is_snap and par_path.endswith('/x1')
76 # if is_snap:
77 # return str(Path(par_path).absolute())
78 # #return getcwd()
79 # #curr_path = dirname(__file__)
80 # curr_path = str(Path(__file__).parent.parent.parent.absolute())
81 # info('current path: %s' % curr_path)
82 # return curr_path
83
8ce16d6c
FC
84 @property
85 def curr_path(self):
dd32d640
FC
86 if system() == 'Windows':
87 return ''
88 if exists('main.py'):
89 return ''
90 else:
91 par_path = str(Path(__file__).parent.absolute())
8ce16d6c 92 if self.is_appimage:
dd32d640
FC
93 par_path = str(Path(par_path).absolute())
94 par_path += '/'
95 return par_path
8ce16d6c
FC
96
97 @property
98 def build_version(self):
99 appimg_mnt = glob('/tmp/.mount_Pmachi*')
100 if appimg_mnt:
101 #with open(appimg_mnt[0] + '/usr/bin/appimage_version.txt') as fver:
dd32d640 102 with open(self.curr_path + 'assets/bld_version.txt') as fver:
8ce16d6c
FC
103 return fver.read().strip()
104 try:
dd32d640 105 with open(self.curr_path + 'assets/bld_version.txt') as fver:
8ce16d6c
FC
106 return fver.read().strip()
107 except FileNotFoundError:
dd32d640 108 info('not found ' + self.curr_path + 'assets/bld_version.txt')
8ce16d6c
FC
109 return 'notfound'
110
8ee66edd
FC
111 def log_cfg(self):
112 if '--version' in argv:
113 path = str(Filename.get_user_appdata_directory())
114 home = '/home/flavio' # we must force this for wine
115 if path.startswith('/c/users/') and exists(home + '/.wine/'):
116 path = home + '/.wine/drive_' + path[1:]
8ce16d6c
FC
117 info('writing %s' % path + '/pmachines/obs_version.txt')
118 with open(path + '/pmachines/obs_version.txt', 'w') as f:
119 #f.write(self.eng.logic.version)
120 f.write(self.build_version)
8ee66edd
FC
121 if not platform.startswith('win'):
122 from os import ttyname # here because it doesn't work on windows
123 import sys
baf27697
FC
124 try:
125 with open(ttyname(0), 'w') as fout:
126 sys.stdout = fout
127 print('version: ' + self.build_version) # self.eng.logic.version)
128 except OSError: # it doesn't work with crontab
129 print('version: ' + self.build_version)
8ce16d6c 130 messages = ['version: ' + self.build_version] # self.eng.logic.version]
8ee66edd
FC
131 messages += ['argv[0]: %s' % argv[0]]
132 messages += ['getcwd: %s' % getcwd()]
133 messages += ['__file__: %s' % __file__]
134 for elm in environ.items():
135 messages += ['env::%s: %s' % elm]
136 # os_info = (system(), release(), version())
137 # messages += ['operative system: %s %s %s' % os_info]
138 # messages += ['architecture: ' + str(architecture())]
139 # messages += ['machine: ' + machine()]
140 # messages += ['platform: ' + platform()]
141 # messages += ['processor: ' + processor()]
142 # try:
143 # messages += ['cores: ' + str(cpu_count())]
144 # except NotImplementedError: # on Windows
145 # messages += ['cores: not implemented']
8ce16d6c 146 lib_ver = PandaSystem.get_version_string()
8ee66edd
FC
147 try:
148 import psutil
149 mem = psutil.virtual_memory().total / 1000000000.0
150 messages += ['memory: %s GB' % round(mem, 2)]
151 except ImportError: info("can't import psutil") # windows
8ce16d6c 152 lib_commit = PandaSystem.get_git_commit()
8ee66edd
FC
153 py_ver = [str(elm) for elm in version_info[:3]]
154 messages += ['python version: %s' % '.'.join(py_ver)]
155 messages += ['panda version: %s %s' % (lib_ver, lib_commit)]
8ce16d6c
FC
156 messages += ['bullet version: ' + str(get_bullet_version())]
157 messages += ['appdata: ' + str(Filename.get_user_appdata_directory())]
8ee66edd
FC
158 if base.win and isinstance(base.win, GraphicsWindow): # not headless
159 print(base.win.get_keyboard_map())
160 list(map(self.log, messages))
161
162 @staticmethod
163 def log_tasks():
164 info('tasks: %s' % taskMgr.getAllTasks())
165 info('do-laters: %s' % taskMgr.getDoLaters())
166
167 @staticmethod
168 def plog(obj):
169 print('\n\n')
170 print_stack()
171 pprint(obj)
172 print('\n\n')
173
174
175class LogMgr(LogMgrBase):
176
177 def log_cfg(self):
178 LogMgrBase.log_cfg(self)
8ce16d6c
FC
179 messages = [base.win.get_gsg().get_driver_vendor()]
180 messages += [base.win.get_gsg().get_driver_renderer()]
181 shad_maj = base.win.get_gsg().get_driver_shader_version_major()
182 shad_min = base.win.get_gsg().get_driver_shader_version_minor()
8ee66edd 183 messages += ['shader: {maj}.{min}'.format(maj=shad_maj, min=shad_min)]
8ce16d6c
FC
184 messages += [base.win.get_gsg().get_driver_version()]
185 drv_maj = base.win.get_gsg().get_driver_version_major()
186 drv_min = base.win.get_gsg().get_driver_version_minor()
8ee66edd
FC
187 drv = 'driver version: {maj}.{min}'
188 messages += [drv.format(maj=drv_maj, min=drv_min)]
8ce16d6c
FC
189 fullscreen = None
190 if isinstance(base.win, GraphicsWindow):
191 fullscreen = base.win.get_properties().get_fullscreen()
192 messages += ['fullscreen: ' + str(fullscreen)]
193 def resolution():
194 if not isinstance(base.win, GraphicsWindow):
195 return 800, 600
196 win_prop = base.win.get_properties()
197 return win_prop.get_x_size(), win_prop.get_y_size()
198 res_x, res_y = resolution()
8ee66edd
FC
199 res_tmpl = 'resolution: {res_x}x{res_y}'
200 messages += [res_tmpl.format(res_x=res_x, res_y=res_y)]
201 list(map(self.log, messages))