ya2 · news · projects · code · about

a5d7ea66f9770f19d1c1992e9df54eee327b7335
[pmachines.git] / lib / engine / log.py
1 from logging import basicConfig, info, INFO, DEBUG, getLogger
2 from configparser import ConfigParser
3 from sys import platform, argv
4 from platform import system
5 from pathlib import Path
6 from glob import glob
7 from json import load, dumps
8 #from datetime import datetime
9 from pprint import pprint
10 from os import getcwd, environ
11 from os.path import exists, dirname
12 from traceback import print_stack
13 from sys import version_info
14 # from platform import system, release, architecture, platform, processor, \
15 # version, machine
16 # from multiprocessing import cpu_count
17 from panda3d.core import Filename, GraphicsWindow, PandaSystem
18 from panda3d.bullet import get_bullet_version
19 from lib.gameobject import Colleague
20 from lib.lib.builder import LibP3d
21 import sys
22
23
24 lev = INFO
25 opt_path = ''
26 if platform in ['win32', 'linux'] and not exists('main.py'):
27 # it is the deployed version for windows
28 opt_path = str(Filename.get_user_appdata_directory()) + '/pmachines'
29 opath = LibP3d.fixpath(opt_path + '/options.ini') if opt_path else \
30 'options.ini'
31 if 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
40 basicConfig(level=lev, format='%(asctime)s %(message)s', datefmt='%H:%M:%S')
41 getLogger().setLevel(lev) # it doesn't work otherwise
42
43
44 class 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
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
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 info('current path: %s' % curr_path)
81 return curr_path
82
83 @property
84 def build_version(self):
85 appimg_mnt = glob('/tmp/.mount_Pmachi*')
86 if appimg_mnt:
87 #with open(appimg_mnt[0] + '/usr/bin/appimage_version.txt') as fver:
88 with open(self.curr_path + '/assets/bld_version.txt') as fver:
89 return fver.read().strip()
90 try:
91 with open(self.curr_path + '/assets/bld_version.txt') as fver:
92 return fver.read().strip()
93 except FileNotFoundError:
94 info('not found ' + self.curr_path + '/assets/bld_version.txt')
95 return 'notfound'
96
97 def log_cfg(self):
98 if '--version' in argv:
99 path = str(Filename.get_user_appdata_directory())
100 home = '/home/flavio' # we must force this for wine
101 if path.startswith('/c/users/') and exists(home + '/.wine/'):
102 path = home + '/.wine/drive_' + path[1:]
103 info('writing %s' % path + '/pmachines/obs_version.txt')
104 with open(path + '/pmachines/obs_version.txt', 'w') as f:
105 #f.write(self.eng.logic.version)
106 f.write(self.build_version)
107 if not platform.startswith('win'):
108 from os import ttyname # here because it doesn't work on windows
109 import sys
110 with open(ttyname(0), 'w') as fout:
111 sys.stdout = fout
112 print('version: ' + self.build_version) # self.eng.logic.version)
113 messages = ['version: ' + self.build_version] # self.eng.logic.version]
114 messages += ['argv[0]: %s' % argv[0]]
115 messages += ['getcwd: %s' % getcwd()]
116 messages += ['__file__: %s' % __file__]
117 for elm in environ.items():
118 messages += ['env::%s: %s' % elm]
119 # os_info = (system(), release(), version())
120 # messages += ['operative system: %s %s %s' % os_info]
121 # messages += ['architecture: ' + str(architecture())]
122 # messages += ['machine: ' + machine()]
123 # messages += ['platform: ' + platform()]
124 # messages += ['processor: ' + processor()]
125 # try:
126 # messages += ['cores: ' + str(cpu_count())]
127 # except NotImplementedError: # on Windows
128 # messages += ['cores: not implemented']
129 lib_ver = PandaSystem.get_version_string()
130 try:
131 import psutil
132 mem = psutil.virtual_memory().total / 1000000000.0
133 messages += ['memory: %s GB' % round(mem, 2)]
134 except ImportError: info("can't import psutil") # windows
135 lib_commit = PandaSystem.get_git_commit()
136 py_ver = [str(elm) for elm in version_info[:3]]
137 messages += ['python version: %s' % '.'.join(py_ver)]
138 messages += ['panda version: %s %s' % (lib_ver, lib_commit)]
139 messages += ['bullet version: ' + str(get_bullet_version())]
140 messages += ['appdata: ' + str(Filename.get_user_appdata_directory())]
141 if base.win and isinstance(base.win, GraphicsWindow): # not headless
142 print(base.win.get_keyboard_map())
143 list(map(self.log, messages))
144
145 @staticmethod
146 def log_tasks():
147 info('tasks: %s' % taskMgr.getAllTasks())
148 info('do-laters: %s' % taskMgr.getDoLaters())
149
150 @staticmethod
151 def plog(obj):
152 print('\n\n')
153 print_stack()
154 pprint(obj)
155 print('\n\n')
156
157
158 class LogMgr(LogMgrBase):
159
160 def log_cfg(self):
161 LogMgrBase.log_cfg(self)
162 messages = [base.win.get_gsg().get_driver_vendor()]
163 messages += [base.win.get_gsg().get_driver_renderer()]
164 shad_maj = base.win.get_gsg().get_driver_shader_version_major()
165 shad_min = base.win.get_gsg().get_driver_shader_version_minor()
166 messages += ['shader: {maj}.{min}'.format(maj=shad_maj, min=shad_min)]
167 messages += [base.win.get_gsg().get_driver_version()]
168 drv_maj = base.win.get_gsg().get_driver_version_major()
169 drv_min = base.win.get_gsg().get_driver_version_minor()
170 drv = 'driver version: {maj}.{min}'
171 messages += [drv.format(maj=drv_maj, min=drv_min)]
172 fullscreen = None
173 if isinstance(base.win, GraphicsWindow):
174 fullscreen = base.win.get_properties().get_fullscreen()
175 messages += ['fullscreen: ' + str(fullscreen)]
176 def resolution():
177 if not isinstance(base.win, GraphicsWindow):
178 return 800, 600
179 win_prop = base.win.get_properties()
180 return win_prop.get_x_size(), win_prop.get_y_size()
181 res_x, res_y = resolution()
182 res_tmpl = 'resolution: {res_x}x{res_y}'
183 messages += [res_tmpl.format(res_x=res_x, res_y=res_y)]
184 list(map(self.log, messages))