Arch: Remove Py2 code

This commit is contained in:
Chris Hennes
2022-11-07 22:05:55 -06:00
committed by Uwe
parent c355810538
commit f6f1928cf8
8 changed files with 15 additions and 125 deletions

View File

@@ -533,8 +533,6 @@ class _ViewProviderAxis:
tx = coin.SoAsciiText()
tx.justification = coin.SoText2.LEFT
t = vobj.Object.Labels[i]
if six.PY2 and isinstance(t,six.text_type):
t = t.encode("utf8")
tx.string.setValue(t)
if hasattr(vobj,"FontSize"):
fs = vobj.FontSize.Value
@@ -566,10 +564,7 @@ class _ViewProviderAxis:
('C',100),('XC',90),('L',50),('XL',40),
('X',10),('IX',9),('V',5),('IV',4),('I',1))
if hasattr(vobj.Object,"CustomNumber") and vobj.Object.CustomNumber:
if six.PY2:
return vobj.Object.CustomNumber.encode("utf8")
else:
return vobj.Object.CustomNumber
return vobj.Object.CustomNumber
elif hasattr(vobj,"NumberingStyle"):
if vobj.NumberingStyle == "1,2,3":
return str(num+1)

View File

@@ -46,22 +46,6 @@ __url__ = "https://www.freecadweb.org"
# module functions ###############################################
def string_replace(text, pattern, replacement):
"""
if py2 isn't supported anymore calls to this function
should be replaced with:
`text.replace(pattern, replacement)`
for python2 the encoding must be done, as unicode replacement leads to something like this:
```
>>> a = u'abc mm ^3'
>>> a.replace(u"^3", u"³")
u'abc mm \xc2\xb3'
```
"""
return text.replace(pattern, replacement)
def getStringList(objects):
'''getStringList(objects): returns a string defining a list
of objects'''
@@ -859,14 +843,14 @@ def survey(callback=False):
if o.Object.Shape.Solids:
u = FreeCAD.Units.Quantity(o.Object.Shape.Volume,FreeCAD.Units.Volume)
t = u.getUserPreferred()[0]
t = string_replace(t, "^3","³")
t = t.replace("^3","³")
anno.LabelText = "v " + t
FreeCAD.Console.PrintMessage("Object: " + n + ", Element: Whole, Volume: " + utf8_decode(t) + "\n")
FreeCAD.SurveyObserver.totalVolume += u.Value
elif o.Object.Shape.Faces:
u = FreeCAD.Units.Quantity(o.Object.Shape.Area,FreeCAD.Units.Area)
t = u.getUserPreferred()[0]
t = string_replace(t, "^2","²")
t = t.replace("^2","²")
anno.LabelText = "a " + t
FreeCAD.Console.PrintMessage("Object: " + n + ", Element: Whole, Area: " + utf8_decode(t) + "\n")
FreeCAD.SurveyObserver.totalArea += u.Value
@@ -902,7 +886,7 @@ def survey(callback=False):
if "Face" in el:
u = FreeCAD.Units.Quantity(e.Area,FreeCAD.Units.Area)
t = u.getUserPreferred()[0]
t = string_replace(t, "^2","²")
t = t.replace("^2","²")
anno.LabelText = "a " + t
FreeCAD.Console.PrintMessage("Object: " + n + ", Element: " + el + ", Area: "+ utf8_decode(t) + "\n")
FreeCAD.SurveyObserver.totalArea += u.Value
@@ -938,12 +922,12 @@ def survey(callback=False):
if FreeCAD.SurveyObserver.totalArea:
u = FreeCAD.Units.Quantity(FreeCAD.SurveyObserver.totalArea,FreeCAD.Units.Area)
t = u.getUserPreferred()[0]
t = string_replace(t, "^2","²")
t = t.replace("^2","²")
msg += " Area: " + t
if FreeCAD.SurveyObserver.totalVolume:
u = FreeCAD.Units.Quantity(FreeCAD.SurveyObserver.totalVolume,FreeCAD.Units.Volume)
t = u.getUserPreferred()[0]
t = string_replace(t, "^3","³")
t = t.replace("^3","³")
msg += " Volume: " + t
FreeCAD.Console.PrintMessage(msg+"\n")
@@ -1049,7 +1033,7 @@ class SurveyTaskPanel:
if hasattr(FreeCAD,"SurveyObserver"):
u = FreeCAD.Units.Quantity(FreeCAD.SurveyObserver.totalArea,FreeCAD.Units.Area)
t = u.getUserPreferred()[0]
t = string_replace(t, "^2","²")
t = t.replace("^2","²")
if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetBool("surveyUnits",True):
QtGui.QApplication.clipboard().setText(t)
else:

View File

@@ -47,7 +47,6 @@ import exportIFCStructuralTools
from DraftGeomUtils import vec
from importIFCHelper import dd2dms
from importIFCHelper import decode
from draftutils.messages import _msg, _err
if FreeCAD.GuiUp:
@@ -253,9 +252,6 @@ def export(exportList, filename, colors=None, preferences=None):
templatefilehandle, templatefile = tempfile.mkstemp(suffix=".ifc")
of = pyopen(templatefile, "w")
if six.PY2:
template = template.encode("utf8")
of.write(template)
of.close()
os.close(templatefilehandle)
@@ -588,8 +584,6 @@ def export(exportList, filename, colors=None, preferences=None):
r2,p2,c2 = getRepresentation(ifcfile,context,o,colors=colors,preferences=preferences)
if preferences['DEBUG']: print(" adding ",c2," : ",o.Label)
l = o.Label
if six.PY2:
l = l.encode("utf8")
prod2 = ifcfile.createIfcBuildingElementProxy(
ifcopenshell.guid.new(),
history,
@@ -625,8 +619,6 @@ def export(exportList, filename, colors=None, preferences=None):
r2,p2,c2 = getRepresentation(ifcfile,context,o,subtraction=True,colors=colors,preferences=preferences)
if preferences['DEBUG']: print(" subtracting ",c2," : ",o.Label)
l = o.Label
if six.PY2:
l = l.encode("utf8")
prod2 = ifcfile.createIfcOpeningElement(
ifcopenshell.guid.new(),
history,
@@ -703,15 +695,8 @@ def export(exportList, filename, colors=None, preferences=None):
val = sheet.get('D'+str(n))
else:
val = ''
if six.PY2 and isinstance(key, six.text_type):
key = key.encode("utf8")
else:
key = str(key)
if six.PY2 and isinstance(tp, six.text_type):
tp = tp.encode("utf8")
else:
tp = str(tp)
#tp = tp.encode("utf8")
key = str(key)
tp = str(tp)
if tp in ["IfcLabel","IfcText","IfcIdentifier",'IfcDescriptiveMeasure']:
val = val.encode("utf8")
elif tp == "IfcBoolean":
@@ -782,8 +767,7 @@ def export(exportList, filename, colors=None, preferences=None):
val = val.strip('"')
#if preferences['DEBUG']: print(" property ",key," : ",val.encode("utf8"), " (", str(tp), ")")
if tp in ["IfcLabel","IfcText","IfcIdentifier",'IfcDescriptiveMeasure']:
if six.PY2:
val = val.encode("utf8")
pass
elif tp == "IfcBoolean":
if val == ".T.":
val = True
@@ -1276,8 +1260,6 @@ def export(exportList, filename, colors=None, preferences=None):
relobjs.append(subproducts[o.Name])
if relobjs:
l = m.Label
if six.PY2:
l = l.encode("utf8")
mat = ifcfile.createIfcMaterial(l)
materials[m.Label] = mat
rgb = None
@@ -1349,8 +1331,6 @@ def export(exportList, filename, colors=None, preferences=None):
pos = ifcbin.createIfcCartesianPoint((l.x,l.y,l.z))
tpl = ifcbin.createIfcAxis2Placement3D(pos,None,None)
s = ";".join(anno.LabelText)
if six.PY2:
s = s.encode("utf8")
txt = ifcfile.createIfcTextLiteral(s,tpl,"LEFT")
reps = [txt]
elif Draft.getType(anno) in ["DraftText","Text"]:
@@ -1365,8 +1345,6 @@ def export(exportList, filename, colors=None, preferences=None):
if anno.ViewObject.Justification == "Right":
alg = "RIGHT"
s = ";".join(anno.Text)
if six.PY2:
s = s.encode("utf8")
txt = ifcfile.createIfcTextLiteral(s,tpl,alg)
reps = [txt]
elif Draft.getType(anno) in ["Dimension","LinearDimension","AngularDimension"]:
@@ -1399,8 +1377,6 @@ def export(exportList, filename, colors=None, preferences=None):
xdir = ifcbin.createIfcDirection(tuple(r.multVec(FreeCAD.Vector(1,0,0))))
pos = ifcbin.createIfcCartesianPoint((l.x,l.y,l.z))
tpl = ifcbin.createIfcAxis2Placement3D(pos,zdir,xdir)
if six.PY2:
s = s.encode("utf8")
txt = ifcfile.createIfcTextLiteral(vp.string,tpl,"LEFT")
reps.append(txt)
else:
@@ -1425,8 +1401,6 @@ def export(exportList, filename, colors=None, preferences=None):
shp = ifcfile.createIfcShapeRepresentation(context,'Annotation','Annotation2D',reps)
rep = ifcfile.createIfcProductDefinitionShape(None,None,[shp])
l = anno.Label
if six.PY2:
l = l.encode("utf8")
ann = ifcfile.createIfcAnnotation(
ifcopenshell.guid.new(),
history,l,
@@ -1468,8 +1442,6 @@ def export(exportList, filename, colors=None, preferences=None):
swallowed.append(annos[o])
if children:
name = FreeCAD.ActiveDocument.getObject(g[0]).Label
if six.PY2:
name = name.encode("utf8")
grp = ifcfile.createIfcGroup(
ifcopenshell.guid.new(),
history,
@@ -1626,8 +1598,6 @@ def export(exportList, filename, colors=None, preferences=None):
if preferences['DEBUG']: print("writing ",filename,"...")
filename = decode(filename)
if filename.lower().endswith("json"):
writeJson(filename,ifcfile)
else:
@@ -1682,8 +1652,7 @@ def getPropertyData(key,value,preferences):
if pvalue == "":
return pset, pname, ptype, None
if ptype in ["IfcLabel","IfcText","IfcIdentifier",'IfcDescriptiveMeasure']:
if six.PY2:
pvalue = pvalue.encode("utf8")
pass
elif ptype == "IfcBoolean":
if pvalue == ".T.":
pvalue = True
@@ -1703,8 +1672,6 @@ def getPropertyData(key,value,preferences):
try:
pvalue = FreeCAD.Units.Quantity(pvalue).Value
except Exception:
if six.PY2:
pvalue = pvalue.encode("utf8")
if preferences['DEBUG']:print(" warning: unable to export property as numeric value:",pname,pvalue)
# print('pset: {}, pname: {}, ptype: {}, pvalue: {}'.format(pset, pname, ptype, pvalue))
@@ -1804,17 +1771,6 @@ def buildAddress(obj,ifcfile):
t = obj.City or None
r = obj.Region or None
c = obj.Country or None
if six.PY2:
if a:
a = a.encode("utf8")
if p:
p = p.encode("utf8")
if t:
t = t.encode("utf8")
if r:
r = r.encode("utf8")
if c:
c = c.encode("utf8")
if a or p or t or r or c:
addr = ifcfile.createIfcPostalAddress("SITE",'Site Address','',None,[a],None,t,r,p,c)
else:
@@ -2382,8 +2338,6 @@ def getRepresentation(
if hasattr(obj,"Material"):
if obj.Material:
m = obj.Material.Label
if six.PY2:
m = m.encode("utf8")
psa = ifcbin.createIfcPresentationStyleAssignment(m,rgbt[i][0],rgbt[i][1],rgbt[i][2],rgbt[i][3])
surfstyles[key] = psa
isi = ifcfile.createIfcStyledItem(shape,[psa],None)
@@ -2478,8 +2432,6 @@ def getText(field,obj):
field = "Label"
if hasattr(obj,field):
result = getattr(obj,field)
if six.PY2:
result = result.encode("utf8")
return result

View File

@@ -166,7 +166,6 @@ def open(filename, skip=[], only=[], root=None):
Most of the work is done in the `insert` function.
"""
docname = os.path.splitext(os.path.basename(filename))[0]
docname = importIFCHelper.decode(docname, utf=True)
doc = FreeCAD.newDocument(docname)
doc.Label = docname
doc = insert(filename, doc.Name, skip, only, root)
@@ -251,7 +250,7 @@ def insert(srcfile, docname, skip=[], only=[], root=None, preferences=None):
else:
if preferences['DEBUG']:
_msg("Opening '{}'... ".format(srcfile), end="")
filename = importIFCHelper.decode(srcfile, utf=True)
filename = srcfile
filesize = os.path.getsize(filename) * 1E-6 # in megabytes
ifcfile = ifcopenshell.open(filename)
@@ -397,8 +396,6 @@ def insert(srcfile, docname, skip=[], only=[], root=None, preferences=None):
name = str(ptype[3:])
if product.Name:
name = product.Name
if six.PY2:
name = name.encode("utf8")
if preferences['PREFIX_NUMBERS']:
name = "ID" + str(pid) + " " + name
obj = None
@@ -837,9 +834,6 @@ def insert(srcfile, docname, skip=[], only=[], root=None, preferences=None):
if l.is_a("IfcPropertySingleValue"):
if preferences['DEBUG']:
print("property name",l.Name,type(l.Name))
if six.PY2:
catname = catname.encode("utf8")
lname = lname.encode("utf8")
ifc_spreadsheet.set(str('A'+str(n)), catname)
ifc_spreadsheet.set(str('B'+str(n)), lname)
if l.NominalValue:
@@ -849,10 +843,7 @@ def insert(srcfile, docname, skip=[], only=[], root=None, preferences=None):
# print("l.NominalValue.Unit",l.NominalValue.Unit,type(l.NominalValue.Unit))
ifc_spreadsheet.set(str('C'+str(n)), l.NominalValue.is_a())
if l.NominalValue.is_a() in ['IfcLabel','IfcText','IfcIdentifier','IfcDescriptiveMeasure']:
if six.PY2:
ifc_spreadsheet.set(str('D'+str(n)), "'" + str(l.NominalValue.wrappedValue.encode("utf8")))
else:
ifc_spreadsheet.set(str('D'+str(n)), "'" + str(l.NominalValue.wrappedValue))
ifc_spreadsheet.set(str('D'+str(n)), "'" + str(l.NominalValue.wrappedValue))
else:
ifc_spreadsheet.set(str('D'+str(n)), str(l.NominalValue.wrappedValue))
if hasattr(l.NominalValue,'Unit'):
@@ -1016,8 +1007,6 @@ def insert(srcfile, docname, skip=[], only=[], root=None, preferences=None):
else:
if preferences['DEBUG']: print("no group name specified for entity: #", ifcfile[host].id(), ", entity type is used!")
grp_name = ifcfile[host].is_a() + "_" + str(ifcfile[host].id())
if six.PY2:
grp_name = grp_name.encode("utf8")
grp = doc.addObject("App::DocumentObjectGroup",grp_name)
grp.Label = grp_name
objects[host] = grp
@@ -1171,8 +1160,6 @@ def insert(srcfile, docname, skip=[], only=[], root=None, preferences=None):
name = "Material"
if material.Name:
name = material.Name
if six.PY2:
name = name.encode("utf8")
# mdict["Name"] = name on duplicate material names in IFC this could result in crash
# https://forum.freecadweb.org/viewtopic.php?f=23&t=63260
# thus use "Description"

View File

@@ -43,16 +43,6 @@ DEBUG_prod_repr = False
DEBUG_prod_colors = False
def decode(filename, utf=False):
"""Turn unicode into strings, only for Python 2."""
if six.PY2 and isinstance(filename, six.text_type):
# This is a workaround since ifcopenshell 0.6 currently
# can't handle unicode filenames
encoding = "utf8" if utf else sys.getfilesystemencoding()
filename = filename.encode(encoding)
return filename
def dd2dms(dd):
"""Convert decimal degrees to degrees, minutes, seconds.
@@ -630,20 +620,14 @@ def getIfcProperties(ifcfile, pid, psets, d):
for pset in psets.keys():
# print("reading pset: ",pset)
psetname = ifcfile[pset].Name
if six.PY2:
psetname = psetname.encode("utf8")
for prop in psets[pset]:
e = ifcfile[prop]
pname = e.Name
if six.PY2:
pname = pname.encode("utf8")
if e.is_a("IfcPropertySingleValue"):
if e.NominalValue:
ptype = e.NominalValue.is_a()
if ptype in ['IfcLabel','IfcText','IfcIdentifier','IfcDescriptiveMeasure']:
pvalue = e.NominalValue.wrappedValue
if six.PY2:
pvalue = pvalue.encode("utf8")
else:
pvalue = str(e.NominalValue.wrappedValue)
if hasattr(e.NominalValue,'Unit'):
@@ -1101,8 +1085,6 @@ def createAnnotation(annotation,doc,ifcscale,preferences):
grid_placement = None
if annotation.Name:
name = annotation.Name
if six.PY2:
name = name.encode("utf8")
if annotation.ObjectPlacement:
# https://forum.freecadweb.org/viewtopic.php?f=39&t=40027
grid_placement = getPlacement(annotation.ObjectPlacement,scaling=1)
@@ -1116,8 +1098,6 @@ def createAnnotation(annotation,doc,ifcscale,preferences):
name = "Annotation"
if annotation.Name:
name = annotation.Name
if six.PY2:
name = name.encode("utf8")
if "annotation" not in name.lower():
name = "Annotation " + name
if preferences['PREFIX_NUMBERS']: name = "ID" + str(aid) + " " + name

View File

@@ -49,10 +49,7 @@ def export(exportList, filename):
}
# Write file
if six.PY2:
outfile = pythonopen(filename, "wb")
else:
outfile = pythonopen(filename, "w")
outfile = pythonopen(filename, "w")
json.dump(data, outfile, separators = (',', ':'))
outfile.close()

View File

@@ -24,7 +24,6 @@ from __future__ import print_function
import os
import FreeCAD
import importIFCHelper
translate = FreeCAD.Qt.translate
if open.__module__ in ['__builtin__','io']:
@@ -35,7 +34,6 @@ def open(filename):
"""opens a SHP/SHX/DBF file in a new FreeCAD document"""
docname = os.path.splitext(os.path.basename(filename))[0]
docname = importIFCHelper.decode(docname,utf=True)
doc = FreeCAD.newDocument(docname)
doc.Label = docname
doc = insert(filename,doc.Name)

View File

@@ -864,10 +864,7 @@ def export( exportList, filename, colors = None, camera = None ):
html = html.replace('$data', json.dumps(data, separators=(',', ':')) ) # Shape Data
if six.PY2:
outfile = pythonopen(filename, "wb")
else:
outfile = pythonopen(filename, "w")
outfile = pythonopen(filename, "w")
outfile.write( html )
outfile.close()
FreeCAD.Console.PrintMessage( translate("Arch", "Successfully written") + ' ' + filename + "\n" )