-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path__main__.py
288 lines (251 loc) · 10.2 KB
/
__main__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#!/usr/local/bin/python3
# coding: utf-8
"""
You can run this module with ``python3 -m RTOC`` to start RTOC with GUI.
To start a remote-session (in GUI) run ``python3 -m RTOC -r <HOSTNAME>``.
To start an explicit local RTOC GUI (even if database enabled) run ``python3 -m RTOC -l``.
"""
import sys
import os
import json
import getopt
import traceback
import logging as log
log.basicConfig(level=log.INFO)
logging = log.getLogger(__name__)
__package__ = "RTOC"
__main__ = __name__
def main():
"""
An example docstring for a main definition.
"""
opts, args = getopt.getopt(sys.argv[1:], "hlr:", [
"remote="])
if len(opts) == 0:
startRTOC()
else:
for opt, arg in opts:
if opt in ('-p', '--port'):
port = int(arg)
break
else:
port = 5050
for opt, arg in opts:
if opt == '-h':
logging.info(
'RTOC.py [-h] [-r <Remoteadress>]\n -h: Help\n-r (--remote) <Remoteadress>: Websocket client for RTOC server\nFor options without GUI, run "python3 -m RTOC.RTLogger -h"')
sys.exit(0)
elif opt == '-v':
logging.info("3.0")
elif opt in ("-r", "--remote"):
remotepath = arg
startRemoteRTOC(remotepath)
sys.exit(0)
elif opt == '-l':
startRTOC(local =True)
sys.exit(0)
def configureRTOC(arg):
userpath = os.path.expanduser('~/.RTOC')
if os.path.exists(userpath+"/config.json"):
try:
with open(userpath+"/config.json", encoding="UTF-8") as jsonfile:
config = json.load(jsonfile, encoding="UTF-8")
except Exception:
config = {}
logging.debug(traceback.format_exc())
logging.error('Could not load config')
else:
logging.error('No config-file found in ~/.RTOC/\nPlease start RTOC at least once.')
sys.exit(1)
if arg == 'list':
logging.info('This is your current configuration:')
for key in config.keys():
if key not in ['csv_profiles', 'telegram_chat_ids', 'lastSessions', 'grid', 'plotLegendEnabled', 'blinkingIdentifier', 'scriptWidget', 'deviceWidget', 'signalsWidget', 'pluginsWidget', 'eventWidget', 'newSignalSymbols', 'plotLabelsEnabled', 'plotGridEnabled', 'plotLegendEnabled', 'signalStyles', 'plotInverted', 'plotRate', 'xTimeBase', 'timeAxis', 'systemTray', 'documentfolder', 'language']:
logging.info(key+"\t"+str(config[key]))
else:
splitted = arg.split('=')
if len(splitted) != 2:
logging.info(
'Please provide options like this: "python3 -m RTOC -c websocketserver=False\nYour entry didn\'t include a "="')
sys.exit(1)
else:
if splitted[0] not in config.keys():
logging.warning('The config file has no option '+splitted[0])
sys.exit(1)
t = type(config[splitted[0]])
try:
if t != bool:
newValue = t(splitted[1])
elif splitted[1].lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh', 'ja', 'j', 'jupp', 'jawohl']:
newValue = True
else:
newValue = False
oldValue = config[splitted[0]]
config[splitted[0]] = newValue
with open(userpath+"/config.json", 'w', encoding="utf-8") as fp:
json.dump(config, fp, sort_keys=False, indent=4, separators=(',', ': '))
logging.info('Option "'+splitted[0]+'" was changed from "' + str(oldValue)+'" to "'+str(newValue)+'"')
except Exception:
logging.warning('Your entered value "'+splitted[1]+'" is not of the correct type.')
sys.exit(1)
def setStyleSheet(app, myapp):
if os.name == 'posix':
type = 'QDarkStyle'
else:
type = 'QtModern'
if type == 'QtModern':
try:
import qtmodern.styles
import qtmodern.windows
packagedir = os.path.dirname(os.path.realpath(__file__))
with open(packagedir+"/RTOC_GUI/ui/qtmodern.qss", 'r') as myfile:
stylesheet = myfile.read().replace('\n', '')
app.setStyleSheet(stylesheet)
qtmodern.styles.dark(app)
# mw = qtmodern.windows.ModernWindow(myapp)
mw = myapp
return app, mw
except (ImportError, SystemError):
tb = traceback.format_exc()
logging.debug(tb)
logging.warning("QtModern not installed")
type = 'QDarkStyle'
if type == 'QDarkStyle':
try:
import qdarkstyle
dark_stylesheet = qdarkstyle.load_stylesheet_pyqt5()
app.setStyleSheet(dark_stylesheet)
return app, myapp
except (ImportError, SystemError):
tb = traceback.format_exc()
logging.debug(tb)
logging.warning("QtModern not installed")
type == 'qdarkgraystyle'
if type == 'qdarkgraystyle':
try:
import qdarkgraystyle
dark_stylesheet = qdarkgraystyle.load_stylesheet()
app.setStyleSheet(dark_stylesheet)
return app, myapp
except (ImportError, SystemError):
tb = traceback.format_exc()
logging.debug(tb)
logging.warning("QtModern not installed")
packagedir = os.path.dirname(os.path.realpath(__file__))
with open(packagedir+"/RTOC_GUI/ui/darkmode.html", 'r') as myfile:
stylesheet = myfile.read().replace('\n', '')
stylesheet = stylesheet.replace(
'/RTOC_GUI/ui/icons', os.path.join(packagedir, 'data', 'ui', 'icons').replace('\\', '/'))
# stylesheet = stylesheet.replace('/RTOC_GUI/ui/icons','./RTOC_GUI/ui/icons')
app.setStyleSheet(stylesheet)
return app, myapp
# def setLanguage(app):
#
# from PyQt5 import QtCore
# # from PyQt5 import QtWidgets
# userpath = os.path.expanduser('~/.RTOC')
# if os.path.exists(userpath+"/config.json"):
# try:
# with open(userpath+"/config.json", encoding="UTF-8") as jsonfile:
# config = json.load(jsonfile, encoding="UTF-8")
# except Exception:
# logging.debug(traceback.format_exc())
# config = {'global': {'language': 'en'}}
# else:
# config = {'global': {'language': 'en'}}
# if config['global']['language'] == 'en':
# translator = QtCore.QTranslator()
# if getattr(sys, 'frozen', False):
# # frozen
# packagedir = os.path.dirname(sys.executable)
# else:
# # unfrozen
# packagedir = os.path.dirname(os.path.realpath(__file__))
# translator.load(packagedir+"/locales/en_en.qm")
# app.installTranslator(translator)
# import gettext
# el = gettext.translation('base', localedir='locales', languages=['en'])
# el.install()
# _ = el.gettext
# more info here: http://kuanyui.github.io/2014/09/03/pyqt-i18n/
# generate translationfile: % pylupdate5 RTOC.py -ts lang/de_de.ts
# compile translationfile: % lrelease-qt5 lang/de_de.ts
# use self.tr("TEXT TO TRANSLATE") in the code
def startRemoteRTOC(remotepath):
from PyQt5 import QtCore
from PyQt5 import QtWidgets
# try:
from .RTOC import RTOC
app = QtWidgets.QApplication(sys.argv)
from PyQt5 import QtCore
# from PyQt5 import QtWidgets
userpath = os.path.expanduser('~/.RTOC')
if os.path.exists(userpath+"/config.json"):
try:
with open(userpath+"/config.json", encoding="UTF-8") as jsonfile:
config = json.load(jsonfile, encoding="UTF-8")
except Exception:
logging.debug(traceback.format_exc())
config = {'global': {'language': 'en'}}
else:
config = {'global': {'language': 'en'}}
if config['global']['language'] == 'de':
translator = QtCore.QTranslator()
if getattr(sys, 'frozen', False):
# frozen
packagedir = os.path.dirname(sys.executable)
else:
# unfrozen
packagedir = os.path.dirname(os.path.realpath(__file__))
translator.load(packagedir+"/locales/de_de.qm")
app.installTranslator(translator)
# import gettext
# el = gettext.translation('base', localedir='locales', languages=['en'])
# el.install()
# _ = el.gettext
myapp = RTOC(False)
myapp.config['websocket']['active'] = True
app, myapp = setStyleSheet(app, myapp)
logging.info(remotepath)
myapp.show()
myapp.logger.remote.connect(hostname=remotepath, port=5050)
app.exec_()
def startRTOC(websocket=None, port=None, local =False, customConfigPath=None):
from PyQt5 import QtCore
from PyQt5 import QtWidgets
# try:
from .RTOC import RTOC
app = QtWidgets.QApplication(sys.argv)
from PyQt5 import QtCore
# from PyQt5 import QtWidgets
userpath = os.path.expanduser('~/.RTOC')
if os.path.exists(userpath+"/config.json"):
try:
with open(userpath+"/config.json", encoding="UTF-8") as jsonfile:
config = json.load(jsonfile, encoding="UTF-8")
except Exception:
logging.debug(traceback.format_exc())
config = {'global': {'language': 'en'}}
else:
config = {'global': {'language': 'en'}}
if config['global']['language'] == 'de':
translator = QtCore.QTranslator()
if getattr(sys, 'frozen', False):
# frozen
packagedir = os.path.dirname(sys.executable)
else:
# unfrozen
packagedir = os.path.dirname(os.path.realpath(__file__))
translator.load(packagedir+"/locales/de_de.qm")
app.installTranslator(translator)
# import gettext
# el = gettext.translation('base', localedir='locales', languages=['en'])
# el.install()
# _ = el.gettext
myapp = RTOC(websocket, port, local, customConfigPath=customConfigPath)
app, myapp = setStyleSheet(app, myapp)
myapp.show()
app.exec_()
if __name__ == '__main__':
main()
sys.exit()