-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.py
More file actions
428 lines (354 loc) · 12.5 KB
/
Utils.py
File metadata and controls
428 lines (354 loc) · 12.5 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# -*- coding: ascii -*-
# $Id$
#
# Author: [email protected]
# Date: 16-Apr-2015
from __future__ import absolute_import
from __future__ import print_function
__author__ = "Vasilis Vlachoudis"
__email__ = "[email protected]"
import os
import sys
import hashlib
import glob
import traceback
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
import gettext
try:
import __builtin__
except:
import builtins as __builtin__
#__builtin__.unicode = str # dirty hack for python3
try:
import serial
except:
serial = None
from datetime import datetime
__prg__ = "bCNC"
__tool__ = "TOOL"
prgpath = os.path.abspath(os.path.dirname(sys.argv[0]))
iniSystem = os.path.join(prgpath,"%s.ini"%(__prg__))
iniUser = os.path.expanduser("~/.%s" % (__prg__))
hisFile = os.path.expanduser("~/.%s.history" % (__prg__))
iniTool = os.path.expanduser("~/.%s" % (__tool__))
# dirty way of substituting the "_" on the builtin namespace
#__builtin__.__dict__["_"] = gettext.translation('bCNC', 'locale', fallback=True).ugettext
__builtin__._ = gettext.translation('bCNC', os.path.join(prgpath,'locale'), fallback=True).gettext
__builtin__.N_ = lambda message: message
icons = {}
images = {}
config = ConfigParser.ConfigParser()
toolconfig = ConfigParser.ConfigParser()
print("new-config", __name__, config) #This is here to debug the fact that config is sometimes instantiated twice
language = ""
_errorReport = True
errors = []
_maxRecent = 10
_FONT_SECTION = "Font"
#New class to provide config for everyone
#FIXME: create single instance of this and pass it to all parts of application
class Config():
def greet(self, who=__name__):
print("Config class loaded in %s"%(who))
#------------------------------------------------------------------------------
# Load configuration
#------------------------------------------------------------------------------
def loadConfiguration(systemOnly=False):
global config, _errorReport, language
if systemOnly:
config.read(iniSystem)
else:
config.read([iniSystem, iniUser])
_errorReport = getInt("Connection","errorreport",1)
language = getStr(__prg__, "language")
if language:
# replace language
__builtin__._ = gettext.translation('bCNC', os.path.join(prgpath,'locale'),
fallback=True, languages=[language]).gettext
#------------------------------------------------------------------------------
# Save configuration file
#------------------------------------------------------------------------------
def saveConfiguration():
global config
cleanConfiguration()
f = open(iniUser,"w")
config.write(f)
f.close()
#----------------------------------------------------------------------
# Remove items that are the same as in the default ini
#----------------------------------------------------------------------
def cleanConfiguration():
global config
newconfig = config # Remember config
config = ConfigParser.ConfigParser()
loadConfiguration(True)
# Compare items
for section in config.sections():
for item, value in config.items(section):
try:
new = newconfig.get(section, item)
if value==new:
newconfig.remove_option(section, item)
except ConfigParser.NoOptionError:
pass
config = newconfig
#------------------------------------------------------------------------------
# Load tool config
#------------------------------------------------------------------------------
def loadToolConfig():
global toolconfig
toolconfig.read(iniTool)
#------------------------------------------------------------------------------
# Save tool config
#------------------------------------------------------------------------------
def saveToolConfig():
global toolconfig
f = open(iniTool, "w")
toolconfig.write(f)
f.close()
#------------------------------------------------------------------------------
# add section if it doesn't exist
#------------------------------------------------------------------------------
def addSection(section):
global config
if not config.has_section(section):
config.add_section(section)
#------------------------------------------------------------------------------
def getStr(section, name, default=""):
global config
try:
return config.get(section, name)
except:
return default
#------------------------------------------------------------------------------
def getUtf(section, name, default=""):
global config
try:
return config.get(section, name).decode("utf8")
except:
return default
#------------------------------------------------------------------------------
def getInt(section, name, default=0):
global config
try: return int(config.get(section, name))
except: return default
#------------------------------------------------------------------------------
def getFloat(section, name, default=0.0):
global config
try: return float(config.get(section, name))
except: return default
#------------------------------------------------------------------------------
def getBool(section, name, default=False):
global config
try: return bool(int(config.get(section, name)))
except: return default
#------------------------------------------------------------------------------
def getToolInt(section, name, default=0):
global toolconfig
try: return int(toolconfig.get(section, name))
except: return default
#------------------------------------------------------------------------------
def getToolFloat(section, name, default=0.0):
global toolconfig
try: return float(toolconfig.get(section, name))
except: return default
#------------------------------------------------------------------------------
def setToolStr(section, name, value):
global toolconfig
if not toolconfig.has_section(section):
toolconfig.add_section(section)
toolconfig.set(section, name, str(value))
#-------------------------------------------------------------------------------
# Set font in configuration
#-------------------------------------------------------------------------------
def setFont(name, font):
if font is None: return
if isinstance(font,str):
config.set(_FONT_SECTION, name, font)
elif isinstance(font,tuple):
config.set(_FONT_SECTION, name, ",".join(map(str,font)))
else:
config.set(_FONT_SECTION, name, "%s,%s,%s" % \
(font.cget("family"),font.cget("size"),font.cget("weight")))
#------------------------------------------------------------------------------
def setBool(section, name, value):
global config
config.set(section, name, str(int(value)))
#------------------------------------------------------------------------------
def setStr(section, name, value):
global config
config.set(section, name, str(value))
#------------------------------------------------------------------------------
def setUtf(section, name, value):
global config
try:
s = str(value.encode("utf8"))
except:
s = str(value)
config.set(section, name, s)
setInt = setStr
setFloat = setStr
#-------------------------------------------------------------------------------
# Add Recent
#-------------------------------------------------------------------------------
def addRecent(filename):
try:
sfn = str(os.path.abspath(filename))
except UnicodeEncodeError:
sfn = filename.encode("utf8")
last = _maxRecent-1
for i in range(_maxRecent):
rfn = getRecent(i)
if rfn is None:
last = i-1
break
if rfn == sfn:
if i==0: return
last = i-1
break
# Shift everything by one
for i in range(last, -1, -1):
config.set("File", "recent.%d"%(i+1), getRecent(i))
config.set("File", "recent.0", sfn)
#-------------------------------------------------------------------------------
def getRecent(recent):
try:
return config.get("File","recent.%d"%(recent))
except ConfigParser.NoOptionError:
return None
#------------------------------------------------------------------------------
# Return all comports when serial.tools.list_ports is not available!
#------------------------------------------------------------------------------
def comports(include_links=True):
locations=[ '/dev/ttyACM',
'/dev/ttyUSB',
'/dev/ttyS',
'com']
comports = []
for prefix in locations:
for i in range(32):
device = "%s%d"%(prefix,i)
try:
os.stat(device)
comports.append((device,None,None))
except OSError:
pass
# Detects windows XP serial ports
try:
s = serial.Serial(device)
s.close()
comports.append((device,None,None))
except:
pass
return comports
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
#------------------------------------------------------------------------------
# Return readable size string
#------------------------------------------------------------------------------
def humansize(nbytes):
nbytes = int(nbytes)
i = 0
while nbytes >= 1024 and i < len(suffixes)-1:
nbytes /= 1024.
i += 1
f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
return '%s %s' % (f, suffixes[i])
#------------------------------------------------------------------------------
# Return readable date string
#------------------------------------------------------------------------------
def humandate(date):
return datetime.fromtimestamp(date).strftime("%Y-%m-%d %H:%M")
#------------------------------------------------------------------------------
# Return hours, minutes, seconds from seconds
#------------------------------------------------------------------------------
def second2hour(seconds):
total_seconds = int(seconds)
hour = total_seconds // 3600
total_seconds = total_seconds % 3600
minute = total_seconds // 60
total_seconds = total_seconds % 60
second = total_seconds
ret_value = str(second) + 's'
if minute > 0:
ret_value = str(minute) + 'm' + ret_value
if hour > 0:
ret_value = str(hour) + 'h' + ret_value
return ret_value
#------------------------------------------------------------------------------
# Return md5 of a file
#------------------------------------------------------------------------------
def md5(filename):
hash_md5 = hashlib.md5()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
#------------------------------------------------------------------------------
# Return float array
#------------------------------------------------------------------------------
def xfrange(start, stop, steps):
if steps <= 1:
return
interval = (stop - start) / (steps - 1)
i = 0
if interval == 0:
for i in range(steps):
yield start
else:
while start + i * interval <= stop:
yield start + i * interval
i += 1
#------------------------------------------------------------------------------
# Return float array
#------------------------------------------------------------------------------
def translate(value, leftMin, leftMax, rightMin, rightMax):
# Figure out how 'wide' each range is
leftSpan = leftMax - leftMin
rightSpan = rightMax - rightMin
# Convert the left range into a 0-1 range (float)
valueScaled = float(value - leftMin) / float(leftSpan)
# Convert the 0-1 range into a value in the right range.
return rightMin + (valueScaled * rightSpan)
#------------------------------------------------------------------------------
# convert from config string
#------------------------------------------------------------------------------
def from_config(type, value_string):
if type == 'bool':
if value_string.lower() == "true":
return 1
else:
return 0
elif type == 'numeric':
return float(value_string)
else:
return value_string
#------------------------------------------------------------------------------
# convert from config string to panel value
#------------------------------------------------------------------------------
def from_config(type, value_string):
if type == 'bool':
if value_string.lower() == "true":
return 1
else:
return 0
elif type == 'numeric':
return float(value_string)
else:
return value_string
#------------------------------------------------------------------------------
# convert from config string
#------------------------------------------------------------------------------
def to_config(type, value_string):
if type == 'bool':
if value_string.lower() == "1":
return 'true'
else:
return 'false'
else:
return value_string
def digitize_v(version):
v_list = version.split('.')
return int(v_list[0]) * 1000 * 1000 + int(v_list[1]) * 1000 + int(v_list[2])